---
title: 操作系统详细复习笔记
author: Dm0u
pubDatetime: 2026-11-19T22:55:00Z
featured: false
draft: false
printable: true
copyable: false
tags:
  - 操作系统
  - cs408
  - 考研
description: 系统梳理操作系统七大核心章节（概述、进程与线程、同步与互斥、处理机调度与死锁、内存管理、文件管理、I/O 与磁盘管理），含 122 张四主题自适应内联 SVG 示意图、核心公式推导与 408 历年真题精讲。
---

## 第1章 操作系统概述

### 1.1 操作系统的概念、角色与五大功能

从本质上看，<strong>操作系统（Operating System，OS）</strong>是一个运行在裸机之上的大型系统程序（如现代 Linux 内核代码量达数千万行），也是管理计算机硬件与软件资源的控制中心。从底层设计哲学来看，操作系统干的是同一件事——**“欺骗的艺术”**：物理世界只有一套有限、异构且难用的硬件（几个 CPU 核心、一块内存、若干速度悬殊的外设），而操作系统通过软件抽象向上层应用程序编织出一个<strong>“独占硬件”的完美谎言</strong>，并将整门课凝练为三条核心主线：

1. **虚拟化（Virtualization）**：把有限的物理 CPU 虚拟为多个逻辑 CPU（**进程**），让每个程序都以为自己独占处理器；把物理内存抽象为从 0 开始的连续私有空间（**虚拟地址空间**），让每个程序都以为自己独占大内存。
2. **并发（Concurrency）**：妥善处理多道程序在时间上交叉推进时的资源竞争、同步互斥与死锁问题。
3. **持久化（Persistence）**：将易失的内存状态与用户数据以统一、可检索的方式长期保存在非易失外存上（**文件系统与 I/O 管理**）。

#### 操作系统的三大身份与层次定位

在计算机系统“硬件 → 指令集架构（ISA）→ 操作系统 → 库函数/系统软件 → 应用程序 → 用户”的层次栈中，操作系统承上启下，扮演着**三重核心角色**：

| 角色身份 | 面向视角 | 核心职责与实质 | 缺失后果 |
| --- | --- | --- | --- |
| **系统资源管理者** | 向下管硬件 | 统一组织与分配处理器、存储器、I/O 设备与文件四大类资源，兼顾效率（利用率/吞吐量）与安全隔离 | 多道程序相互踩踏内存、争抢打印机或死循环独占 CPU |
| **用户与硬件之间的接口** | 向上供服务 | 为普通用户提供**命令控制接口**（联机命令/脱机命令/GUI），为程序员提供**程序接口**（系统调用/广义指令） | 用户只能面对裸机直接操作硬件端口与二进制指令 |
| **扩充机器（虚拟机器）** | 提升抽象层 | 将裸机粗糙的“**指令级接口**”抬高包装为“**系统调用级接口**”，屏蔽设备控制器的繁琐细节与硬件差异 | 哪怕输出一行字符串也需程序员手写上百行显卡端口控制代码 |

> **★考点**：所谓“扩充机器（虚拟机器）”，**扩充的是接口的抽象层次，而非物理硬件的真实性能**——在用户和程序看来，机器仿佛天生就能直接执行 `open`、`read`、`write` 这类高级操作。

操作系统向用户提供的两类核心接口如下（不同教材划分略有差异，408 重点区分命令接口与程序接口）：

- **命令控制接口**：面向终端用户，分为**联机命令接口**（交互式输入命令，如 Linux Shell、Windows CMD）、**脱机命令接口**（批处理作业控制语言 JCL，一次性提交整批作业控制清单）和**图形用户接口（GUI）**（本质上是利用图形元素触发系统操作的扩展命令接口，**仍运行在用户态**）。
- **程序接口**：面向开发人员与应用程序，**由一组系统调用（System Call，又称广义指令）构成**，是应用程序请求操作系统内核服务的**唯一合法入口**。

#### 操作系统的四大管理功能（加开放接口共五项）

操作系统有几类核心资源，就对应几大管理功能：

| 管理功能 | 管理对象 | 核心机制与主要任务（贯穿全书） |
| --- | --- | --- |
| **处理器（处理机）管理** | CPU | 进程创建与撤销、进程状态转换、进程同步与互斥、进程通信、死锁处理与 CPU 调度 |
| **存储器管理** | 主存与虚存 | 内存分配与回收、内存隔离与保护、逻辑地址到物理地址的映射、虚拟存储扩充 |
| **设备管理** | I/O 设备 | 缓冲管理、设备分配与回收、设备驱动程序处理、SPOOLing 虚拟设备技术 |
| **文件管理** | 磁盘文件 | 文件存储空间管理、目录管理、文件逻辑/物理结构组织、文件读写与存取保护 |

<figure class="cpd-figure not-content" id="os-c1-fig-1">
  <svg viewBox="0 0 720 330" role="img" aria-label="计算机系统层次栈与操作系统三大身份、四大管理功能全景图">
    <defs>
      <marker id="os-c1-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="338" height="302" rx="6"/>
    <rect class="fig-box-subtle" x="366" y="14" width="338" height="302" rx="6"/>
    <line class="fig-line-accent" x1="306" y1="268" x2="306" y2="56" marker-end="url(#os-c1-arr-1)"/>
    <rect class="fig-box" x="26" y="46" width="262" height="34" rx="4"/>
    <rect class="fig-box-blue" x="26" y="86" width="262" height="34" rx="4"/>
    <rect class="fig-box" x="26" y="126" width="262" height="34" rx="4"/>
    <rect class="fig-box-accent" x="26" y="166" width="262" height="36" rx="5"/>
    <rect class="fig-box-orange" x="26" y="208" width="262" height="34" rx="4"/>
    <rect class="fig-box-purple" x="26" y="248" width="262" height="34" rx="4"/>
    <rect class="fig-box-green" x="378" y="46" width="314" height="36" rx="4"/>
    <rect class="fig-box-blue" x="378" y="88" width="314" height="36" rx="4"/>
    <rect class="fig-box-accent" x="378" y="130" width="314" height="36" rx="4"/>
    <rect class="fig-box-orange" x="378" y="182" width="314" height="38" rx="4"/>
    <rect class="fig-box-purple" x="378" y="226" width="314" height="38" rx="4"/>
    <rect class="fig-box-green" x="378" y="270" width="314" height="36" rx="4"/>
    <text class="fig-title" x="185" y="34" text-anchor="middle" font-size="12">计算机系统层次栈（自底向上抽象跃迁）</text>
    <g text-anchor="middle" font-size="11">
      <text class="fig-label" x="157" y="67">最终用户（通过终端 CLI / 桌面 GUI 交互）</text>
      <text class="fig-blue" x="157" y="107">应用程序（编译器·浏览器·用户业务进程）</text>
      <text class="fig-label" x="157" y="147">标准库函数（C 标准库 printf / malloc 等）</text>
      <text class="fig-accent" x="157" y="188" font-size="11.5">★ 操作系统 OS（提供系统调用级接口）</text>
      <text class="fig-orange" x="157" y="229">指令系统 ISA（机器指令级硬件接口）</text>
      <text class="fig-purple" x="157" y="269">计算机硬件裸机（CPU · 主存 · 磁盘 · I/O）</text>
      <text class="fig-accent" x="330" y="132" font-size="11">逐</text>
      <text class="fig-accent" x="330" y="152" font-size="11">层</text>
      <text class="fig-accent" x="330" y="172" font-size="11">抽</text>
      <text class="fig-accent" x="330" y="192" font-size="11">象</text>
      <text class="fig-accent" x="330" y="212" font-size="11">封</text>
      <text class="fig-accent" x="330" y="232" font-size="11">装</text>
      <text class="fig-muted" x="185" y="303" font-size="10">★ 扩充机器 = 把“指令级接口”抬高至“系统调用级”</text>
    </g>
    <text class="fig-title" x="535" y="34" text-anchor="middle" font-size="12">OS 三大身份与“欺骗的艺术”三大主线</text>
    <g text-anchor="middle" font-size="10.8">
      <text class="fig-green" x="535" y="62">① 资源管理者：管处理机 / 存储 / 设备 / 文件</text>
      <text class="fig-muted" x="535" y="76" font-size="9.8">在资源有限与多道争用下实现高效分配与隔离</text>
      <text class="fig-blue" x="535" y="104">② 用户接口：命令控制接口 + 程序接口</text>
      <text class="fig-muted" x="535" y="118" font-size="9.8">CLI / 脱机 JCL / GUI（用户态）与系统调用</text>
      <text class="fig-accent" x="535" y="146">③ 扩充机器：吸收复杂度并抹平设备差异</text>
      <text class="fig-muted" x="535" y="160" font-size="9.8">使硬件仿佛天生具备 read/write 等高级能力</text>
      <text class="fig-orange" x="535" y="198">CPU 虚拟化 → 进程与线程（调度 + 切换）</text>
      <text class="fig-muted" x="535" y="213" font-size="9.8">“谎言”：让每个进程以为自己独占整个 CPU</text>
      <text class="fig-purple" x="535" y="242">内存虚拟化 → 虚拟地址空间（分段 / 分页）</text>
      <text class="fig-muted" x="535" y="257" font-size="9.8">“谎言”：让每个进程以为独占连续私有大内存</text>
      <text class="fig-green" x="535" y="292">持久化与并发 → 文件系统 + 同步互斥与 I/O</text>
    </g>
  </svg>
  <figcaption>图 1-1　计算机系统层次栈、操作系统三重角色及“欺骗的艺术”三条核心主线</figcaption>
</figure>

---

### 1.2 ★操作系统的四大基本特征

操作系统的**并发、共享、虚拟、异步**四大特征并非互不相干的四条并列条目，而是一条严密的**因果推导链**：

1. <strong>并发（Concurrency）</strong>是起点：系统中同时存在多个待推进的运行程序（多道程序设计）。
2. <strong>共享（Sharing）</strong>由并发直接导出：多道程序共同驻留内存，必然需要共同使用有限的 CPU、内存与 I/O 设备；反之若资源不可共享，并发也无从谈起。因此**并发与共享互为存在条件，是操作系统最基本的两个特征**。
3. <strong>虚拟（Virtual）</strong>建立在并发与共享之上：既然同一份物理硬件要被多个程序分着使用，操作系统就需要通过虚拟技术欺骗上层程序，让每个程序都以为自己独占资源。
4. <strong>异步（Asynchronism）</strong>同样由并发与共享导出：多道程序在有限资源上相互竞争、走走停停，使单个程序的推进速度变得不可预知。

#### 1. 并发 vs 并行（★高频边界辨析）

- **并发性**：指两个或多个事件在**同一时间间隔（时间段）内**发生。在单核处理机系统中，宏观上多个进程似乎在同时推进，但**微观上同一时刻只有一个进程占用 CPU**，各个进程分时交替使用处理器。
- **并行性**：指两个或多个事件在<strong>同一时刻（瞬间）</strong>真正同时发生。

| 比较维度 | 并发（Concurrency） | 并行（Parallelism） | 常见真题陷阱（`09#23`, `18#23`） |
| --- | --- | --- | --- |
| **时间尺度** | **同一时间段**内交替推进 | **同一时刻**真正同时执行 | 把“时间段”与“瞬间”混淆 |
| **单核能否做到** | **可以**（时间片轮转交替执行） | **看对象**：进程间**不能**并行，但 **CPU 与外设/DMA/通道之间可以并行**！ | 误以为“并行必须多核” |
| **多核条件** | 允许多个进程同时推进 | **多核/多处理机是“多个进程之间并行”的前提** | 误以为单核多任务系统没有并行性 |

> **★考点**：408 真题反复利用对象的不同设坑——“在单处理机系统中，可以并行的是：**处理机与设备、处理机与通道、设备与设备**（`09#23`）”；而“多任务操作系统运行在单 CPU 上时，进程之间并发执行，**CPU 与外设之间依然可以并行工作**（`18#23`）”。此外，操作系统最基本的特征是“**并发与共享**”，若把“并发”偷换为“并行”则错误！

#### 2. 共享的两种方式

系统中的资源可供内存中多个并发执行的进程共同使用，按同一时间段内是否允许交替独占，分为两类：

- **互斥共享方式**：资源虽然可以提供给多个进程使用，但规定**在一段时间内只允许一个进程访问该资源**（一旦分配则独占使用完毕再释放）。典型代表为**打印机、磁带机**以及各类软件**临界资源**（若两个进程交错输出到同一台打印机，纸面上会混杂两份完全无关的文档）。
- **同时访问方式（分时共享）**：允许**在一段时间内由多个进程“同时”访问**同一类资源。这里所说的“同时”主要是宏观上的——微观上各进程可能仍是分时交替访问（如**磁盘设备与盘上文件、主存**）。

#### 3. 虚拟的两种复用技术

虚拟技术的本质是通过软件映射将**一个物理实体变为若干个逻辑对应物**（物理实体的真实数量与能力并未改变，改变的只是用户视角）。实现虚拟只有两类物理切分维度：

- **时分复用技术（Time-Division Multiplexing）**：将宝贵的物理资源在**时间维度**上切成极短的时间片，轮流分配给不同任务，利用人眼或应用感知的尺度差形成“独占”假象。典型应用：**虚拟处理器**（将 1 个物理 CPU 虚拟成多个逻辑 CPU）、**虚拟设备**（SPOOLing 技术将 1 台物理打印机虚拟成多台共享打印机）。
- **空分复用技术（Space-Division Multiplexing）**：将物理资源在**空间维度**上切分成互不干扰的区域或页框进行复用。典型应用：**虚拟存储器**（利用局部性原理，将少量物理页框与海量外存联动映射出远超物理内存容量的地址空间）、**磁盘逻辑分区**。

> **注意**：**CPU 只能采用时分复用，绝对不能空分复用**——同一个单核处理器无法被在空间上劈成两半同时执行两条指令流。若题目出现“虚拟处理器技术利用了空分复用”，可直接判错。

#### 4. 异步性与结果可再现性

在多道程序环境下，由于资源有限且存在外设等待、时间片抢占与动态到达的新作业，各进程何时能获得 CPU、何时因请求资源未果而阻塞、总耗时多久都无法提前精确测定，因此进程是以**不可预知的速度向前推进**的，这就是**异步性**。

> **★考点**：异步性绝不意味着结果可以随机错乱！异步必须守住一条工程底线——只要运行环境与输入相同，无论各进程以何种交错时序推进，程序的执行结果都必须完全一致，即**结果的“可再现性”**。后续第 3 章“进程同步与互斥”的全部机制，正是为了在异步执行下守住可再现性底线。

<figure class="cpd-figure not-content" id="os-c1-fig-2">
  <svg viewBox="0 0 720 318" role="img" aria-label="操作系统四大基本特征因果推导链与单核并发、并行微观时序图">
    <defs>
      <marker id="os-c1-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="118" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="142" width="338" height="162" rx="6"/>
    <rect class="fig-box-subtle" x="366" y="142" width="338" height="162" rx="6"/>
    <line class="fig-line-accent" x1="176" y1="82" x2="198" y2="82" marker-start="url(#os-c1-arr-2)" marker-end="url(#os-c1-arr-2)"/>
    <line class="fig-line-accent" x1="348" y1="82" x2="370" y2="82" marker-end="url(#os-c1-arr-2)"/>
    <line class="fig-line-accent" x1="520" y1="82" x2="542" y2="82" marker-end="url(#os-c1-arr-2)"/>
    <rect class="fig-box-accent" x="28" y="48" width="146" height="72" rx="5"/>
    <rect class="fig-box-green" x="200" y="48" width="146" height="72" rx="5"/>
    <rect class="fig-box-blue" x="372" y="48" width="146" height="72" rx="5"/>
    <rect class="fig-box-orange" x="544" y="48" width="146" height="72" rx="5"/>
    <rect class="fig-box" x="104" y="182" width="59" height="28" rx="3"/>
    <rect class="fig-box-blue" x="163" y="182" width="59" height="28" rx="3"/>
    <rect class="fig-box" x="222" y="182" width="59" height="28" rx="3"/>
    <rect class="fig-box-blue" x="281" y="182" width="59" height="28" rx="3"/>
    <rect class="fig-box" x="104" y="220" width="59" height="28" rx="3"/>
    <rect class="fig-box-green" x="163" y="220" width="59" height="28" rx="3"/>
    <rect class="fig-box-orange" x="222" y="220" width="59" height="28" rx="3"/>
    <rect class="fig-box" x="281" y="220" width="59" height="28" rx="3"/>
    <line class="fig-line-dashed" x1="192" y1="173" x2="192" y2="182"/>
    <line class="fig-line-dashed" x1="192" y1="210" x2="192" y2="220"/>
    <line class="fig-line-dashed" x1="192" y1="248" x2="192" y2="256"/>
    <rect class="fig-box-accent" x="454" y="182" width="234" height="28" rx="3"/>
    <rect class="fig-box-blue" x="454" y="220" width="234" height="28" rx="3"/>
    <line class="fig-line-dashed" x1="571" y1="173" x2="571" y2="182"/>
    <line class="fig-line-dashed" x1="571" y1="210" x2="571" y2="220"/>
    <line class="fig-line-dashed" x1="571" y1="248" x2="571" y2="256"/>
    <text class="fig-title" x="360" y="34" text-anchor="middle" font-size="12">四大基本特征因果推导链（★ 并发与共享互为存在条件，最基本）</text>
    <g text-anchor="middle" font-size="11">
      <text class="fig-accent" x="101" y="68">① 并发（起点）</text>
      <text class="fig-label" x="101" y="86" font-size="10">同时间段交替</text>
      <text class="fig-muted" x="101" y="104" font-size="9.8">宏观并·微观串</text>
      <text class="fig-accent" x="187" y="68" font-size="9.5">互存</text>
      <text class="fig-green" x="273" y="68">② 共享（基石）</text>
      <text class="fig-label" x="273" y="86" font-size="10">共用有限资源</text>
      <text class="fig-muted" x="273" y="104" font-size="9.8">互斥 / 同时访问</text>
      <text class="fig-blue" x="445" y="68">③ 虚拟（假象）</text>
      <text class="fig-label" x="445" y="86" font-size="10">1 变 N 逻辑资源</text>
      <text class="fig-muted" x="445" y="104" font-size="9.8">时分 / 空分复用</text>
      <text class="fig-orange" x="617" y="68">④ 异步（结果）</text>
      <text class="fig-label" x="617" y="86" font-size="10">速度不可预知</text>
      <text class="fig-muted" x="617" y="104" font-size="9.8">★ 底线：可再现性</text>
    </g>
    <text class="fig-title" x="185" y="162" text-anchor="middle" font-size="11.5">单核场景：进程并发 + CPU 与外设并行 ★</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-label" x="62" y="200">CPU 核心</text>
      <text class="fig-label" x="62" y="238">外设/DMA</text>
      <text class="fig-label" x="133" y="200">P1 计算</text>
      <text class="fig-blue" x="192" y="200">P2 计算</text>
      <text class="fig-label" x="251" y="200">P1 计算</text>
      <text class="fig-blue" x="310" y="200">P2 计算</text>
      <text class="fig-muted" x="133" y="238">空闲</text>
      <text class="fig-green" x="192" y="238">P1 DMA</text>
      <text class="fig-orange" x="251" y="238">P2 输出</text>
      <text class="fig-muted" x="310" y="238">空闲</text>
      <text class="fig-accent" x="192" y="268" font-size="9.8">↑ 同一时刻 t0：CPU 与外设同时工作（并行）</text>
      <text class="fig-muted" x="185" y="288" font-size="9.8">两进程交替用 CPU（并发）；CPU 与外设同时动（并行）</text>
    </g>
    <text class="fig-title" x="535" y="162" text-anchor="middle" font-size="11.5">多核场景：多进程之间真正并行</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-label" x="412" y="200">CPU 核 0</text>
      <text class="fig-label" x="412" y="238">CPU 核 1</text>
      <text class="fig-accent" x="571" y="200">P1 指令流持续执行</text>
      <text class="fig-blue" x="571" y="238">P2 指令流持续执行</text>
      <text class="fig-accent" x="571" y="268" font-size="9.8">↑ 同一时刻 t1：两进程同时运行</text>
      <text class="fig-muted" x="535" y="288" font-size="9.8">多核只是“进程间并行”前提，非“并行”的必要条件</text>
    </g>
  </svg>
  <figcaption>图 1-2　四大基本特征因果推导链与单核/多核环境下并发与并行的精确时空边界</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c1-fig-3">
  <svg viewBox="0 0 720 272" role="img" aria-label="互斥共享与同时访问共享对比，以及时分复用与空分复用虚拟技术对比图">
    <rect class="fig-box-subtle" x="16" y="14" width="336" height="244" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="14" width="336" height="244" rx="6"/>
    <rect class="fig-box-red" x="28" y="48" width="312" height="96" rx="5"/>
    <rect class="fig-box-green" x="28" y="154" width="312" height="92" rx="5"/>
    <rect class="fig-box" x="44" y="84" width="136" height="24" rx="3"/>
    <rect class="fig-box" x="188" y="84" width="136" height="24" rx="3"/>
    <rect class="fig-box" x="44" y="190" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="114" y="190" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="184" y="190" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="254" y="190" width="66" height="24" rx="3"/>
    <rect class="fig-box-blue" x="380" y="48" width="312" height="96" rx="5"/>
    <rect class="fig-box-purple" x="380" y="154" width="312" height="92" rx="5"/>
    <rect class="fig-box" x="396" y="84" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="466" y="84" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="536" y="84" width="66" height="24" rx="3"/>
    <rect class="fig-box" x="606" y="84" width="70" height="24" rx="3"/>
    <rect class="fig-box" x="396" y="190" width="68" height="24" rx="3"/>
    <rect class="fig-box" x="468" y="190" width="68" height="24" rx="3"/>
    <rect class="fig-box" x="540" y="190" width="68" height="24" rx="3"/>
    <rect class="fig-box" x="612" y="190" width="64" height="24" rx="3"/>
    <text class="fig-title" x="184" y="34" text-anchor="middle" font-size="12">资源共享的两种方式（以打印机 vs 磁盘为例）</text>
    <g text-anchor="middle" font-size="10.8">
      <text class="fig-red" x="184" y="68">① 互斥共享（临界资源：打印机 / 磁带机）</text>
      <text class="fig-label" x="112" y="100" font-size="10">进程 A：独占印完</text>
      <text class="fig-muted" x="256" y="100" font-size="10">进程 B：释放后才可用</text>
      <text class="fig-muted" x="184" y="130" font-size="9.8">时间段内仅限 1 个进程持有，禁止交错输出</text>
      <text class="fig-green" x="184" y="174">② 同时访问 / 分时共享（磁盘、主存）</text>
      <text class="fig-label" x="77" y="206" font-size="10">A 读盘</text>
      <text class="fig-label" x="147" y="206" font-size="10">B 写盘</text>
      <text class="fig-label" x="217" y="206" font-size="10">A 读盘</text>
      <text class="fig-label" x="287" y="206" font-size="10">B 读盘</text>
      <text class="fig-muted" x="184" y="234" font-size="9.8">宏观上同时共享，微观上多进程交替访问</text>
    </g>
    <text class="fig-title" x="536" y="34" text-anchor="middle" font-size="12">虚拟化的两种复用方式（时间维度 vs 空间维度）</text>
    <g text-anchor="middle" font-size="10.8">
      <text class="fig-blue" x="536" y="68">① 时分复用（虚拟处理器 / SPOOLing 设备）</text>
      <text class="fig-label" x="429" y="100" font-size="10">P1 10ms</text>
      <text class="fig-label" x="499" y="100" font-size="10">P2 10ms</text>
      <text class="fig-label" x="569" y="100" font-size="10">P3 10ms</text>
      <text class="fig-label" x="641" y="100" font-size="10">P1 10ms</text>
      <text class="fig-muted" x="536" y="130" font-size="9.8">★ CPU 只能时分复用（极速轮转造成多 CPU 假象）</text>
      <text class="fig-purple" x="536" y="174">② 空分复用（虚拟存储器 / 磁盘分区）</text>
      <text class="fig-label" x="430" y="206" font-size="10">OS 内核</text>
      <text class="fig-label" x="502" y="206" font-size="10">P1 页框</text>
      <text class="fig-label" x="574" y="206" font-size="10">P2 页框</text>
      <text class="fig-label" x="644" y="206" font-size="10">空闲框</text>
      <text class="fig-muted" x="536" y="234" font-size="9.8">按物理空间切块或联动外存，映射更大私有地址</text>
    </g>
  </svg>
  <figcaption>图 1-3　资源共享（互斥 vs 同时）与虚拟技术（时分复用 vs 空分复用）原理对照</figcaption>
</figure>

---

### 1.3 操作系统的发展历程与典型计算模型

操作系统的发展史就是一部<strong>“用新技术化解上一代核心矛盾”</strong>的演进史：

| 发展阶段 | 标志特征与引入技术 | 解决的核心矛盾 | 遗留缺陷 / 代价 |
| --- | --- | --- | --- |
| **1. 手工操作阶段** | 无 OS；程序员兼操作员，穿孔纸带/卡片机器语言编程 | — | ① **用户独占全机**；② **CPU 等待手工操作**，利用率极低 |
| **（过渡）脱机 I/O** | 引入**外围机（卫星机）+ 磁带**，输入输出脱离主机直接控制 | 缓解高速 CPU 与低速纸带机的速度不匹配矛盾 | 仍缺自动调度主体的软件控制 |
| **2. 单道批处理** | 引入**监督程序（Monitor，OS 雏形）**；具有**自动性、顺序性、单道性** | 作业成批自动连跑，解决“CPU 等人”的问题 | 内存仅一道作业，**发出 I/O 时 CPU 只能空转等待**；小作业占大内存浪费空间 |
| **3. 多道批处理 ★** | 多道程序驻留内存共享资源；依托**中断 + 通道/DMA** 实现重叠执行 | 解决“CPU 等 I/O”，**标志真正意义上操作系统的诞生** | **平均周转时间长、无交互能力**、系统调度与切换**开销变大** |
| **4. 分时系统** | CPU 按**时间片轮转**，多用户通过终端共享主机；具**多路/独立/及时/交互性** | **满足人机交互需求**（不再只是为了榨干吞吐量） | 仅保证平均响应快，**无严格实时截止时间保证** |
| **5. 实时系统** | 以抢占式优先级或时间约束保证<strong>截止时间（Deadline）</strong>与高可靠性 | 满足工业控制、航空航天、音视频等硬/软实时需求 | 资源利用率往往让位于最坏响应确定性 |

> **★考点**：关于批处理与多道程序设计的四大高频考点（`16#23`, `17#28`, `22#23`）：
> 1. **批处理系统不允许多个用户与计算机直接交互**（`16#23`），交互是分时系统的产物。
> 2. 与单道相比，多道程序设计的优点是 **CPU 利用率高、系统吞吐量大、I/O 设备利用率高**；代价是**系统开销更大（非更小！）**、平均周转时间可能变长（`17#28`）。多道并不加快任何单个作业自身的纯计算速度，只是用开销填平了 CPU 的空闲时间缝隙。
> 3. **“内存中的进程数越多，CPU 利用率越高”是错误结论（`22#23`）**：当并发道数超过物理内存承载极限时，各进程工作集放不下，缺页率飙升并陷入**抖动（Thrashing）**，CPU 忙于调度换页而利用率断崖下跌。
> 4. **多道程序不必支持虚拟存储管理（`22#23`）**：早期多道批处理采用固定/动态分区分配即可运行，虚拟存储是锦上添花的扩充选项而非前提条件。
> 5. **区分“多道批处理系统”与“多道程序设计技术”**：前者是操作系统形态（批处理 + 多道），后者是允许多道程序同时驻留内存交替执行的底层思想——分时系统、实时系统同样广泛应用了多道程序设计技术。

#### 分时系统 vs 实时系统及现代扩展形态

| 对比项 | 分时系统 | 硬实时系统 | 软实时系统 |
| --- | --- | --- | --- |
| **核心设计目标** | 人机交互友好、用户公平响应 | **严格在截止时间前完成**，绝不超时 | 尽量在截止时间前完成，偶发超时可容忍 |
| **核心衡量指标** | **平均响应时间** | **最坏响应时间**（确定性上界） | 超时概率与平均服务质量 |
| **调度策略** | 时间片轮转（时间片过短则切换开销激增） | 抢占式优先级调度（高优必立刻抢占） | 优先级调度（**可非抢占**） |
| **典型场景** | Unix 分时主机、现代通用桌面终端 | 导弹制导、汽车安全气囊、飞行控制系统 | 音视频播放、在线游戏、订票系统 |

在传统三类之上，现代操作系统进一步演化出：
- **个人计算机（微机）操作系统**：兼顾图形交互与多任务并发（如 Windows、macOS、桌面 Linux）。
- **网络操作系统**：在普通 OS 上叠加网络通信协议与网络资源共享服务（文件共享、远程打印）。
- **分布式操作系统**：将物理分散的多台计算机连接成逻辑统一的整体，具有**透明性、协同并行计算与全局统一资源管理**能力，用户感受如同一台超级计算机。
- **嵌入式操作系统**：运行在专用硬件芯片/嵌入式设备上，强调代码紧凑、低功耗、高可靠与强实时响应。

<figure class="cpd-figure not-content" id="os-c1-fig-4">
  <svg viewBox="0 0 720 296" role="img" aria-label="操作系统五阶段发展演进路线与核心历史矛盾驱动图">
    <defs>
      <marker id="os-c1-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="146" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="170" width="688" height="112" rx="6"/>
    <line class="fig-line-accent" x1="142" y1="98" x2="158" y2="98" marker-end="url(#os-c1-arr-4)"/>
    <line class="fig-line-accent" x1="282" y1="98" x2="298" y2="98" marker-end="url(#os-c1-arr-4)"/>
    <line class="fig-line-accent" x1="422" y1="98" x2="438" y2="98" marker-end="url(#os-c1-arr-4)"/>
    <line class="fig-line-accent" x1="562" y1="98" x2="578" y2="98" marker-end="url(#os-c1-arr-4)"/>
    <rect class="fig-box" x="20" y="48" width="122" height="100" rx="5"/>
    <rect class="fig-box-orange" x="160" y="48" width="122" height="100" rx="5"/>
    <rect class="fig-box-accent" x="300" y="48" width="122" height="100" rx="5"/>
    <rect class="fig-box-blue" x="440" y="48" width="122" height="100" rx="5"/>
    <rect class="fig-box-green" x="580" y="48" width="122" height="100" rx="5"/>
    <rect class="fig-box-orange" x="28" y="200" width="212" height="70" rx="5"/>
    <rect class="fig-box-accent" x="254" y="200" width="212" height="70" rx="5"/>
    <rect class="fig-box-blue" x="480" y="200" width="212" height="70" rx="5"/>
    <text class="fig-title" x="360" y="34" text-anchor="middle" font-size="12">操作系统五阶段发展演进路线</text>
    <g text-anchor="middle" font-size="10.5">
      <text class="fig-label" x="81" y="68" font-size="11">① 手工操作</text>
      <text class="fig-muted" x="81" y="86">纸带卡片·无 OS</text>
      <text class="fig-muted" x="81" y="104">人独占机·等人工</text>
      <text class="fig-muted" x="81" y="122">CPU 利用率极低</text>
      <text class="fig-muted" x="81" y="138" font-size="9.5">过渡：卫星机脱机 I/O</text>
      <text class="fig-orange" x="221" y="68" font-size="11">② 单道批处理</text>
      <text class="fig-label" x="221" y="86">监督程序 Monitor</text>
      <text class="fig-muted" x="221" y="104">自动·顺序·单道</text>
      <text class="fig-muted" x="221" y="122">遇 I/O 即空转</text>
      <text class="fig-muted" x="221" y="138" font-size="9.5">大内存装小作业浪费</text>
      <text class="fig-accent" x="361" y="68" font-size="11">③ 多道批处理 ★</text>
      <text class="fig-label" x="361" y="86">标志 OS 正式诞生</text>
      <text class="fig-muted" x="361" y="104">中断 + DMA/通道</text>
      <text class="fig-muted" x="361" y="122">高吞吐·高利用率</text>
      <text class="fig-muted" x="361" y="138" font-size="9.5">周转长·无交互·开销大</text>
      <text class="fig-blue" x="501" y="68" font-size="11">④ 分时系统</text>
      <text class="fig-label" x="501" y="86">时间片轮转 RR</text>
      <text class="fig-muted" x="501" y="104">多路·独立·及时</text>
      <text class="fig-muted" x="501" y="122">★ 具备人机交互</text>
      <text class="fig-muted" x="501" y="138" font-size="9.5">关注平均响应时间</text>
      <text class="fig-green" x="641" y="68" font-size="11">⑤ 实时系统</text>
      <text class="fig-label" x="641" y="86">截止时间 Deadline</text>
      <text class="fig-muted" x="641" y="104" font-size="9.5">硬实时（绝不超时）</text>
      <text class="fig-muted" x="641" y="122" font-size="9.5">软实时（可偶发超时）</text>
      <text class="fig-muted" x="641" y="138" font-size="9.5">关注最坏响应时间</text>
    </g>
    <text class="fig-title" x="360" y="190" text-anchor="middle" font-size="11.5">每一代演进的“矛盾 → 破局技术”映射</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-orange" x="134" y="218">矛盾 1：手工装纸带耗时太长</text>
      <text class="fig-label" x="134" y="236">破局：脱机 I/O（磁带）+ 监督程序</text>
      <text class="fig-muted" x="134" y="254">分离程序员与操作员，自动连跑成批作业</text>
      <text class="fig-accent" x="360" y="218">矛盾 2：单道遇慢速 I/O 就空等</text>
      <text class="fig-label" x="360" y="236">破局：硬件中断 + DMA / 通道</text>
      <text class="fig-muted" x="360" y="254">一道 I/O 时另道跑 CPU，硬件并行</text>
      <text class="fig-blue" x="586" y="218">矛盾 3：批处理不可实时插话控制</text>
      <text class="fig-label" x="586" y="236">破局：时间片轮转 / 优先级抢占</text>
      <text class="fig-muted" x="586" y="254">分时图交互均快，实时图截止不超时</text>
    </g>
  </svg>
  <figcaption>图 1-4　操作系统五阶段演进历程与每代核心矛盾破局机制</figcaption>
</figure>

#### ★多道批处理时间线与“瓶颈资源法”计算专题

408 考察多道批处理时间计算有两种经典模型，解题策略截然不同：

- **模型 A（求总时间与 CPU 利用率——排布 Gantt 时间线）**：
  设两道作业 $J_1$、$J_2$ 均执行“CPU 计算 $20\text{ ms}$ → I/O 操作 $40\text{ ms}$ → CPU 计算 $10\text{ ms}$”，单核 CPU，两作业各自使用**独立**的 I/O 设备，忽略切换开销。
  - **单道**：$J_1$（$70\text{ ms}$）完成后才启动 $J_2$（$70\text{ ms}$），总耗时 $140\text{ ms}$，CPU 仅忙 $60\text{ ms}$，利用率 $\frac{60}{140} \approx 42.9\%$。
  - **多道**：$0\text{–}20\text{ ms}$ $J_1$ 计算；$20\text{–}40\text{ ms}$ $J_1$ 转入 I/O 的同时 $J_2$ 使用 CPU（**黄金重叠段！**）；$40\text{–}60\text{ ms}$ 两作业同时在各自 I/O，CPU 空闲；$60\text{–}70\text{ ms}$ $J_1$ 第二段计算；$70\text{–}80\text{ ms}$ $J_1$ 已结束而 $J_2$ 仍在 I/O，CPU 空闲；$80\text{–}90\text{ ms}$ $J_2$ 第二段计算。总耗时降至 $90\text{ ms}$，CPU 忙时仍为 $60\text{ ms}$，利用率升至 $\frac{60}{90} \approx 66.7\%$。
- **模型 B（多个同构作业共享有限单台设备——瓶颈资源公式，`16#24`）**：
  当输入设备、CPU、输出设备各只有 1 台时，同一设备上的阶段必须串行，总时间由**最繁忙的瓶颈资源**决定：

$$
T_{\min} = t_{\text{首作业抵达瓶颈前耗时}} + \sum T_{\text{瓶颈资源被全部作业占用总长}} + t_{\text{末作业离开瓶颈后余量}}
$$

  - **例 1（`16#24`）**：3 个作业均按“输入 $2\text{ ms}$ → 计算 $3\text{ ms}$ → 输出 $4\text{ ms}$”。最繁忙设备为**输出设备**（$3 \times 4 = 12\text{ ms}$）；第 1 个作业抵达输出设备前需经历输入+计算 $2 + 3 = 5\text{ ms}$；输出是最后阶段，尾余为 $0$。故 $T_{\min} = 5 + 12 + 0 = 17\text{ ms}$（若误算成完全串行得 $3 \times 9 = 27\text{ ms}$，漏算串行约束则会算小）。
  - **例 2（瓶颈在中间）**：若阶段改为“输入 $2\text{ ms}$ → 计算 $4\text{ ms}$ → 输出 $3\text{ ms}$”。瓶颈变为 **CPU**（$3 \times 4 = 12\text{ ms}$），第 1 个作业 $2\text{ ms}$ 后到 CPU，第 3 个作业 $2 + 12 = 14\text{ ms}$ 才算完，还需继续占输出设备 $3\text{ ms}$，故 $T_{\min} = 2 + 12 + 3 = 17\text{ ms}$（切忌忘加尾余！）。

<figure class="cpd-figure not-content" id="os-c1-fig-5">
  <svg viewBox="0 0 720 330" role="img" aria-label="单道与多道批处理时间线及 CPU 利用率计算，以及三作业瓶颈资源调度最短耗时图">
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="172" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="198" width="688" height="118" rx="6"/>
    <rect class="fig-box-accent" x="108" y="48" width="80" height="24" rx="2"/>
    <rect class="fig-box-dashed" x="188" y="48" width="160" height="24" rx="2"/>
    <rect class="fig-box-accent" x="348" y="48" width="40" height="24" rx="2"/>
    <rect class="fig-box-blue" x="388" y="48" width="80" height="24" rx="2"/>
    <rect class="fig-box-dashed" x="468" y="48" width="160" height="24" rx="2"/>
    <rect class="fig-box-blue" x="628" y="48" width="40" height="24" rx="2"/>
    <rect class="fig-box-accent" x="108" y="88" width="80" height="24" rx="2"/>
    <rect class="fig-box-blue" x="188" y="88" width="80" height="24" rx="2"/>
    <rect class="fig-box-dashed" x="268" y="88" width="80" height="24" rx="2"/>
    <rect class="fig-box-accent" x="348" y="88" width="40" height="24" rx="2"/>
    <rect class="fig-box-dashed" x="388" y="88" width="40" height="24" rx="2"/>
    <rect class="fig-box-blue" x="428" y="88" width="40" height="24" rx="2"/>
    <rect class="fig-box-green" x="188" y="120" width="160" height="22" rx="2"/>
    <rect class="fig-box-orange" x="268" y="146" width="160" height="22" rx="2"/>
    <rect class="fig-box" x="482" y="88" width="210" height="84" rx="5"/>
    <rect class="fig-box-accent" x="108" y="226" width="40" height="22" rx="2"/>
    <rect class="fig-box-blue" x="148" y="226" width="40" height="22" rx="2"/>
    <rect class="fig-box-green" x="188" y="226" width="40" height="22" rx="2"/>
    <rect class="fig-box-accent" x="148" y="254" width="60" height="22" rx="2"/>
    <rect class="fig-box-blue" x="208" y="254" width="60" height="22" rx="2"/>
    <rect class="fig-box-green" x="268" y="254" width="60" height="22" rx="2"/>
    <rect class="fig-box-accent" x="208" y="282" width="80" height="22" rx="2"/>
    <rect class="fig-box-blue" x="288" y="282" width="80" height="22" rx="2"/>
    <rect class="fig-box-green" x="368" y="282" width="80" height="22" rx="2"/>
    <rect class="fig-box-red" x="466" y="226" width="226" height="78" rx="5"/>
    <text class="fig-title" x="360" y="34" text-anchor="middle" font-size="11.5">模型 A：单道 vs 多道执行时间线（每道：CPU 20ms → I/O 40ms → CPU 10ms，独立 I/O）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-label" x="62" y="64" font-size="10.5">单道总览</text>
      <text class="fig-accent" x="148" y="64">J1 CPU</text>
      <text class="fig-muted" x="268" y="64">J1 I/O（CPU 空闲 40ms）</text>
      <text class="fig-accent" x="368" y="64">J1</text>
      <text class="fig-blue" x="428" y="64">J2 CPU</text>
      <text class="fig-muted" x="548" y="64">J2 I/O（CPU 空闲 40ms）</text>
      <text class="fig-blue" x="648" y="64">J2</text>
      <text class="fig-label" x="62" y="104" font-size="10.5">多道 CPU</text>
      <text class="fig-accent" x="148" y="104">J1 0-20</text>
      <text class="fig-blue" x="228" y="104">J2 20-40</text>
      <text class="fig-muted" x="308" y="104">空闲 40-60</text>
      <text class="fig-accent" x="368" y="104">J1</text>
      <text class="fig-muted" x="408" y="104">空</text>
      <text class="fig-blue" x="448" y="104">J2</text>
      <text class="fig-label" x="62" y="135" font-size="10">I/O 设备 1</text>
      <text class="fig-green" x="268" y="135">J1 I/O（20–60ms）重叠</text>
      <text class="fig-label" x="62" y="161" font-size="10">I/O 设备 2</text>
      <text class="fig-orange" x="348" y="161">J2 I/O（40–80ms）</text>
      <text class="fig-title" x="587" y="108" font-size="10.8">计算结果对比</text>
      <text class="fig-label" x="587" y="128">单道：60 / 140 = 42.9%</text>
      <text class="fig-accent" x="587" y="146">多道：60 / 90 = 66.7%</text>
      <text class="fig-muted" x="587" y="163" font-size="9.5">20–70ms 多段重叠省 50ms</text>
    </g>
    <text class="fig-title" x="360" y="216" text-anchor="middle" font-size="11.5">模型 B：3 作业共享单设备（16#24：输入 2ms → 计算 3ms → 输出 4ms，输出设备为瓶颈）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-label" x="62" y="241" font-size="10.2">输入设备</text>
      <text class="fig-accent" x="128" y="241">J1</text>
      <text class="fig-blue" x="168" y="241">J2</text>
      <text class="fig-green" x="208" y="241">J3</text>
      <text class="fig-label" x="62" y="269" font-size="10.2">CPU</text>
      <text class="fig-accent" x="178" y="269" font-size="9">J1 (2–5)</text>
      <text class="fig-blue" x="238" y="269" font-size="9">J2 (5–8)</text>
      <text class="fig-green" x="298" y="269" font-size="9">J3 (8–11)</text>
      <text class="fig-red" x="62" y="297" font-size="10.2">输出(瓶颈)</text>
      <text class="fig-accent" x="248" y="297">J1 (5–9)</text>
      <text class="fig-blue" x="328" y="297">J2 (9–13)</text>
      <text class="fig-green" x="408" y="297">J3 (13–17)</text>
      <text class="fig-red" x="579" y="245" font-size="10.8">★ 瓶颈资源法公式</text>
      <text class="fig-label" x="579" y="264" font-size="10">T_min = 抵达瓶颈 + 瓶颈总长 + 尾余</text>
      <text class="fig-label" x="579" y="282" font-size="10">= (2 + 3) + 3 × 4 + 0 = 17 ms</text>
      <text class="fig-muted" x="579" y="298" font-size="9.5">错法：全串行 27 ms / 无约束并行 9 ms</text>
    </g>
  </svg>
  <figcaption>图 1-5　单道/多道利用率 Gantt 算例对比与三作业瓶颈资源最短耗时排程（16#24 模型）</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c1-fig-6">
  <svg viewBox="0 0 720 264" role="img" aria-label="多道程序数量与 CPU 利用率抖动拐点曲线及分时与实时系统对比图">
    <defs>
      <marker id="os-c1-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="340" height="236" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="14" width="336" height="236" rx="6"/>
    <line class="fig-line" x1="56" y1="210" x2="334" y2="210" marker-end="url(#os-c1-arr-6)"/>
    <line class="fig-line" x1="56" y1="210" x2="56" y2="54" marker-end="url(#os-c1-arr-6)"/>
    <path class="fig-line-accent" stroke-width="2.2" d="M 60 202 Q 116 90 186 78 Q 212 78 232 132 Q 264 192 316 202"/>
    <line class="fig-line-dashed" x1="186" y1="78" x2="186" y2="210"/>
    <circle class="fig-dot" cx="186" cy="78" r="4"/>
    <rect class="fig-box-green" x="66" y="54" width="108" height="34" rx="4"/>
    <rect class="fig-box-red" x="234" y="48" width="114" height="42" rx="4"/>
    <rect class="fig-box-blue" x="380" y="48" width="312" height="90" rx="5"/>
    <rect class="fig-box-orange" x="380" y="148" width="312" height="90" rx="5"/>
    <text class="fig-title" x="186" y="34" text-anchor="middle" font-size="11.5">多道度 N 与 CPU 利用率关系（22#23 考点）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-muted" x="42" y="128">利</text>
      <text class="fig-muted" x="42" y="142">用</text>
      <text class="fig-muted" x="42" y="156">率</text>
      <text class="fig-muted" x="284" y="226">内存驻留进程数 N →</text>
      <text class="fig-accent" x="186" y="226">最佳多道度</text>
      <text class="fig-green" x="120" y="69">上升段：填补 I/O</text>
      <text class="fig-muted" x="120" y="83" font-size="9.5">进程越多利用率越高</text>
      <text class="fig-red" x="291" y="65" font-size="9.5">★ 拐点后：抖动</text>
      <text class="fig-muted" x="291" y="81" font-size="8.8">超内存承载，缺页暴涨</text>
      <text class="fig-muted" x="186" y="242" font-size="9.5">错论：“进程数越多 CPU 利用率越高”</text>
    </g>
    <text class="fig-title" x="536" y="34" text-anchor="middle" font-size="11.5">分时系统 vs 实时系统目标与调度差异</text>
    <g text-anchor="middle" font-size="10.5">
      <text class="fig-blue" x="536" y="68" font-size="11">分时系统：平均响应时间最短（交互性）</text>
      <text class="fig-label" x="536" y="90">机制：时间片轮转（多用户终端）</text>
      <text class="fig-muted" x="536" y="110" font-size="9.8">注意：时间片并非越短越好，过短则切换开销激增</text>
      <text class="fig-muted" x="536" y="128" font-size="9.8">允许偶尔响应较慢，不承诺绝对截止时限</text>
      <text class="fig-orange" x="536" y="168" font-size="11">实时系统：最坏响应时间 ≤ 截止时间（Deadline）</text>
      <text class="fig-label" x="536" y="190">硬实时：超时即灾难（导弹/飞控），常采用抢占式优先级</text>
      <text class="fig-muted" x="536" y="210" font-size="9.8">软实时：偶发超时可容忍（流媒体），可采用非抢占</text>
      <text class="fig-muted" x="536" y="228" font-size="9.8">核心追求高可靠性与确定性时限上界</text>
    </g>
  </svg>
  <figcaption>图 1-6　多道程序并发度的抖动拐点效应及分时/实时系统设计目标对比</figcaption>
</figure>

---

### 1.4 ★操作系统的运行环境：CPU 运行模式与特权指令

操作系统的权威并非源于“写得早或跑得早”，而源于**CPU 硬件自身携带的模式位（Mode Bit）**——位于 <strong>PSW（程序状态字，如 x86 中的 EFLAGS/RFLAGS 及特权级字段）</strong>中。硬件执行每条指令前都会比对这一比特，使隔离在物理层面牢不可破。

#### 1. CPU 的两种运行模式

| 运行模式（2026 大纲术语） | 常见别名 | 硬件模式位 | x86 保护环 | 可执行的指令集合 | 运行程序示例 |
| --- | --- | --- | --- | --- | --- |
| **内核模式（内核态）** | 核心态、**管态**、特权态 | `1` | **Ring 0** | **全部指令**（特权指令 + 非特权指令） | OS 内核代码、设备驱动、中断/异常处理程序 |
| **用户模式（用户态）** | **目态** | `0` | **Ring 3** | **仅非特权指令** | 应用程序、标准库函数、**命令解释程序（shell）** |

> **★考点**：
> 1. **“内核态只能执行特权指令”是经典错句（`22#27`）！** 内核代码里大量是普通的加减乘除与跳转指令；正确的表述只有一句：**“用户态只能执行非特权指令，内核态可以执行全部指令”**。
> 2. **x86 4 级特权环**：硬件提供 Ring 0（最高：I/O 与中断）→ Ring 1（系统调用）→ Ring 2（共享库）→ Ring 3（最低：应用）共 4 级（编号越小权限越高，与模式位 1/0 方向相反），但**通用操作系统仅使用 Ring 0 与 Ring 3**，中间两级被跳过。

#### 2. 特权指令 vs 非特权指令 & 特权指令 vs 敏感指令

界定某条指令是否属于特权指令，核心标准只有一条：**它是否可能影响其他进程或整个计算机系统的安全与全局状态**——集中于**改硬件状态、改保护规则、改控制流权限**三类。

| 指令 / 操作类别 | 是否特权指令 | 核心依据与真题考法（`14#25`, `21#23`） |
| --- | --- | --- |
| **直接 I/O 操作**（`IN`、`OUT`、启动 DMA） | **是** | 若放给用户态，任意进程可绕过权限读写他人磁盘/网卡（`21#23`） |
| **关中断 / 开中断**（`CLI`、`STI`，修改 `IF` 位） | **是** | 用户态若能关中断再进入死循环，时钟中断失灵，整机卡死（`14#25`） |
| **设置中断屏蔽字 / 装入定时器** | **是** | 干扰硬件中断响应与时间片抢占频率 |
| **修改 PSW / 中断返回指令（`iret`/`sysret`/`eret`）** | **是** | `iret` 会直接写回 PSW 模式位；若用户可执行即可自构造 `PSW=内核态` 自举升权 |
| **修改页表基址寄存器（PTBR/`CR3`）、界地址寄存器** | **是** | 改写虚实地址映射与内存边界隔离规则 |
| **停机指令 `HLT`、清内存指令** | **是** | 一条指令即可停掉整台主机或破坏全机数据 |
| **陷入指令 / 访管指令**（`trap`、`syscall`、`int 0x80`、`ecall`） | **★否（非特权）** | **必须在用户态可执行**，否则无法向 OS 求助；安全性靠“执行后硬件强行跳入内核系统调用表入口”来保底 |
| **设置断点指令** `int 3` | **否（非特权）** | 用户态可执行用于调试，执行后触发断点异常交由 OS 接管通知调试器 |
| **算术逻辑运算、普通访存与跳转**（`ADD`、`NOT`、`MOV`） | **否（非特权）** | 只涉及自身进程空间（越界/缺页另由 MMU 硬件检测拦截） |

> **★考点**：**用户态执行特权指令会发生什么？** 仅回答“不能执行”是不完整的，完整隔离闭环为：**检查发生在指令译码阶段 → 指令根本不被执行 → 硬件触发非法指令异常（内中断） → 陷入内核态 → OS 异常处理程序终止该违规进程**。

在进一步区分虚拟化架构时，还必须区分**特权指令**与**敏感指令**：
- **敏感指令**：会**读取或修改机器关键配置/状态**（模式位、中断开关、页表基址等），或其执行行为随当前处理器模式不同而变化的指令。
- **★核心结论**：**所有特权指令都是敏感指令，但敏感指令不一定是特权指令**。“敏感但不特权”指令在用户态执行时既不触发异常也不报错，而是静默返回错误信息，是虚拟机“陷入-模拟”方案失效的根本隐患。

#### 3. 如何判定某个“程序”运行在哪一态（`11#24`）

问“指令”看权限，问“程序”则看**它要访问什么资源**：
- 只要需操作内核数据结构（PCB、就绪队列、页表、内核时钟变量）或执行特权指令，就运行在**内核态**——如**缺页处理程序、进程调度程序、时钟中断处理程序、设备驱动程序**。
- 只需用户态资源，即便内部频繁调用系统调用封装 API，该程序本身依然运行在**用户态**——最典型的考题干扰项是**命令解释程序（shell / bash / cmd）**：它是一个普通的开机自启用户进程，其本身逻辑（读取输入 → 解析 → `fork`/`exec`/`wait`）运行在用户态，仅在执行到系统调用服务例程内部时才短暂切入内核态。

#### 4. 非对称的状态转换与操作系统内核的组成

CPU 模式的双向切换具有**严格的不对称性**：
- **用户态 → 内核态（唯一途径：广义中断）**：**必须由硬件自动完成**（包括外部异步中断、内部同步异常、主动执行的 `trap` 陷入指令）。用户程序绝不可能写一条指令自己把模式位改成内核态。
- **内核态 → 用户态**：由内核软件主动执行一条特权指令（`iret` / `sysret` / `eret`）将 PSW 中的模式位改回 `0`。

> **注意**：**态切换不等于进程切换**。一次普通系统调用（如 `getpid`）发生两次态切换后通常仍回到同一进程；但反过来<strong>“进程切换必然发生在内核态”</strong>则绝对成立，因为必须读写 PCB 与队列。

**操作系统内核常驻内存（高地址内核区）**，按“用户态做不成的才留进内核”的原则，包含两大类组成：
1. **与硬件紧密相关的底层基本功能**：
   - **时钟管理**：提供标准系统节拍与计时，**时钟中断是抢占式调度得以实现的物理基础**（用于更新系统时钟、进程运行时间及时间片剩余值，`18#29`）。
   - **中断机制**：操作系统运转的唯一驱动力，用于回收控制权并完成软硬件协调。
   - **原语（Primitive）**：由若干条指令组成、完成特定功能的不可分割的原子操作（如 `TestAndSet`、`Swap`、PCB 挂入/摘除队列等）。其原子性靠“**关中断 → 执行全部原语指令 → 开中断**”保证；因开关中断是特权指令，**原语只能在内核态运行，且代码必须极其短小**（避免长时间屏蔽外部/时钟中断）。
2. **核心资源管理功能**（具体是否全留内核取决于宏/微内核取舍）：进程管理、存储器管理、设备管理。

<figure class="cpd-figure not-content" id="os-c1-fig-7">
  <svg viewBox="0 0 720 306" role="img" aria-label="CPU 双运行模式、非对称状态切换闭环及特权指令与敏感指令集合关系图">
    <defs>
      <marker id="os-c1-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="418" height="278" rx="6"/>
    <rect class="fig-box-subtle" x="446" y="14" width="258" height="278" rx="6"/>
    <rect class="fig-box-blue" x="28" y="46" width="394" height="72" rx="5"/>
    <rect class="fig-box-red" x="28" y="124" width="394" height="36" rx="4"/>
    <rect class="fig-box-accent" x="28" y="218" width="394" height="62" rx="5"/>
    <line class="fig-line-accent" x1="36" y1="164" x2="36" y2="214" marker-end="url(#os-c1-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="414" y1="214" x2="414" y2="164" marker-end="url(#os-c1-arr-7)"/>
    <rect class="fig-box" x="48" y="168" width="178" height="42" rx="4"/>
    <rect class="fig-box-green" x="234" y="168" width="170" height="42" rx="4"/>
    <ellipse class="fig-box-orange" cx="575" cy="118" rx="116" ry="72"/>
    <ellipse class="fig-box-accent" cx="575" cy="144" rx="86" ry="38"/>
    <rect class="fig-box" x="462" y="198" width="226" height="82" rx="5"/>
    <text class="fig-title" x="225" y="34" text-anchor="middle" font-size="11.5">CPU 双模式与非对称态切换闭环（PSW 模式位）</text>
    <g text-anchor="middle" font-size="10.5">
      <text class="fig-blue" x="225" y="64" font-size="11">用户态 / 目态 / Ring 3（模式位 = 0）</text>
      <text class="fig-label" x="225" y="83">仅可执行非特权指令：ALU / MOV / trap / int 3</text>
      <text class="fig-muted" x="225" y="102" font-size="9.8">代表程序：应用进程 · 标准库 · 命令解释器 shell（11#24）</text>
      <text class="fig-red" x="225" y="146" font-size="10.2">违规执行特权指令 → 译码拦截(不执行) → 非法指令异常 → 终止进程</text>
      <text class="fig-label" x="137" y="185" font-size="10">★ 硬件自动切换（唯一入口）</text>
      <text class="fig-muted" x="137" y="201" font-size="9.5">外中断 / 内异常 / trap 陷入</text>
      <text class="fig-green" x="319" y="185" font-size="10">软件主动返回（特权指令）</text>
      <text class="fig-muted" x="319" y="201" font-size="9.5">执行 iret/sysret 置 PSW=0</text>
      <text class="fig-accent" x="225" y="238" font-size="11">内核态 / 管态 / Ring 0（模式位 = 1）</text>
      <text class="fig-label" x="225" y="256">可执行全部指令（★ 并非“只能执行特权指令” 22#27）</text>
      <text class="fig-muted" x="225" y="272" font-size="9.5">代表程序：OS 内核 · 调度程序 · 缺页处理 · 时钟中断处理</text>
    </g>
    <text class="fig-title" x="575" y="34" text-anchor="middle" font-size="11.5">特权指令 ⊆ 敏感指令关系</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-orange" x="575" y="74">敏感指令（读/写关键状态）</text>
      <text class="fig-muted" x="575" y="91" font-size="9.5">★ 敏感但非特权：不陷入不报错</text>
      <text class="fig-accent" x="575" y="132" font-size="10.8">特权指令</text>
      <text class="fig-muted" x="575" y="148" font-size="9.2">CLI/STI·IN/OUT·置PTBR·iret</text>
      <text class="fig-muted" x="575" y="163" font-size="8.8">特权必敏感，敏感未必特权</text>
      <text class="fig-title" x="575" y="216" font-size="10.5">x86 四级环实际使用</text>
      <text class="fig-label" x="575" y="235" font-size="9.8">Ring 0（内核态）↔ Ring 3（用户态）</text>
      <text class="fig-muted" x="575" y="253" font-size="9.5">Ring 1 / Ring 2 通用 OS 跳过不用</text>
      <text class="fig-muted" x="575" y="270" font-size="9.5">Ring 数值越大权限越低（反模式位）</text>
    </g>
  </svg>
  <figcaption>图 1-7　CPU 双模式、非对称态切换闭环及特权指令与敏感指令集合关系</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c1-fig-8">
  <svg viewBox="0 0 720 268" role="img" aria-label="操作系统内核内存空间位置与内核五大核心组成示意图">
    <rect class="fig-box-subtle" x="16" y="14" width="248" height="240" rx="6"/>
    <rect class="fig-box-subtle" x="278" y="14" width="426" height="240" rx="6"/>
    <rect class="fig-box-accent" x="28" y="48" width="224" height="72" rx="5"/>
    <line class="fig-line-dashed" x1="28" y1="135" x2="252" y2="135"/>
    <rect class="fig-box-blue" x="28" y="150" width="224" height="90" rx="5"/>
    <rect class="fig-box-subtle" x="290" y="46" width="402" height="106" rx="5"/>
    <rect class="fig-box-orange" x="300" y="72" width="120" height="70" rx="4"/>
    <rect class="fig-box-accent" x="431" y="72" width="120" height="70" rx="4"/>
    <rect class="fig-box-red" x="562" y="72" width="120" height="70" rx="4"/>
    <rect class="fig-box-subtle" x="290" y="160" width="402" height="82" rx="5"/>
    <rect class="fig-box-green" x="300" y="186" width="120" height="46" rx="4"/>
    <rect class="fig-box-blue" x="431" y="186" width="120" height="46" rx="4"/>
    <rect class="fig-box-purple" x="562" y="186" width="120" height="46" rx="4"/>
    <rect class="fig-box" x="80" y="126" width="120" height="18" rx="3"/>
    <text class="fig-title" x="140" y="34" text-anchor="middle" font-size="11.5">内存空间划分（高地址常驻内核）</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-accent" x="140" y="68" font-size="11">内核空间（高地址 · 常驻 RAM）</text>
      <text class="fig-label" x="140" y="88">OS 内核代码 · 中断向量表</text>
      <text class="fig-muted" x="140" y="108">PCB · 进程队列 · 页表 · 核心栈</text>
      <text class="fig-red" x="140" y="138" font-size="9.5">硬件模式位隔离边界</text>
      <text class="fig-blue" x="140" y="172" font-size="11">用户空间（低地址 · 进程私有）</text>
      <text class="fig-label" x="140" y="194">用户栈 ↓   /   共享库   /   堆 ↑</text>
      <text class="fig-muted" x="140" y="216">数据段（.data/.bss）· 代码段（.text）</text>
      <text class="fig-muted" x="140" y="232" font-size="9.5">0x0 起步，用户/内核态均可访问</text>
    </g>
    <text class="fig-title" x="491" y="34" text-anchor="middle" font-size="11.5">OS 内核组成（筛选原则：用户态做不成的进内核）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-label" x="491" y="63" font-size="10.5">一、与硬件紧密相关的三大最底层基石（必须内核态）</text>
      <text class="fig-orange" x="360" y="92" font-size="10.8">时钟管理</text>
      <text class="fig-muted" x="360" y="110" font-size="9.5">计时与节拍基准</text>
      <text class="fig-muted" x="360" y="128" font-size="9.5">抢占调度时间片基础</text>
      <text class="fig-accent" x="491" y="92" font-size="10.8">中断机制 ★</text>
      <text class="fig-muted" x="491" y="110" font-size="9.5">OS 唯一驱动力</text>
      <text class="fig-muted" x="491" y="128" font-size="9.5">夺回 CPU 控制权</text>
      <text class="fig-red" x="622" y="92" font-size="10.8">原语（原子操作）</text>
      <text class="fig-muted" x="622" y="110" font-size="9.5">关中断→执行→开中断</text>
      <text class="fig-muted" x="622" y="128" font-size="9.5">短小·一气呵成不可断</text>
      <text class="fig-label" x="491" y="177" font-size="10.5">二、核心资源管理模块（宏内核全在内核态，微内核部分外移）</text>
      <text class="fig-green" x="360" y="206" font-size="10.5">进程管理</text>
      <text class="fig-muted" x="360" y="222" font-size="9.5">PCB · 队列 · 调度</text>
      <text class="fig-blue" x="491" y="206" font-size="10.5">存储器管理</text>
      <text class="fig-muted" x="491" y="222" font-size="9.5">页表 · 地址变换</text>
      <text class="fig-purple" x="622" y="206" font-size="10.5">设备管理</text>
      <text class="fig-muted" x="622" y="222" font-size="9.5">I/O 驱动 · 缓冲</text>
    </g>
  </svg>
  <figcaption>图 1-8　操作系统内核高地址常驻布局及“硬件基石 + 资源管理”组成架构</figcaption>
</figure>

---

### 1.5 ★中断与异常的全景机制

如果把操作系统比作一台引擎，**中断就是驱动整台引擎运转的心跳与唯一动力源**：没有中断，死循环程序无法被抢占、慢速 I/O 只能由 CPU 轮询空耗、用户程序也无法安全地切入内核态。

#### 1. 广义中断的双视角分类

408 体系下，广义中断（打断当前指令流控制权移交的事件）按触发源分为**外部中断**与**内部异常**：

| 一级分类 | 触发源与同步性 | 硬件检测时机 | 二级子类 | 核心特征、处理方式与**返回断点** |
| --- | --- | --- | --- | --- |
| **外部中断**（狭义中断） | CPU 外部设备产生，与当前执行指令**异步无关** | **每条指令执行完毕后、取下条指令前** | **可屏蔽中断**（`INTR`） | 常规外设（键盘/磁盘/网卡）与时钟中断；受标志位 `IF` 控制（`IF=0` 时可屏蔽）；返回**下条指令** |
| | | | **不可屏蔽中断**（`NMI`） | 电源掉电、内存读写致命故障；**即使关中断（`IF=0`）也无法屏蔽**，立即抢占保存关键信息或停机 |
| **内部异常**（内中断） | CPU 内部在执行当前指令时检测，与当前指令**同步直接相关**，**不可用 `IF` 屏蔽** | **当前指令执行过程中**（如译码、算术、访存阶段） | **★ 故障（Fault）** | **非本意，但可能修复**（如**缺页异常**、除零未修复则转终止）。修复成功后**返回引起故障的当前指令重新执行** |
| | | | **★ 自陷（Trap）** | **程序预先有意安排**（`syscall`、`int 0x80` 系统调用、`int 3` 调试断点）。处理后**返回陷入指令的下一条指令** |
| | | | **★ 终止（Abort）** | **非本意且不可恢复**的致命错误（SRAM/DRAM 校验错、非法操作码、用户态执特权指令），无返回点，**直接终止进程** |

> **注意**：另一经典教材（孙钟秀版）按中断源将中断分为五类——**硬件故障中断**（↔ NMI）、**程序性中断**（↔ Fault + Abort）、**自愿性中断**（↔ Trap 系统调用）、**I/O 中断**与**外部（时钟）中断**（↔ 可屏蔽外中断）。需格外注意：**“程序性中断事件”同时包含可恢复的虚拟地址异常（重执当前条）与不可恢复的非法指令/越界（终止进程），故并非 Fault 的同义词**。

<figure class="cpd-figure not-content" id="os-c1-fig-9">
  <svg viewBox="0 0 720 318" role="img" aria-label="广义中断树状分类及内异常 Fault、Trap、Abort 返回断点对比图">
    <defs>
      <marker id="os-c1-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="148" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="172" width="688" height="132" rx="6"/>
    <path class="fig-line-accent" d="M 300 44 L 176 44 L 176 62" marker-end="url(#os-c1-arr-9)"/>
    <path class="fig-line-accent" d="M 420 44 L 516 44 L 516 62" marker-end="url(#os-c1-arr-9)"/>
    <path class="fig-line" d="M 120 98 L 94 98 L 94 114" marker-end="url(#os-c1-arr-9)"/>
    <path class="fig-line" d="M 232 98 L 258 98 L 258 114" marker-end="url(#os-c1-arr-9)"/>
    <path class="fig-line" d="M 450 98 L 392 98 L 392 114" marker-end="url(#os-c1-arr-9)"/>
    <line class="fig-line" x1="516" y1="98" x2="516" y2="114" marker-end="url(#os-c1-arr-9)"/>
    <path class="fig-line" d="M 582 98 L 638 98 L 638 114" marker-end="url(#os-c1-arr-9)"/>
    <rect class="fig-box-accent" x="280" y="24" width="160" height="32" rx="5"/>
    <rect class="fig-box-blue" x="86" y="64" width="180" height="34" rx="4"/>
    <rect class="fig-box-orange" x="414" y="64" width="204" height="34" rx="4"/>
    <rect class="fig-box" x="26" y="116" width="136" height="36" rx="4"/>
    <rect class="fig-box-red" x="176" y="116" width="154" height="36" rx="4"/>
    <rect class="fig-box-green" x="342" y="116" width="106" height="36" rx="4"/>
    <rect class="fig-box-blue" x="458" y="116" width="114" height="36" rx="4"/>
    <rect class="fig-box-red" x="582" y="116" width="112" height="36" rx="4"/>
    <rect class="fig-box-green" x="28" y="198" width="212" height="96" rx="5"/>
    <rect class="fig-box-blue" x="254" y="198" width="212" height="96" rx="5"/>
    <rect class="fig-box-red" x="480" y="198" width="212" height="96" rx="5"/>
    <path class="fig-line-accent" d="M 96 252 C 118 273, 52 273, 66 254" marker-end="url(#os-c1-arr-9)"/>
    <line class="fig-line-accent" x1="328" y1="240" x2="354" y2="240" marker-end="url(#os-c1-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" x1="546" y1="240" x2="574" y2="240" marker-end="url(#os-c1-arr-9)"/>
    <rect class="fig-box" x="42" y="228" width="60" height="24" rx="3"/>
    <rect class="fig-box" x="164" y="228" width="60" height="24" rx="3"/>
    <rect class="fig-box" x="266" y="228" width="62" height="24" rx="3"/>
    <rect class="fig-box" x="356" y="228" width="96" height="24" rx="3"/>
    <rect class="fig-box" x="494" y="228" width="52" height="24" rx="3"/>
    <rect class="fig-box" x="578" y="228" width="100" height="24" rx="3"/>
    <g text-anchor="middle" font-size="10.5">
      <text class="fig-accent" x="360" y="44" font-size="11.5">广义中断事件分类</text>
      <text class="fig-blue" x="176" y="85">外部中断（异步 · 指令后检）</text>
      <text class="fig-orange" x="516" y="85">内部异常（同步 · 指令中检）</text>
      <text class="fig-label" x="94" y="132" font-size="10">可屏蔽 INTR</text>
      <text class="fig-muted" x="94" y="146" font-size="9.5">I/O · 时钟中断</text>
      <text class="fig-red" x="253" y="132" font-size="10">不可屏蔽 NMI</text>
      <text class="fig-muted" x="253" y="146" font-size="9.5">电源掉电 · 内存错</text>
      <text class="fig-green" x="395" y="132" font-size="10">故障 Fault</text>
      <text class="fig-muted" x="395" y="146" font-size="9.5">缺页等可修复</text>
      <text class="fig-blue" x="515" y="132" font-size="10">自陷 Trap</text>
      <text class="fig-muted" x="515" y="146" font-size="9.5">系统调用 · int 3</text>
      <text class="fig-red" x="638" y="132" font-size="10">终止 Abort</text>
      <text class="fig-muted" x="638" y="146" font-size="9.5">硬件错/非法指令</text>
    </g>
    <text class="fig-title" x="360" y="190" text-anchor="middle" font-size="11.5">内异常三子类断点返回位置对照（以指令地址 400 → 404 为例）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-green" x="134" y="216" font-size="10.5">① Fault：返回“故障指令 400”重执</text>
      <text class="fig-label" x="72" y="244">400 缺页</text>
      <text class="fig-label" x="194" y="244">404 下条</text>
      <text class="fig-muted" x="134" y="286" font-size="9.5">调页 ISR 完成后，PC 指回 400 重试</text>
      <text class="fig-blue" x="360" y="216" font-size="10.5">② Trap：返回“下条指令 404”</text>
      <text class="fig-label" x="297" y="244" font-size="9.2">400 trap</text>
      <text class="fig-label" x="404" y="244">404 继续</text>
      <text class="fig-muted" x="360" y="286" font-size="9.5">若指回 400 将陷入无限自陷死循环</text>
      <text class="fig-red" x="586" y="216" font-size="10.5">③ Abort：无返回点，终止进程</text>
      <text class="fig-label" x="520" y="244">400 错</text>
      <text class="fig-red" x="628" y="244">✕ 终止进程</text>
      <text class="fig-muted" x="586" y="286" font-size="9.5">致命硬件错/非法码/越权指令</text>
    </g>
  </svg>
  <figcaption>图 1-9　广义中断双大类树状分解及 Fault / Trap / Abort 断点返回行为对照</figcaption>
</figure>

#### 2. 中断向量与中断向量地址（表驱动寻址）

现代处理器普遍采用**向量中断**（表驱动定位），使得无论有多少种中断源，定位入口地址的耗时均与中断源个数无关（$O(1)$ 查表）：

- **中断向量**：中断服务程序（ISR）的**入口地址**（某些系统还包含配套的初始 PSW），存放在<strong>中断向量表（IVT）</strong>的表项中。
- **中断向量地址**：该中断向量在内存中被保存的表项自身的地址（即<strong>“入口地址的地址”</strong>）。

$$
\text{中断类型号 } i \xrightarrow{\text{硬件计算 } \text{IVT基址} + i \times \text{表项长}} \text{中断向量地址} \xrightarrow{\text{访存读取表项内容}} \text{中断向量（ISR 入口）} \xrightarrow{\text{送入 } \text{PC}} \text{转入处理程序}
$$

> **注意**：说“中断向量地址就是中断服务程序入口地址”是典型的计组+OS 跨科错误，两者之间还隔着一次**访存读取**！

#### 3. ★中断响应与处理全流程（硬件 vs 软件黄金分界线）

完整的指令执行周期在“取指 → 译码 → 执行”后增加了一个“**检查中断**”的微操作。一旦检测到需要响应的中断/异常，整个流程按<strong>硬件响应（中断隐指令）</strong>与<strong>软件处理（OS 中断服务程序）</strong>两半段接力完成：

1. **★关键时刻辨析（`24#23`）**：
   - 中断/异常<strong>“发生时”</strong>（触发瞬间），CPU **通常仍处于用户态**（绝大多数 I/O 中断、时钟中断、缺页、陷阱都是在用户程序运行过程中触发的）。
   - 中断/异常<strong>“处理程序开始执行时”</strong>，CPU **必然已处于内核态**！
2. **★软硬件分工铁律（`22#31`）**：**凡是要改写 PC、PSW（包括模式位、中断允许位 `IF`）以及读写中断向量的动作，由于此时 CPU 仍处用户态、没有指令权限，全部由硬件自动完成（称“中断隐指令”）；凡是用普通指令即可完成的保存通用寄存器、查表跳转服务逻辑，全部由 OS 软件完成。**
3. **★断点 vs 现场区分**：
   - **断点** = 被中断指令的 `PC`（及 `PSW`），**由硬件保存**（压入核心栈或存入如 MIPS `EPC` 等专用寄存器）。
   - **现场** = CPU 内通用寄存器（`EAX/EBX/...`），**由 OS 软件保存**（ISR 入口处的 `pusha` 等指令压入核心栈）。

#### 4. 单重中断 vs 多重中断（中断嵌套）

| 比较维度 | 单重中断 | 多重中断（中断嵌套） |
| --- | --- | --- |
| **处理期间开不开中断** | **全程关中断**（直到返回前才开中断） | 硬件响应时关中断 → **保护现场并设新屏蔽字后开中断** |
| **新到高优中断** | 只能挂起等待当前处理完全部结束 | **立即打断**当前处理程序并响应 |
| **处理完成次序** | 严格遵循到达先后 | **先响应的中断反而可能后完成**（后到的高优抢先跑完） |
| **现场保存结构** | 1 层核心栈即可 | 多层现场**依次压入核心栈**，返回时逆序弹出（一般**不超过 3 层**） |

是否允许嵌套必须**同时满足两道门禁**：① **当前中断已开放（`IF=1`）**；② **新中断优先级高于当前软件所设中断屏蔽字放行的下限**。哪怕新中断优先级再高，若系统正处于 `IF=0` 关中断期间，可屏蔽中断依然进不来（`NMI` 除外）。硬件预设优先级一般由高到低为：硬件故障中断 → 自愿性中断 → 程序性中断 → 外部中断 → I/O 中断；而**中断屏蔽字由处理程序用软件动态设置**，典型做法是**屏蔽同级及更低级中断，只放行更高级中断**。

<figure class="cpd-figure not-content" id="os-c1-fig-10">
  <svg viewBox="0 0 720 298" role="img" aria-label="向量中断四步寻址链及单重中断与多重中断嵌套时序图">
    <defs>
      <marker id="os-c1-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="328" height="270" rx="6"/>
    <rect class="fig-box-subtle" x="356" y="14" width="348" height="270" rx="6"/>
    <line class="fig-line-accent" x1="178" y1="78" x2="178" y2="92" marker-end="url(#os-c1-arr-10)"/>
    <line class="fig-line-accent" x1="178" y1="126" x2="178" y2="140" marker-end="url(#os-c1-arr-10)"/>
    <line class="fig-line-accent" x1="178" y1="174" x2="178" y2="188" marker-end="url(#os-c1-arr-10)"/>
    <line class="fig-line-accent" x1="178" y1="222" x2="178" y2="236" marker-end="url(#os-c1-arr-10)"/>
    <rect class="fig-box-blue" x="34" y="46" width="288" height="32" rx="4"/>
    <rect class="fig-box" x="34" y="94" width="288" height="32" rx="4"/>
    <rect class="fig-box-orange" x="34" y="142" width="288" height="32" rx="4"/>
    <rect class="fig-box-accent" x="34" y="190" width="288" height="32" rx="4"/>
    <rect class="fig-box-green" x="34" y="238" width="288" height="34" rx="4"/>
    <rect class="fig-box-subtle" x="368" y="46" width="324" height="104" rx="5"/>
    <rect class="fig-box-blue" x="382" y="92" width="200" height="28" rx="3"/>
    <rect class="fig-box-red" x="582" y="92" width="44" height="28" rx="3"/>
    <line class="fig-line-dashed" x1="442" y1="83" x2="442" y2="92"/>
    <line class="fig-line-dashed" x1="442" y1="120" x2="442" y2="128"/>
    <rect class="fig-box-subtle" x="368" y="160" width="324" height="112" rx="5"/>
    <rect class="fig-box-blue" x="382" y="206" width="60" height="28" rx="3"/>
    <rect class="fig-box-red" x="442" y="206" width="44" height="28" rx="3"/>
    <rect class="fig-box-blue" x="486" y="206" width="140" height="28" rx="3"/>
    <line class="fig-line-dashed" x1="442" y1="196" x2="442" y2="206"/>
    <line class="fig-line-dashed" x1="442" y1="234" x2="442" y2="244"/>
    <text class="fig-title" x="180" y="34" text-anchor="middle" font-size="11.5">向量中断 5 步寻址链（★ 向量地址 ≠ 入口地址）</text>
    <g text-anchor="middle" font-size="10.2">
      <text class="fig-blue" x="178" y="66">① 硬件/中断控制器给出类型号 i（如 14=缺页）</text>
      <text class="fig-label" x="178" y="114">② 硬件乘表项长 + IVT 基址（如 IVT + 14×4）</text>
      <text class="fig-orange" x="178" y="162">③ 中断向量地址（IVT 表项自身的内存地址）</text>
      <text class="fig-accent" x="178" y="210">④ 按表项地址访存读取 → 中断向量（ISR 入口地址）</text>
      <text class="fig-green" x="178" y="259">⑤ 将中断向量送入 PC → O(1) 定位，与源数量无关</text>
    </g>
    <text class="fig-title" x="530" y="34" text-anchor="middle" font-size="11">单重 vs 多重中断（I/O 100μs，t=30 故障 20μs）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-label" x="530" y="60" font-size="10.5">单重中断：全程关中断，按到达顺序串行（延迟 70μs）</text>
      <text class="fig-blue" x="482" y="110">I/O 中断处理 (0–100μs)</text>
      <text class="fig-red" x="604" y="110">故障</text>
      <text class="fig-muted" x="442" y="79" font-size="9.5">t=30 故障到达被屏蔽</text>
      <text class="fig-muted" x="530" y="142" font-size="9.5">t=100 开中断后才响应故障（延迟 70μs），故障 120μs 完</text>
      <text class="fig-accent" x="530" y="177" font-size="10.5">多重中断：保护现场后开中断，高优插队（延迟 0μs ★）</text>
      <text class="fig-blue" x="412" y="224">I/O 前段</text>
      <text class="fig-red" x="464" y="224">故障</text>
      <text class="fig-blue" x="556" y="224">I/O 后段 (50–120μs)</text>
      <text class="fig-muted" x="442" y="193" font-size="9.5">t=30 压现场进核心栈</text>
      <text class="fig-muted" x="530" y="258" font-size="9.5">高优 50μs 先完，★ 先响应的 I/O 反而后完成（120μs）</text>
    </g>
  </svg>
  <figcaption>图 1-10　向量中断五步寻址链与单重/多重中断嵌套响应时间线对照</figcaption>
</figure>

#### 5. 哪些指令可能引起态切换 & 中断与进程切换的关系

判断一条汇编/机器指令在用户态执行时**会不会导致切换到内核态**，只需检查两条（`13#28`, `15#24`）：
1. 它本身是不是**主动陷入指令**（`trap` / `INT n` / `syscall`）——是则**必然**切换；
2. 它执行过程中**是否可能触发异常**——除法指令可能除零或溢出、访存指令（如 `MOV R0, addr`）可能发生**缺页异常或地址越界**，都属于“**可能**”。

两条都不沾、**“绝不可能引起态切换”的只有不访存且不触发算术异常的纯寄存器操作**，例如<strong>寄存器内容取反（<code>NOT R0</code>）</strong>或寄存器逻辑位运算（`15#24`）。

此外，中断处理与进程切换不可画等号：**中断必然使 CPU 进入内核态，但不必然引起进程切换**。仅当内核决定重新调度（如时钟中断导致时间片耗尽、I/O 完成中断唤醒更高优先级进程、缺页阻塞当前进程）时，才会切换进程；普通系统调用（如 `getpid`）返回时通常仍回到原进程。

<figure class="cpd-figure not-content" id="os-c1-fig-11">
  <svg viewBox="0 0 720 318" role="img" aria-label="一次完整中断响应与处理过程中的软硬件分工与断点、现场区别泳道图">
    <defs>
      <marker id="os-c1-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="290" rx="6"/>
    <rect class="fig-box-blue" x="28" y="46" width="114" height="174" rx="5"/>
    <rect class="fig-box-orange" x="156" y="46" width="176" height="174" rx="5"/>
    <rect class="fig-box-accent" x="346" y="46" width="222" height="174" rx="5"/>
    <rect class="fig-box-green" x="582" y="46" width="110" height="174" rx="5"/>
    <line class="fig-line-accent" x1="142" y1="132" x2="154" y2="132" marker-end="url(#os-c1-arr-11)"/>
    <line class="fig-line-accent" x1="332" y1="132" x2="344" y2="132" marker-end="url(#os-c1-arr-11)"/>
    <line class="fig-line-accent" x1="568" y1="132" x2="580" y2="132" marker-end="url(#os-c1-arr-11)"/>
    <rect class="fig-box" x="166" y="88" width="156" height="26" rx="3"/>
    <rect class="fig-box" x="166" y="120" width="156" height="28" rx="3"/>
    <rect class="fig-box" x="166" y="154" width="156" height="28" rx="3"/>
    <rect class="fig-box" x="166" y="188" width="156" height="24" rx="3"/>
    <rect class="fig-box" x="356" y="88" width="202" height="26" rx="3"/>
    <rect class="fig-box" x="356" y="120" width="202" height="28" rx="3"/>
    <rect class="fig-box" x="356" y="154" width="202" height="28" rx="3"/>
    <rect class="fig-box" x="356" y="188" width="202" height="24" rx="3"/>
    <rect class="fig-box" x="28" y="232" width="328" height="60" rx="5"/>
    <rect class="fig-box" x="368" y="232" width="324" height="60" rx="5"/>
    <text class="fig-title" x="360" y="34" text-anchor="middle" font-size="11.5">中断/异常完整生命周期：硬件响应（中断隐指令） vs OS 软件处理边界（★ 22#31 · 24#23）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-blue" x="85" y="66" font-size="10.8">① 触发瞬间</text>
      <text class="fig-label" x="85" y="92">执行用户程序</text>
      <text class="fig-red" x="85" y="118" font-size="10">★ 发生时</text>
      <text class="fig-red" x="85" y="136" font-size="10">通常仍在用户态</text>
      <text class="fig-muted" x="85" y="164" font-size="9.5">指令执行中(异常)</text>
      <text class="fig-muted" x="85" y="182" font-size="9.5">或执行后(外中断)</text>
      <text class="fig-muted" x="85" y="204" font-size="9.5">检测到事件请求</text>
      <text class="fig-orange" x="244" y="66" font-size="10.8">② 硬件响应：中断隐指令</text>
      <text class="fig-muted" x="244" y="80" font-size="9.5">正在过渡 → 内核态</text>
      <text class="fig-label" x="244" y="105" font-size="9.5">1. 关中断（IF ← 0）</text>
      <text class="fig-label" x="244" y="138" font-size="9.2">2. 硬件保存断点（PC + PSW）</text>
      <text class="fig-label" x="244" y="172" font-size="9.5">3. 查向量表引出入口地址→PC</text>
      <text class="fig-orange" x="244" y="204" font-size="9.5">4. 硬件置模式位 = 内核态</text>
      <text class="fig-accent" x="457" y="66" font-size="10.8">③ OS 软件处理（ISR）</text>
      <text class="fig-accent" x="457" y="80" font-size="9.5">★ 开始执行时：必然在内核态</text>
      <text class="fig-label" x="457" y="105">5. 保护现场（pusha 存通用寄存器）</text>
      <text class="fig-label" x="457" y="138">6. [多重:设屏蔽+开中断] 执行服务主体</text>
      <text class="fig-label" x="457" y="172">7. 关中断并恢复现场（popa 出栈）</text>
      <text class="fig-label" x="457" y="204">8. 开中断 + 执行特权指令 iret</text>
      <text class="fig-green" x="637" y="66" font-size="10.8">④ 返回断点</text>
      <text class="fig-label" x="637" y="102">iret 弹 PSW/PC</text>
      <text class="fig-green" x="637" y="128">切回用户态</text>
      <text class="fig-muted" x="637" y="158" font-size="9.5">或触发调度器</text>
      <text class="fig-muted" x="637" y="176" font-size="9.5">切换到另一进程</text>
      <text class="fig-muted" x="637" y="202" font-size="9.5">继续执行指令流</text>
    </g>
    <g text-anchor="middle" font-size="10">
      <text class="fig-orange" x="192" y="252" font-size="10.5">★ 断点 vs 现场千万别记反</text>
      <text class="fig-label" x="192" y="270">断点（PC 与 PSW）→ 硬件自动保存</text>
      <text class="fig-label" x="192" y="285">现场（通用寄存器）→ OS 软件压栈保存</text>
      <text class="fig-accent" x="530" y="252" font-size="10.5">★ 软硬件职责判别万能规则</text>
      <text class="fig-label" x="530" y="270">凡动 PC / PSW / 模式位 / 向量表 → 硬件做</text>
      <text class="fig-label" x="530" y="285">凡用普通指令可完成的压栈与服务逻辑 → OS 做</text>
    </g>
  </svg>
  <figcaption>图 1-11　中断/异常完整周期的“硬件中断隐指令 vs OS 软件处理”职责切分与两时刻模式辨析</figcaption>
</figure>

---

### 1.6 ★系统调用与用户接口

如果说外中断解决的是“硬件主动通知 OS”，那么<strong>系统调用（System Call）</strong>解决的就是**用户程序主动向内核请求服务**。由于内核空间与用户空间逻辑隔离，用户程序无法直接读写硬件端口、页表或内核 PCB，只能通过系统调用向内核发起委托。**系统调用是用户程序请求 OS 内核服务的唯一途径（`10#23`）**，其存在的根本原因是**系统保护**，发挥着**权限裁决**与**资源抽象**两大作用。

#### 1. 教材三大同义术语与六大功能分类

- **术语映射**：**陷入指令（Trap）**（如 x86 `int 0x80`/`sysenter`/`syscall`、RISC-V `ecall`）= **访管指令**（从目态请求访问管态程序的指令）= **广义指令**（程序级接口对外呈现的功能调用抽象）。
- **六大功能分类**：
  1. **进程控制**：创建、撤销、阻塞、唤醒、获取/设置属性（`fork`、`exec`、`exit`、`wait`）。
  2. **文件管理**：建立、删除、打开、关闭、读、写、定位（`open`、`close`、`read`、`write`）。
  3. **设备管理**：申请与释放设备、控制与检查状态（`ioctl`）。
  4. **存储管理**：向内核申请与归还动态虚拟内存空间（`brk`、`mmap`，部分教材并入进程管理）。
  5. **进程通信**：管道、共享内存、消息队列、网络套接字（`pipe`、`shmget`、`socket`）。
  6. **信息维护**：读取系统时间、进程标识等（`getpid`、`time`、`gettimeofday`）。

#### 2. ★双条件门禁：判断一件事是不是系统调用（`21#32`, `19#25`）

判断某操作是否通过系统调用实现，必须**同时满足两问**：
1. **是否由用户进程主动发起？** → 排除**缺页中断处理、页面置换、进程调度**（`21#32`）等由硬件异常或时钟中断触发的内核内部自主行为。
2. **是否需要内核特权/触碰内核管理的资源？** → 排除 `strlen()`、`strcpy()`、`sin()`、`rand()` 等在用户空间即可算完的纯用户态函数。

| 操作 / 函数 | 所属层次 | 是否触发系统调用 | 核心原理解析 |
| --- | --- | --- | --- |
| `fork()` / `CreateProcess()` | 系统调用 / 封装 API | **是** | 用户主动发起，且需内核分配 PCB、建立页表 |
| `open` / `read` / `write` / `socket` | 系统调用 / 封装 API | **是** | 涉及内核文件系统、设备驱动与特权 I/O |
| `printf("...\n")` | **C 库函数**（用户态） | **视缓冲而定** | 命中行缓冲不刷新时不触发；遇 `\n` 或缓冲满时内部调用 `write` |
| `malloc(size)` | **C 库函数**（用户态） | **大块时间接触发** | 小块内存由用户态堆分配器直接切分（不陷入）；大块或堆不足时调 `brk`/`mmap` |
| `sin(x)` / `strlen(s)` / `rand()` | **C 库函数**（用户态） | **否** | 纯用户态指令计算，不访问内核资源（`13#28`） |
| **页面置换 / 进程调度** | 内核内部例程 | **否** | 运行在内核态，但非用户进程主动发出系统调用请求（`21#32`） |

> **★考点**：
> 1. **库函数 vs 系统调用（`10#23`, `19#25`）**：库函数本身属于**用户程序/语言运行库**，运行在**用户态**，它的价值在于“把压参数、填调用号、执行访管指令打包成一次过程调用，隐藏机器细节并消除平台差异”。**真正跨操作系统统一的是库函数层（以及 POSIX 源码级规范），而不同操作系统（Linux/Windows/macOS）的系统调用接口（调用号、参数约定）并不统一！（`19#25` 必考点）**。
> 2. **为什么按“功能号”而不按“入口地址”调用？** 防止用户绕过入口检验直接跳进内核代码段中间，并用“一次数组查表”换取入口完全可控及跨内核版本的二进制稳定性。

#### 3. ★系统调用完整执行流程与参数传递（`17#24`, `12#28`, `22#31`, `23#26`）

一次系统调用从发起至返回的 5 个关键步骤（以库函数封装调用 `read(fd, buf, n)` 为例）：

1. **准备参数与系统调用号（用户态，★必须在陷入之前！`17#24`）**：
   库函数将参数按约定摆放好，并将**系统调用功能号**装入约定寄存器。**★参数传递的三种方式**：
   - ① **陷入指令自带参数**（直接参数或紧邻存放参数区地址的间接参数，受指令长度限制）；
   - ② **CPU 通用寄存器传递**（最快、最常用；**当参数多或为结构体/缓冲区时，改为将参数存放在主存参数区/表内，仅将首地址送入寄存器**，内核读取时需校验地址合法性）；
   - ③ **主存专用堆栈区传递**（适用于参数数目不定及嵌套情况）。
   - **★为何传参必须在陷入之前？** 一旦执行陷入指令，硬件栈指针便会切换到内核态核心栈，内核看不见陷入之后才压到用户栈上的参数！
   - **★为什么 `read(fd, buf, n)` 参数中不含文件名？（`12#28`）**：按路径名查目录只在上一次 `open()` 时做一次，换取内核句柄（文件描述符 `fd`）并由调用者传入用户缓冲地址 `buf`；若每次 `read` 都传文件名则每次都要重搜目录树，且若数据不在内存则 `read` 使当前进程阻塞睡眠直至 I/O 完成。
2. **执行陷入指令（用户态 → 内核态，硬件完成）**：
   执行非特权指令 `trap` / `syscall` / `int 0x80`。硬件自动保存断点 `PC` 与 `PSW` 到核心栈，将模式位置为**内核态（`1`）**，切换至核心栈。
3. **保护现场与查表分发（内核态，OS 软件完成 `22#31`）**：
   内核通用入口程序先将通用寄存器现场压入核心栈，再校验系统调用号并查**系统调用入口地址表**，转入对应的内核服务例程（如 `sys_read`）。
4. **执行服务例程（内核态，OS 软件完成 `22#31`）**：
   在内核态权限下操作设备、文件系统或内存结构，将读取到的数据拷回用户态提供的 `buf` 中，并把返回值写入约定返回寄存器。
5. **恢复现场并执行返回指令（内核态 → 用户态，`23#26`）**：
   恢复通用寄存器，执行特权指令 `iret`/`sysret` 恢复原 `PSW`（**模式位写回用户态（`0`）**）与 `PC`，返回陷入指令的**下一条指令**继续执行。

> **★考点**：对比**中断处理/系统调用 vs 普通子程序调用（`12#23`）**：
> - 普通子程序调用（`CALL`）**只保存返回地址（`PC`）**，**不保存也不应恢复（`PSW`）**（调用子函数算加法正是要更新进位/零标志，且不会引发模式位切换）；
> - 中断与系统调用必须同时保存**程序计数器 `PC` 与状态字 `PSW`**（状态标志与原处理器模式位）。

<figure class="cpd-figure not-content" id="os-c1-fig-12">
  <svg viewBox="0 0 720 306" role="img" aria-label="普通函数调用、库函数封装与系统调用五步执行完整时序对比图">
    <defs>
      <marker id="os-c1-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="234" height="278" rx="6"/>
    <rect class="fig-box-subtle" x="262" y="14" width="442" height="278" rx="6"/>
    <rect class="fig-box" x="28" y="48" width="210" height="72" rx="5"/>
    <rect class="fig-box-blue" x="28" y="130" width="210" height="72" rx="5"/>
    <rect class="fig-box-orange" x="28" y="212" width="210" height="68" rx="5"/>
    <rect class="fig-box-blue" x="276" y="48" width="414" height="58" rx="5"/>
    <line class="fig-line-dashed" x1="276" y1="120" x2="690" y2="120"/>
    <rect class="fig-box-accent" x="276" y="134" width="414" height="106" rx="5"/>
    <line class="fig-line-accent" x1="330" y1="106" x2="330" y2="146" marker-end="url(#os-c1-arr-12)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="644" y1="146" x2="644" y2="106" marker-end="url(#os-c1-arr-12)"/>
    <rect class="fig-box" x="358" y="110" width="258" height="20" rx="3"/>
    <rect class="fig-box" x="288" y="148" width="126" height="44" rx="4"/>
    <rect class="fig-box" x="424" y="148" width="144" height="44" rx="4"/>
    <rect class="fig-box-green" x="578" y="148" width="100" height="44" rx="4"/>
    <line class="fig-line-accent" x1="414" y1="170" x2="422" y2="170" marker-end="url(#os-c1-arr-12)"/>
    <line class="fig-line-accent" x1="568" y1="170" x2="576" y2="170" marker-end="url(#os-c1-arr-12)"/>
    <rect class="fig-box" x="284" y="200" width="398" height="30" rx="3"/>
    <rect class="fig-box" x="276" y="248" width="414" height="32" rx="4"/>
    <text class="fig-title" x="133" y="34" text-anchor="middle" font-size="11.5">普通调用 vs 库函数 vs 系统调用</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-label" x="133" y="66" font-size="10.2">纯用户态库函数（sin / strlen）</text>
      <text class="fig-muted" x="133" y="84">按转向地址 CALL，只压 PC 不压 PSW</text>
      <text class="fig-muted" x="133" y="102">全程在用户态运行，不触发模式切换</text>
      <text class="fig-blue" x="133" y="148" font-size="9.8">封装库函数（printf / fopen / read）</text>
      <text class="fig-label" x="133" y="166">用户态库函数 → 内部触发系统调用</text>
      <text class="fig-muted" x="133" y="184">★ 跨 OS 统一的是库函数层，非系统调用</text>
      <text class="fig-orange" x="133" y="230" font-size="10.2">双门禁判别：是否是系统调用？</text>
      <text class="fig-label" x="133" y="248">① 用户主动发起 + ② 需内核权限</text>
      <text class="fig-muted" x="133" y="266">页置换/进程调度（非用户发起）→ 不是！</text>
    </g>
    <text class="fig-title" x="483" y="34" text-anchor="middle" font-size="11.5">系统调用 5 步标准流程（17#24 · 22#31 · 12#28）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-blue" x="483" y="66" font-size="10.2">用户态：1. 传参（寄存器/参数区指针/专用栈）+ 放调用号（★ 传参在陷入前）</text>
      <text class="fig-label" x="483" y="88" font-size="9.2">2. 执行非特权指令 trap / syscall / int 0x80（read 传句柄 fd，不传文件名）</text>
      <text class="fig-red" x="487" y="124" font-size="9.5">硬件存断点(PC/PSW)、置模式位=1、切核心栈</text>
      <text class="fig-accent" x="351" y="166">3. 保护现场</text>
      <text class="fig-muted" x="351" y="182" font-size="9.5">通用寄存器入核心栈</text>
      <text class="fig-accent" x="496" y="166">4. 按调用号查表执行</text>
      <text class="fig-muted" x="496" y="182" font-size="9.5">sys_read 内核例程</text>
      <text class="fig-green" x="628" y="166">5. 恢复+返回</text>
      <text class="fig-muted" x="628" y="182" font-size="9.5">popa + iret</text>
      <text class="fig-label" x="483" y="219" font-size="9.2">内核态下按功能号走“正门”查表，结束后特权指令 iret 将模式位写回 0（23#26）</text>
      <text class="fig-muted" x="483" y="268" font-size="9.5">返回系统调用下条指令继续执行（硬件完成陷入/切态与返回，OS 做 3/4/5）</text>
    </g>
  </svg>
  <figcaption>图 1-12　库函数与系统调用边界辨析及系统调用“传参 → 陷入 → 查表执行 → iret 返回”五步流程</figcaption>
</figure>

> **说明**：2026 大纲在“程序运行环境”末尾还列出了“程序的链接与装入”和“运行时内存映像与地址空间”——即静态链接 vs 动态链接（`.so`/`.dll`）、绝对装入/静态重定位/动态重定位以及进程虚存分布的高地址内核区与低地址用户栈/堆/数据/代码段，其完整地址翻译与硬件 MMU 细节将在第 5 章内存管理专题详述。

---

### 1.7 ★操作系统的引导（Booting）

运行任意程序都需要操作系统的调度与加载，而操作系统本身在关机时只是一个静静躺在磁盘上的二进制文件集合——开机瞬间主存（**RAM**）中空空如也，究竟是谁把操作系统拉进内存？打破这层“鸡生蛋”循环的机制叫做**自举（Bootstrap）**。

#### 1. 自举核心思想与存储设备分工

自举之所以能成立，依赖两个条件：**位置固定 + 断电不丢**。因此整个启动链条采用“**两段式分工，用一个约定位置顶替尚不存在的抽象**”：

- **第一段：ROM（主板只读非易失存储器）中的固化固件（BIOS/UEFI）**：加电瞬间，硬件将 CPU 的程序计数器 `PC` 强制初始化为一固定物理入口地址（如 x86 的 `FFFF0H`），此处固化了一段与具体 OS 无关的硬件自检与磁盘读扇区指令。
- **第二段：磁盘上的分级引导程序（MBR → PBR → Boot Manager）**：随具体 OS 安装而写定，负责理解分区与文件系统结构，最终将 OS 内核从磁盘加载到 **RAM（`13#29`）**。

#### 2. ★启动盘的制作四步 vs 开机引导的四步（`21#46`, `22#24` 必考大题！）

**两条顺序千万不要混淆**：制作启动盘是在安装前由物理向逻辑逐层筑基（写入磁盘，**仅做一次，断电保留**）；开机引导则是开机时由固件往分区逐级交权（把代码读入内存）。

**启动盘制作四步（持久化在磁盘，只建一次）**：
1. **物理格式化（低级格式化）**：在磁道上**划分扇区**、安排扇区编号并标记坏道（磁盘硬件层操作，通常出厂已完成）。
2. **磁盘分区**：将整块磁盘划出若干逻辑分区（如 C 盘、D 盘），并**写入第 0 扇区的 MBR 及分区表**（整盘层操作）。
3. **逻辑格式化（高级格式化）**：针对单个分区建立文件系统结构，写入**分区引导记录（PBR/DBR）、FAT 表或索引节点表（inode）、根目录、数据区**（文件系统层操作）。
4. **操作系统安装**：把内核映像文件及系统文件写入已建立好的文件系统分区中，并配置引导项。

**传统 BIOS + MBR 开机引导完整流程（按顺序执行）**：
1. **执行 ROM 中的引导程序（BIOS）**：加电后 `PC` 强置为固定复位地址并跳入 ROM 中的 BIOS 主体（**在 ROM 里直接执行**）→ 执行<strong>加电自检（POST）</strong>排查硬件 → 初始化显卡等基础外设 → **在 RAM 低地址建立初始中断向量表（IVT）** 并填入基础 I/O 例程 → 读取 **CMOS** 参数确定启动设备顺序（如硬盘或装机 U 盘）。
2. **加载并执行主引导记录（MBR，位于启动盘第 0 扇区）**：BIOS 将磁盘 0 号扇区读入 RAM 并验证末尾两字节魔数 `0x55AA`，随后移交控制权。**MBR 共 512 B 的精确瓜分公式**：

$$
512\text{ B（扇区）} = 446\text{ B（磁盘引导程序）} + 64\text{ B（分区表，} 4 \times 16\text{ B）} + 2\text{ B（结束标志 0x55AA）}
$$

   **MBR 磁盘最多只能有 4 个主分区**，正是被分区表总空间 $64\text{ B}$ 与表项宽度 $16\text{ B}$ 唯一决定的！磁盘引导程序扫描分区表，定位到标记为<strong>“活动分区”（含操作系统的分区）</strong>的起始扇区号。
3. **加载并执行分区引导记录（PBR，位于活动分区的第 0 扇区）**：MBR 将活动分区的首扇区读入 RAM 并跳转过去。此时完整的文件系统驱动尚未加载，但 PBR 在逻辑格式化时已由格式化程序写入了一小段针对该分区文件系统（如 FAT/ext/NTFS）的硬编码读盘代码，它根据分区头元数据算出根目录扇区并读取**操作系统引导管理器（如 Windows Boot Manager / Linux GRUB）**。
4. **加载操作系统内核进 RAM 并初始化（OS 初始化程序）**：引导管理器将操作系统内核文件加载至 **RAM**（`13#29`）并交出控制权 → 内核重建自身所需的完整运行环境（**在 RAM 中重建完整的内核中断向量表**（`22#24`）、内核页表、空闲页框表、PCB 表并初始化驱动）→ **手工构造 0 号进程**（无父进程，随后退化为闲逛进程 `idle`）→ 由 0 号进程创建 **1 号用户进程（`init`）**，启动系统服务与用户登录界面。

> **★考点（`22#24` 判断秒杀法）**：**在磁盘上的制盘时只建一次，在内存里的每次开机都要重建！**
> - **开机初始化时必须重建（RAM）**：**中断向量表（IVT）**、内核页表。
> - **制盘时已写定持久化（磁盘）**：硬盘分区表（分区步）、文件系统根目录（逻辑格式化步）、索引节点表 inode（逻辑格式化步）。

#### 3. 现代引导体系：BIOS + MBR vs UEFI + GPT

| 比较维度 | 传统 BIOS + MBR | 现代 UEFI + GPT | 本质根源 |
| --- | --- | --- | --- |
| **固件位置** | 主板 ROM（不可轻易升级） | Flash ROM（可在线更新） | 硬件扩展性 |
| **固件认不认识文件系统** | **不认识**，仅按约定扇区号硬读 | **认识**（固件内置 FAT 驱动，可直接打开文件） | **★ 最根本的差别** |
| **引导代码位置** | 挤在 MBR 第 0 扇区 **446 B** 中 | 存放在 **ESP（EFI 系统分区）** 的 `.efi` 可执行文件 | 彻底跳过 MBR 446 B 瓶颈 |
| **分区数与容量上限** | 最多 4 个主分区，32 位寻址约 2 TB 封顶 | 支持高达 128+ 分区，64 位 LBA 突破容量限制 | GPT 全局唯一标识分区表 |
| **多系统共存** | 互相覆盖争夺 MBR 引导代码 | 各系统在 ESP 中各自放置 `.efi` 文件，互不干扰 | 固件内部维护启动项列表 |

<figure class="cpd-figure not-content" id="os-c1-fig-13">
  <svg viewBox="0 0 720 336" role="img" aria-label="操作系统自举引导链路、MBR 512 字节解剖图与制盘四步、UEFI 对比图">
    <defs>
      <marker id="os-c1-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="174" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="198" width="336" height="124" rx="6"/>
    <rect class="fig-box-subtle" x="364" y="198" width="340" height="124" rx="6"/>
    <line class="fig-line-accent" x1="142" y1="74" x2="158" y2="74" marker-end="url(#os-c1-arr-13)"/>
    <line class="fig-line-accent" x1="282" y1="74" x2="298" y2="74" marker-end="url(#os-c1-arr-13)"/>
    <line class="fig-line-accent" x1="422" y1="74" x2="438" y2="74" marker-end="url(#os-c1-arr-13)"/>
    <line class="fig-line-accent" x1="562" y1="74" x2="578" y2="74" marker-end="url(#os-c1-arr-13)"/>
    <rect class="fig-box-orange" x="24" y="44" width="118" height="62" rx="4"/>
    <rect class="fig-box-blue" x="160" y="44" width="122" height="62" rx="4"/>
    <rect class="fig-box-purple" x="300" y="44" width="122" height="62" rx="4"/>
    <rect class="fig-box-accent" x="440" y="44" width="122" height="62" rx="4"/>
    <rect class="fig-box-green" x="580" y="44" width="120" height="62" rx="4"/>
    <line class="fig-line-dashed" x1="221" y1="106" x2="221" y2="122"/>
    <rect class="fig-box-blue" x="28" y="124" width="424" height="48" rx="4"/>
    <rect class="fig-box-orange" x="452" y="124" width="176" height="48" rx="4"/>
    <rect class="fig-box-red" x="628" y="124" width="64" height="48" rx="4"/>
    <rect class="fig-box" x="26" y="232" width="68" height="46" rx="4"/>
    <rect class="fig-box" x="108" y="232" width="68" height="46" rx="4"/>
    <rect class="fig-box" x="190" y="232" width="68" height="46" rx="4"/>
    <rect class="fig-box" x="272" y="232" width="68" height="46" rx="4"/>
    <line class="fig-line-accent" x1="94" y1="255" x2="106" y2="255" marker-end="url(#os-c1-arr-13)"/>
    <line class="fig-line-accent" x1="176" y1="255" x2="188" y2="255" marker-end="url(#os-c1-arr-13)"/>
    <line class="fig-line-accent" x1="258" y1="255" x2="270" y2="255" marker-end="url(#os-c1-arr-13)"/>
    <rect class="fig-box-green" x="376" y="226" width="316" height="42" rx="4"/>
    <rect class="fig-box-accent" x="376" y="274" width="316" height="38" rx="4"/>
    <text class="fig-title" x="360" y="32" text-anchor="middle" font-size="11.5">传统 BIOS + MBR 操作系统开机自举引导链路（21#46 第一问 · 13#29）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-orange" x="83" y="61" font-size="10.5">① ROM 中 BIOS</text>
      <text class="fig-muted" x="83" y="78">PC=FFFF0H→POST</text>
      <text class="fig-muted" x="83" y="95" font-size="9">建初态 IVT · 读 CMOS</text>
      <text class="fig-blue" x="221" y="61" font-size="10.5">② 磁盘引导 MBR</text>
      <text class="fig-muted" x="221" y="78">读盘 0 号扇区到 RAM</text>
      <text class="fig-muted" x="221" y="95">查分区表找活动分区</text>
      <text class="fig-purple" x="361" y="61" font-size="10.5">③ 分区引导 PBR</text>
      <text class="fig-muted" x="361" y="78">活动分区第 0 扇区</text>
      <text class="fig-muted" x="361" y="95">读盘加载引导管理器</text>
      <text class="fig-accent" x="501" y="61" font-size="10.5">④ Boot Manager</text>
      <text class="fig-muted" x="501" y="78">GRUB / WinBootMgr</text>
      <text class="fig-muted" x="501" y="95">★ 拉内核进 RAM</text>
      <text class="fig-green" x="640" y="61" font-size="10.5">⑤ 内核初始化</text>
      <text class="fig-muted" x="640" y="78" font-size="9">重建内存 IVT（22#24）</text>
      <text class="fig-muted" x="640" y="95">构造 0/1 号进程</text>
      <text class="fig-blue" x="240" y="144" font-size="10.2">MBR 第 0 扇区 512 B 解剖：引导代码 446 B</text>
      <text class="fig-muted" x="240" y="162" font-size="9.5">主引导程序，查右方分区表并加载活动分区 PBR</text>
      <text class="fig-orange" x="540" y="144" font-size="10.2">分区表 64 B（4×16B）</text>
      <text class="fig-muted" x="540" y="162" font-size="9.5">★ 决定最多 4 主分区</text>
      <text class="fig-red" x="660" y="144" font-size="10">0x55AA</text>
      <text class="fig-muted" x="660" y="162" font-size="9.5">2B 魔数</text>
    </g>
    <text class="fig-title" x="184" y="218" text-anchor="middle" font-size="11">启动盘制作 4 步（写进磁盘，只做一次）</text>
    <g text-anchor="middle" font-size="9.5">
      <text class="fig-label" x="60" y="250">①物理格式</text>
      <text class="fig-muted" x="60" y="266">划分扇区</text>
      <text class="fig-label" x="142" y="250">②磁盘分区</text>
      <text class="fig-muted" x="142" y="266">写MBR/表</text>
      <text class="fig-label" x="224" y="250">③逻辑格式</text>
      <text class="fig-muted" x="224" y="266">根目录/PBR</text>
      <text class="fig-label" x="306" y="250">④安装 OS</text>
      <text class="fig-muted" x="306" y="266">写入内核</text>
      <text class="fig-accent" x="184" y="302">★ 分区表、根目录、inode 都在磁盘上；IVT 在 RAM 每次现建</text>
    </g>
    <text class="fig-title" x="534" y="218" text-anchor="middle" font-size="11">现代 UEFI + GPT 演进核心（跳过 MBR 限制）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-green" x="534" y="244">★ 根因：UEFI 固件内置 FAT 驱动（认识文件系统）</text>
      <text class="fig-muted" x="534" y="260">自检 → 直读 ESP 分区 .efi → 装入内核（跳过 MBR）</text>
      <text class="fig-accent" x="534" y="297" font-size="9.2">GPT 支持 128+ 分区与 >2TB 大盘，多 OS 启动项各自独立不覆盖</text>
    </g>
  </svg>
  <figcaption>图 1-13　BIOS + MBR 引导全链、512 B 扇区解剖、启动盘制作四步及 UEFI + GPT 演进对照</figcaption>
</figure>

---

### 1.8 ★操作系统的体系结构与虚拟机

#### 1. 五种 OS 结构的“三维正交”视图

2026 大纲列出了**分层、模块化、宏内核、微内核、外核**五个结构术语。切忌把它们排成一排比较“谁更好”，因为它们回答的是**三个正交维度**的问题：

| 结构类型 | 回答的维度 | 核心设计思想 | 典型代表 |
| --- | --- | --- | --- |
| **简单（无）结构** | （未模块化前） | 过程间无边界任意互调 | 早期 MS-DOS |
| **模块化结构** | **代码如何切分**（软件工程维度） | 按功能切分独立模块并定义接口（**模块-接口法**），模块间**可互相调用** | Solaris |
| **分层结构** | **代码如何切分**（软件工程维度） | 按层次自底向上堆叠，各层之间**严格单向依赖**（仅调用紧邻下层） | THE（6 层）、Multics（同心环） |
| **宏内核（大内核）** | **哪些功能进内核态**（特权级维度） | 进程、内存、文件、驱动等全跑在内核态，模块间**直接函数调用** | 传统 Unix、Linux、Windows |
| **微内核** | **哪些功能进内核态**（特权级维度） | 应用“**机制与策略分离**”，内核仅留极少机制，服务外放为**用户态服务器进程**，靠**消息传递**通信 | Mach、MINIX、QNX |
| **外核（Exokernel）** | **资源抽象由谁来做**（抽象维度） | 内核极小且**不做任何资源抽象**，只负责物理资源的分配与保护，将抽象权下放给应用链接的 **LibOS** | MIT Exokernel |

> **注意**：三个维度相互正交——Linux 既采用模块化组织源码（如动态可装载内核模块 LKM），又是典型的宏内核。

#### 2. 模块化 vs 分层结构

- **模块化结构**：按独立性准则设计，衡量独立性的两个指标是**内聚性**（模块内部各元素的紧密程度，**越高越好**）与**耦合度**（模块间的相互关联强度，**越低越好**）。局限在于各模块往往齐头并进开发，难以确定可靠的设计顺序，故又称“**无序模块法**”。
- **分层结构**：为消除无序性与循环依赖而生。由于下层完全不依赖上层，可实行**自底向上的逐层验证**（调试第 $i$ 层时无需假定更高层正确），极大提高了系统正确性与可扩充性（不改接口则互不干扰）；缺点在于每执行一个请求必须**自上而下穿越多层**，层间通信开销累加导致**效率降低**，且层次顺序往往难以完美划分。

#### 3. ★宏内核 vs 微内核（`23#23`）

- **微内核的四大特征与三大基本功能**：
  微内核遵循“**足够小的内核 + 基于客户/服务器（C/S）模式 + 机制与策略分离 + 面向对象技术**”四条原则。按“**内核留机制，用户态服务器放策略**”的黄金准绳，微内核内只保留：
  1. **进程（线程）管理机制**：优先级队列维护、调度切换动作、多处理机同步及最基本的 **IPC 消息传递**（至于优先级如何确定等策略放外部进程服务器）；
  2. **低级存储器管理机制**：依赖硬件的页表查找与地址变换机制（页面置换算法、内存分配回收策略放外部存储服务器）；
  3. **中断和陷入处理**：仅负责捕获中断/陷入、保护现场与识别类型，再将其包装为消息发给相应的用户态服务器完成后续处理。

| 对比维度 | 宏内核（大内核） | 微内核 | 因果解释与考法（`23#23`） |
| --- | --- | --- | --- |
| **内核代码体积** | 庞大 | **极小**（精简可形式化验证） | 决定于保留在内核态的功能多少 |
| **服务间通信方式** | **直接函数调用**（同地址空间） | **消息传递（IPC）**（跨进程通信） | 微内核服务器均在用户态独立运行 |
| **一次服务请求模式切换数** | **2 次**（用户→内核→用户） | **至少 4 次**（需再调他服务器时达 **8 次**） | 客户 → 微内核 → 服务器 → 微内核 → 客户 |
| **运行性能** | **★ 高** | 较低（代价） | 频繁状态切换与消息拷贝开销 |
| **可靠性与安全性** | 较差（任一驱动崩溃拖垮全内核） | **★ 极高** | 用户态服务器隔离崩溃，不波及内核与其他服务 |
| **可扩展性与可移植性** | 差（LKM 仅改善扩展未改善隔离） | **★ 强** | 增删服务只需动独立服务器；硬件代码集中内核 |
| **分布式计算支持** | 弱 | **★ 天然支持** | 本身就是基于 C/S 与消息传递架构 |

> **★考点**：
> 1. `23#23` 考微内核相对宏内核的优势：**可靠性高、安全性高、可扩展性强**，唯独“性能更好”是错的——微内核正是**以性能下降为代价换取其余全部优势**！
> 2. **支持可装载内核模块（LKM）的 Linux 依然是宏内核**：LKM 只是把模块链接到内核的时间从编译期推迟到运行时动态装卸，装入后它**仍然运行在内核态、共享同一个地址空间、模块间仍是直接函数调用**，只借到了微内核的“可扩展性”，并未借到“故障隔离”。

#### 4. 外核（Exokernel）

传统 OS 提供的统一抽象（如通用分页策略、固定块文件布局）对所有应用一视同仁，反而限制了数据库、高性能 Web 服务器等专用软件榨干硬件潜力。<strong>外核（1995 年提出）</strong>做出更激进的拆分：**将“资源抽象”本身从内核彻底搬走**。
- **外核职责**：极其微小的内核只管**物理资源分配与隔离保护**——确保请求的物理内存页框或特定磁盘块当前空闲且操作不越界，随后直接将**未经抽象的物理资源**分配给用户应用。
- **库操作系统（LibOS）**：原本的文件系统、页置换算法打包成用户态运行库链接到各应用中，应用调它们等于**普通函数调用**（省去通用系统调用映射开销）。
- **代价（未成主流原因）**：应用开发复杂度剧增、失去统一抽象导致各应用间共享数据困难、只能按物理块做保护、缺乏跨应用的全局统筹优化能力。

<figure class="cpd-figure not-content" id="os-c1-fig-14">
  <svg viewBox="0 0 720 318" role="img" aria-label="操作系统五种结构三维正交分类对比与微内核四次、八次状态切换示意图">
    <defs>
      <marker id="os-c1-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="218" height="174" rx="6"/>
    <rect class="fig-box-subtle" x="246" y="14" width="234" height="174" rx="6"/>
    <rect class="fig-box-subtle" x="492" y="14" width="212" height="174" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="198" width="688" height="106" rx="6"/>
    <rect class="fig-box" x="28" y="48" width="194" height="58" rx="4"/>
    <rect class="fig-box-blue" x="28" y="116" width="194" height="62" rx="4"/>
    <rect class="fig-box-orange" x="258" y="48" width="210" height="58" rx="4"/>
    <rect class="fig-box-accent" x="258" y="116" width="210" height="62" rx="4"/>
    <rect class="fig-box-green" x="504" y="48" width="188" height="58" rx="4"/>
    <rect class="fig-box-purple" x="504" y="116" width="188" height="62" rx="4"/>
    <rect class="fig-box-blue" x="30" y="232" width="136" height="44" rx="4"/>
    <rect class="fig-box-accent" x="292" y="232" width="136" height="44" rx="4"/>
    <rect class="fig-box-purple" x="554" y="232" width="136" height="44" rx="4"/>
    <line class="fig-line-accent" x1="166" y1="244" x2="290" y2="244" marker-end="url(#os-c1-arr-14)"/>
    <line class="fig-line-accent" x1="428" y1="244" x2="552" y2="244" marker-end="url(#os-c1-arr-14)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="552" y1="266" x2="428" y2="266" marker-end="url(#os-c1-arr-14)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="290" y1="266" x2="166" y2="266" marker-end="url(#os-c1-arr-14)"/>
    <text class="fig-title" x="125" y="34" text-anchor="middle" font-size="11">维 1：代码切分（工程维度）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-label" x="125" y="65" font-size="10.5">模块化（模块-接口法）</text>
      <text class="fig-muted" x="125" y="81">高内聚·低耦合·允许相互调用</text>
      <text class="fig-muted" x="125" y="96">缺陷：开发顺序无序难定义</text>
      <text class="fig-blue" x="125" y="133" font-size="10.5">分层结构（严格单向依赖）</text>
      <text class="fig-muted" x="125" y="149">自底向上逐层独立验证正确性</text>
      <text class="fig-muted" x="125" y="165">缺点：穿越多层通信开销降低性能</text>
    </g>
    <text class="fig-title" x="363" y="34" text-anchor="middle" font-size="11">维 2：特权边界（内核放多少）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-orange" x="363" y="65" font-size="10.5">宏内核（Linux / Unix / Win）</text>
      <text class="fig-muted" x="363" y="81">服务全在内核态·直接函数调用快</text>
      <text class="fig-muted" x="363" y="96">LKM 仍运行内核态，一损俱损</text>
      <text class="fig-accent" x="363" y="133" font-size="10.5">微内核（Mach / QNX / MINIX）</text>
      <text class="fig-muted" x="363" y="149">内核留机制，策略置用户态服务器</text>
      <text class="fig-muted" x="363" y="165">★ 可靠/安全/扩展高，性能降（23#23）</text>
    </g>
    <text class="fig-title" x="598" y="34" text-anchor="middle" font-size="11">维 3：抽象归属（谁来做抽象）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-green" x="598" y="65" font-size="10.5">外核（Exokernel）</text>
      <text class="fig-muted" x="598" y="81">内核仅管物理资源分配与保护</text>
      <text class="fig-muted" x="598" y="96">不做高层抽象（直分物理页/块）</text>
      <text class="fig-purple" x="598" y="133" font-size="10.5">用户态 LibOS 库操作系统</text>
      <text class="fig-muted" x="598" y="149">按应用特性自定义文件系统/置换</text>
      <text class="fig-muted" x="598" y="165">普通函数调用提效，但兼容性差</text>
    </g>
    <text class="fig-title" x="360" y="218" text-anchor="middle" font-size="11.5">微内核“一次服务请求至少 4 次上下文/模式切换”路径示意（宏内核仅需 2 次）</text>
    <g text-anchor="middle" font-size="10">
      <text class="fig-blue" x="98" y="251">客户进程</text>
      <text class="fig-muted" x="98" y="267" font-size="9.5">（用户态）</text>
      <text class="fig-accent" x="360" y="251">微内核</text>
      <text class="fig-muted" x="360" y="267" font-size="9.5">（内核态·IPC）</text>
      <text class="fig-purple" x="622" y="251">文件服务器进程</text>
      <text class="fig-muted" x="622" y="267" font-size="9.5">（用户态）</text>
      <text class="fig-accent" x="228" y="238" font-size="9.5">① 请求陷入</text>
      <text class="fig-accent" x="490" y="238" font-size="9.5">② 转交消息</text>
      <text class="fig-green" x="490" y="282" font-size="9.5">③ 结果返回内核</text>
      <text class="fig-green" x="228" y="282" font-size="9.5">④ 返回客户态</text>
      <text class="fig-muted" x="360" y="297" font-size="9.5">注：若文件服务器还需再通过微内核向磁盘服务器发送请求，总切换次数增至 8 次！</text>
    </g>
  </svg>
  <figcaption>图 1-14　操作系统结构三维正交视图及微内核 C/S 消息传递导致的 4 次/8 次切换开销</figcaption>
</figure>

#### 5. ★虚拟机（Virtual Machine，VMM / Hypervisor，`25#24`）

若想在同一台物理计算机上同时隔离运行多个完整的操作系统（**客户机操作系统 Guest OS**），就必须在最底层引入**虚拟机监控程序（VMM，又称 Hypervisor）**。

> **★考点（`25#24` 核心结论）**：**真正掌握物理硬件最高特权级（内核态 / VMX Root Mode / Ring -1）的是 VMM；每个 Guest OS 都被降级运行在用户态（或硬件虚拟化非根模式）下！** 任何称“VMM 与 Guest OS 特权级相同”的说法均为错误——若两者同级，VMM 将无法拦截 Guest OS 执行的特权指令。

**成功虚拟化的三条准则（Popek–Goldberg）**：
1. **等价性（保真）**：程序在虚拟机上的运行行为应与在真机上基本相同。
2. **资源控制（安全）**：VMM 完全掌控物理硬件资源，各虚拟机相互隔离（**OS 级隔离**）。
3. **效率**：绝大多数非敏感指令直接在物理硬件上原生执行，无需 VMM 软件介入。

##### 两类虚拟机监控程序（Type 1 vs Type 2）

划分唯一依据是：**VMM 访问物理硬件需不需要经过另一个宿主操作系统（Host OS）**。

| 比较维度 | Type 1（第一类：裸金属架构） | Type 2（第二类：寄居架构） |
| --- | --- | --- |
| **底层支撑** | **直接运行在物理硬件裸机之上**（下面没有 OS） | **运行在宿主操作系统（Host OS）之上**（作为宿主上的普通应用） |
| **资源控制权** | VMM 自身扮演 OS 角色，直接掌控 CPU、内存与原始磁盘分区 | 宿主 OS 掌控硬件，VMM 必须向宿主 OS 申请资源 |
| **I/O 路径层级** | Guest → VMM → 物理硬件 | Guest → VMM → **宿主 OS** → 物理硬件（虚拟磁盘是宿主上的普通文件） |
| **权限与性能** | VMM 独占最高内核权限，性能高、实时性强 | 权限低于宿主 OS，开销大、调度受宿主 OS 制约，但安装易用 |
| **代表产品** | VMware ESXi、Xen、Hyper-V、嵌入 Linux 内核的 KVM | VMware Workstation、VirtualBox、Parallels Desktop |

##### CPU、内存与 I/O 虚拟化核心机制

1. **CPU 虚拟化四条演进路线**：
   - **① 陷入-模拟（Trap-and-Emulate）**：Guest 执行特权指令时因特权级不足触发异常陷入 VMM，由 VMM 模拟其语义。**★充要条件：当且仅当所有敏感指令都是特权指令时才成立**！若指令“敏感但不特权”（如早期 x86），在用户态执行既不陷入也不报错，直接破坏等价性。
   - **② 二进制翻译（Binary Translation）**：VMM 在执行前动态扫描 Guest 指令流，将“敏感但不特权”指令替换为安全调用（Guest 毫不知情，可兼容闭源 OS）。
   - **③ 半虚拟化（Paravirtualization）**：显式修改 Guest OS 源码，将敏感操作替换为对 VMM 的显式接口调用（**Hypercall**）。
   - **④ 硬件辅助虚拟化（Intel VT-x / AMD-V）**：CPU 新增<strong>根模式（VMX Root，跑 VMM）</strong>与<strong>非根模式（VMX Non-root，跑 Guest OS 与其应用）</strong>两套独立特权环。Guest OS 仍可运行在自己的非根 Ring 0，敏感操作由硬件配置直接触发 **VM Exit** 陷入 VMM，彻底消除了“敏感但不特权”隐患。
2. **内存虚拟化三层映射（`GVA → GPA → HPA`）**：
   Guest 应用看到 **GVA（客户虚拟地址）**，Guest OS 自以为自己控制了 **GPA（客户物理地址）**，真实物理内存地址则是 **HPA（宿主机物理地址）**。而 MMU 只认直接映向 HPA 的映射表：
   - **影子页表（Shadow Page Table）**：VMM 在软件层将 `GVA → GPA` 与 `GPA → HPA` 合成一张影子页表交给 MMU，**开销压在修改页表时**（访存时硬件无感）。
   - **二维页表（EPT / NPT）**：硬件 MMU 直接支持两级遍历翻译，**改页表零软件同步开销，把开销分摊到每次 TLB 未命中时**（现代主流方案）。
3. **I/O 虚拟化三条路**：
   **全模拟**（用软件完整仿真旧网卡等，兼容最佳但陷入频繁最慢）→ **半虚拟化 I/O（virtio）**（Guest 装专用驱动，经共享环形缓冲区批量提交请求）→ **设备直通（IOMMU + SR-IOV）**（近原生性能，**必须配置 IOMMU** 完成设备 DMA 地址的 `GPA → HPA` 翻译与隔离）。

> **★考点（`25#24` 补充细节）**：**虚拟机可以跨指令集（ISA）！** 利用纯软件指令集全仿真（如 QEMU 模拟器），可在 ARM 宿主机上运行 x86 虚拟机，只是每条指令都要翻译导致性能大幅下降；此外，虚拟机提供的是 **OS 级隔离**（一台客户机崩溃不影响宿主机或其他虚机，资源消耗大、启动慢），而进程提供的是**进程级隔离**（轻量启动快，但所有进程共用同一内核，**内核崩溃则全盘崩溃**）。

<figure class="cpd-figure not-content" id="os-c1-fig-15">
  <svg viewBox="0 0 720 296" role="img" aria-label="Type-1 裸金属虚拟机与 Type-2 寄居虚拟机分层架构及特权级边界对比图">
    <rect class="fig-box-subtle" x="16" y="14" width="336" height="268" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="14" width="336" height="268" rx="6"/>
    <rect class="fig-box-blue" x="30" y="44" width="148" height="96" rx="4"/>
    <rect class="fig-box-green" x="190" y="44" width="148" height="96" rx="4"/>
    <rect class="fig-box" x="40" y="66" width="128" height="24" rx="3"/>
    <rect class="fig-box" x="40" y="98" width="128" height="34" rx="3"/>
    <rect class="fig-box" x="200" y="66" width="128" height="24" rx="3"/>
    <rect class="fig-box" x="200" y="98" width="128" height="34" rx="3"/>
    <rect class="fig-box-accent" x="30" y="148" width="308" height="44" rx="4"/>
    <rect class="fig-box-orange" x="30" y="200" width="308" height="36" rx="4"/>
    <rect class="fig-box" x="30" y="242" width="308" height="30" rx="4"/>
    <rect class="fig-box-blue" x="382" y="46" width="196" height="84" rx="4"/>
    <rect class="fig-box" x="392" y="58" width="176" height="22" rx="3"/>
    <rect class="fig-box" x="392" y="86" width="176" height="34" rx="3"/>
    <rect class="fig-box-purple" x="382" y="136" width="196" height="30" rx="4"/>
    <rect class="fig-box" x="588" y="46" width="102" height="120" rx="4"/>
    <rect class="fig-box-accent" x="382" y="172" width="308" height="34" rx="4"/>
    <rect class="fig-box-orange" x="382" y="212" width="308" height="30" rx="4"/>
    <rect class="fig-box" x="382" y="248" width="308" height="26" rx="4"/>
    <text class="fig-title" x="184" y="34" text-anchor="middle" font-size="11.5">Type 1：裸金属架构（ESXi / Xen / KVM）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-blue" x="104" y="58" font-size="10">虚拟机 1（隔离）</text>
      <text class="fig-label" x="104" y="82">客户机应用程序</text>
      <text class="fig-label" x="104" y="112">Guest OS（Linux）</text>
      <text class="fig-muted" x="104" y="126" font-size="9.5">★ 降级用户态/非根</text>
      <text class="fig-green" x="264" y="58" font-size="10">虚拟机 2（隔离）</text>
      <text class="fig-label" x="264" y="82">客户机应用程序</text>
      <text class="fig-label" x="264" y="112">Guest OS（Win）</text>
      <text class="fig-muted" x="264" y="126" font-size="9.5">★ 降级用户态/非根</text>
      <text class="fig-accent" x="184" y="167" font-size="10.5">★ VMM / Hypervisor（最高特权级：内核态 / Ring -1）</text>
      <text class="fig-muted" x="184" y="183" font-size="9.5">直接调度 CPU、内存与原始分区（25#24）</text>
      <text class="fig-orange" x="184" y="222" font-size="10.5">物理硬件资源（CPU · RAM · 磁盘 · 网卡）</text>
      <text class="fig-muted" x="184" y="261" font-size="9.5">I/O 路径：Guest → VMM → 硬件（无宿主 OS 阻隔）</text>
    </g>
    <text class="fig-title" x="536" y="34" text-anchor="middle" font-size="11.5">Type 2：寄居架构（Workstation / VirtualBox）</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-label" x="480" y="73">客户机应用程序</text>
      <text class="fig-label" x="480" y="100">Guest OS（客户机系统）</text>
      <text class="fig-muted" x="480" y="114" font-size="9.5">虚拟磁盘=宿主普通文件</text>
      <text class="fig-purple" x="480" y="155" font-size="10.2">VMM（作为宿主上的普通应用软件）</text>
      <text class="fig-label" x="639" y="100">宿主普通应用</text>
      <text class="fig-muted" x="639" y="118" font-size="9.5">(浏览器 / IDE)</text>
      <text class="fig-accent" x="536" y="193" font-size="10.5">★ 宿主操作系统 Host OS（真正内核态与硬件掌控者）</text>
      <text class="fig-orange" x="536" y="231" font-size="10.5">物理硬件资源（CPU · RAM · 磁盘 · 网卡）</text>
      <text class="fig-muted" x="536" y="265" font-size="9.5">I/O 路径：Guest → VMM → 宿主 OS → 硬件（多穿一层）</text>
    </g>
  </svg>
  <figcaption>图 1-15　Type-1（裸金属）与 Type-2（寄居）虚拟机体系分层及 VMM 特权级边界对比</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c1-fig-16">
  <svg viewBox="0 0 720 298" role="img" aria-label="CPU 虚拟化四条演进路线、内存虚拟化三层映射 GVA 到 HPA 及 I/O 虚拟化三条路线">
    <defs>
      <marker id="os-c1-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="140" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="164" width="340" height="120" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="164" width="336" height="120" rx="6"/>
    <line class="fig-line-accent" x1="180" y1="94" x2="196" y2="94" marker-end="url(#os-c1-arr-16)"/>
    <line class="fig-line-accent" x1="352" y1="94" x2="368" y2="94" marker-end="url(#os-c1-arr-16)"/>
    <line class="fig-line-accent" x1="524" y1="94" x2="540" y2="94" marker-end="url(#os-c1-arr-16)"/>
    <rect class="fig-box-red" x="28" y="46" width="152" height="96" rx="4"/>
    <rect class="fig-box-orange" x="198" y="46" width="154" height="96" rx="4"/>
    <rect class="fig-box-blue" x="370" y="46" width="154" height="96" rx="4"/>
    <rect class="fig-box-green" x="542" y="46" width="150" height="96" rx="4"/>
    <rect class="fig-box-blue" x="30" y="196" width="76" height="32" rx="4"/>
    <rect class="fig-box-orange" x="148" y="196" width="76" height="32" rx="4"/>
    <rect class="fig-box-accent" x="266" y="196" width="76" height="32" rx="4"/>
    <line class="fig-line-accent" x1="106" y1="212" x2="146" y2="212" marker-end="url(#os-c1-arr-16)"/>
    <line class="fig-line-accent" x1="224" y1="212" x2="264" y2="212" marker-end="url(#os-c1-arr-16)"/>
    <rect class="fig-box" x="30" y="238" width="312" height="36" rx="4"/>
    <rect class="fig-box" x="380" y="194" width="312" height="26" rx="4"/>
    <rect class="fig-box-blue" x="380" y="224" width="312" height="26" rx="4"/>
    <rect class="fig-box-green" x="380" y="254" width="312" height="24" rx="4"/>
    <text class="fig-title" x="360" y="34" text-anchor="middle" font-size="11.5">CPU 虚拟化四条演进路线（围绕“敏感但不特权指令”破局）</text>
    <g text-anchor="middle" font-size="9.5">
      <text class="fig-red" x="104" y="65" font-size="10.5">① 陷入-模拟</text>
      <text class="fig-label" x="104" y="84">敏感⊆特权才自动成立</text>
      <text class="fig-muted" x="104" y="102">若遇“敏感但非特权”指令</text>
      <text class="fig-muted" x="104" y="120">不陷入也不报错→静默失效</text>
      <text class="fig-orange" x="275" y="65" font-size="10.5">② 二进制翻译</text>
      <text class="fig-label" x="275" y="84">执行前扫描并重写指令流</text>
      <text class="fig-muted" x="275" y="102">Guest 无感 · 可跑闭源 OS</text>
      <text class="fig-muted" x="275" y="120">代价：翻译与缓存开销</text>
      <text class="fig-blue" x="447" y="65" font-size="10.5">③ 半虚拟化</text>
      <text class="fig-label" x="447" y="84">修改 Guest OS 源代码</text>
      <text class="fig-muted" x="447" y="102">敏感操作改显式 Hypercall</text>
      <text class="fig-muted" x="447" y="120">局限：闭源系统无法修改</text>
      <text class="fig-green" x="617" y="65" font-size="10.5">④ 硬件辅助 VT-x</text>
      <text class="fig-label" x="617" y="84">Root / Non-Root 两套环</text>
      <text class="fig-muted" x="617" y="102">硬件直发 VM Exit 进 VMM</text>
      <text class="fig-muted" x="617" y="120">根治敏感非特权难题</text>
    </g>
    <text class="fig-title" x="186" y="184" text-anchor="middle" font-size="11">内存虚拟化：GVA → GPA → HPA 三层映射</text>
    <g text-anchor="middle" font-size="9.5">
      <text class="fig-blue" x="68" y="216">GVA (虚)</text>
      <text class="fig-muted" x="126" y="203" font-size="9.5">Guest</text>
      <text class="fig-orange" x="186" y="216">GPA (假物)</text>
      <text class="fig-muted" x="244" y="203" font-size="9.5">VMM</text>
      <text class="fig-accent" x="304" y="216">HPA (真物)</text>
      <text class="fig-label" x="186" y="253">影子页表：VMM 软件合成（改页表时同步开销）</text>
      <text class="fig-muted" x="186" y="268">EPT/NPT：MMU 硬件两级走（TLB 未命中时分摊开销）</text>
    </g>
    <text class="fig-title" x="536" y="184" text-anchor="middle" font-size="11">I/O 虚拟化三条路线（性能由低到高）</text>
    <g text-anchor="middle" font-size="9.5">
      <text class="fig-label" x="536" y="211">① 全模拟（软件仿真物理网卡，兼容最广但频繁陷入最慢）</text>
      <text class="fig-blue" x="536" y="241">② 半虚拟化 virtio（Guest 专用驱动 + 共享环形队列批量传）</text>
      <text class="fig-green" x="536" y="270">③ 设备直通（SR-IOV + ★ IOMMU 为 DMA 译 GPA→HPA）</text>
    </g>
  </svg>
  <figcaption>图 1-16　CPU 虚拟化四条路线、内存 GVA→GPA→HPA 双阶方案与 I/O 虚拟化三路径汇总</figcaption>
</figure>

---

### 1.9 本章 408 核心真题索引与易错点总览

| 真题年份与题号 | 考察知识点 | 一句话秒杀结论 / 易错警示 |
| --- | --- | --- |
| `09#23` / `18#23` | 并发与并行的对象界定 | 单核可让进程并发，同时 **CPU 与外设/DMA/通道之间可并行**；多核是“进程间并行”的条件，并非“多任务 OS 必具多 CPU” |
| `10#23` / `19#25` | 系统调用与库函数边界 | OS 给应用的接口是**系统调用**（不是库函数）；**跨 OS 统一的是库函数层**，不同 OS 系统调用接口并不统一 |
| `11#24` | 判断程序运行的 CPU 模式 | 看访问什么资源：**命令解释程序（shell）在用户态**，缺页处理/调度/时钟中断在内核态 |
| `12#23` | 中断 vs 子程序调用保存内容 | 子程序调用仅保存 `PC`；中断响应与系统调用需保存 `PC` 与 `PSW` |
| `12#28` / `17#24` | 系统调用参数与执行顺序 | 顺序：**传参（必须在陷入前！）→ 执行陷入指令 → 内核服务例程 → 返回用户态**；`read` 传 `fd` 不传文件名 |
| `13#28` / `15#24` | 导致态切换的指令判断 | 只有**不访存、不引发算术异常的纯寄存器操作**（如 `NOT R0`）绝不切态；访存指令可能缺页而切态 |
| `13#29` / `21#46` / `22#24` | OS 引导与启动盘制作 | OS 最终加载进 **RAM**；引导链 `ROM(BIOS)→MBR→PBR→OS初始化`；制盘 `物理格式化→分区→逻辑格式化→装OS`；**IVT 在 RAM 每次开机重建** |
| `14#25` / `21#23` / `22#27` | 特权指令与运行模式 | `关中断`、`I/O指令`、`iret` 是特权指令；`trap`（陷入指令）**不是特权指令**；用户态只能执非特权指令，内核态可执行**全部**指令 |
| `16#23` / `16#24` / `17#28` / `22#23` | 批处理与多道程序边界 | 批处理无交互；多道**系统开销更大**；进程数超内存极限后**抖动使 CPU 利用率下降**；多作业最短耗时用**瓶颈资源公式** |
| `21#32` / `22#31` / `23#26` | 系统调用判定与软硬件分工 | 页置换与调度不是用户发起的系统调用；**硬件存断点与切模式位**，**OS 存通用寄存器与执行服务**；系统调用返回时内核态→用户态 |
| `23#23` / `24#23` / `25#24` | 内核架构、中断时刻与虚拟机 | 微内核以**性能下降**换高可靠/安全/扩展；中断**发生时通常仍用户态**、处理开始时必内核态；**VMM 特权级严格高于 Guest OS** |

## 第2章 进程与线程管理

### 2.1 进程的概念、组成与特征

#### 2.1.1 从静态程序到动态进程：为何必须引入进程

操作系统核心设计哲学之一是**虚拟化**——用软件把单一或有限的物理硬件包装成“每个应用独占硬件”的假象。在 CPU 维度上，机器往往只有少数几个甚至一个处理机核心，却要同时服务上百个运行中的程序。操作系统通过时间片轮转与快速切换编织出“每个程序独占一个虚拟 CPU”的幻觉，而这个被虚拟出来的动态执行实体，正是**进程（Process）**。

从逻辑演进看，进程是被**并发执行**逼出来的产物：

1. **单道程序时代**：内存中只有一个程序，它独占全部硬件资源从头跑到尾，执行过程具备**封闭性**（运行结果仅由自身逻辑与输入决定，不受外界干扰）和**可再现性**（给定相同输入，无论何时重跑，结果必定一致）。
2. **多道并发时代**：内存中同时驻留多个程序，CPU 交替执行它们的指令。由于共享内存或全局变量可能被其他程序插队修改，程序丧失了封闭性，进而丧失了可再现性。

例如，设共享变量初值 $N = 5$，程序 A 循环执行语句 `N = N + 1`（编译为“读 $N$ 到寄存器 `R1` → `R1` 加 1 → 写回 $N$”三条机器指令），程序 B 循环执行 `print(N); N = 0;`。在单 CPU 交替执行下，若时钟中断发生的位置不同：
- 若调度次序为“A 完整执行 3 条指令 → B 打印并清零”，则打印输出 `6`，最终 $N = 0$；
- 若调度次序为“A 刚读完 `N=5` 并算出 `R1=6` 尚未写回 → 切换到 B 打印 `5` 并置 `N=0` → 切回 A 执行写回”，则打印输出 `5`，最终 $N = 6$。

同一段代码、同一组初始输入，仅仅因为并发调度时机不同便产生了截然不同的结果。**静态的程序（指令与数据的有序集合）既无法预知并发推进轨迹，也无法保存被中断时的现场信息**。把“程序”比作静止在桌面上的菜谱，无论在 0 秒还是 30 秒拍照，菜谱本身毫无变化；而“进程”则是厨师照着菜谱炒菜的动态过程，在不同时刻处于切菜、下锅、翻炒等不同状态，还必须记录火候、已加调料与临时碗碟位置。为此，系统必须为每一次执行实例建立一个专用的管理结构——**进程控制块（PCB）**，由此诞生了“进程”的概念。

#### 2.1.2 进程实体（进程映像）的组成与 PCB 结构

> **★考点**：<strong>进程实体（进程映像）</strong>由**程序段、数据段和 PCB** 三部分组成；**PCB 是进程存在的唯一标志**（`2010#24`、`2021#24`、`2024#24` 均以此为底层依据）。

1. **三大部分的分工与空间归属**：
   - **程序段（Text）**：存放经过编译链接形成的二进制机器指令序列，供 CPU 取指执行；内容只读，运行同一程序的多个进程可共享同一份程序段。
   - **数据段（Data / BSS）**：存放程序运行过程中使用的原始数据与产生的各种中间变量（如全局/静态变量、工作区等）；每个进程各自独立一份。
   - **进程控制块（PCB，Process Control Block）**：系统为描述和控制进程运行而专门设置的数据结构，常驻**内核空间**。OS 依靠 PCB 感知、调度并管理进程；创建进程实质就是创建并初始化其 PCB，撤销进程实质就是回收资源并删除其 PCB。

> **注意**：教材表述存在两处细节差异需打通辨析：
> 1. **进程映像的构成**：汤小丹《计算机操作系统》将进程实体定义为 **PCB + 程序段 + 数据段**；孙钟秀《操作系统教程》将进程映像拆为 **PCB + 进程数据块 + 进程核心栈**（程序块单列）。**核心栈**是每个进程在内核态执行（保存中断/系统调用现场及内核函数栈帧）时专用的私有栈，归属进程自身且位于内核空间。因此判断“进程在内核态执行时使用的栈属于该进程”时为**正确**。
> 2. **进程 vs 进程实体**：严格来说，**进程实体（进程映像）是静态的**，相当于进程在某一瞬间的状态快照；**进程是动态的**，是进程实体的执行过程。除非题目专门辨析二者动静属性，一般可认为“进程实体即进程在内存中的存在形态”。

2. **PCB 的四大类核心信息**（由操作系统对进程的四项基本管理动作直接推出）：

| 操作系统要做的事 | 对应 PCB 信息类别 | 典型字段内容 | 备注与真题关联 |
| --- | --- | --- | --- |
| ① 在众多进程中唯一**认出**它及家族关系 | **进程描述（标识）信息** | 内部标识符 **PID**（数字进程号）、外部标识符（进程名）、父进程标识 **PPID**、子进程标识、用户标识 **UID** | 同一程序运行 3 次会分配 3 个互异的 PID（如 Linux `task_struct` 中的 `pid`） |
| ② 让进程**停下后能接着跑**（间断性运行） | **处理机状态信息（上下文）** | 通用寄存器（`AX`–`DX`）、程序计数器 **PC**、程序状态字 **PSW**、用户栈指针 **SP** | **只有这一类信息在上下文切换时必须从 CPU 搬进 PCB 保存、再从 PCB 恢复** |
| ③ 决定**下一个轮到谁**占用 CPU | **进程调度信息** | 进程当前状态 `state`（就绪/阻塞/运行）、优先级、已运行时间、剩余时间片、阻塞原因（所等事件） | 调度器据 `state` 与优先级选人并修改 `state` |
| ④ 找到代码数据位置并管理其**全部资源** | **进程控制与资源信息** | 程序段与数据段内存/外存首址、页表指针、打开文件表 `files`、I/O 设备清单、同步通信机制（信号量/消息队列指针）、队列链接指针 `next` | 孙钟秀教材将③④合并统称为“控制信息”（三类分法：标识、现场、控制） |

<figure class="cpd-figure not-content" id="os-c2-fig-1">
  <svg viewBox="0 0 720 318" role="img" aria-label="进程实体三部分组成与同一程序多开对应多个独立进程实体对比图">
    <defs>
      <marker id="os-c2-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="318" height="290" rx="8"/>
    <rect class="fig-box-subtle" x="348" y="14" width="356" height="290" rx="8"/>
    <rect class="fig-box-dashed" x="28" y="44" width="294" height="88" rx="6"/>
    <rect class="fig-box-dashed" x="28" y="154" width="294" height="138" rx="6"/>
    <line class="fig-line-dashed" x1="24" y1="143" x2="326" y2="143"/>
    <line class="fig-line-accent" x1="466" y1="90" x2="413" y2="122" marker-end="url(#os-c2-arr-1)"/>
    <line class="fig-line-accent" x1="526" y1="90" x2="526" y2="122" marker-end="url(#os-c2-arr-1)"/>
    <line class="fig-line-accent" x1="586" y1="90" x2="639" y2="122" marker-end="url(#os-c2-arr-1)"/>
    <rect class="fig-box-purple" x="34" y="66" width="282" height="54" rx="5"/>
    <rect class="fig-box-blue" x="34" y="176" width="282" height="34" rx="5"/>
    <rect class="fig-box-green" x="34" y="216" width="282" height="34" rx="5"/>
    <rect class="fig-box-orange" x="34" y="256" width="282" height="28" rx="5"/>
    <rect class="fig-box" x="108" y="133" width="134" height="18" rx="3"/>
    <rect class="fig-box" x="362" y="44" width="328" height="46" rx="5"/>
    <rect class="fig-box" x="360" y="124" width="106" height="166" rx="6"/>
    <rect class="fig-box" x="473" y="124" width="106" height="166" rx="6"/>
    <rect class="fig-box" x="586" y="124" width="106" height="166" rx="6"/>
    <rect class="fig-box-purple" x="364" y="150" width="98" height="32" rx="4"/>
    <rect class="fig-box-blue" x="364" y="188" width="98" height="28" rx="4"/>
    <rect class="fig-box-green" x="364" y="222" width="98" height="28" rx="4"/>
    <rect class="fig-box-orange" x="364" y="256" width="98" height="26" rx="4"/>
    <rect class="fig-box-purple" x="477" y="150" width="98" height="32" rx="4"/>
    <rect class="fig-box-blue" x="477" y="188" width="98" height="28" rx="4"/>
    <rect class="fig-box-green" x="477" y="222" width="98" height="28" rx="4"/>
    <rect class="fig-box-orange" x="477" y="256" width="98" height="26" rx="4"/>
    <rect class="fig-box-purple" x="590" y="150" width="98" height="32" rx="4"/>
    <rect class="fig-box-blue" x="590" y="188" width="98" height="28" rx="4"/>
    <rect class="fig-box-green" x="590" y="222" width="98" height="28" rx="4"/>
    <rect class="fig-box-orange" x="590" y="256" width="98" height="26" rx="4"/>
    <text class="fig-title" x="30" y="32" font-size="12.5">进程实体（进程映像）三部分组成</text>
    <text class="fig-muted" x="40" y="59" font-size="10.5">内核空间（常驻内存，用户态不可直接修改）</text>
    <text class="fig-purple" x="175" y="86" font-size="11.5" text-anchor="middle">★ PCB（进程控制块）：进程存在的唯一标志</text>
    <text class="fig-muted" x="175" y="105" font-size="9.2" text-anchor="middle">PID / 状态 / 寄存器现场 / 调度 / 资源清单 (+核心栈)</text>
    <text class="fig-label" x="175" y="146" font-size="10" text-anchor="middle">用户态 / 内核态隔离边界</text>
    <text class="fig-muted" x="40" y="169" font-size="10.5">用户空间（供本进程自身指令执行与数据读写）</text>
    <text class="fig-blue" x="175" y="197" font-size="10.5" text-anchor="middle">程序段（Text）：二进制指令序列（只读/可共享）</text>
    <text class="fig-green" x="175" y="237" font-size="10.5" text-anchor="middle">数据段（Data / BSS）：全局与静态变量（进程私有）</text>
    <text class="fig-orange" x="175" y="274" font-size="10.5" text-anchor="middle">动态区：堆（Heap）与用户栈（Stack）</text>
    <text class="fig-title" x="364" y="32" font-size="12.5">“一程序多实例”：同一程序对应多个独立进程</text>
    <text class="fig-label" x="526" y="63" font-size="11.5" text-anchor="middle">磁盘静态可执行文件 QQ.exe</text>
    <text class="fig-muted" x="526" y="80" font-size="10.5" text-anchor="middle">静态代码与初始数据模板（无 PID、无状态、不占用 CPU）</text>
    <text class="fig-title" x="413" y="142" font-size="11.5" text-anchor="middle">进程 1</text>
    <text class="fig-purple" x="413" y="170" font-size="9.5" text-anchor="middle">PCB 1 (PID=101)</text>
    <text class="fig-blue" x="413" y="206" font-size="9.5" text-anchor="middle">程序段 (相同)</text>
    <text class="fig-green" x="413" y="240" font-size="9.5" text-anchor="middle">数据段 1 (账号A)</text>
    <text class="fig-orange" x="413" y="273" font-size="9.5" text-anchor="middle">用户栈 1</text>
    <text class="fig-title" x="526" y="142" font-size="11.5" text-anchor="middle">进程 2</text>
    <text class="fig-purple" x="526" y="170" font-size="9.5" text-anchor="middle">PCB 2 (PID=102)</text>
    <text class="fig-blue" x="526" y="206" font-size="9.5" text-anchor="middle">程序段 (相同)</text>
    <text class="fig-green" x="526" y="240" font-size="9.5" text-anchor="middle">数据段 2 (账号B)</text>
    <text class="fig-orange" x="526" y="273" font-size="9.5" text-anchor="middle">用户栈 2</text>
    <text class="fig-title" x="639" y="142" font-size="11.5" text-anchor="middle">进程 3</text>
    <text class="fig-purple" x="639" y="170" font-size="9.5" text-anchor="middle">PCB 3 (PID=103)</text>
    <text class="fig-blue" x="639" y="206" font-size="9.5" text-anchor="middle">程序段 (相同)</text>
    <text class="fig-green" x="639" y="240" font-size="9.5" text-anchor="middle">数据段 3 (账号C)</text>
    <text class="fig-orange" x="639" y="273" font-size="9.5" text-anchor="middle">用户栈 3</text>
  </svg>
  <figcaption>图 2-1　进程实体（PCB + 程序段 + 数据段）跨空间构成与“一程序对应多进程”独立实体示意</figcaption>
</figure>

#### 2.1.3 进程的五大特征与“程序 vs 进程”辨析

进程的五大特征并非孤立词条，其中**前四大特征是一条严密的因果推导链**：

1. **★动态性（最基本特征）**：进程的实质是程序的一次执行过程，它由创建而产生、由调度而执行、由撤销而消亡，具有明确的生命周期；而程序只是静态指令集合。
2. **并发性**：正因为进程是动态执行实体，内存中才能同时驻留多个进程实体，并在一段时间内交替推进执行。未建立 PCB 的程序不能参与并发。
3. **独立性**：每个进程实体都能够**独立运行、独立获得资源、独立接受调度**（注：引入线程后，独立调度的基本单位转由线程承担，但进程仍为资源分配基本单位）。
4. **异步性**：各并发进程以各自独立、不可预知的速度向前推进（受时钟中断、I/O 等待与抢占影响），这正是并发失去可再现性的根源，也催生了后续的进程同步与互斥机制。
5. **结构性**：每个进程在物理/逻辑组成上都具备完整结构——由 **PCB + 程序段 + 数据段**（或含核心栈）构成。

<figure class="cpd-figure not-content" id="os-c2-fig-2">
  <svg viewBox="0 0 720 288" role="img" aria-label="并发异步性破坏封闭性与可再现性的交错示例及进程五大特征因果链">
    <defs>
      <marker id="os-c2-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="386" height="260" rx="8"/>
    <rect class="fig-box-subtle" x="416" y="14" width="288" height="260" rx="8"/>
    <line class="fig-line-accent" x1="528" y1="86" x2="528" y2="104" marker-end="url(#os-c2-arr-2)"/>
    <line class="fig-line-accent" x1="528" y1="142" x2="528" y2="160" marker-end="url(#os-c2-arr-2)"/>
    <line class="fig-line-accent" x1="528" y1="198" x2="528" y2="216" marker-end="url(#os-c2-arr-2)"/>
    <rect class="fig-box-blue" x="28" y="42" width="176" height="54" rx="5"/>
    <rect class="fig-box-orange" x="214" y="42" width="176" height="54" rx="5"/>
    <rect class="fig-box-green" x="28" y="108" width="362" height="70" rx="5"/>
    <rect class="fig-box-red" x="28" y="188" width="362" height="74" rx="5"/>
    <rect class="fig-box-accent" x="430" y="44" width="196" height="42" rx="5"/>
    <rect class="fig-box-blue" x="430" y="104" width="196" height="38" rx="5"/>
    <rect class="fig-box-green" x="430" y="160" width="196" height="38" rx="5"/>
    <rect class="fig-box-orange" x="430" y="216" width="196" height="42" rx="5"/>
    <rect class="fig-box-purple" x="632" y="88" width="64" height="140" rx="5"/>
    <text class="fig-title" x="28" y="32" font-size="12.5">并发异步性如何破坏可再现性（设初值 N = 5）</text>
    <text class="fig-blue" x="116" y="61" font-size="11" text-anchor="middle">进程 A：N = N + 1</text>
    <text class="fig-muted" x="116" y="79" font-size="10" text-anchor="middle">①读N ②R1+1 ③写回N</text>
    <text class="fig-orange" x="302" y="61" font-size="11" text-anchor="middle">进程 B：输出后清零</text>
    <text class="fig-muted" x="302" y="79" font-size="10" text-anchor="middle">④print(N)  ⑤N = 0</text>
    <text class="fig-green" x="40" y="128" font-size="11.5">时序 ①（串行完整）：A①②③ → B④⑤</text>
    <text class="fig-label" x="40" y="148" font-size="10.5">A 将 N 改为 6 → B 打印 6 后将 N 置为 0</text>
    <text class="fig-muted" x="40" y="166" font-size="10.5">结果：输出 6，终值 N = 0（符合单道预期）</text>
    <text class="fig-red" x="40" y="208" font-size="11.5">时序 ②（中途被抢占）：A①② → B④⑤ → A③</text>
    <text class="fig-label" x="40" y="228" font-size="10.5">A 读 5 算得 6 未写回 → B 打印 5、置 N=0 → A 写回 6</text>
    <text class="fig-muted" x="40" y="248" font-size="10.5">结果：输出 5，终值 N = 6（失去封闭性与可再现性）</text>
    <text class="fig-title" x="430" y="32" font-size="12.5">进程五大特征的因果逻辑链</text>
    <text class="fig-accent" x="528" y="62" font-size="11.5" text-anchor="middle">① 动态性（最基本特征）</text>
    <text class="fig-muted" x="528" y="78" font-size="10" text-anchor="middle">创建 → 调度 → 消亡的生命周期</text>
    <text class="fig-blue" x="528" y="121" font-size="11.5" text-anchor="middle">② 并发性</text>
    <text class="fig-muted" x="528" y="136" font-size="10" text-anchor="middle">多实体同驻内存，宏观并行</text>
    <text class="fig-green" x="528" y="177" font-size="11.5" text-anchor="middle">③ 独立性</text>
    <text class="fig-muted" x="528" y="192" font-size="10" text-anchor="middle">独立获资源、独立运行与调度</text>
    <text class="fig-orange" x="528" y="234" font-size="11.5" text-anchor="middle">④ 异步性</text>
    <text class="fig-muted" x="528" y="250" font-size="10" text-anchor="middle">推进速度不可预知 → 需同步</text>
    <text class="fig-purple" x="664" y="120" font-size="11" text-anchor="middle">⑤</text>
    <text class="fig-purple" x="664" y="138" font-size="11" text-anchor="middle">结</text>
    <text class="fig-purple" x="664" y="156" font-size="11" text-anchor="middle">构</text>
    <text class="fig-purple" x="664" y="174" font-size="11" text-anchor="middle">性</text>
    <text class="fig-muted" x="664" y="198" font-size="9.5" text-anchor="middle">PCB +</text>
    <text class="fig-muted" x="664" y="214" font-size="9.5" text-anchor="middle">代码/数据</text>
  </svg>
  <figcaption>图 2-2　并发执行失去封闭性/可再现性的交错示例与进程五大特征因果链（动态性居首，结构性为载体）</figcaption>
</figure>

**程序与进程的全面辨析**：

| 比较维度 | 程序（Program） | 进程（Process） |
| --- | --- | --- |
| **本质属性** | **静态的**、永久的指令与数据有序集合（如磁盘上的 `.exe`） | **动态的**、暂时的执行过程，有创建、执行与撤销的生命周期 |
| **存在标志** | 磁盘上的可执行文件 | 内存中的 **PCB**（创建即生成，消亡即撤销） |
| **资源占有** | 不直接占有运行时资源（只占外存存储空间） | 系统进行**资源分配**的基本单位（拥有地址空间、打开文件、I/O 设备等） |
| **并发能力** | 本身被动，不能直接参与并发 | 可以并发执行，各进程异步推进 |
| **数量对应关系** | **一程序多进程**：同一代码可同时运行出多个独立进程（如三开 QQ） | **一进程多程序**：进程运行时可加载多个动态链接库（`.so`/`.dll`），或先后执行不同程序（`exec`） |

---

### 2.2 进程运行时内存映像与地址空间 ★

#### 2.2.1 逻辑地址空间与物理地址空间、用户空间与内核空间隔离

编译程序并生成可执行文件时，指令里的跳转目标（`jmp`）与取数地址（`mov`）必须在装入内存前就确定下来；但多道并发环境下，程序每次被加载进物理内存的起始位置都不可预知。操作系统通过**虚拟地址空间**化解这一矛盾——对每个进程撒一个漂亮的谎：“你从 `0` 地址开始独占了一整块连续内存。”

| 概念 | 定义 | 规模决定因素 | 可见性与归属 |
| --- | --- | --- | --- |
| **逻辑地址（虚拟地址）** | 程序地址空间内相对基准（通常为 `0`）连续编号的地址 | CPU 产生的指令与操作数地址，需要经 MMU 翻译 | 用户程序全程可见 |
| **物理地址（绝对地址）** | 主存芯片上真实的存储单元编号 | 送上地址总线、直接选中物理内存单元 | 仅内核与硬件 MMU 直接操作 |
| **逻辑地址空间** | 单个进程全部合法逻辑地址的集合 | **$n$ 位地址 $\Rightarrow 2^{n}$ B**（如 32 位为 4 GB；64 位常用 48 位 = 256 TB） | **每个进程各自一份、互不可见** |
| **物理地址空间** | 机器全部物理内存单元的地址集合 | **取决于实际安装的主存容量**（如插 2 GB 内存条则只有 2 GB） | 全机唯一共享 |

> **★考点**：32 位系统即便只装了 2 GB 物理内存，每个进程的逻辑地址空间依然是 $2^{32}\text{ B} = 4\text{ GB}$。正因为逻辑地址空间可以远大于物理内存，才催生了第 3 章的虚拟存储管理。

以经典的 **32 位 Linux** 为例，4 GB（`0x00000000`～`0xFFFFFFFF`）虚拟地址空间被划分为两段：
- **用户空间（低 3 GB，`0x00000000`～`0xBFFFFFFF`）**：用户态和内核态均可访问，存放本进程自己的代码、数据、堆、共享库与用户栈。不同进程的用户空间映射到彼此不交叠的物理页框，实现严格内存隔离。
- **内核空间（高 1 GB，`0xC0000000`～`0xFFFFFFFF`）**：**仅内核态可访问**（用户态直接访问将触发段错误/保护异常），存放操作系统代码（调度器、中断服务程序、系统调用处理函数）、内核数据结构以及**所有进程的 PCB 与页表**。

> **★考点（内核空间的共享与免切换原理）**：为什么每个进程的虚拟地址空间顶部都要映入 1 GB 内核空间？
> 1. **操作系统不是一个独立的进程**，而是作为被所有进程共享的内核代码与数据集合存在；中断或系统调用发生后，CPU 的 `PC` 仍按当前虚拟地址空间取指，因此内核例程必须落在当前进程的高位虚拟地址内。
> 2. **省去进出内核时的地址空间切换**：所有进程高 1 GB 内核空间中的绝大部分区域都映射到**同一份物理内存**。当进程陷入内核态处理系统调用或中断时，无需更换页表基址寄存器，也无需刷新快表（TLB），只需靠页表项中的<strong>特权级位（U/S 位）</strong>阻止用户态非法越权访问即可。

#### 2.2.2 进程虚拟内存映像逐段解析与 C 语言对象定位 ★

一个可执行文件装入内存后形成**进程运行时内存映像**，绝非文件内容的简单拷贝：几 KB 的可执行文件在内存中可能占据数 MB（BSS 段展开），文件中不存在的堆与栈在运行后动态开辟并相向生长。

<figure class="cpd-figure not-content" id="os-c2-fig-3">
  <svg viewBox="0 0 720 404" role="img" aria-label="32位进程虚拟地址空间分布、C语言对象定位与函数调用栈帧结构图">
    <defs>
      <marker id="os-c2-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="336" height="378" rx="8"/>
    <rect class="fig-box-subtle" x="366" y="14" width="338" height="378" rx="8"/>
    <line class="fig-line-accent" x1="208" y1="126" x2="208" y2="148" marker-end="url(#os-c2-arr-3)"/>
    <line class="fig-line-accent" x1="208" y1="224" x2="208" y2="202" marker-end="url(#os-c2-arr-3)"/>
    <line class="fig-divider" x1="88" y1="44" x2="92" y2="44"/>
    <line class="fig-divider" x1="88" y1="91" x2="92" y2="91"/>
    <line class="fig-divider" x1="88" y1="362" x2="92" y2="362"/>
    <line class="fig-divider" x1="88" y1="384" x2="92" y2="384"/>
    <rect class="fig-box-purple" x="92" y="44" width="244" height="44" rx="5"/>
    <rect class="fig-box-orange" x="92" y="94" width="244" height="38" rx="5"/>
    <rect class="fig-box-blue" x="92" y="152" width="244" height="44" rx="5"/>
    <rect class="fig-box-orange" x="92" y="218" width="244" height="38" rx="5"/>
    <rect class="fig-box-green" x="92" y="262" width="244" height="30" rx="5"/>
    <rect class="fig-box-green" x="92" y="296" width="244" height="30" rx="5"/>
    <rect class="fig-box-accent" x="92" y="330" width="244" height="30" rx="5"/>
    <rect class="fig-box" x="92" y="364" width="244" height="20" rx="3"/>
    <rect class="fig-box-purple" x="378" y="44" width="314" height="30" rx="4"/>
    <rect class="fig-box-orange" x="378" y="78" width="314" height="30" rx="4"/>
    <rect class="fig-box-green" x="378" y="112" width="314" height="30" rx="4"/>
    <rect class="fig-box-orange" x="378" y="146" width="314" height="30" rx="4"/>
    <rect class="fig-box-accent" x="378" y="180" width="314" height="44" rx="4"/>
    <rect class="fig-box" x="378" y="238" width="314" height="146" rx="5"/>
    <line class="fig-divider" x1="390" y1="286" x2="680" y2="286"/>
    <line class="fig-divider" x1="390" y1="310" x2="680" y2="310"/>
    <line class="fig-divider" x1="390" y1="334" x2="680" y2="334"/>
    <line class="fig-divider" x1="390" y1="358" x2="680" y2="358"/>
    <text class="fig-title" x="30" y="32" font-size="12.5">32 位 Linux 虚拟地址空间（4 GB）</text>
    <text class="fig-muted" x="86" y="48" font-size="9.5" text-anchor="end">0xFFFFFFFF</text>
    <text class="fig-muted" x="86" y="94" font-size="9.5" text-anchor="end">0xC0000000</text>
    <text class="fig-muted" x="86" y="365" font-size="9.5" text-anchor="end">0x08048000</text>
    <text class="fig-muted" x="86" y="387" font-size="9.5" text-anchor="end">0x00000000</text>
    <text class="fig-purple" x="214" y="64" font-size="11.5" text-anchor="middle">内核空间 1 GB（共享物理内核）</text>
    <text class="fig-muted" x="214" y="81" font-size="10" text-anchor="middle">PCB / 页表 / 内核代码 · 用户态不可访问</text>
    <text class="fig-orange" x="214" y="111" font-size="11" text-anchor="middle">用户栈 Stack（向下生长 ↓ ESP）</text>
    <text class="fig-muted" x="214" y="126" font-size="10" text-anchor="middle">局部自动变量 / 实参 / 返回地址</text>
    <text class="fig-blue" x="214" y="171" font-size="11" text-anchor="middle">共享库 / mmap 内存映射区</text>
    <text class="fig-muted" x="214" y="188" font-size="10" text-anchor="middle">动态库 .so / 匿名与文件映射 / 共享内存</text>
    <text class="fig-orange" x="214" y="234" font-size="11" text-anchor="middle">堆 Heap（向上生长 ↑ brk）</text>
    <text class="fig-muted" x="214" y="249" font-size="10" text-anchor="middle">malloc / new 动态申请（需手动 free）</text>
    <text class="fig-green" x="214" y="281" font-size="10" text-anchor="middle">BSS 段：未初始化全局/静态变量（装入清零）</text>
    <text class="fig-green" x="214" y="315" font-size="10" text-anchor="middle">Data 段：已初始化全局/静态变量（文件存初值）</text>
    <text class="fig-accent" x="214" y="349" font-size="10" text-anchor="middle">Text + .rodata：只读代码与 const 只读数据</text>
    <text class="fig-muted" x="214" y="378" font-size="9.5" text-anchor="middle">低地址保留未分配区（空指针保护）</text>
    <text class="fig-title" x="378" y="32" font-size="12.5">★ C 语言对象落区速判（对标 2025#46）</text>
    <text class="fig-purple" x="390" y="63" font-size="11">进程 PCB (task_struct) → 内核空间（OS 私有）</text>
    <text class="fig-orange" x="390" y="97" font-size="11">局部变量 int len / 形参 → 用户栈（Stack）</text>
    <text class="fig-green" x="386" y="131" font-size="10.2">全局指针 char *ptr; / static → 数据段（Data/BSS）</text>
    <text class="fig-orange" x="390" y="165" font-size="11">ptr = malloc(100) 所指空间 → 堆（Heap）</text>
    <text class="fig-accent" x="390" y="198" font-size="10.5">main() / const int c → 只读代码/只读数据区</text>
    <text class="fig-muted" x="390" y="216" font-size="10">#define X 1024 宏常量预编译为指令立即数，不单占变量区</text>
    <text class="fig-title" x="390" y="256" font-size="11.5">单次函数调用栈帧结构（高地址 → 低地址）</text>
    <text class="fig-label" x="535" y="278" font-size="10.5" text-anchor="middle">调用者传入的实参（第 n 个 → 第 1 个）</text>
    <text class="fig-red" x="535" y="302" font-size="10.5" text-anchor="middle">返回地址 RA（call 指令下一条 PC · 溢出高危靶点）</text>
    <text class="fig-blue" x="535" y="326" font-size="10.5" text-anchor="middle">保存调用者旧栈帧基址 EBP（当前 EBP 所指）</text>
    <text class="fig-label" x="535" y="350" font-size="10.5" text-anchor="middle">被调用者保存寄存器 + 本函数局部变量（ESP 栈顶）</text>
    <text class="fig-muted" x="535" y="375" font-size="10" text-anchor="middle">LIFO 整帧压入与弹出 · 无外部碎片 · 分配开销 O(1)</text>
  </svg>
  <figcaption>图 2-3　32 位虚拟地址空间各分段特征、C 程序对象落区速判（2025#46）与函数调用栈帧内部布局</figcaption>
</figure>

各分段核心特性与考题辨析汇总如下：

| 内存区域 | 内容来源与典型 C 对象 | 可执行文件占空间？ | 读写执行权限 | 大小变化与增长方向 |
| --- | --- | --- | --- | --- |
| **代码段（Text）** | 编译后的机器指令（含 `main()` 等函数）；`#define X 1024` 宏常量经预编译替换成指令中的**立即数**，不单独分配变量内存 | **占** | 只读、可执行 | 固定 |
| **只读数据区（`.rodata`）** | `const` 修饰的常变量（如 `const int c = 10`）、字符串字面量（`"hello"`） | **占** | 只读 | 固定 |
| **已初始化数据段（Data）** | 有显式非零初值的全局变量、静态变量（`static`） | **占**（需存初值） | 可读可写 | 固定 |
| **未初始化数据段（BSS）** | 未赋初值或初始化为 0 的全局/静态变量（如 `int b[1000000];`） | **不占正文空间**（文件只记段长，装入时清零） | 可读可写 | 固定（这就是几 KB 可执行文件运行后占数 MB 内存的原因） |
| **堆（Heap）** | 运行时由 `malloc`/`new` 动态申请、须显式 `free`/`delete` 释放 | 不占 | 可读可写 | 动态增减，**向高地址增长**（经空闲块链表搜索，有内部/外部碎片） |
| **共享库 / `mmap` 映射区** | 动态链接库（如 `printf` 所在的 `.so`/`.dll`）、`mmap` 映射文件及匿名共享内存 | 不占（只记依赖库名） | 按段属性而定 | 动态映射变动 |
| **用户栈（Stack）** | 函数实参、返回地址、旧 `EBP`、局部变量（若未放入寄存器） | 不占 | 可读可写 | 动态增减，**向低地址增长**（移动栈指针 $O(1)$，严格 LIFO，无碎片） |
| **内核空间（Kernel）** | OS 内核代码与数据、页表、各进程 **PCB** 及进程核心栈 | — | 仅内核态可读写执行 | 系统启动及动态内核态分配 |

> **★考点（`2025#46` 8 分真题精析）**：给出一份虚拟地址空间图与包含全局指针 `char *ptr;`、局部变量 `int length;` 和 `ptr = (char *)malloc(100);` 的 C 程序：
> 1. **PCB 位于内核空间**：PCB 是 OS 的私有管理数据结构，用户进程无权直接访问或修改。
> 2. **指针变量本身 vs 指针指向的内容**：全局指针变量 `ptr`（占用 4 B 或 8 B 存地址值）位于**读写数据段（Data/BSS）**，而 `malloc(100)` 分配出的 100 字节空间位于**堆区（Heap）**——这是极高频易错点。
> 3. **局部自动变量 `length`** 若未分配在通用寄存器中，则存放在**用户栈（Stack）**。
> 4. **堆栈为何相向增长**：堆与栈的大小在运行前均无法预知，将两者置于共享空闲区两端并相向增长，避免各自划定死上限造成的空间浪费，直到两者之和耗尽中间空闲区时才发生溢出。
> 5. **数据结构“堆” vs 内存“堆”**：前者是按优先级组织的完全二叉树（二叉堆），后者是无序动态分配的内存区域，二者英文均为 Heap 但毫无关联。

#### 2.2.3 动态地址重定位、越界保护与进程地址创建（`fork` / `exec` / COW）

1. **地址重定位与硬件越界保护**：
   - **静态重定位**：在程序装入内存时由装入程序一次性将指令中的相对地址改写为物理地址；**无需硬件支持，但程序装入后无法在内存中移动**。
   - **动态重定位**：程序在内存中仍保留逻辑地址，每次 CPU 访存时由硬件 **MMU（内存管理单元）** 实时将逻辑地址变换为物理地址；允许程序换出后移入不同物理地址，便于共享。
   - **两套保护机制的检查顺序与对象（极易搞反！）**：
     - **基址 + 界地址寄存器**（现代动态重定位与分页均采用此逻辑）：**先对逻辑地址做越界检查（`逻辑地址 < 界地址`），合法后再加基址变换为物理地址**。若越界（`逻辑地址 ≥ 界地址`），硬件立刻中止变换并触发**地址越界异常**（程序性中断事件），由 OS **终止该进程**；切不可在越界时“顺手算出”一个物理地址，否则可能指向其他进程空间。
     - **上下限（界限）寄存器**：早期连续分配机制，检查的是变换后的**物理地址**是否落在 `[下限, 上限]` 内；程序换出重装时需修改两个寄存器，且非法地址在变换后才被拦截。

> **注意**：在**分页存储管理**下，检查逻辑不变但计量单位由“字节数”降至“页表项个数”——先比较 **`页号 P < 页表长度 M`**（$M$ 为页表项数，非页表字节数！），通过后再查页表拼物理地址。越界属于不可恢复异常，处理原则是**终止进程**；同一步检测到的**缺页异常**则是可恢复故障，调入页面后**重新执行**原指令。

<figure class="cpd-figure not-content" id="os-c2-fig-4">
  <svg viewBox="0 0 720 278" role="img" aria-label="硬件动态地址重定位先检查逻辑地址越界后变换地址流程与上下限寄存器对比图">
    <defs>
      <marker id="os-c2-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="160" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="184" width="688" height="80" rx="8"/>
    <line class="fig-line-accent" x1="126" y1="104" x2="174" y2="104" marker-end="url(#os-c2-arr-4)"/>
    <line class="fig-line" x1="256" y1="74" x2="256" y2="84" marker-end="url(#os-c2-arr-4)"/>
    <line class="fig-line-accent" x1="336" y1="104" x2="404" y2="104" marker-end="url(#os-c2-arr-4)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="256" y1="124" x2="256" y2="142"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="256" y1="142" x2="352" y2="142" marker-end="url(#os-c2-arr-4)"/>
    <line class="fig-line" x1="450" y1="74" x2="450" y2="84" marker-end="url(#os-c2-arr-4)"/>
    <line class="fig-line-accent" x1="496" y1="104" x2="554" y2="104" marker-end="url(#os-c2-arr-4)"/>
    <rect class="fig-box-blue" x="28" y="84" width="98" height="40" rx="5"/>
    <rect class="fig-box" x="190" y="44" width="132" height="30" rx="4"/>
    <rect class="fig-box-accent" x="176" y="84" width="160" height="40" rx="5"/>
    <rect class="fig-box-red" x="354" y="130" width="218" height="34" rx="5"/>
    <rect class="fig-box" x="382" y="44" width="136" height="30" rx="4"/>
    <rect class="fig-box-green" x="406" y="84" width="88" height="40" rx="5"/>
    <rect class="fig-box-green" x="556" y="84" width="134" height="40" rx="5"/>
    <rect class="fig-box-orange" x="30" y="212" width="318" height="42" rx="5"/>
    <rect class="fig-box-purple" x="366" y="212" width="324" height="42" rx="5"/>
    <text class="fig-title" x="28" y="33" font-size="11.8">① 基址 + 界地址寄存器（MMU 硬件动态重定位：先查逻辑地址，后做变换）</text>
    <text class="fig-blue" x="77" y="102" font-size="11" text-anchor="middle">CPU 送出</text>
    <text class="fig-muted" x="77" y="117" font-size="10" text-anchor="middle">逻辑地址 LA</text>
    <text class="fig-label" x="256" y="63" font-size="10.5" text-anchor="middle">界地址寄存器 (限长 L)</text>
    <text class="fig-accent" x="256" y="102" font-size="11" text-anchor="middle">比较器：LA &lt; L ?</text>
    <text class="fig-muted" x="256" y="117" font-size="9.5" text-anchor="middle">① 越界检查先于变换</text>
    <text class="fig-green" x="368" y="98" font-size="10" text-anchor="middle">是(合法)</text>
    <text class="fig-red" x="292" y="137" font-size="10" text-anchor="middle">否(≥ L)</text>
    <text class="fig-red" x="463" y="145" font-size="10.5" text-anchor="middle">触发地址越界异常（中止变换）</text>
    <text class="fig-muted" x="463" y="159" font-size="9.5" text-anchor="middle">陷入内核 → OS 终止该进程</text>
    <text class="fig-label" x="450" y="63" font-size="10.5" text-anchor="middle">重定位(基址)寄存器 B</text>
    <text class="fig-green" x="450" y="102" font-size="11" text-anchor="middle">加法器</text>
    <text class="fig-muted" x="450" y="117" font-size="10" text-anchor="middle">PA = B + LA</text>
    <text class="fig-green" x="623" y="102" font-size="11" text-anchor="middle">物理地址 PA</text>
    <text class="fig-muted" x="623" y="117" font-size="10" text-anchor="middle">送上总线访问主存</text>
    <text class="fig-title" x="30" y="203" font-size="11.5">② 机制与分页对照</text>
    <text class="fig-orange" x="189" y="230" font-size="11" text-anchor="middle">上下限（界限）寄存器：查变换后的物理地址</text>
    <text class="fig-muted" x="189" y="246" font-size="10" text-anchor="middle">检查 PA ∈ [下限, 上限]；重装移动需改两个寄存器</text>
    <text class="fig-purple" x="528" y="230" font-size="11" text-anchor="middle">分页管理下等价检查：页号 P &lt; 页表长度 M</text>
    <text class="fig-muted" x="528" y="246" font-size="10" text-anchor="middle">M 以表项个数计（非字节数）；合法后再查页表项</text>
  </svg>
  <figcaption>图 2-4　动态地址重定位“先检查逻辑地址越界、后进行地址变换”硬件链路与保护机制对照</figcaption>
</figure>

2. **`fork`、`exec`、`wait` 与写时复制（COW）语义**：
   - **`pid_t fork(void)`**：以**复制调用进程**的方式创建子进程。调用成功后，父子进程各自从 `fork()` 返回处继续并发执行，但返回值不同：父进程返回子进程 PID（`&gt; 0`），子进程返回 `0`，失败在父进程返回 `-1`。
     - **复制项**：子进程获得父进程虚拟地址空间（代码、数据、堆、栈）的**独立副本**（不是共享！`2020#29`）、PCB 中除标识符外绝大部分信息、以及打开文件的**文件描述符表**。
     - **独立项**：全新分配的 `PID`、`PPID`（指向父进程）以及 CPU 时间统计、未决信号集等。
     - **共享项**：由于只复制了描述符表项而非底层系统打开文件表，父子进程指向同一打开文件表项，从而**共享打开文件的当前读写偏移量（位置）**。
   - **写时复制（COW，Copy-On-Write）**：真把父进程整个地址空间拷一遍既慢又浪费——尤其是 `fork` 后子进程常立刻调用 `exec`。现代 OS 在 `fork` 时先让父子进程的页表指向**同一批物理页框**并将页表项统一标为**只读（Read-Only）**；直到父或子进程尝试写入某页时触发页保护异常，内核才真正复制该物理页到新页框并恢复各自页表项为**可写**，其余未修改页（如代码段）继续共享。
   - **`exec` 系列调用**：**不创建新进程**，而是在当前进程壳内用新程序的代码段、数据段、堆和栈**原地替换**原进程映像，原 **PID 等身份信息保持不变**。调用成功则不再返回原程序（原代码已被覆盖），仅失败时返回 `-1`。
   - **`wait` / `waitpid` 与边界状态**：

| 边界概念 | 成因与状态 | 资源与 PCB 占用 | 处理结局 |
| --- | --- | --- | --- |
| **级联终止** | 终止父进程时连同其所有子孙进程一并终止 | 全部回收 | 防止产生失控后台子孙进程（Windows 无进程层次结构故不级联） |
| **孤儿进程（Orphan）** | 父进程先于子进程终止，子进程仍在正常运行 | 占用正常运行所需资源与 CPU | 被 `init`/`systemd` 等祖先进程**收养**，待其结束后由新父进程回收 |
| **僵尸进程（Zombie）** | 子进程已终止，但父进程尚未调用 `wait`/`waitpid` 读取其退出状态 | 用户空间已释放，但**内核进程表中的 PCB 项（PID、退出码）仍被占用**，不占 CPU | 僵尸堆积会耗尽有限的 PCB 表槽位导致无法创建新进程；需父进程 `wait` 或杀死父进程让收养者收割 |

<figure class="cpd-figure not-content" id="os-c2-fig-5">
  <svg viewBox="0 0 720 302" role="img" aria-label="fork写时复制COW共享只读物理页框、写入分裂机制与exec原地替换对比图">
    <defs>
      <marker id="os-c2-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="218" height="274" rx="8"/>
    <rect class="fig-box-subtle" x="246" y="14" width="234" height="274" rx="8"/>
    <rect class="fig-box-subtle" x="492" y="14" width="212" height="274" rx="8"/>
    <line class="fig-line-accent" x1="72" y1="142" x2="96" y2="178" marker-end="url(#os-c2-arr-5)"/>
    <line class="fig-line-accent" x1="176" y1="142" x2="152" y2="178" marker-end="url(#os-c2-arr-5)"/>
    <line class="fig-line-accent" x1="306" y1="142" x2="328" y2="178" marker-end="url(#os-c2-arr-5)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="420" y1="142" x2="420" y2="188" marker-end="url(#os-c2-arr-5)"/>
    <line class="fig-line-accent" x1="598" y1="112" x2="598" y2="136" marker-end="url(#os-c2-arr-5)"/>
    <rect class="fig-box-blue" x="28" y="64" width="90" height="78" rx="5"/>
    <rect class="fig-box-green" x="132" y="64" width="90" height="78" rx="5"/>
    <rect class="fig-box-purple" x="42" y="180" width="166" height="58" rx="5"/>
    <rect class="fig-box-orange" x="28" y="246" width="194" height="32" rx="4"/>
    <rect class="fig-box-blue" x="258" y="64" width="96" height="78" rx="5"/>
    <rect class="fig-box-green" x="370" y="64" width="98" height="78" rx="5"/>
    <rect class="fig-box-purple" x="258" y="180" width="106" height="58" rx="5"/>
    <rect class="fig-box-red" x="372" y="190" width="96" height="48" rx="5"/>
    <rect class="fig-box" x="258" y="246" width="210" height="32" rx="4"/>
    <rect class="fig-box-green" x="506" y="64" width="184" height="48" rx="5"/>
    <rect class="fig-box-accent" x="506" y="138" width="184" height="92" rx="5"/>
    <rect class="fig-box" x="506" y="238" width="184" height="40" rx="4"/>
    <text class="fig-title" x="26" y="34" font-size="10.8">① fork() 刚返回（写时复制 COW）</text>
    <text class="fig-muted" x="28" y="52" font-size="10">不真拷物理页，虚存地址逻辑独立</text>
    <text class="fig-blue" x="73" y="84" font-size="11" text-anchor="middle">父进程页表</text>
    <text class="fig-muted" x="73" y="102" font-size="10" text-anchor="middle">PID=10, ret&gt;0</text>
    <text class="fig-red" x="73" y="122" font-size="10" text-anchor="middle">权限标记：只读</text>
    <text class="fig-green" x="177" y="84" font-size="11" text-anchor="middle">子进程页表</text>
    <text class="fig-muted" x="177" y="102" font-size="10" text-anchor="middle">PID=11, ret=0</text>
    <text class="fig-red" x="177" y="122" font-size="10" text-anchor="middle">权限标记：只读</text>
    <text class="fig-purple" x="125" y="203" font-size="11" text-anchor="middle">暂共享同一批物理页框</text>
    <text class="fig-muted" x="125" y="222" font-size="10" text-anchor="middle">代码页 / 数据页 / 栈页 (RO)</text>
    <text class="fig-orange" x="125" y="266" font-size="9.5" text-anchor="middle">★ 不共享虚存，但共享打开文件偏移量</text>
    <text class="fig-title" x="258" y="34" font-size="12">② 子进程写数据页（按页触发复制）</text>
    <text class="fig-muted" x="258" y="52" font-size="10">写只读页触发保护异常 → 仅复制该页</text>
    <text class="fig-blue" x="306" y="84" font-size="11" text-anchor="middle">父进程页表</text>
    <text class="fig-muted" x="306" y="104" font-size="10" text-anchor="middle">仍指原物理页框</text>
    <text class="fig-muted" x="306" y="124" font-size="10" text-anchor="middle">(未改页继续共享)</text>
    <text class="fig-green" x="419" y="84" font-size="11" text-anchor="middle">子进程页表</text>
    <text class="fig-red" x="419" y="104" font-size="10" text-anchor="middle">写数据页触发异常</text>
    <text class="fig-green" x="419" y="124" font-size="10" text-anchor="middle">改指新页框(RW)</text>
    <text class="fig-purple" x="311" y="204" font-size="10.5" text-anchor="middle">原物理页框</text>
    <text class="fig-muted" x="311" y="223" font-size="10" text-anchor="middle">代码页仍共享</text>
    <text class="fig-red" x="420" y="211" font-size="10.5" text-anchor="middle">新分配页框</text>
    <text class="fig-muted" x="420" y="228" font-size="10" text-anchor="middle">仅复制被写页</text>
    <text class="fig-label" x="363" y="266" font-size="10" text-anchor="middle">代价只与实际修改页数成正比，非全量拷贝</text>
    <text class="fig-title" x="504" y="34" font-size="12">③ exec() 原地加载新程序</text>
    <text class="fig-muted" x="504" y="52" font-size="10">不建新进程，直接覆写当前虚存映像</text>
    <text class="fig-green" x="598" y="84" font-size="11" text-anchor="middle">子进程 (PID 仍为 11)</text>
    <text class="fig-muted" x="598" y="101" font-size="10" text-anchor="middle">调用 execve("/bin/ls", ...)</text>
    <text class="fig-accent" x="598" y="160" font-size="11" text-anchor="middle">新程序映像完全替换旧空间</text>
    <text class="fig-label" x="598" y="180" font-size="8.2" text-anchor="middle">新 Text / Data / BSS / Heap / Stack</text>
    <text class="fig-muted" x="598" y="200" font-size="10" text-anchor="middle">与原父进程代码彻底脱离</text>
    <text class="fig-muted" x="598" y="218" font-size="10" text-anchor="middle">省去 fork 时的无效全量复制</text>
    <text class="fig-label" x="598" y="254" font-size="10" text-anchor="middle">PID 不变 · 成功不返回原程序</text>
    <text class="fig-muted" x="598" y="270" font-size="10" text-anchor="middle">仅调用失败时返回 -1</text>
  </svg>
  <figcaption>图 2-5　fork() 写时复制（COW）共享与按需分裂流程及 exec() 原地映像替换对比</figcaption>
</figure>

---

### 2.3 进程的状态与转换 ★

#### 2.3.1 三态模型与五态模型：两个追问与三条非法转换

操作系统随时需要知道每个进程此刻所处的境况。所有表象复杂的情况，均可通过两个追问归入**三种基本状态**：
1. **现在占着 CPU 吗？** 占着 $\Rightarrow$ **运行态（Running）**（单处理机下任一时刻最多只有 1 个进程处于运行态；多核下最多等于核心数）。
2. **不占 CPU 时，除了 CPU 还缺其他资源或等待事件吗？** 什么都不缺、只缺 CPU $\Rightarrow$ **就绪态（Ready）**；仍在等待某事件（I/O 完成、信号量 $P$ 操作失败、缓冲区/内存暂不可得）$\Rightarrow$ **阻塞态/等待态（Blocked）**。

在三态之上补全生命周期的起止两极——正在创建分配资源的<strong>创建态（New）</strong>与执行结束等待回收资源的**终止态（Terminated）**，即构成标准的**五态模型**。

**五态模型六条合法转换边清单**：

| 状态转换 | 触发原因 / 典型事件 | 发起者与调度依赖 |
| --- | --- | --- |
| **创建态 $\rightarrow$ 就绪态** | 申请空白 PCB、分配除 CPU 外资源、初始化 PCB 完成，插入就绪队列 | 操作系统（创建原语） |
| **就绪态 $\rightarrow$ 运行态** | CPU 空闲时，调度程序从就绪队列选中该进程并分配 CPU | 调度程序（Dispatch） |
| **运行态 $\rightarrow$ 就绪态** | **时间片用完**（时钟中断），或**被更高优先级进程抢占**，或自愿放弃 CPU | OS 调度程序（★**依赖抢占式调度**） |
| **运行态 $\rightarrow$ 阻塞态** | 进程请求等待某事件（启动 I/O、执行 `P` 操作失败、申请内存失败、`wait()`、`sleep()`、缺页） | **★进程自身主动发起** |
| **阻塞态 $\rightarrow$ 就绪态** | 所等事件已发生（I/O 完成中断、`V` 操作释放信号量、另一进程退出临界区释放资源、定时器到期） | **★外部事件触发，OS/中断处理程序被动唤醒** |
| **运行态 $\rightarrow$ 终止态** | 正常执行完毕（`exit`）、遇到致命异常（除零、越界、非法指令）或被外部 `kill` | 进程自身 / 操作系统 |

> **★考点（三大永不发生的非法转换 & 命题铁律）**：
> 1. **就绪态 $\not\rightarrow$ 阻塞态**：阻塞是进程发出请求后主动等待结果，**就绪态进程根本没有占用 CPU，发不出任何请求**！
> 2. **阻塞态 $\not\rightarrow$ 运行态**：**唤醒 $\neq$ 调度**。事件发生后只能唤醒回到**就绪态**排队，必须等调度程序挑中才能上 CPU（`2014#26`：读磁盘完成后 OS 必做的是修改进程状态为**就绪态**，而非置为运行态或改优先级/时间片）。
> 3. **终止态 $\not\rightarrow$ 任意状态**：进程一旦终止即不可逆，仅待父进程或系统回收其 PCB。
> 4. **“运行 $\rightarrow$ 就绪” vs “运行 $\rightarrow$ 阻塞” vs “阻塞 $\rightarrow$ 就绪”**（`2015#25`、`2019#24`）：
>    - 自己主动让出并等待某结果（执行 `P` 操作、申请内存失败、启动 I/O）$\Rightarrow$ **运行 $\rightarrow$ 阻塞**；
>    - 被动被外部踢下 CPU（时间片用完、被高优先级抢占）$\Rightarrow$ **运行 $\rightarrow$ 就绪**（**时间片用完不会唤醒任何别的进程！**）；
>    - 外界条件满足使等待者恢复可执行（I/O 完成、他人退出临界区、`V` 操作）$\Rightarrow$ **阻塞 $\rightarrow$ 就绪**。

<figure class="cpd-figure not-content" id="os-c2-fig-6">
  <svg viewBox="0 0 720 288" role="img" aria-label="进程五状态模型六条合法转换与三条禁止转换状态机">
    <defs>
      <marker id="os-c2-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="260" rx="8"/>
    <line class="fig-line-accent" x1="120" y1="120" x2="176" y2="120" marker-end="url(#os-c2-arr-6)"/>
    <line class="fig-line-accent" x1="284" y1="110" x2="424" y2="110" marker-end="url(#os-c2-arr-6)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 454 96 L 454 58 L 230 58 L 230 94" marker-end="url(#os-c2-arr-6)"/>
    <path class="fig-line" stroke="var(--sl-color-purple)" d="M 476 144 L 476 226 L 414 226" marker-end="url(#os-c2-arr-6)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" d="M 304 226 L 230 226 L 230 146" marker-end="url(#os-c2-arr-6)"/>
    <line class="fig-line-accent" x1="532" y1="120" x2="588" y2="120" marker-end="url(#os-c2-arr-6)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 200 144 L 200 248 L 304 248" marker-end="url(#os-c2-arr-6)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 358 202 L 358 128 L 424 128" marker-end="url(#os-c2-arr-6)"/>
    <rect class="fig-box" x="26" y="96" width="94" height="48" rx="6"/>
    <rect class="fig-box-blue" x="178" y="96" width="106" height="48" rx="6"/>
    <rect class="fig-box-green" x="426" y="96" width="106" height="48" rx="6"/>
    <rect class="fig-box-purple" x="306" y="202" width="106" height="48" rx="6"/>
    <rect class="fig-box-red" x="590" y="96" width="100" height="48" rx="6"/>
    <rect class="fig-box" x="256" y="44" width="176" height="22" rx="3"/>
    <rect class="fig-box" x="290" y="98" width="126" height="20" rx="3"/>
    <text class="fig-title" x="30" y="34" font-size="12.5">进程五状态转换图（★六条合法转换 vs 非法跳转禁区）</text>
    <text class="fig-label" x="73" y="117" font-size="12" text-anchor="middle">创建态</text>
    <text class="fig-muted" x="73" y="133" font-size="10" text-anchor="middle">New</text>
    <text class="fig-blue" x="231" y="117" font-size="12" text-anchor="middle">就绪态</text>
    <text class="fig-muted" x="231" y="133" font-size="10" text-anchor="middle">Ready</text>
    <text class="fig-green" x="479" y="117" font-size="12" text-anchor="middle">运行态</text>
    <text class="fig-muted" x="479" y="133" font-size="10" text-anchor="middle">Running</text>
    <text class="fig-purple" x="359" y="223" font-size="12" text-anchor="middle">阻塞态</text>
    <text class="fig-muted" x="359" y="239" font-size="10" text-anchor="middle">Blocked</text>
    <text class="fig-red" x="640" y="117" font-size="12" text-anchor="middle">终止态</text>
    <text class="fig-muted" x="640" y="133" font-size="10" text-anchor="middle">Terminated</text>
    <text class="fig-muted" x="148" y="112" font-size="10" text-anchor="middle">资源就位</text>
    <text class="fig-accent" x="353" y="112" font-size="10" text-anchor="middle">调度选中 (Dispatch)</text>
    <text class="fig-orange" x="344" y="59" font-size="10" text-anchor="middle">时间片用完 / 被抢占 (★抢占式)</text>
    <text class="fig-muted" x="560" y="112" font-size="10" text-anchor="middle">正常/异常</text>
    <text class="fig-purple" x="488" y="178" font-size="10.5">主动阻塞 (Block)</text>
    <text class="fig-muted" x="488" y="194" font-size="10">请求 I/O · P操作 · 缺资源</text>
    <text class="fig-green" x="220" y="178" font-size="10.5" text-anchor="end">被动唤醒 (Wakeup)</text>
    <text class="fig-muted" x="220" y="194" font-size="10" text-anchor="end">I/O完成 · V操作唤醒</text>
    <text class="fig-red" x="190" y="264" font-size="10">✕ 就绪 → 阻塞：无 CPU 发不出请求</text>
    <text class="fig-red" x="364" y="156" font-size="10">✕ 阻塞 → 运行</text>
    <text class="fig-red" x="364" y="170" font-size="9.5">唤醒 ≠ 调度</text>
  </svg>
  <figcaption>图 2-6　进程五状态模型：六条合法状态转换边与三条永不发生的非法跳转（含终止不可逆）</figcaption>
</figure>

#### 2.3.2 引入挂起操作与七状态模型

<strong>挂起（Suspend）</strong>是将暂不需要运行或内存吃紧的进程映像**换出到外存**并使其处于“静止”状态的操作，对应唤醒内存化操作的为**激活（Active）**。引入挂起主要有四类发起者：
1. **终端用户请求**：发现程序运行异常，暂停下来查看或调试修改；
2. **父进程请求**：父进程检查、协调或暂停子进程活动；
3. **负荷调节需要**：系统负载过重影响实时任务时，把低优先进程换出外存；
4. **操作系统自身需要**：OS 进行记账、审计资源或虚拟存储页面紧张时换出进程。

> **★考点（“挂起 $\neq$ 阻塞”，两者完全正交）**：
> 挂起关注“**映像在不在内存、参不参与调度**”，阻塞关注“**缺不缺 CPU 以外的事件/资源**”。两个维度正交 $2 \times 2$ 组合，将原有的就绪态与阻塞态一分为四（汤小丹教材称“活动/静止”，另一套常见叫法为“就绪/挂起就绪”），加上创建、运行、终止共成**七状态模型**：
> - **活动就绪（`Ready_a` / 就绪）**：在内存中，仅缺 CPU，可被直接调度；
> - **静止就绪（`Ready_s` / 挂起就绪）**：已换出到外存，**不再参与 CPU 调度**，须激活入内存后才可调度；
> - **活动阻塞（`Blocked_a` / 阻塞）**：在内存中等待某事件；
> - **静止阻塞（`Blocked_s` / 挂起阻塞）**：在外存中同时还在等待某事件。

<figure class="cpd-figure not-content" id="os-c2-fig-7">
  <svg viewBox="0 0 720 358" role="img" aria-label="引入挂起操作的进程七状态模型（内存中活动态与外存中静止态正交转换图）">
    <defs>
      <marker id="os-c2-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="212" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="236" width="688" height="108" rx="8"/>
    <line class="fig-line-accent" x1="112" y1="88" x2="174" y2="88" marker-end="url(#os-c2-arr-7)"/>
    <path class="fig-line-dashed" d="M 70 110 L 70 231 L 22 231 L 22 296 L 170 296" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line-accent" x1="296" y1="88" x2="404" y2="88" marker-end="url(#os-c2-arr-7)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 460 66 L 460 44 L 236 44 L 236 64" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line-accent" x1="516" y1="88" x2="584" y2="88" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="460" y1="110" x2="460" y2="160" marker-end="url(#os-c2-arr-7)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" d="M 398 184 L 266 184 L 266 112" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="216" y1="110" x2="216" y2="270" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="246" y1="272" x2="246" y2="112" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="444" y1="206" x2="444" y2="270" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="476" y1="272" x2="476" y2="208" marker-end="url(#os-c2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="410" y1="302" x2="286" y2="302" marker-end="url(#os-c2-arr-7)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 516 102 L 558 102 L 558 328 L 236 328 L 236 318" marker-end="url(#os-c2-arr-7)"/>
    <rect class="fig-box" x="28" y="66" width="84" height="44" rx="5"/>
    <rect class="fig-box-blue" x="176" y="66" width="120" height="44" rx="5"/>
    <rect class="fig-box-green" x="406" y="66" width="110" height="44" rx="5"/>
    <rect class="fig-box-red" x="586" y="66" width="104" height="44" rx="5"/>
    <rect class="fig-box-purple" x="400" y="162" width="120" height="44" rx="5"/>
    <rect class="fig-box-blue" x="172" y="272" width="112" height="44" rx="5"/>
    <rect class="fig-box-purple" x="412" y="272" width="112" height="44" rx="5"/>
    <rect class="fig-box" x="292" y="34" width="116" height="18" rx="3"/>
    <text class="fig-title" x="28" y="32" font-size="12">内存中：活动状态（参与调度或正在内存中等待）</text>
    <text class="fig-title" x="28" y="254" font-size="11.5">外存中：静止状态（★不参与调度）</text>
    <text class="fig-muted" x="628" y="254" font-size="10" text-anchor="middle">进程映像已换出到外存</text>
    <text class="fig-label" x="70" y="86" font-size="11.5" text-anchor="middle">创建态</text>
    <text class="fig-muted" x="70" y="102" font-size="10" text-anchor="middle">New</text>
    <text class="fig-blue" x="236" y="85" font-size="11.5" text-anchor="middle">活动就绪</text>
    <text class="fig-muted" x="236" y="102" font-size="10" text-anchor="middle">Ready_a</text>
    <text class="fig-green" x="461" y="85" font-size="11.5" text-anchor="middle">运行态</text>
    <text class="fig-muted" x="461" y="102" font-size="10" text-anchor="middle">Running</text>
    <text class="fig-red" x="638" y="85" font-size="11.5" text-anchor="middle">终止态</text>
    <text class="fig-muted" x="638" y="102" font-size="10" text-anchor="middle">Terminated</text>
    <text class="fig-purple" x="460" y="181" font-size="11.5" text-anchor="middle">活动阻塞</text>
    <text class="fig-muted" x="460" y="198" font-size="10" text-anchor="middle">Blocked_a</text>
    <text class="fig-blue" x="228" y="291" font-size="11.5" text-anchor="middle">静止就绪</text>
    <text class="fig-muted" x="228" y="308" font-size="10" text-anchor="middle">Ready_s</text>
    <text class="fig-purple" x="468" y="291" font-size="11.5" text-anchor="middle">静止阻塞</text>
    <text class="fig-muted" x="468" y="308" font-size="10" text-anchor="middle">Blocked_s</text>
    <text class="fig-muted" x="142" y="81" font-size="10" text-anchor="middle">内存充裕</text>
    <text class="fig-accent" x="350" y="81" font-size="10" text-anchor="middle">调度选中</text>
    <text class="fig-orange" x="350" y="47" font-size="10" text-anchor="middle">时间片到 / 抢占</text>
    <text class="fig-muted" x="550" y="81" font-size="10" text-anchor="middle">结束</text>
    <text class="fig-purple" x="468" y="139" font-size="10">请求/等待</text>
    <text class="fig-green" x="332" y="176" font-size="10" text-anchor="middle">事件完成 (内存中唤醒)</text>
    <text class="fig-muted" x="122" y="288" font-size="10" text-anchor="middle">内存不足先置外存</text>
    <text class="fig-orange" x="208" y="218" font-size="10" text-anchor="end">挂起 Suspend</text>
    <text class="fig-green" x="254" y="218" font-size="10">激活 Active</text>
    <text class="fig-orange" x="436" y="255" font-size="10" text-anchor="end">挂起</text>
    <text class="fig-green" x="484" y="255" font-size="10">激活</text>
    <text class="fig-green" x="348" y="292" font-size="9.2" text-anchor="middle">★ 外存期间事件完成</text>
    <text class="fig-orange" x="564" y="288" font-size="10">运行态直接被挂起</text>
  </svg>
  <figcaption>图 2-7　七状态转换模型：活动/静止与就绪/阻塞的正交关系及 Suspend/Active 七条挂起相关转换边</figcaption>
</figure>

**七状态模型易漏转换边点睛**：
1. **创建 $\rightarrow$ 静止就绪**：系统负载重或内存紧缺时，创建原语暂不给新进程分配主存，先将其放到外存（创建工作尚未完全结束）。
2. **运行 $\rightarrow$ 静止就绪**：用户或父进程对正在 CPU 上运行的进程发出 `Suspend`，直接将其换出至静止就绪。
3. **静止阻塞 $\rightarrow$ 静止就绪**：进程已被换出到外存，但在外存等待期间它所请求的 I/O 或信号事件已经发生（此时状态位由静止阻塞改为静止就绪，进程映像仍在外存，不会自动调入内存）。

> **★考点（带挂起与抢占式优先级的事件序列推演）**：
> 设单处理机采用**抢占式优先级调度**，优先级 `P1 > P2 > P3`。三进程就绪后先后发生：$t_0$ 开始调度；$t_1$ `P1` 发出 I/O 请求；$t_2$ `P1` 的 I/O 完成；$t_3$ 内存紧张挂起 `P3`；$t_4$ `P1` 结束；$t_5$ 内存充裕激活 `P3`。
> - $t_0$：`P1` 就绪 $\rightarrow$ 运行；
> - $t_1$：`P1` 运行 $\rightarrow$ 阻塞（主动等 I/O），`P2` 就绪 $\rightarrow$ 运行；
> - $t_2$：`P1` 阻塞 $\rightarrow$ 就绪（**无阻塞 $\rightarrow$ 运行！**）；因抢占式且 `P1 > P2`，`P2` 运行 $\rightarrow$ 就绪，`P1` 就绪 $\rightarrow$ 运行；
> - $t_3$：`P3` 活动就绪 $\rightarrow$ 静止就绪（不在 CPU 上，不影响运行态 `P1`）；
> - $t_4$：`P1` 运行 $\rightarrow$ 终止，`P2` 就绪 $\rightarrow$ 运行（此时 `P3` 在静止就绪，**不参与调度**）；
> - $t_5$：`P3` 静止就绪 $\rightarrow$ 活动就绪（`P2` 正在运行且无更高优先级，不触发抢占）。
> 总计 **10 次状态转换**。若改为**非抢占式调度**，则在 $t_2$ 时 `P1` 只能停在就绪态等待 `P2` 主动让出，少了 `P2` 被踢回就绪与 `P1` 上 CPU 这 **2 次**转换！

---

### 2.4 进程的组织与控制原语

#### 2.4.1 PCB 的三种组织方式与状态队列

当系统中同时存在数百甚至数千个并发进程时，调度程序绝不能每次都做全表扫描。操作系统围绕“**查找快还是修改快**”的权衡，形成三种 PCB 组织方式：

| 组织方式 | 结构做法 | 查找代价 | 增删/改状态代价 | 适用场景 |
| --- | --- | --- | --- | --- |
| **线性方式** | 所有 PCB 集中存放在一张连续线性表（PCB 表）中，首址存专用区 | **差**：每次按状态查找都需顺序扫描整张表 | **低**：状态变化仅修改表项中 `state` 字段，PCB 本身不搬动 | 进程数目较少的早期系统 |
| **链接方式（★最通用）** | 利用 PCB 内部链接指针，按状态与阻塞原因串成多个队列：**就绪队列**、**若干阻塞队列**、**空白队列** | **好**：取就绪队列队首即得，复杂度退化为 $O(1)$ | **中**：状态变化需**摘链 + 挂链**指针操作 | **绝大多数实际操作系统** |
| **索引方式** | 按进程状态分别建立**索引表**（紧凑数组），各表首址存专用单元，表项记录对应 PCB 地址 | **好**：查表即得，且支持按序号随机访问第 $k$ 项 | **高**：状态切换时需向紧凑数组插入/删除，可能移动大量表项 | 按状态频繁检索但状态变化少时 |

> **★考点（状态队列与量化查找比较）**：
> 1. **为何单 CPU 系统没有“运行队列”？** 单处理机任一时刻最多只有 **1 个**进程在 CPU 上运行，只需一个全局指针（执行指针 `run`）指向它即可，无需排队（多核系统可按核心设置运行指针或运行队列）。
> 2. **为何阻塞队列常按“阻塞原因”分成多条？** 设 PCB 表共 $n = 512$ 槽位，含 $k = 40$ 个就绪进程与 $m = 60$ 个阻塞进程（等 I/O 25 个、等缓冲区 20 个、等信号量 15 个）：
>    - 线性方式寻找**任意第一个**就绪进程的期望比较次数为 $E = \frac{n + 1}{k + 1} = \frac{513}{41} \approx 12.51$ 次（切勿误算成 $\frac{n}{2} = 256$）；而链接方式直接取就绪队首仅需 **1 次**。
>    - 唤醒**指定**阻塞进程时需顺序比对，平均比较 $\frac{m + 1}{2}$ 次：60 个挤在一条队列平均比 **30.5 次**；按事件拆成三条后，只在“等信号量”队列（15 个）中找仅需 **8.0 次**，比较次数下降 $73.8\%$！当然，若阻塞原因高达数十种，维护过多头指针的空间开销会反超收益，此时宜按事件建索引表。

<figure class="cpd-figure not-content" id="os-c2-fig-8">
  <svg viewBox="0 0 720 298" role="img" aria-label="PCB链接方式状态队列（就绪队列、按原因划分的阻塞队列、空闲队列）与索引方式结构图">
    <defs>
      <marker id="os-c2-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="424" height="270" rx="8"/>
    <rect class="fig-box-subtle" x="452" y="14" width="252" height="270" rx="8"/>
    <line class="fig-line-accent" x1="126" y1="64" x2="158" y2="64" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="126" y1="112" x2="158" y2="112" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="234" y1="112" x2="254" y2="112" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="330" y1="112" x2="350" y2="112" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="126" y1="162" x2="158" y2="162" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="234" y1="162" x2="254" y2="162" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="126" y1="208" x2="158" y2="208" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="126" y1="252" x2="158" y2="252" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="234" y1="252" x2="254" y2="252" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="542" y1="88" x2="566" y2="88" marker-end="url(#os-c2-arr-8)"/>
    <line class="fig-line-accent" x1="542" y1="168" x2="566" y2="168" marker-end="url(#os-c2-arr-8)"/>
    <rect class="fig-box-green" x="28" y="48" width="98" height="32" rx="4"/>
    <rect class="fig-box-green" x="160" y="48" width="110" height="32" rx="4"/>
    <rect class="fig-box-blue" x="28" y="96" width="98" height="32" rx="4"/>
    <rect class="fig-box-blue" x="160" y="96" width="74" height="32" rx="4"/>
    <rect class="fig-box-blue" x="256" y="96" width="74" height="32" rx="4"/>
    <rect class="fig-box-blue" x="352" y="96" width="74" height="32" rx="4"/>
    <rect class="fig-box-purple" x="28" y="146" width="98" height="32" rx="4"/>
    <rect class="fig-box-purple" x="160" y="146" width="74" height="32" rx="4"/>
    <rect class="fig-box-purple" x="256" y="146" width="74" height="32" rx="4"/>
    <rect class="fig-box-purple" x="28" y="192" width="98" height="32" rx="4"/>
    <rect class="fig-box-purple" x="160" y="192" width="74" height="32" rx="4"/>
    <rect class="fig-box" x="28" y="236" width="98" height="32" rx="4"/>
    <rect class="fig-box" x="160" y="236" width="74" height="32" rx="4"/>
    <rect class="fig-box" x="256" y="236" width="74" height="32" rx="4"/>
    <rect class="fig-box-blue" x="466" y="54" width="76" height="68" rx="4"/>
    <rect class="fig-box" x="568" y="54" width="124" height="68" rx="4"/>
    <line class="fig-divider" x1="466" y1="77" x2="542" y2="77"/>
    <line class="fig-divider" x1="466" y1="100" x2="542" y2="100"/>
    <rect class="fig-box-purple" x="466" y="136" width="76" height="64" rx="4"/>
    <rect class="fig-box" x="568" y="136" width="124" height="64" rx="4"/>
    <line class="fig-divider" x1="466" y1="158" x2="542" y2="158"/>
    <line class="fig-divider" x1="466" y1="180" x2="542" y2="180"/>
    <rect class="fig-box-orange" x="466" y="212" width="224" height="58" rx="5"/>
    <text class="fig-title" x="28" y="34" font-size="12.5">① 链接方式（实际 OS 最常用：状态队列）</text>
    <text class="fig-green" x="77" y="68" font-size="11" text-anchor="middle">执行指针</text>
    <text class="fig-green" x="215" y="68" font-size="11" text-anchor="middle">PCB 1 (运行)</text>
    <text class="fig-muted" x="282" y="68" font-size="10">← 单核最多 1 个，无队列</text>
    <text class="fig-blue" x="77" y="116" font-size="11" text-anchor="middle">就绪队列头</text>
    <text class="fig-blue" x="197" y="116" font-size="10.5" text-anchor="middle">PCB 4</text>
    <text class="fig-blue" x="293" y="116" font-size="10.5" text-anchor="middle">PCB 2</text>
    <text class="fig-blue" x="389" y="116" font-size="10.5" text-anchor="middle">PCB 10</text>
    <text class="fig-purple" x="77" y="166" font-size="10.5" text-anchor="middle">阻塞(等磁盘)</text>
    <text class="fig-purple" x="197" y="166" font-size="10.5" text-anchor="middle">PCB 3</text>
    <text class="fig-purple" x="293" y="166" font-size="10.5" text-anchor="middle">PCB 8</text>
    <text class="fig-muted" x="352" y="166" font-size="10">按原因拆分</text>
    <text class="fig-purple" x="77" y="212" font-size="10.5" text-anchor="middle">阻塞(信号量)</text>
    <text class="fig-purple" x="197" y="212" font-size="10.5" text-anchor="middle">PCB 7</text>
    <text class="fig-muted" x="260" y="212" font-size="10">按因分队免全扫</text>
    <text class="fig-label" x="77" y="256" font-size="11" text-anchor="middle">空白队列头</text>
    <text class="fig-muted" x="197" y="256" font-size="10.5" text-anchor="middle">空闲槽位</text>
    <text class="fig-muted" x="293" y="256" font-size="10.5" text-anchor="middle">空闲槽位</text>
    <text class="fig-muted" x="352" y="256" font-size="10">新建直接取槽</text>
    <text class="fig-title" x="466" y="34" font-size="12.5">② 索引方式（状态索引表）</text>
    <text class="fig-blue" x="504" y="70" font-size="10.5" text-anchor="middle">就绪表[0]</text>
    <text class="fig-blue" x="504" y="93" font-size="10.5" text-anchor="middle">就绪表[1]</text>
    <text class="fig-blue" x="504" y="116" font-size="10.5" text-anchor="middle">就绪表[2]</text>
    <text class="fig-label" x="630" y="76" font-size="10.5" text-anchor="middle">连续 PCB 表中</text>
    <text class="fig-muted" x="630" y="96" font-size="9.4" text-anchor="middle">对应 PCB 4 / 2 / 10</text>
    <text class="fig-purple" x="504" y="152" font-size="10.5" text-anchor="middle">阻塞表[0]</text>
    <text class="fig-purple" x="504" y="174" font-size="10.5" text-anchor="middle">阻塞表[1]</text>
    <text class="fig-purple" x="504" y="196" font-size="10.5" text-anchor="middle">...</text>
    <text class="fig-label" x="630" y="160" font-size="10.5" text-anchor="middle">连续 PCB 表中</text>
    <text class="fig-muted" x="630" y="180" font-size="9.4" text-anchor="middle">对应 PCB 3 / 8 / 7</text>
    <text class="fig-orange" x="578" y="232" font-size="10.5" text-anchor="middle">★ 索引方式特征总结</text>
    <text class="fig-label" x="578" y="249" font-size="10" text-anchor="middle">支持随机访问，检索极快</text>
    <text class="fig-muted" x="578" y="264" font-size="10" text-anchor="middle">数组增删需搬移表项，改状态慢</text>
  </svg>
  <figcaption>图 2-8　PCB 链接方式（就绪/按原因拆分的阻塞/空白队列）与索引方式结构及查找效率对比</figcaption>
</figure>

#### 2.4.2 原语的原子性：为何必须关中断与多核边界

进程控制的核心动作是**实现进程状态转换**。一次状态转换至少包含两步分离的内存操作：修改 `PCB.state` 字段，并将 PCB 从旧队列摘除、插入新队列。

如果在修改 `PCB.state = 就绪` 之后、尚未将其从阻塞队列摘链之前，CPU 检测到一个外部中断信号并转去调度其他进程，就会出现 **`PCB.state` 显示就绪但实体还挂在阻塞队列里** 的撕裂状态——不仅自相矛盾，一旦调度器或其他并发控制代码触及该队列，链表就会损坏甚至让进程从此“失联”。因此，进程控制动作必须做成**原语（Primitive）**——由内核在系统态执行、**一气呵成、绝对不可被中断**的原子操作。

原语的原子性在单处理机上由两条特权指令实现：
```text
关中断指令（CLI）   ← CPU 暂停例行检查外部中断信号，不会触发调度切换
  ... 修改 PCB 状态与队列指针的一系列动作 ...
开中断指令（STI）   ← 恢复中断检查，补响应期间滞留的中断信号
```

> **注意（关中断为何必须是特权指令 & 三大硬边界）**：
> 1. **为何用户态禁用**：若普通程序可随意执行关中断，它只需在程序开头关中断、死循环中永不开中断，时钟中断就永远进不来，整个 OS 将彻底丧失抢占与调度权。因此**原语必然运行在内核态**。
> 2. **关中断的三大局限**：① 滥用关中断可能导致系统瘫痪；② 关中断时间过长会严重降低系统并发效率与中断响应实时性；③ **★不适用于多处理机系统**：关中断只能屏蔽**当前 CPU 核心**的中断响应，另一颗核依然可以同时进入内核改同一条全局队列，因此多核下必须配合 `TSL` / `Swap` 等硬件原子锁指令保护临界队列。

<figure class="cpd-figure not-content" id="os-c2-fig-9">
  <svg viewBox="0 0 720 278" role="img" aria-label="进程控制原语通过关中断和开中断实现原子执行机制对比图">
    <defs>
      <marker id="os-c2-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="114" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="138" width="688" height="126" rx="8"/>
    <line class="fig-line" x1="176" y1="78" x2="210" y2="78" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="336" y1="78" x2="370" y2="78" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="504" y1="78" x2="534" y2="78" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line-accent" x1="124" y1="194" x2="152" y2="194" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line-accent" x1="264" y1="194" x2="288" y2="194" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line-accent" x1="398" y1="194" x2="422" y2="194" marker-end="url(#os-c2-arr-9)"/>
    <line class="fig-line-accent" x1="534" y1="194" x2="558" y2="194" marker-end="url(#os-c2-arr-9)"/>
    <rect class="fig-box-blue" x="28" y="54" width="146" height="48" rx="5"/>
    <rect class="fig-box-red" x="212" y="54" width="122" height="48" rx="5"/>
    <rect class="fig-box-orange" x="372" y="54" width="130" height="48" rx="5"/>
    <rect class="fig-box-red" x="536" y="54" width="154" height="48" rx="5"/>
    <rect class="fig-box-purple" x="28" y="170" width="96" height="48" rx="5"/>
    <rect class="fig-box-green" x="154" y="170" width="110" height="48" rx="5"/>
    <rect class="fig-box-green" x="290" y="170" width="108" height="48" rx="5"/>
    <rect class="fig-box-green" x="424" y="170" width="110" height="48" rx="5"/>
    <rect class="fig-box-purple" x="560" y="170" width="130" height="48" rx="5"/>
    <rect class="fig-box" x="154" y="226" width="380" height="26" rx="4"/>
    <text class="fig-red" x="28" y="34" font-size="12">✕ 未用原语保护：唤醒过程半途被打断导致 PCB 状态与队列撕裂</text>
    <text class="fig-blue" x="101" y="75" font-size="11" text-anchor="middle">① PCB2.state = 就绪</text>
    <text class="fig-muted" x="101" y="93" font-size="10" text-anchor="middle">(仍在阻塞队列中)</text>
    <text class="fig-red" x="273" y="75" font-size="11" text-anchor="middle">⚡ 外部中断到达</text>
    <text class="fig-muted" x="273" y="93" font-size="10" text-anchor="middle">例行检查立即响应</text>
    <text class="fig-orange" x="437" y="75" font-size="11" text-anchor="middle">转去处理中断/调度</text>
    <text class="fig-muted" x="437" y="93" font-size="10" text-anchor="middle">后续摘链被推迟</text>
    <text class="fig-red" x="613" y="75" font-size="11" text-anchor="middle">状态=就绪却在阻塞队</text>
    <text class="fig-muted" x="613" y="93" font-size="10" text-anchor="middle">数据结构冲突/丢失</text>
    <text class="fig-green" x="28" y="158" font-size="12">✓ 使用原语（内核态特权指令）：关中断 → 原子操作 → 开中断</text>
    <text class="fig-purple" x="76" y="191" font-size="11" text-anchor="middle">关中断</text>
    <text class="fig-muted" x="76" y="207" font-size="9.5" text-anchor="middle">屏蔽中断检查</text>
    <text class="fig-green" x="209" y="191" font-size="10.5" text-anchor="middle">① 改 state=就绪</text>
    <text class="fig-muted" x="209" y="207" font-size="9.5" text-anchor="middle">(中断滞留不查)</text>
    <text class="fig-green" x="344" y="191" font-size="10.5" text-anchor="middle">② 从阻塞队摘链</text>
    <text class="fig-muted" x="344" y="207" font-size="9.5" text-anchor="middle">(一气呵成)</text>
    <text class="fig-green" x="479" y="191" font-size="10.5" text-anchor="middle">③ 挂入就绪队列</text>
    <text class="fig-muted" x="479" y="207" font-size="9.5" text-anchor="middle">(状态队列同步)</text>
    <text class="fig-purple" x="625" y="191" font-size="11" text-anchor="middle">开中断 → 补响应</text>
    <text class="fig-muted" x="625" y="207" font-size="9.5" text-anchor="middle">恢复例行检查中断</text>
    <text class="fig-accent" x="344" y="243" font-size="10" text-anchor="middle">注意：关中断仅屏蔽本 CPU 核心；多核系统须改用 TSL / Swap 硬件原子锁</text>
  </svg>
  <figcaption>图 2-9　原语利用关/开中断确保 PCB 状态修改与队列指针变更一气呵成，及多处理机场景局限</figcaption>
</figure>

#### 2.4.3 五大进程控制原语与必做/可选操作辨析

无论哪一类进程控制原语，底层都绕不开三件事：**更新 PCB 信息（`state`/现场）**、**将 PCB 插入或移出相应队列**、**分配或回收资源**。

| 控制原语 | 典型触发事件 | 核心执行步骤（无需死背逐字，重在逻辑） | ★ 408 真题必做 vs 可选辨析 |
| --- | --- | --- | --- |
| **创建原语** `Create` | 用户登录成功、作业调度、系统提供服务、进程请求创建子进程（如 `fork`） | ① 申请空白 PCB；② 分配运行所需资源；③ 初始化 PCB（PID/PPID/PC/SP/初始状态）；④ **插入就绪队列**（或静止就绪队列） | **必做**：申请空白 PCB + 初始化 PCB（`2021#24`）。**注意**：① 新建进程**不会设为运行态**，只能进就绪队列等调度；② **设备分配不创建新进程**（只是把设备指给已有进程，`2010#24`） |
| **撤销原语** `Terminate` | 正常完成（`exit`）、致命异常（除零/越界/非法指令）、外界干预（`kill`、任务管理器结束） | ① 按 PID 找到 PCB 读状态；② 若正在运行则立即剥夺 CPU 并置调度标志；③ 若有子孙进程且采用级联终止则一并终止；④ 归还资源给父进程或系统；⑤ **撤销/移出 PCB** | **必做**：撤销 PCB、回收内存、回收设备。**不一定执行**：**终止子进程**（`2024#24`）——一需进程本身有子进程，二需 OS 采用级联终止策略 |
| **阻塞原语** `Block` | 等待 I/O 完成、等待缓冲区/内存、信号量 $P$ 操作失败、等待消息 | ① 停止运行并保存 CPU 现场到 PCB；② 置状态为阻塞态；③ **插入相应事件的阻塞队列**；④ 转调度程序重新调度 | **只能由进程自身主动调用**（别人无法替你发等待请求） |
| **唤醒原语** `Wakeup` | I/O 结束中断、另一进程执行 $V$ 操作或退出临界区、收到消息 | ① 从对应阻塞队列取出 PCB；② 置状态为就绪态；③ **插入就绪队列** | **必然来自外部**（已阻塞进程无法唤醒自己）；与 `Block` **必须成对出现**，否则永久阻塞 |
| **切换原语** `Switch` | 时间片到、抢占、阻塞、自愿放弃 CPU | 保存旧进程寄存器上下文至旧 PCB、入对应队列、选中新进程、恢复新 PCB 上下文 | 触发调度**未必一定切换**（若选中原进程则免切） |

---

### 2.5 上下文及其切换机制 ★

#### 2.5.1 进程上下文的三层结构与现场保存原则

调度算法决定“**下一个选谁**”，而<strong>上下文切换（Context Switch）</strong>解决“**怎么安全换过去**”。判断是否需要保存某个信息的唯一准绳是：**它会不会被下一个进程改写，以及改写后原进程能否恢复运行**。

由此将<strong>进程上下文（Process Context）</strong>划分为三层：

| 上下文层次 | 具体包含内容 | 存放位置 | 上下文切换时的处理动作 |
| --- | --- | --- | --- |
| **① 用户级上下文** | 程序段（指令序列）、数据段、共享主存区、用户栈 | 进程的**虚拟地址空间** | **不搬动数据**，仅通过换页表基址寄存器使 CPU 看到新进程虚存 |
| **② 寄存器上下文（★核心搬运对象）** | **程序计数器 `PC`**、**程序状态字 `PSW`**、**栈指针 `SP`**、**通用寄存器（`AX`–`DX` 等）** | CPU 内部物理寄存器组 | **★必须逐个保存进原 PCB，再从新 PCB 恢复到 CPU**（全机只有一套） |
| **③ 系统级上下文** | PCB、主存管理信息（页表/段表及页表基址寄存器 **PTBR**）、**核心栈** | 操作系统**内核空间** | 大部分不搬动，只需将当前核心栈指针与 PTBR 切换为新进程的 |

> **★考点（页式虚存切换什么 vs 不切换什么 & 现场存放地点）**：
> 1. **为何现场不能保存在进程自己的用户栈里？**
>    - **循环依赖**：若把栈指针 `SP` 也压进用户栈，恢复时“为了恢复 `SP` 得先知道 `SP` 在哪”，陷入死循环；
>    - **换出外存不可达**：若进程随后被挂起换出外存，OS 根本够不着其用户空间，而 **PCB 常驻内核空间**。
> 2. **页式虚存发生进程上下文切换时，哪些内容需要保存/切换，哪些不需要？**（`2025#23`）
>    - **要保存/切换**：通用寄存器、程序计数器 `PC`、程序状态字 `PSW`、栈指针 `SP`、**页表基址寄存器（PTBR）**——判断标准：**是不是每个进程各有一份**（每个进程拥有独立页表，故 PTBR 必须换）。
>    - **不需要切换**：**内核中断向量表基址寄存器（IDTR）**——因为**中断向量表全系统只有唯一一份**，与当前运行哪个进程毫无关系！

#### 2.5.2 模式切换 vs 进程切换：触发时机与硬件/软件分工

| 对比维度 | 模式切换（Mode Switch） | 进程切换（Process/Context Switch） |
| --- | --- | --- |
| **触发场景** | 系统调用（`read`/`write`）、外部中断、内部异常 | 时间片到（时钟中断）、阻塞等待、高优先级抢占、进程结束 |
| **本质动作** | **仅改变 `PSW` 中的处理器模式位**（用户态 $\leftrightarrow$ 内核态）与切至核心栈；**通用寄存器不变、地址空间不变** | 除模式切换外，**必须保存旧进程寄存器上下文至 PCB、执行调度、切换 PTBR 与核心栈、恢复新进程寄存器上下文** |
| **切换开销** | 极小 | 较大（含直接拷贝 + TLB/Cache 冷启动间接惩罚） |
| **包含关系** | 模式切换**不一定**引起进程切换（如系统调用未阻塞直接返回原进程） | 进程切换**一定**包含模式切换（通常是一进一出的**两次**模式切换：用户态 $\rightarrow$ 内核态 $\rightarrow$ 用户态） |

> **★考点（四条必记逻辑命题 + 硬件与软件分工）**：
> 1. **四句铁律**：① 系统调用**一定**引起模式切换；② 系统调用**不一定**引起进程切换；③ 进程切换**一定**包含模式切换；④ 发生调度**不一定**发生进程切换（例如选中的仍是原进程），发生进程切换必然先发生了调度。
> 2. **硬件与软件分工**：**头尾两步由硬件原子完成**，**中间全由软件（内核）完成**——**规则：只要软件动了它就无法继续执行的东西，必须由硬件原子处理**。
>    - **头部硬件（中断隐指令）**：响应该中断/陷入时，硬件自动将原 `PC` 与 `PSW` 压入核心栈（或专用保存位置），置 `PSW` 为内核态，并将 `PC` 置为中断向量表入口（因为软件只要执行第一条指令就会立刻覆盖 `PC`）。
>    - **中间软件（内核切换器）**：保存原进程通用寄存器与用户栈指针到 `PCB_A` $\rightarrow$ 更新状态并入队 $\rightarrow$ 调度器选 `B` $\rightarrow$ 切换 `PTBR` 与核心栈 $\rightarrow$ 从 `PCB_B` 恢复通用寄存器。
>    - **尾部硬件（中断返回指令 `iret`）**：原子地同时恢复 `B` 的 `PC` 与 `PSW`（切回用户态），使 CPU 无缝从 `B` 的断点指令继续执行。

<figure class="cpd-figure not-content" id="os-c2-fig-10">
  <svg viewBox="0 0 720 336" role="img" aria-label="模式切换与进程上下文切换（头尾硬件+中间软件）全流程双轨对比图">
    <defs>
      <marker id="os-c2-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="286" height="308" rx="8"/>
    <rect class="fig-box-subtle" x="314" y="14" width="390" height="308" rx="8"/>
    <line class="fig-line-accent" x1="159" y1="84" x2="159" y2="96" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="159" y1="130" x2="159" y2="142" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="159" y1="178" x2="159" y2="190" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="159" y1="224" x2="159" y2="236" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="509" y1="80" x2="509" y2="92" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="509" y1="128" x2="509" y2="140" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="509" y1="176" x2="509" y2="188" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="509" y1="224" x2="509" y2="236" marker-end="url(#os-c2-arr-10)"/>
    <line class="fig-line-accent" x1="509" y1="272" x2="509" y2="282" marker-end="url(#os-c2-arr-10)"/>
    <rect class="fig-box-blue" x="30" y="48" width="258" height="36" rx="5"/>
    <rect class="fig-box-orange" x="30" y="98" width="258" height="32" rx="5"/>
    <rect class="fig-box-red" x="30" y="144" width="258" height="34" rx="5"/>
    <rect class="fig-box-orange" x="30" y="192" width="258" height="32" rx="5"/>
    <rect class="fig-box-blue" x="30" y="238" width="258" height="36" rx="5"/>
    <rect class="fig-box" x="30" y="282" width="258" height="28" rx="4"/>
    <rect class="fig-box-blue" x="328" y="46" width="362" height="34" rx="5"/>
    <rect class="fig-box-orange" x="328" y="94" width="362" height="34" rx="5"/>
    <rect class="fig-box-purple" x="328" y="142" width="362" height="34" rx="5"/>
    <rect class="fig-box-purple" x="328" y="190" width="362" height="34" rx="5"/>
    <rect class="fig-box-orange" x="328" y="238" width="362" height="34" rx="5"/>
    <rect class="fig-box-green" x="328" y="284" width="362" height="28" rx="5"/>
    <text class="fig-title" x="30" y="34" font-size="12">模式切换（全程仍为进程 A）</text>
    <text class="fig-blue" x="159" y="64" font-size="11" text-anchor="middle">① 进程 A 用户态运行</text>
    <text class="fig-muted" x="159" y="78" font-size="9.5" text-anchor="middle">PSW = 用户态 · 触发系统调用 read()</text>
    <text class="fig-orange" x="159" y="118" font-size="10.5" text-anchor="middle">② [硬件] 陷入内核 · PSW 改为内核态</text>
    <text class="fig-red" x="159" y="160" font-size="10.5" text-anchor="middle">③ 内核态执行 read() 例程</text>
    <text class="fig-muted" x="159" y="173" font-size="9.5" text-anchor="middle">★ 不切换 PTBR，不搬寄存器到 PCB</text>
    <text class="fig-orange" x="159" y="212" font-size="10.5" text-anchor="middle">④ [硬件] 返回指令 · PSW 改回用户态</text>
    <text class="fig-blue" x="159" y="254" font-size="11" text-anchor="middle">⑤ 进程 A 用户态恢复继续运行</text>
    <text class="fig-muted" x="159" y="268" font-size="9.5" text-anchor="middle">寄存器与地址空间从头到尾未换</text>
    <text class="fig-accent" x="159" y="300" font-size="10" text-anchor="middle">开销极小：仅改 PSW 模式位 + 用核心栈</text>
    <text class="fig-title" x="328" y="34" font-size="12">进程切换（头尾硬件原子，中间软件搬运）</text>
    <text class="fig-blue" x="509" y="61" font-size="10.5" text-anchor="middle">① 进程 A 用户态运行 → 时钟中断时间片到 / 请求阻塞</text>
    <text class="fig-muted" x="509" y="74" font-size="9.5" text-anchor="middle">CPU 正在执行 A，即将由内核接管</text>
    <text class="fig-orange" x="509" y="109" font-size="10.5" text-anchor="middle">② [硬件] 中断隐指令：压栈保存 A 的 PC / PSW，切内核态</text>
    <text class="fig-muted" x="509" y="122" font-size="9.5" text-anchor="middle">改了 PC 软件就跑不回来，故必须硬件原子做</text>
    <text class="fig-purple" x="509" y="157" font-size="10.5" text-anchor="middle">③ [软件] 保存 A 通用寄存器/SP → PCB_A；更新状态并入队</text>
    <text class="fig-muted" x="509" y="170" font-size="9.5" text-anchor="middle">同时调度器选中下一进程 B（若选回 A 则免切）</text>
    <text class="fig-purple" x="509" y="205" font-size="9.8" text-anchor="middle">④ [软件] 切换 PTBR（刷旧 TLB）与核心栈；恢复 B 通用寄存器</text>
    <text class="fig-muted" x="509" y="218" font-size="9.5" text-anchor="middle">★ 中断向量表基址寄存器全系统唯一，无需切换！</text>
    <text class="fig-orange" x="509" y="253" font-size="10.5" text-anchor="middle">⑤ [硬件] 中断返回指令 iret：恢复 B 的 PC 与 PSW(用户态)</text>
    <text class="fig-muted" x="509" y="266" font-size="9.5" text-anchor="middle">原子切换至 B 断点指令并切回用户态</text>
    <text class="fig-green" x="509" y="302" font-size="11" text-anchor="middle">⑥ 进程 B 在新地址空间中恢复运行（含两次模式切换）</text>
  </svg>
  <figcaption>图 2-10　模式切换（系统调用不换进程）vs 进程切换（头尾硬件 + 中间软件、PTBR 切换与向量表免切）对比</figcaption>
</figure>

#### 2.5.3 切换开销分解（直接 vs 间接）与时间片下限推导

1. **切换开销的两笔账**：
   - **直接开销 $\delta_d$**：执行切换例程本身所耗时间——保存/恢复寄存器上下文（可执行上千条指令）、更新 PCB 与队列指针、切换页表基址寄存器 PTBR 与核心栈。
   - **★间接开销 $\delta_i$（往往更大！）**：切换**完成之后**，新进程在一段时间内因缓存冷启动承受的减速损失——**TLB 冷启动**（页表更换后原有 TLB 快表项全部作废刷新，新进程经历 TLB 缺失密集期）与 **Cache 冷启动**（L1/L2 Cache 中全留着旧进程工作集，新进程初期频发未命中）。

2. **CPU 利用率公式与“忽略间接开销”算例**：
   设时间片长度为 $q$，单次切换总等效开销 $\delta = \delta_d + \delta_i$，则 CPU 有效利用率为：

   $$
   \text{CPU 利用率} = \frac{q}{q + \delta} = \frac{q}{q + \delta_d + \delta_i}
   $$

   - **例**：设实测直接开销 $\delta_d = 2\,\mu\text{s}$，TLB/Cache 冷启动折算间接开销 $\delta_i = 8\,\mu\text{s}$，故 $\delta = 10\,\mu\text{s}$。
     - 当 $q = 10\text{ ms} = 10000\,\mu\text{s}$ 时，实际利用率为 $\frac{10000}{10010} = 99.90\%$（忽略 $\delta_i$ 仅高估 $0.08\%$）；
     - 当时间片缩至 $q = 100\,\mu\text{s}$ 时，实际利用率为 $\frac{100}{110} = 90.91\%$，而仅算 $\delta_d$ 会误算出 $\frac{100}{102} = 98.04\%$——高估高达 **7.13 个百分点**！
     - 若要求利用率 $\ge 99\%$，反推时间片下限：$\frac{q}{q + 10} \ge 0.99 \Rightarrow q \ge 990\,\mu\text{s} \approx 1\text{ ms}$（若只按 $\delta_d=2\,\mu\text{s}$ 会误设成 $198\,\mu\text{s}$，相差 5 倍）。这也解释了多核调度中引入<strong>处理器亲和性（尽量让进程回原核运行）</strong>的工程意义：保护未过期的 Cache 热度。

3. **跨层级切换对比（含用户态协程）**：
   - **进程切换**：模式切换 + 搬寄存器 + 换 PTBR + **TLB/Cache 失效**（开销最大，约 $5.3\,\mu\text{s}$ 量级）。
   - **同进程内内核级线程（KLT）切换**：模式切换 + 搬寄存器至 TCB，但**共享进程页表、PTBR 不动、TLB 不失效**（消除最大间接开销，约 $2.0\,\mu\text{s}$）。
   - **用户级线程（ULT）与用户态协程（Coroutine）切换**：全程在用户空间换保存区/栈指针，`PSW` 不切换、**无需陷入内核**（约 $0.5\,\mu\text{s}$）；差异在于协程通常由程序员显式 `yield`/`await` 协作式让出控制权，而抢占式 ULT 库可借助信号时钟中断在用户态切换。

<figure class="cpd-figure not-content" id="os-c2-fig-11">
  <svg viewBox="0 0 720 274" role="img" aria-label="进程上下文切换直接开销与TLB和Cache冷启动间接开销分布及四类执行流切换开销对比图">
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="128" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="152" width="336" height="108" rx="8"/>
    <rect class="fig-box-subtle" x="364" y="152" width="340" height="108" rx="8"/>
    <rect class="fig-box-blue" x="28" y="54" width="136" height="44" rx="4"/>
    <rect class="fig-box-red" x="166" y="54" width="84" height="44" rx="4"/>
    <rect class="fig-box-orange" x="252" y="54" width="198" height="44" rx="4"/>
    <rect class="fig-box-green" x="452" y="54" width="238" height="44" rx="4"/>
    <rect class="fig-box" x="166" y="106" width="284" height="24" rx="4"/>
    <rect class="fig-box-red" x="378" y="182" width="120" height="14" rx="3"/>
    <rect class="fig-box-blue" x="378" y="204" width="45" height="14" rx="3"/>
    <rect class="fig-box-green" x="378" y="226" width="12" height="14" rx="3"/>
    <text class="fig-title" x="28" y="34" font-size="12">进程切换时间轴：直接开销 δ_d + 间接冷启动惩罚 δ_i（总开销 δ = δ_d + δ_i）</text>
    <text class="fig-blue" x="96" y="74" font-size="11" text-anchor="middle">进程 A 稳态运行</text>
    <text class="fig-muted" x="96" y="90" font-size="9.5" text-anchor="middle">TLB/Cache 命中率高</text>
    <text class="fig-red" x="208" y="74" font-size="10.5" text-anchor="middle">切换开销 δ_d</text>
    <text class="fig-muted" x="208" y="90" font-size="9.5" text-anchor="middle">搬现场+换PTBR</text>
    <text class="fig-orange" x="351" y="74" font-size="10.5" text-anchor="middle">进程 B 冷启动期（折算 δ_i）</text>
    <text class="fig-muted" x="351" y="90" font-size="9.5" text-anchor="middle">★ TLB 失效重填 + Cache 频未命中</text>
    <text class="fig-green" x="571" y="74" font-size="11" text-anchor="middle">进程 B 进入稳态运行</text>
    <text class="fig-muted" x="571" y="90" font-size="9.5" text-anchor="middle">B 的工作集重新载入缓存</text>
    <text class="fig-label" x="308" y="122" font-size="9.5" text-anchor="middle">总浪费 δ = δ_d + δ_i（通常 δ_i 远大于 δ_d）</text>
    <text class="fig-title" x="28" y="172" font-size="11.5">利用率与时间片下限公式</text>
    <text class="fig-accent" x="28" y="196" font-size="11">CPU 利用率 = q / (q + δ_d + δ_i)</text>
    <text class="fig-label" x="28" y="218" font-size="10">· 时间片 q 越小，忽略 δ_i 的误差越大</text>
    <text class="fig-label" x="28" y="236" font-size="10">· 若 δ_d=2μs, δ_i=8μs, 利用率≥99%</text>
    <text class="fig-muted" x="28" y="252" font-size="10">  则须 q ≥ 990μs（只算 δ_d 会错算成 198μs）</text>
    <text class="fig-title" x="378" y="172" font-size="11.5">切换开销对比（若无 ASID 标识）</text>
    <text class="fig-red" x="506" y="193" font-size="10">进程：5.3 μs (换PTBR+刷TLB)</text>
    <text class="fig-blue" x="431" y="215" font-size="10">同进程 KLT：2.0 μs (免刷 TLB!)</text>
    <text class="fig-green" x="398" y="237" font-size="10">ULT / 协程：0.5 μs (免陷内核)</text>
    <text class="fig-muted" x="378" y="253" font-size="9.5">带 ASID 标识可免整体刷 TLB，缩小进程与 KLT 差距</text>
  </svg>
  <figcaption>图 2-11　上下文切换直接开销与 TLB/Cache 冷启动间接开销结构及多层级切换代价对比</figcaption>
</figure>

---

### 2.6 进程间通信（IPC）

#### 2.6.1 隔离与通信的矛盾：四种核心 IPC 机制机理

各进程拥有彼此独立的虚拟地址空间，一个进程无法直接读写另一进程的用户内存——这是操作系统安全隔离的基石；但协作任务（如浏览器渲染进程与合成进程配合、`ls | grep` 管道串联）又要求进程之间交换数据或传递通知。解决这一天然冲突的唯一办法是：**由操作系统内核在进程之间开一个受控的通道**。口子怎么开，直接决定了四种 IPC 机制（**共享内存、消息传递、管道、信号**）的全部特性。

1. **共享存储（共享内存，Shared Memory）**：
   - **实现步骤**：通信双方先向内核申请共享存储区 $\rightarrow$ 各自通过系统调用将其<strong>附加（映射）</strong>到自己的虚拟地址空间 $\rightarrow$ 随后像普通内存一样直接读写 $\rightarrow$ 用毕归还分区。
   - **两种类型**：
     - **基于数据结构的共享**（**低级通信**）：OS 事先规定共享区中只能放置特定格式数据结构（如长度受限的有界缓冲区），仅适于传递少量数据。
     - **基于存储区的共享**（**高级通信**）：OS 仅划出整片物理共享区，存放数据的格式与位置全由进程自行决定，适于大批量高速数据交换。
   - **★核心机制（`2023#30` 真题直击）**：在页式虚拟存储下，内核将**同一批物理页框**分别填进进程 A 与进程 B 的页表。由于双方虚拟地址空间相互独立分配，同一份共享数据在 A、B 眼中**虚拟页号（VPN）不一定相同，但映射到的物理页框号（PPN）一定相同**！反之，同一个进程内的同一个虚拟页在同一时刻只能映射到一个物理页框。
   - **★为何最快且必须外挂互斥**：映射一旦建好，**内核就彻底退出了数据通路**，后续读写不触发系统调用、也不经过任何内存拷贝；正因为内核完全不介入读写过程，共享存储**不自带同步互斥机制**，程序员必须自行外挂信号量或互斥锁防止并发写乱。

2. **消息传递（Message Passing）**：
   进程间的数据交换以格式化的<strong>消息（Message）</strong>为单位，每条消息由长度固定的**消息头**（含发送者/接收者 PID、消息类型、消息长度等控制信息）和承载数据的<strong>消息体（正文）</strong>组成。发送方与接收方通过 `send` 与 `receive` 两条系统调用原语经**内核缓冲区**中转，数据需经历“发送方用户区 $\rightarrow$ 内核缓冲区 $\rightarrow$ 接收方用户区”**两次拷贝**。
   - **消息格式取舍**：**定长消息**处理与内存管理开销小（适于单机内部、同环境短报文通信），但长数据需人工拆分；**变长消息**对用户方便，但内核分配与存储开销大。
   - **两种寻址方式**：
     - **直接通信**：原语直接指明对方进程标识。收发双方均指名道姓为**对称寻址**（`send(B, msg); receive(A, msg);`），缺点是一旦某进程改名会牵连大量修改；仅发送方指定接收者、接收方用一个变量带回实际源 PID 的为**非对称寻址**（`send(P, msg); receive(id, msg);`），适合打印服务等一对多服务器模型。
     - **间接通信（信箱通信 / 消息队列）**：消息经由内核中转数据结构<strong>信箱（Mailbox）</strong>收发，收发双方彼此解耦。信箱由**信箱头**（信箱 ID、拥有者、口令、**空格数**等）与**信箱体**（若干**信箱格**，格数与每格容量在**创建信箱时确定**）构成。正因格数有限，信箱满时发送端可能阻塞。
   - **链路建立与阻塞组合**：
     - 链路按建立方式分**显式建链**（用连接原语手动建拆，多用于计算机网络）和**隐式建链**（首次 `send` 时由 OS 自动创建，多用于单机）；按方向分单向与双向；按容量分无容量（不可暂存）与有容量（可暂存 $n$ 条）。
     - **send / receive 阻塞组合**：
       - **发送阻塞 + 接收阻塞**：双方紧密同步会合（通常对应无容量链路，如双方都不缓存直接握手）。
       - **发送不阻塞 + 接收阻塞（★应用最广）**：客户端发出请求即走，服务端平时阻塞在 `receive` 上，来消息才被唤醒。
       - **发送不阻塞 + 接收不阻塞**：双方各忙各的，条件不具备再自阻塞；而“发送阻塞 + 接收不阻塞”因接收方盲目轮询、发送方却等待，设计意图自相矛盾而极少采用。

<figure class="cpd-figure not-content" id="os-c2-fig-12">
  <svg viewBox="0 0 720 318" role="img" aria-label="共享内存（双页表映至同一物理页框）与直接/间接消息传递原理对比图">
    <defs>
      <marker id="os-c2-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="338" height="290" rx="8"/>
    <rect class="fig-box-subtle" x="366" y="14" width="338" height="290" rx="8"/>
    <line class="fig-line-accent" x1="100" y1="114" x2="146" y2="150" marker-end="url(#os-c2-arr-12)"/>
    <line class="fig-line-accent" x1="270" y1="114" x2="224" y2="150" marker-end="url(#os-c2-arr-12)"/>
    <line class="fig-line-accent" x1="454" y1="102" x2="484" y2="102" marker-end="url(#os-c2-arr-12)"/>
    <line class="fig-line-accent" x1="586" y1="102" x2="616" y2="102" marker-end="url(#os-c2-arr-12)"/>
    <line class="fig-line-accent" x1="454" y1="228" x2="484" y2="228" marker-end="url(#os-c2-arr-12)"/>
    <line class="fig-line-accent" x1="586" y1="228" x2="616" y2="228" marker-end="url(#os-c2-arr-12)"/>
    <rect class="fig-box-blue" x="28" y="54" width="144" height="60" rx="5"/>
    <rect class="fig-box-green" x="198" y="54" width="144" height="60" rx="5"/>
    <rect class="fig-box-purple" x="64" y="152" width="242" height="58" rx="5"/>
    <rect class="fig-box-orange" x="28" y="222" width="314" height="70" rx="5"/>
    <rect class="fig-box" x="378" y="48" width="314" height="106" rx="6"/>
    <rect class="fig-box" x="378" y="166" width="314" height="126" rx="6"/>
    <rect class="fig-box-blue" x="388" y="80" width="66" height="44" rx="4"/>
    <rect class="fig-box-purple" x="486" y="76" width="100" height="52" rx="4"/>
    <rect class="fig-box-green" x="618" y="80" width="64" height="44" rx="4"/>
    <rect class="fig-box-blue" x="388" y="204" width="66" height="46" rx="4"/>
    <rect class="fig-box-purple" x="486" y="198" width="100" height="60" rx="4"/>
    <rect class="fig-box-green" x="618" y="204" width="64" height="46" rx="4"/>
    <text class="fig-title" x="28" y="34" font-size="12.5">① 共享存储（共享内存：零拷贝、最快）</text>
    <text class="fig-blue" x="100" y="74" font-size="11" text-anchor="middle">进程 A 虚拟空间</text>
    <text class="fig-muted" x="100" y="92" font-size="10" text-anchor="middle">虚拟页号 VPN = 0x10</text>
    <text class="fig-muted" x="100" y="106" font-size="9.5" text-anchor="middle">通过 A 的页表映射</text>
    <text class="fig-green" x="270" y="74" font-size="11" text-anchor="middle">进程 B 虚拟空间</text>
    <text class="fig-muted" x="270" y="92" font-size="10" text-anchor="middle">虚拟页号 VPN = 0x85</text>
    <text class="fig-muted" x="270" y="106" font-size="9.5" text-anchor="middle">通过 B 的页表映射</text>
    <text class="fig-purple" x="185" y="176" font-size="11.5" text-anchor="middle">同一批物理页框（PPN = 200）</text>
    <text class="fig-muted" x="185" y="196" font-size="10" text-anchor="middle">直接读写主存 · 建好后内核退出数据通路</text>
    <text class="fig-orange" x="185" y="241" font-size="10.5" text-anchor="middle">★ 虚拟页号不一定同，物理页框号一定同 (2023#30)</text>
    <text class="fig-label" x="185" y="261" font-size="10" text-anchor="middle">无内核拷贝与系统调用，但须自行外挂信号量互斥</text>
    <text class="fig-muted" x="185" y="279" font-size="9.5" text-anchor="middle">低级：基于数据结构（定格式）| 高级：基于存储区</text>
    <text class="fig-title" x="378" y="34" font-size="12.5">② 消息传递（内核中转：两次数据拷贝）</text>
    <text class="fig-label" x="390" y="66" font-size="11">A. 直接通信（显式指定对方进程标识）</text>
    <text class="fig-blue" x="421" y="99" font-size="10.5" text-anchor="middle">进程 A</text>
    <text class="fig-muted" x="421" y="114" font-size="9.5" text-anchor="middle">send(B)</text>
    <text class="fig-purple" x="536" y="97" font-size="10.5" text-anchor="middle">内核消息缓冲</text>
    <text class="fig-muted" x="536" y="114" font-size="9.5" text-anchor="middle">[消息头 | 正文]</text>
    <text class="fig-green" x="650" y="99" font-size="10.5" text-anchor="middle">进程 B</text>
    <text class="fig-muted" x="650" y="114" font-size="8.6" text-anchor="middle">recv(A/id)</text>
    <text class="fig-muted" x="536" y="144" font-size="9.5" text-anchor="middle">对称寻址(双向指名) vs 非对称寻址(id 带回发送方)</text>
    <text class="fig-label" x="390" y="186" font-size="11">B. 间接通信（经由内核信箱 Mailbox 解耦）</text>
    <text class="fig-blue" x="421" y="224" font-size="10.5" text-anchor="middle">发送方</text>
    <text class="fig-muted" x="421" y="240" font-size="9.5" text-anchor="middle">send(box)</text>
    <text class="fig-purple" x="536" y="218" font-size="10.5" text-anchor="middle">内核信箱 M</text>
    <text class="fig-muted" x="536" y="234" font-size="9.5" text-anchor="middle">头: 空格数/口令</text>
    <text class="fig-muted" x="536" y="249" font-size="9.5" text-anchor="middle">体: 固定格队列</text>
    <text class="fig-green" x="650" y="224" font-size="10.5" text-anchor="middle">接收方</text>
    <text class="fig-muted" x="650" y="240" font-size="9.5" text-anchor="middle">recv(box)</text>
    <text class="fig-muted" x="536" y="280" font-size="9.5" text-anchor="middle">★ 典型阻塞组合：不阻塞发 + 阻塞收；无缓冲+双阻塞=会合</text>
  </svg>
  <figcaption>图 2-12　共享存储（跨页表同框零拷贝）与直接/间接消息传递（信箱队列两次拷贝）原理对比</figcaption>
</figure>

3. **管道通信（Pipe）**：
   管道本质上是操作系统内核开辟的一块**固定大小的环形内存缓冲区**（又名共享文件 `pipe` 文件），以<strong>无格式字符流（字节流）</strong>的形式按 **先进先出（FIFO）** 顺序传输数据。

   > **★考点（管道通信四大必背结论，`2014#31` 集中考察）**：
   > 1. **半双工通信（单向传输）**：一条管道数据只能从写端单向流向读端；若需双方同时双向读写，**必须建立两条管道**。
   > 2. **容量在内核内存，不在磁盘**：管道是内存里的固定缓冲区（通常几十 KB），**绝非“容量仅受磁盘容量限制”**。
   > 3. **自带同步（读写均可能阻塞），但不自带互斥**：写进程写满缓冲区时 **`write()` 阻塞**（等读进程取走唤醒），读进程读空缓冲区时 **`read()` 阻塞**（等写进程写入唤醒），恰似生产者–消费者模型。同一管道**允许存在多个读进程或多个写进程**，但多写者并发写入仍会相互覆盖错乱，必须配合外部互斥。
   > 4. **确认对方存在**：管道通信还需检查对端是否打开（如向读端已全关闭的管道写入会触发 `SIGPIPE` 异常）。

   **匿名管道 vs 命名管道（FIFO）对比**：

   | 对比项 | 匿名管道（Anonymous Pipe） | 命名管道（Named Pipe / FIFO） |
   | --- | --- | --- |
   | **文件名与路径** | **无名字**，在文件系统中没有路径入口 | **有文件名**，在文件系统中以特殊管道文件存在 |
   | **建立联系的方式** | 创建管道返回两个 fd 后调用 `fork()`，**靠继承文件描述符** | 通信双方各自通过**路径名**调用 `open()` 打开即可 |
   | **适用进程范围** | **★仅限于具有亲缘关系的进程**（父子、兄弟进程） | **任意两个进程**，互不相识也可通信 |
   | **生命周期** | 随最后一个持有其描述符的进程关闭而销毁 | 路径名持久存在于文件目录中，直到显式 `unlink`/删除 |

4. **信号（Signal）**：
   信号是一种用于在**进程级别**异步通知“**发生了某个系统或应用事件**”的通信机制（如除零触发 `SIGFPE`、非法指令触发 `SIGILL`、向无读端管道写触发 `SIGPIPE`、或进程调用 `kill(pid, sig)` 发送信号）。
   - **数据结构与“丢失”原理**：每个进程 PCB 中维护一对 $n$ 位向量——<strong>待处理信号位向量（Pending）</strong>记录已收到但尚未处理的信号（对应位为 `1`），<strong>屏蔽信号位向量（Blocked）</strong>记录当前暂不响应的信号。因为每类信号只占 **1 个比特位**，所以信号**只传事件类型编号、不传数据载荷、不计数也不排队**——同一信号连续到达多次在未处理前会被合并（可能丢失）。
   - **三种处理方式**：① **默认处理**（如 `SIGKILL`/`SIGILL` 默认终止进程）；② **忽略**（特定不可忽略信号如 `SIGKILL` 除外）；③ **自定义捕获处理**（执行用户注册的信号处理函数，多在用户态执行，结束后返回原断点）。

   **为何把信号称为“进程级软中断”？（与硬件中断五维对比）**：

   | 维度 | 硬件中断（Hardware Interrupt） | 信号（Signal） |
   | --- | --- | --- |
   | **触发源** | 外部 I/O 设备、时钟或 CPU 内部异常 | 内核检测到的异常事件，或另一进程 `kill()` |
   | **打断对象** | 打断<strong>处理机（CPU）</strong>当前指令流 | 打断**目标进程**的正常用户态执行流 |
   | **处理程序位置** | 中断服务程序（**内核态**执行） | 信号处理函数（多在**用户态**执行） |
   | **屏蔽手段** | CPU 中断屏蔽字（CLI / 屏蔽寄存器） | PCB 中的屏蔽信号位向量（Signal Mask） |
   | **处理后去向** | 返回被中断指令的断点 | 通常返回进程被中断的断点（除非退出或跳转） |

<figure class="cpd-figure not-content" id="os-c2-fig-13">
  <svg viewBox="0 0 720 314" role="img" aria-label="管道通信内核环形缓冲区双阻塞机制（匿名vs命名）与信号双位向量异步通知图">
    <defs>
      <marker id="os-c2-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="388" height="286" rx="8"/>
    <rect class="fig-box-subtle" x="416" y="14" width="288" height="286" rx="8"/>
    <line class="fig-line-accent" x1="116" y1="86" x2="140" y2="86" marker-end="url(#os-c2-arr-13)"/>
    <line class="fig-line-accent" x1="278" y1="86" x2="304" y2="86" marker-end="url(#os-c2-arr-13)"/>
    <line class="fig-line-accent" x1="560" y1="96" x2="560" y2="116" marker-end="url(#os-c2-arr-13)"/>
    <line class="fig-line-accent" x1="560" y1="210" x2="560" y2="228" marker-end="url(#os-c2-arr-13)"/>
    <rect class="fig-box-blue" x="28" y="62" width="88" height="48" rx="5"/>
    <rect class="fig-box-purple" x="142" y="54" width="136" height="64" rx="5"/>
    <rect class="fig-box-green" x="306" y="62" width="86" height="48" rx="5"/>
    <rect class="fig-box-orange" x="28" y="132" width="176" height="44" rx="4"/>
    <rect class="fig-box-orange" x="216" y="132" width="176" height="44" rx="4"/>
    <rect class="fig-box" x="28" y="188" width="176" height="58" rx="4"/>
    <rect class="fig-box" x="216" y="188" width="176" height="58" rx="4"/>
    <rect class="fig-box-red" x="28" y="254" width="364" height="36" rx="4"/>
    <rect class="fig-box-orange" x="430" y="50" width="260" height="46" rx="5"/>
    <rect class="fig-box-purple" x="430" y="118" width="260" height="92" rx="5"/>
    <rect class="fig-box" x="438" y="148" width="244" height="24" rx="3"/>
    <rect class="fig-box" x="438" y="178" width="244" height="24" rx="3"/>
    <rect class="fig-box-blue" x="430" y="230" width="260" height="58" rx="5"/>
    <text class="fig-title" x="28" y="34" font-size="12.5">③ 管道通信（内核固定缓冲区 · 半双工 FIFO）</text>
    <text class="fig-blue" x="72" y="82" font-size="11" text-anchor="middle">写进程</text>
    <text class="fig-muted" x="72" y="99" font-size="10" text-anchor="middle">write() 写入</text>
    <text class="fig-purple" x="210" y="76" font-size="11" text-anchor="middle">内核环形缓冲区</text>
    <text class="fig-muted" x="210" y="93" font-size="9.5" text-anchor="middle">字节流 FIFO（非磁盘）</text>
    <text class="fig-muted" x="210" y="109" font-size="9" text-anchor="middle">[写指针 → ... → 读指针]</text>
    <text class="fig-green" x="349" y="82" font-size="11" text-anchor="middle">读进程</text>
    <text class="fig-muted" x="349" y="99" font-size="10" text-anchor="middle">read() 读取</text>
    <text class="fig-orange" x="116" y="150" font-size="10.5" text-anchor="middle">★ 满则写阻塞</text>
    <text class="fig-muted" x="116" y="167" font-size="9.5" text-anchor="middle">缓冲区满时写者睡眠等取</text>
    <text class="fig-orange" x="304" y="150" font-size="10.5" text-anchor="middle">★ 空则读阻塞</text>
    <text class="fig-muted" x="304" y="167" font-size="9.5" text-anchor="middle">缓冲区空时读者睡眠等写</text>
    <text class="fig-label" x="116" y="207" font-size="10.5" text-anchor="middle">匿名管道 (pipe)</text>
    <text class="fig-muted" x="116" y="223" font-size="9.5" text-anchor="middle">无路径名，靠 fork 继承 fd</text>
    <text class="fig-muted" x="116" y="238" font-size="9.5" text-anchor="middle">仅限亲缘进程</text>
    <text class="fig-label" x="304" y="207" font-size="10.5" text-anchor="middle">命名管道 (FIFO)</text>
    <text class="fig-muted" x="304" y="223" font-size="9.5" text-anchor="middle">文件系统中有路径名</text>
    <text class="fig-muted" x="304" y="238" font-size="9.5" text-anchor="middle">任意进程均可打开</text>
    <text class="fig-red" x="210" y="276" font-size="10" text-anchor="middle">半双工(双向须开两条) · 可多读多写但多写须外部互斥 (2014#31)</text>
    <text class="fig-title" x="428" y="34" font-size="12.5">④ 信号（Signal：异步事件通知）</text>
    <text class="fig-orange" x="560" y="69" font-size="10.5" text-anchor="middle">信号来源：内核异常 / 进程 kill(pid, sig)</text>
    <text class="fig-muted" x="560" y="86" font-size="9.5" text-anchor="middle">如 SIGILL / SIGPIPE / SIGKILL（不携带数据）</text>
    <text class="fig-purple" x="560" y="138" font-size="11" text-anchor="middle">目标进程 PCB 内双位向量</text>
    <text class="fig-label" x="560" y="164" font-size="9" text-anchor="middle">Pending：[0|1|0|…|1]（置 1 标记）</text>
    <text class="fig-muted" x="560" y="194" font-size="9" text-anchor="middle">Blocked：[0|0|1|…|0]（置 1 暂缓）</text>
    <text class="fig-blue" x="560" y="249" font-size="10.5" text-anchor="middle">三种处理：默认动作 / 忽略 / 自定义函数</text>
    <text class="fig-muted" x="560" y="266" font-size="9.5" text-anchor="middle">★ 位图记录：不计数、不排队、连发可能丢失</text>
    <text class="fig-muted" x="560" y="281" font-size="9.5" text-anchor="middle">进程级“软中断”，多在用户态回调处理</text>
  </svg>
  <figcaption>图 2-13　管道通信环形缓冲区双阻塞特性（匿名 vs 命名）与信号双位向量异步通知机制</figcaption>
</figure>

#### 2.6.2 四类 IPC 对比矩阵与量化选型算例

| IPC 方式 | 数据通路与拷贝次数 | 速度与内核开销 | 同步互斥特性 | 方向与通信范围 | 典型适用场景 |
| --- | --- | --- | --- | --- | --- |
| **共享内存** | 映射同批物理页框，**通信时不经内核、零拷贝** | **最快**（建映射一次性开销，之后为零） | **内核不管**：必须自行加信号量/互斥锁 | 双向；同机多进程 | **高频、大数据量**（如视频帧、渲染共享） |
| **消息传递** | 经内核缓冲区中转，**每条 2 次数据拷贝** | 中等（每次收发均需系统调用与拷贝） | 无容量+双阻塞时由 OS 会合；否则须自理 | 双向；支持单机或跨机器（分布式） | 中小消息、结构化异步报文、跨网扩展 |
| **管道通信** | 经内核环形缓冲区，**2 次拷贝**，无消息头 | 中等（流式读写系统调用） | **自带同步**（满写阻塞/空读阻塞），**不带互斥** | **半双工**（双向建两条）；匿名限亲缘、命名任意 | 流式单向数据衔接（如 Shell 命令行管道） |
| **信号** | 仅改目标进程 PCB 待处理位向量 | 极轻（不传正文） | 异步通知，**不计数不排队，可能丢失** | 单向事件通知 | 异常处理、紧急控制、进程中止通知 |

> **注意（IPC 选型三问与“共享内存并非永远最快”算例）**：
> 选型不能盲从“共享内存最快”，而应先问：**① 传数据还是传事件？② 数据量多大、传输多少次？③ 跨不跨机器？**
> 设内存拷贝速率 $2\text{ GB/s}$（$1\text{ MB}$ 耗时 $500\,\mu\text{s}$，$4\text{ B}$ 耗时 $0.002\,\mu\text{s}$），1 次系统调用 $1\,\mu\text{s}$，1 对 P/V 操作 $1\,\mu\text{s}$，共享内存建映射一次性开销 $200\,\mu\text{s}$：
> - **传 100 条 1 MB 大数据**：消息传递 $t_{\text{消息}} = 100 \times (2 \times 500 + 2 \times 1) = 100.2\text{ ms}$；共享存储 $t_{\text{共享}} = 200 + 100 \times (1 \times 500 + 1) = 50.3\text{ ms}$（省掉一次拷贝，降幅近半）。
> - **只传 1 次 4 B 控制信号**：消息传递 $t_{\text{消息}} = 2.004\,\mu\text{s}$；共享存储 $t_{\text{共享}} = 200 + 1.002 = 201.002\,\mu\text{s}$——**共享存储反而慢 100 倍**！需传输 $N^* = \frac{200}{2.004 - 1.002} \approx 200$ 次以上才能摊平建映射开销。

---

### 2.7 线程的概念、属性与实现方式 ★

#### 2.7.1 引入线程的动因：资源分配单位与独立调度单位分离

传统进程身兼两职：既要作为独立占有虚拟地址空间、文件与设备的“资源容器”，又要作为上 CPU 运行的“调度执行流”。每次创建或切换进程，都要连带搬动整套地址空间与调度开销，代价过于高昂；而且单一执行流的进程无法同时利用多核并行，一旦发起阻塞 I/O 就整个进程挂起。

为此，现代操作系统将进程的这两个身份彻底拆开（`2012#31`）：
- **进程**：继续保留**系统资源分配与保护的基本单位**身份；
- **线程（Thread）**：接过**处理机独立调度和分派的基本单位**身份，成为进程内部的一条独立执行流。

> **★考点**：**不管操作系统是否支持线程，进程始终是资源分配的基本单位**（`2012#31`）！引入线程后被分走的只有“独立调度”这个身份，绝不存在“线程是资源分配基本单位”的情况。

每个进程启动时至少自带一条线程，称为**主线程**；多核处理器可将同一进程内的多个线程同时分派到多个物理/逻辑核心上**真并行**执行。

| 进程形态 | 核心结构与同步需求 | 并行能力与阻塞影响 |
| --- | --- | --- |
| **单线程进程** | 只有 1 条执行流；无线程间数据竞争，设计调试简单 | 任一时刻最多占用 **1 个**逻辑核；唯一线程阻塞则整个进程停摆 |
| **多线程进程** | 多条执行流共用同一地址空间与堆；需用互斥锁/信号量防止竞态 | 可同时调度到**多核并行**；某线程阻塞时同进程其他线程仍可推进（KLT 下）；但一线程越界踩坏共享数据会拖垮全进程 |

#### 2.7.2 线程私有与共享边界、TCB 内容及进程与线程多维对比 ★

考题中反复考察“同一进程内哪些资源线程共享、哪些线程私有”（`2011#25`、`2024#28`、`2026#25`）。无需死记硬背，只需一条**黄金判据**：
**切换一条执行流时必须跟着换掉的东西 $\Rightarrow$ 线程私有；不必换掉的进程容器资产 $\Rightarrow$ 进程内所有线程共享。**

| 归属类别 | 具体内容 | 背后原理与高频考点 |
| --- | --- | --- |
| **★线程私有（每线程各一份）** | **线程标识符（TID）**、**程序计数器（PC）**、**一组寄存器**（通用寄存器、`PSW`）、**栈与栈指针（SP）**（含**用户栈与内核核心栈两个指针**）、**线程控制块（TCB）**、线程状态与优先级、线程专有局部存储区（TLS）、信号屏蔽字 | 每条执行流各有当前指令断点与函数调用链（局部变量/实参/返回地址），绝不能共用；**`栈指针`与`栈`是私有边界最高频考点**（`2011#25`、`2024#28`、`2026#25`）。注意：因同一地址空间不隔离，理论上某线程拿到另一线程栈指针也能强行读写，故称“逻辑独立私有、缺乏硬件隔离” |
| **★进程内共享（所有线程共用）** | **进程虚拟地址空间**（及页表）、**代码段（Text）**、**全局与静态变量（Data / BSS）**、**堆（Heap）**、**打开的文件（文件描述符表 `fd`）**、I/O 设备权限、信号默认处理方式、子进程集合 | 切换同进程线程时不换地址空间与页表；**堆是共享的、栈是私有的**（`2026#25` 正选“同进程多线程共享进程堆”）；某线程 `malloc` 的内存地址可直接交给同伴线程使用 |

**线程控制块（TCB）的七项典型内容**与进程 PCB 对比，少了整套“地址空间/页表基址、打开文件表、资源清单、父子家族层次（线程间平等无父子继承关系）”：
1. 线程标识符（TID）；
2. 一组寄存器（`PC`、`PSW`、通用寄存器现场）；
3. 线程运行状态（仅**就绪、运行、阻塞**三态，转换规律与进程一致；**线程没有独立的挂起态**，挂起是以进程为单位的——进程一旦挂起，其内部所有线程一并挂起）；
4. 优先级（调度参考）；
5. 线程专有存储区（现场保存与统计信息）；
6. 信号屏蔽字；
7. **两个堆栈指针**：指向用户态使用的**用户栈指针**，以及陷入内核态时使用的**核心栈指针**。

<figure class="cpd-figure not-content" id="os-c2-fig-14">
  <svg viewBox="0 0 720 318" role="img" aria-label="多线程进程虚拟地址空间（共享堆代码数据与私有栈）及PCB与TCB职责拆分结构图">
    <defs>
      <marker id="os-c2-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="342" height="290" rx="8"/>
    <rect class="fig-box-subtle" x="370" y="14" width="334" height="290" rx="8"/>
    <line class="fig-line-accent" x1="484" y1="126" x2="454" y2="156" marker-end="url(#os-c2-arr-14)"/>
    <line class="fig-line-accent" x1="590" y1="126" x2="620" y2="156" marker-end="url(#os-c2-arr-14)"/>
    <rect class="fig-box-purple" x="28" y="44" width="318" height="46" rx="5"/>
    <rect class="fig-box-orange" x="28" y="98" width="100" height="58" rx="5"/>
    <rect class="fig-box-orange" x="137" y="98" width="100" height="58" rx="5"/>
    <rect class="fig-box-orange" x="246" y="98" width="100" height="58" rx="5"/>
    <rect class="fig-box-blue" x="28" y="164" width="318" height="32" rx="4"/>
    <rect class="fig-box-green" x="28" y="202" width="318" height="38" rx="5"/>
    <rect class="fig-box-accent" x="28" y="246" width="318" height="46" rx="5"/>
    <rect class="fig-box-purple" x="384" y="44" width="306" height="82" rx="5"/>
    <rect class="fig-box-blue" x="384" y="158" width="146" height="104" rx="5"/>
    <rect class="fig-box-green" x="544" y="158" width="146" height="104" rx="5"/>
    <rect class="fig-box" x="384" y="270" width="306" height="24" rx="4"/>
    <text class="fig-title" x="28" y="32" font-size="12">多线程进程内存布局：共享 vs 私有</text>
    <text class="fig-purple" x="187" y="64" font-size="11" text-anchor="middle">内核空间（PCB · 页表 · 各线程核心栈/KTCB）</text>
    <text class="fig-muted" x="187" y="81" font-size="9.5" text-anchor="middle">核心栈按线程私有，用于陷入内核态执行</text>
    <text class="fig-orange" x="78" y="118" font-size="10.5" text-anchor="middle">线程 1 栈</text>
    <text class="fig-muted" x="78" y="135" font-size="9.5" text-anchor="middle">SP1 私有 ↓</text>
    <text class="fig-muted" x="78" y="149" font-size="9.5" text-anchor="middle">局部变量1</text>
    <text class="fig-orange" x="187" y="118" font-size="10.5" text-anchor="middle">线程 2 栈</text>
    <text class="fig-muted" x="187" y="135" font-size="9.5" text-anchor="middle">SP2 私有 ↓</text>
    <text class="fig-muted" x="187" y="149" font-size="9.5" text-anchor="middle">局部变量2</text>
    <text class="fig-orange" x="296" y="118" font-size="10.5" text-anchor="middle">线程 3 栈</text>
    <text class="fig-muted" x="296" y="135" font-size="9.5" text-anchor="middle">SP3 私有 ↓</text>
    <text class="fig-muted" x="296" y="149" font-size="9.5" text-anchor="middle">局部变量3</text>
    <text class="fig-blue" x="187" y="184" font-size="10.5" text-anchor="middle">共享：动态链接库 / mmap 映射区</text>
    <text class="fig-green" x="187" y="219" font-size="11" text-anchor="middle">★ 共享：堆 Heap（malloc/new，全线程可见）</text>
    <text class="fig-muted" x="187" y="234" font-size="9.5" text-anchor="middle">向上增长 ↑ · 2026#25 明确考点：堆共享、栈私有</text>
    <text class="fig-accent" x="187" y="265" font-size="10.5" text-anchor="middle">共享：Data / BSS (全局变量) + Text (代码段)</text>
    <text class="fig-muted" x="187" y="282" font-size="9.5" text-anchor="middle">+ 打开文件描述符表 (fd) 与全部进程级资源</text>
    <text class="fig-title" x="384" y="32" font-size="12">PCB 与 TCB 职责拆分（1 对多关系）</text>
    <text class="fig-purple" x="537" y="64" font-size="11.5" text-anchor="middle">PCB（进程控制块：管理资源容器）</text>
    <text class="fig-label" x="537" y="84" font-size="10" text-anchor="middle">PID · 虚存页表基址(PTBR) · 打开文件表 fd</text>
    <text class="fig-muted" x="537" y="102" font-size="10" text-anchor="middle">I/O 设备清单 · 信号处理方式 · 关联线程列表</text>
    <text class="fig-muted" x="537" y="119" font-size="9.5" text-anchor="middle">（进程终止或挂起时，其下全部线程一并终止/挂起）</text>
    <text class="fig-blue" x="457" y="177" font-size="11" text-anchor="middle">TCB 1 (线程 1)</text>
    <text class="fig-label" x="457" y="196" font-size="9.5" text-anchor="middle">TID 1 · 状态 · 优先级</text>
    <text class="fig-label" x="457" y="214" font-size="9.5" text-anchor="middle">PC1 · PSW · 通用寄存器</text>
    <text class="fig-muted" x="457" y="232" font-size="9.5" text-anchor="middle">用户栈指针 &amp; 核心栈指针</text>
    <text class="fig-muted" x="457" y="249" font-size="9.5" text-anchor="middle">专有存储区 · 信号屏蔽</text>
    <text class="fig-green" x="617" y="177" font-size="11" text-anchor="middle">TCB 2 (线程 2)</text>
    <text class="fig-label" x="617" y="196" font-size="9.5" text-anchor="middle">TID 2 · 状态 · 优先级</text>
    <text class="fig-label" x="617" y="214" font-size="9.5" text-anchor="middle">PC2 · PSW · 通用寄存器</text>
    <text class="fig-muted" x="617" y="232" font-size="9.5" text-anchor="middle">用户栈指针 &amp; 核心栈指针</text>
    <text class="fig-muted" x="617" y="249" font-size="9.5" text-anchor="middle">专有存储区 · 信号屏蔽</text>
    <text class="fig-accent" x="537" y="286" font-size="10" text-anchor="middle">黄金判据：切执行流时必换的放 TCB/私有；不换的留 PCB/共享</text>
  </svg>
  <figcaption>图 2-14　多线程进程内存空间“栈私有、堆与代码数据共享”边界及 PCB–TCB 控制块拆分结构</figcaption>
</figure>

**进程与线程八大维度深度对比表**：

| 比较维度 | 进程（Process） | 线程（Thread） |
| --- | --- | --- |
| **核心身份** | **系统资源分配与保护的基本单位** | **处理机独立调度与执行的基本单位**（“轻型进程”的执行流本体） |
| **拥有资源** | 拥有完整虚存地址空间、页表、打开文件、I/O 设备与全部资源 | 几乎不拥有系统资源，仅占 **TCB、PC、寄存器组与私有栈**，共享所属进程资源 |
| **创建/撤销开销** | **大**：须分配/回收虚拟地址空间、建立页表、复制文件描述符等 | **小**：仅申请一块几百至数千字节栈空间及 TCB（系统还常保留撤销后 TCB 供复用） |
| **切换开销** | **大**：须陷入内核态、保存 PCB 且**更换地址空间（换 PTBR、刷新 TLB、Cache 冷启动）** | **小**：同进程内切换**不换地址空间（PTBR 不动、TLB 不失效）**；ULT 甚至免陷内核 |
| **通信方式** | 跨独立地址空间，须借助 OS 的 **IPC 机制**（管道/消息/共享内存/信号） | 同进程线程**直接读写共享的全局变量与堆内存**（需互斥锁/信号量同步） |
| **并发与并行性** | 进程间可并发，也可在多核上并行 | 不仅进程间并发，同进程多个（内核级）线程也可在多核上**真并行** |
| **独立性与隔离性** | **强**：虚拟地址空间彼此隔离，互相不可见 | **弱**：同进程线程共用地址空间，某线程可通过指针访问他人的栈空间 |
| **出错容错影响** | 一进程崩溃通常不影响其他独立进程运行 | 任一线程发生除零、野指针写坏共享区或非法指令，**可能导致整个进程一起终止** |

#### 2.7.3 线程的实现方式：用户级线程（ULT）与内核级线程（KLT）

线程实现最根本的分水岭只有一刀——**操作系统内核到底认不认识线程（TCB 究竟建在用户空间还是内核空间）**。这一刀直接决定了两大类别的全部优缺点，无一例外皆为推论：

| 对比维度 | 用户级线程（ULT / 线程库支持） | 内核级线程（KLT / 内核支持线程 KST） |
| --- | --- | --- |
| **管理主体与 TCB 位置** | **用户空间线程库**（如早期 POSIX 线程包）创建并维护线程表；**OS 不建 TCB、不知道线程存在**（`2019#23`、`2026#25`） | **操作系统内核**通过系统调用在**内核空间**创建并维护每个线程的 TCB |
| **内核眼里的调度对象** | **依然只有进程**（时间片按整个进程分配，进程内线程越多每线程分得越少） | **每一个内核级线程** |
| **切换开销** | **★最小**：无需模式切换，纯用户态线程库完成（约 $0.5\,\mu\text{s}$） | 需经“用户态 $\rightarrow$ 内核态 $\rightarrow$ 用户态”模式切换（约 $2.0\,\mu\text{s}$），但免切页表，仍远快于进程切换 |
| **调度算法定制** | **可由应用进程专用**：不同进程各自定制线程调度策略 | 统一归内核调度器管辖 |
| **平台移植性** | **极强**：线程库属用户程序的一部分，**可在不支持线程的 OS 上运行** | 依赖 OS 内核支持 |
| **一个线程阻塞后果** | **★致命缺点——整个进程阻塞**（内核以为进程阻塞，即使其余 ULT 就绪也拿不到 CPU；可用 **Jacketing** 技术把阻塞调用改写为非阻塞轮询缓解） | **仅阻塞该线程**：内核可立即调度同进程中其他就绪 KLT 继续运行 |
| **多处理机并行能力** | **★用不了多核**：内核每次最多给该进程分 1 个 CPU 核心 | **可真并行**：内核可将同一进程的多个 KLT 同时分派到多个 CPU 核上并行；且内核自身也可多线程化 |

> **★考点（三类切换量化开销比 `1 : 4 : 10.6`）**：
> 设单核模式下：模式切换 $0.4\,\mu\text{s}$，保存/恢复寄存器现场 $1.2\,\mu\text{s}$，换 PTBR $0.3\,\mu\text{s}$，TLB 整体失效重填折算 $3.0\,\mu\text{s}$，纯用户态线程库切换 $0.5\,\mu\text{s}$。则：
> - $t_{\text{ULT}} = 0.5\,\mu\text{s}$（无模式切换、无换地址空间）；
> - $t_{\text{KLT}} = 2 \times 0.4 + 1.2 = 2.0\,\mu\text{s}$（一进一出两次模式切换 + 搬现场，PTBR 不动、TLB 不失效）；
> - $t_{\text{进程}} = 2 \times 0.4 + 1.2 + 0.3 + 3.0 = 5.3\,\mu\text{s}$（多出换页表基址与 TLB 刷新重填）。
> 若硬件为 TLB 配备进程地址空间标识符（**ASID**）从而切换进程免整体刷 TLB，进程切换与 KLT 切换的开销差距会显著缩小——**“进程切换贵”最贵就贵在 TLB 失效那 $3.0\,\mu\text{s}$ 上**。

<figure class="cpd-figure not-content" id="os-c2-fig-15">
  <svg viewBox="0 0 720 314" role="img" aria-label="用户级线程ULT（用户态线程库管理）与内核级线程KLT（内核TCB与多核并行）机制对比图">
    <defs>
      <marker id="os-c2-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="338" height="286" rx="8"/>
    <rect class="fig-box-subtle" x="366" y="14" width="338" height="286" rx="8"/>
    <line class="fig-line-dashed" x1="24" y1="162" x2="346" y2="162"/>
    <line class="fig-line-dashed" x1="374" y1="126" x2="696" y2="126"/>
    <line class="fig-line-accent" x1="80" y1="90" x2="108" y2="108" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="185" y1="90" x2="185" y2="108" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="290" y1="90" x2="262" y2="108" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line" x1="185" y1="146" x2="185" y2="178" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="440" y1="98" x2="440" y2="146" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="535" y1="98" x2="535" y2="146" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="630" y1="98" x2="630" y2="146" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="440" y1="188" x2="478" y2="210" marker-end="url(#os-c2-arr-15)"/>
    <line class="fig-line-accent" x1="535" y1="188" x2="594" y2="210" marker-end="url(#os-c2-arr-15)"/>
    <rect class="fig-box-blue" x="34" y="54" width="90" height="36" rx="4"/>
    <rect class="fig-box-blue" x="140" y="54" width="90" height="36" rx="4"/>
    <rect class="fig-box-blue" x="246" y="54" width="90" height="36" rx="4"/>
    <rect class="fig-box-accent" x="48" y="110" width="274" height="36" rx="5"/>
    <rect class="fig-box-purple" x="48" y="180" width="274" height="44" rx="5"/>
    <rect class="fig-box-red" x="28" y="234" width="314" height="56" rx="5"/>
    <rect class="fig-box-green" x="394" y="54" width="90" height="44" rx="4"/>
    <rect class="fig-box-green" x="490" y="54" width="90" height="44" rx="4"/>
    <rect class="fig-box-green" x="586" y="54" width="90" height="44" rx="4"/>
    <rect class="fig-box-purple" x="394" y="148" width="90" height="40" rx="4"/>
    <rect class="fig-box-purple" x="490" y="148" width="90" height="40" rx="4"/>
    <rect class="fig-box-purple" x="586" y="148" width="90" height="40" rx="4"/>
    <rect class="fig-box-blue" x="424" y="212" width="110" height="30" rx="4"/>
    <rect class="fig-box-blue" x="548" y="212" width="110" height="30" rx="4"/>
    <rect class="fig-box-green" x="378" y="250" width="314" height="40" rx="5"/>
    <text class="fig-title" x="28" y="34" font-size="12">① 用户级线程 ULT（内核不认识线程）</text>
    <text class="fig-blue" x="79" y="76" font-size="10.5" text-anchor="middle">ULT 1</text>
    <text class="fig-blue" x="185" y="76" font-size="10.5" text-anchor="middle">ULT 2</text>
    <text class="fig-blue" x="291" y="76" font-size="10.5" text-anchor="middle">ULT 3</text>
    <text class="fig-accent" x="185" y="127" font-size="10.5" text-anchor="middle">用户空间线程库（管创建/调度/用户线程表）</text>
    <text class="fig-muted" x="185" y="141" font-size="9.5" text-anchor="middle">切换不陷内核极快 · 可自定算法 · 可跨 OS 移植</text>
    <text class="fig-muted" x="296" y="158" font-size="9.5" text-anchor="end">用户/内核边界</text>
    <text class="fig-purple" x="185" y="199" font-size="11" text-anchor="middle">内核只见 1 个进程 PCB_A</text>
    <text class="fig-muted" x="185" y="215" font-size="9.5" text-anchor="middle">★ OS 不为 ULT 建 TCB (2019#23, 2026#25)</text>
    <text class="fig-red" x="185" y="252" font-size="10.5" text-anchor="middle">✕ 一线程发阻塞系统调用 → 整个进程阻塞</text>
    <text class="fig-muted" x="185" y="272" font-size="10" text-anchor="middle">✕ 每次最多分 1 个 CPU 核，无法多核真并行</text>
    <text class="fig-title" x="378" y="34" font-size="12">② 内核级线程 KLT（内核直接管 TCB）</text>
    <text class="fig-green" x="439" y="74" font-size="10.5" text-anchor="middle">线程 1</text>
    <text class="fig-muted" x="439" y="90" font-size="9.5" text-anchor="middle">系统调用管理</text>
    <text class="fig-green" x="535" y="74" font-size="10.5" text-anchor="middle">线程 2</text>
    <text class="fig-muted" x="535" y="90" font-size="9.5" text-anchor="middle">系统调用管理</text>
    <text class="fig-green" x="631" y="74" font-size="10.5" text-anchor="middle">线程 3</text>
    <text class="fig-muted" x="631" y="90" font-size="9.5" text-anchor="middle">阻塞(I/O)</text>
    <text class="fig-muted" x="582" y="122" font-size="9.5" text-anchor="middle">用户/内核边界</text>
    <text class="fig-purple" x="439" y="167" font-size="10.5" text-anchor="middle">KTCB 1</text>
    <text class="fig-muted" x="439" y="182" font-size="9.5" text-anchor="middle">内核就绪</text>
    <text class="fig-purple" x="535" y="167" font-size="10.5" text-anchor="middle">KTCB 2</text>
    <text class="fig-muted" x="535" y="182" font-size="9.5" text-anchor="middle">内核就绪</text>
    <text class="fig-purple" x="631" y="167" font-size="10.5" text-anchor="middle">KTCB 3</text>
    <text class="fig-red" x="631" y="182" font-size="9.5" text-anchor="middle">仅此阻塞</text>
    <text class="fig-blue" x="479" y="231" font-size="10.5" text-anchor="middle">CPU Core 0</text>
    <text class="fig-blue" x="603" y="231" font-size="10.5" text-anchor="middle">CPU Core 1</text>
    <text class="fig-green" x="535" y="267" font-size="10.5" text-anchor="middle">✓ T3 阻塞不影响 T1/T2 · 可多核并行</text>
    <text class="fig-muted" x="535" y="282" font-size="9.5" text-anchor="middle">代价：每次切换需“用户态↔内核态”模式切换</text>
  </svg>
  <figcaption>图 2-15　用户级线程（ULT，线程库自管）与内核级线程（KLT，内核维护 TCB 并支持多核并行）本质对比</figcaption>
</figure>

#### 2.7.4 轻型进程（LWP）与三种多线程映射模型

为兼顾 ULT 切换快与 KLT 不全阻塞、能用多核的优势，部分系统引入**组合方式**，以<strong>轻型进程（LWP，Light-Weight Process，又称内核控制线程）</strong>作为用户级线程与内核之间的中间层（将多个 LWP 组成**线程池**供上层 ULT 时分多路复用；只有当前绑定在某 LWP 上的 ULT 才能调用内核服务）。由此抽象出三种**多线程映射模型**：

| 映射模型 | 映射关系（方向不可反） | 并行性与阻塞影响 | 主要代价与典型代表 |
| --- | --- | --- | --- |
| **多对一（M : 1）** | 多个 ULT $\rightarrow$ **1 个** KLT | **不可多核并行**；任一线程阻塞式系统调用会阻塞整个进程 | 并发度受限；等价于纯用户级线程（如早期 Green Threads） |
| **一对一（1 : 1）** | **1 个** ULT $\rightarrow$ **1 个** KLT | **支持多核真并行**；一线程阻塞不影响同进程其他线程 | 每建 1 个用户线程都须创建 1 个内核线程，TCB 开销大须限总量（如 Linux NPTL `pthread`、Windows） |
| **多对多（M : N）** | $m$ 个 ULT $\rightarrow$ $n$ 个 KLT（$m \ge n$，经 LWP 池复用） | **支持多核并行**；一个阻塞只阻塞所绑定的那个 KLT，可调度其余 KLT | 综合性能最佳，但调度器与运行时协同**实现最复杂**（如 Solaris 早期、Go 语言 GMP 协程调度模型相似理念） |

> **★考点（映射方向绝不可反！`2026#25` 新增陷阱）**：
> 映射永远是<strong>用户级线程（ULT）映射到底层内核级线程（KLT）</strong>上，即“多个用户级线程可映射到 1 个或多个内核级线程”；**绝不存在“多个内核级线程映射到一个用户级线程”**！用户级线程是被映射方，不是承载方。

<figure class="cpd-figure not-content" id="os-c2-fig-16">
  <svg viewBox="0 0 720 296" role="img" aria-label="多对一、一对一与多对多（含轻型进程LWP池）三种多线程映射模型对比图">
    <defs>
      <marker id="os-c2-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="220" height="268" rx="8"/>
    <rect class="fig-box-subtle" x="250" y="14" width="220" height="268" rx="8"/>
    <rect class="fig-box-subtle" x="484" y="14" width="220" height="268" rx="8"/>
    <line class="fig-line-dashed" x1="24" y1="138" x2="696" y2="138"/>
    <line class="fig-line-accent" x1="56" y1="100" x2="112" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="126" y1="100" x2="126" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="196" y1="100" x2="140" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="290" y1="100" x2="290" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="360" y1="100" x2="360" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="430" y1="100" x2="430" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="518" y1="100" x2="546" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="572" y1="100" x2="554" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="622" y1="100" x2="634" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <line class="fig-line-accent" x1="674" y1="100" x2="646" y2="152" marker-end="url(#os-c2-arr-16)"/>
    <circle class="fig-box-blue" cx="56" cy="84" r="16"/>
    <circle class="fig-box-blue" cx="126" cy="84" r="16"/>
    <circle class="fig-box-blue" cx="196" cy="84" r="16"/>
    <rect class="fig-box-purple" x="90" y="154" width="72" height="36" rx="5"/>
    <rect class="fig-box-red" x="28" y="206" width="196" height="64" rx="5"/>
    <circle class="fig-box-blue" cx="290" cy="84" r="16"/>
    <circle class="fig-box-blue" cx="360" cy="84" r="16"/>
    <circle class="fig-box-blue" cx="430" cy="84" r="16"/>
    <rect class="fig-box-purple" x="266" y="154" width="48" height="36" rx="5"/>
    <rect class="fig-box-purple" x="336" y="154" width="48" height="36" rx="5"/>
    <rect class="fig-box-purple" x="406" y="154" width="48" height="36" rx="5"/>
    <rect class="fig-box-orange" x="262" y="206" width="196" height="64" rx="5"/>
    <circle class="fig-box-blue" cx="516" cy="84" r="15"/>
    <circle class="fig-box-blue" cx="568" cy="84" r="15"/>
    <circle class="fig-box-blue" cx="620" cy="84" r="15"/>
    <circle class="fig-box-blue" cx="672" cy="84" r="15"/>
    <rect class="fig-box-purple" x="512" y="154" width="76" height="36" rx="5"/>
    <rect class="fig-box-purple" x="602" y="154" width="76" height="36" rx="5"/>
    <rect class="fig-box-green" x="496" y="206" width="196" height="64" rx="5"/>
    <text class="fig-title" x="126" y="34" font-size="12" text-anchor="middle">① 多对一模型 (M : 1)</text>
    <text class="fig-muted" x="126" y="52" font-size="9.5" text-anchor="middle">多 ULT → 1 个 KLT</text>
    <text class="fig-blue" x="56" y="88" font-size="10" text-anchor="middle">U1</text>
    <text class="fig-blue" x="126" y="88" font-size="10" text-anchor="middle">U2</text>
    <text class="fig-blue" x="196" y="88" font-size="10" text-anchor="middle">U3</text>
    <text class="fig-muted" x="22" y="130" font-size="9.2">用户态</text>
    <text class="fig-muted" x="22" y="152" font-size="9.2">内核态</text>
    <text class="fig-purple" x="126" y="176" font-size="10.5" text-anchor="middle">KLT 1</text>
    <text class="fig-red" x="126" y="226" font-size="10.5" text-anchor="middle">切换极快 · 等价纯 ULT</text>
    <text class="fig-muted" x="126" y="244" font-size="9.5" text-anchor="middle">✕ 一阻塞全阻塞</text>
    <text class="fig-muted" x="126" y="260" font-size="9.5" text-anchor="middle">✕ 不能利用多核并行</text>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">② 一对一模型 (1 : 1)</text>
    <text class="fig-muted" x="360" y="52" font-size="9.5" text-anchor="middle">1 ULT ↔ 1 KLT</text>
    <text class="fig-blue" x="290" y="88" font-size="10" text-anchor="middle">U1</text>
    <text class="fig-blue" x="360" y="88" font-size="10" text-anchor="middle">U2</text>
    <text class="fig-blue" x="430" y="88" font-size="10" text-anchor="middle">U3</text>
    <text class="fig-purple" x="290" y="176" font-size="10" text-anchor="middle">K1</text>
    <text class="fig-purple" x="360" y="176" font-size="10" text-anchor="middle">K2</text>
    <text class="fig-purple" x="430" y="176" font-size="10" text-anchor="middle">K3</text>
    <text class="fig-orange" x="360" y="226" font-size="10.5" text-anchor="middle">✓ 多核真并行 · 不牵连阻塞</text>
    <text class="fig-muted" x="360" y="244" font-size="9.5" text-anchor="middle">✕ 每建 1 ULT 须建 1 KLT</text>
    <text class="fig-muted" x="360" y="260" font-size="9.5" text-anchor="middle">开销大(Linux/Win 主流)</text>
    <text class="fig-title" x="594" y="34" font-size="12" text-anchor="middle">③ 多对多模型 (M : N)</text>
    <text class="fig-muted" x="594" y="52" font-size="9.5" text-anchor="middle">m ULT → n KLT / LWP (m ≥ n)</text>
    <text class="fig-blue" x="516" y="88" font-size="9.5" text-anchor="middle">U1</text>
    <text class="fig-blue" x="568" y="88" font-size="9.5" text-anchor="middle">U2</text>
    <text class="fig-blue" x="620" y="88" font-size="9.5" text-anchor="middle">U3</text>
    <text class="fig-blue" x="672" y="88" font-size="9.5" text-anchor="middle">U4</text>
    <text class="fig-purple" x="550" y="176" font-size="10" text-anchor="middle">LWP/K1</text>
    <text class="fig-purple" x="640" y="176" font-size="10" text-anchor="middle">LWP/K2</text>
    <text class="fig-green" x="594" y="226" font-size="10.5" text-anchor="middle">✓ 并行 + 低内核开销折中</text>
    <text class="fig-muted" x="594" y="244" font-size="9.5" text-anchor="middle">★ 方向始终是 ULT → KLT</text>
    <text class="fig-muted" x="594" y="260" font-size="9.5" text-anchor="middle">不存在多 KLT 映到 1 ULT</text>
  </svg>
  <figcaption>图 2-16　三种多线程映射模型（多对一、一对一与基于 LWP 缓冲池的多对多）及映射方向铁律（2026#25）</figcaption>
</figure>

---

### 2.8 本章高频考点速查与 408 真题错点清单

#### 2.8.1 本章历年 408 真题考法索引表

| 年份题号 | 核心考点 | 命题关键结论（避坑必背） |
| --- | --- | --- |
| `2010#24` | 引起创建新进程的事件 | **用户登录成功**、**启动程序执行**会创建进程；**设备分配不创建新进程**（仅把设备分配给已有进程） |
| `2011#25` | 线程私有 vs 共享 | 同进程线程**不能共享栈指针**（栈、PC、寄存器私有；代码段、全局变量、堆、打开文件共享） |
| `2012#31` | 进程与线程基本概念 | **不管是否支持线程，进程都是资源分配基本单位**；ULT 切换不需内核支持；同进程线程共享同一地址空间 |
| `2014#26` | I/O 完成与状态唤醒 | 读磁盘完成后 OS 必做的是**将进程状态改为就绪态**（而非立刻设为运行态或增减时间片/优先级） |
| `2014#31` | 管道通信特性 | **管道读写均可能被阻塞**（满写阻塞/空读阻塞）；半双工（双向开两条）；在内核缓冲区而非磁盘；可多读多写 |
| `2015#25` | 运行 $\rightarrow$ 就绪触发条件 | **被高优先级进程抢占**（或时间片用完）；执行 `P` 操作、申请内存失败、启动 I/O 全是**运行 $\rightarrow$ 阻塞** |
| `2019#23` | ULT vs KLT 实现 | **OS 不为 ULT 建立 TCB**（内核不知 ULT 存在）；ULT 切换快且可在无线程支持的 OS 上实现 |
| `2019#24` | 唤醒进程的事件 | **I/O 结束**、**某进程退出临界区**可唤醒等待进程；**当前进程时间片用完不能唤醒任何人** |
| `2020#29` | 父子进程关系 | **`fork` 后父子进程不共享虚拟地址空间**（子进程得到副本/COW）；但拥有各自 PCB、可并发、互斥用临界资源 |
| `2021#24` | 创建原语必做操作 | 必做：**申请空白 PCB + 初始化 PCB**；不会将新进程直接设为“执行态”（而是插入就绪队列） |
| `2023#30` | 共享内存地址映射 | 两进程共享数据段时，**虚拟页号（VPN）不一定相同，物理页框号（PPN）一定相同** |
| `2024#24` | 终止进程操作辨析 | 回收内存、撤销 PCB、回收设备必做；**终止子进程不一定执行**（需有子进程且系统采用级联终止） |
| `2024#28` | 线程创建共享资源 | 线程 $T$ 创建子线程 $T_a$ 后，共享**所属进程地址空间与文件描述符 `fd`**，**不共享 $T$ 的栈** |
| `2025#23` | 页式虚存上下文切换 | 切换时须切换通用寄存器、`PC`、**页表基址寄存器（PTBR）**；**无需切换内核中断向量表基址寄存器** |
| `2025#46` | 虚拟地址空间对象定位 | `PCB` 在**内核区**；`main()` 在**只读代码段**；全局指针 `ptr` 在**读写数据段**；`malloc(100)` 在**堆**；局部变量在**栈** |
| `2026#25` | 线程实现与映射方向 | **同进程多线程共享进程堆**（不共享栈）；ULT 由线程库创建（非 OS）；**多个 ULT 可映到 1 个 KLT**，反向不成立 |

#### 2.8.2 十二条考场排雷金句

1. **PCB 是进程存在的唯一标志**，常驻**内核空间**，用户进程自己改不了；进程实体是 **PCB + 程序段 + 数据段**（不要把 PCB 等同于整个进程）。
2. 指针变量本身（如全局 `char *ptr` 在数据段）与它指向的动态空间（`malloc` 在堆）处于不同区域；`const` 常变量在只读数据区，而 `#define` 宏常量直接化为代码段指令里的立即数。
3. **动态重定位先查逻辑地址是否越界，合法后再加基址变换**；页式先查 **`页号 < 页表项数`**。越界是不可恢复异常（终止进程），缺页是可恢复异常（换入后重执原指令）。
4. **三大永不发生的状态转换**：**就绪 $\not\rightarrow$ 阻塞**、**阻塞 $\not\rightarrow$ 运行**（唤醒 $\neq$ 调度）、**终止 $\not\rightarrow$ 任意态**。
5. **挂起与阻塞完全正交**：挂起是换出外存静止等待，阻塞是等待资源/事件；静止阻塞状态下等到了事件会变为**静止就绪**，不会立刻进内存。
6. **原语靠关中断（内核特权指令）实现原子性**，但**关中断仅屏蔽本核，多核系统须用硬件原子锁（TSL/Swap）**。
7. **阻塞只能自调用，唤醒必然来自外部，二者须成对**。
8. **模式切换只改 `PSW` 模式位，不搬寄存器也不换页表**；进程切换必含两次模式切换，发生调度未必发生切换，现场必须保存在 PCB 而非用户栈。
9. **进程切换开销的隐形大头在 TLB 与 Cache 冷启动**；同进程线程切换便宜的根本原因是不换地址空间（PTBR 不动、TLB 不刷新）。
10. **管道是内核环形内存缓冲区，不是磁盘文件**；半双工、自带同步不带互斥、读写两端均可能阻塞；仅匿名管道限于亲缘进程。
11. **信号是位图记录，不传数据、不计数、不排队、可能丢失**。
12. **线程的黄金边界**：进程管资源、线程管调度；栈与栈指针私有、堆与地址空间共享；内核认不认识线程决定 ULT 能否用多核及阻塞是否连坐整个进程；映射永远是 `ULT → KLT`。

## 第3章 进程同步与互斥

第 2 章揭示了操作系统如何通过时间片轮转与上下文切换，让多个进程或线程在同一块物理硬件上“并发”推进。然而，一旦多个执行流开始共享同一份内存变量、缓冲区或外设资源，并发的另一面便立刻暴露出来：**调度随时可能发生在两条机器指令之间，将高级语言里看似“一步完成”的操作拦腰截断，进而导致数据覆盖与结果不可再现**。

本章沿着“发现并发失序 → 建立评判标尺 → 逐层升级同步机制 → 攻克经典问题与 408 大题”的脉络展开：先看清竞态条件与临界区四准则，再沿着**软件互斥修补链 → 硬件原子指令 → 自旋锁与互斥锁 → 信号量与 PV 操作 → 管程与条件变量**的演进链把握每一种工具的能力边界，最后集中突破生产者–消费者、读者–写者、哲学家进餐及 408 历年真题专题套路。

---

### 3.1 同步互斥基本概念与并发指令流分析 ★

#### 3.1.1 并发执行的指令流交错与竞态条件

操作系统在并发环境下必须守住一条底线——**程序运行结果的可再现性**，即同样的输入在并发调度下必须算出同样确定且正确的结果。多道程序并发之所以会破坏这条底线，根源只有一句话：**高级语言中的一条语句在底层并非原子操作，而 CPU 调度（如时钟中断触发抢占）可以发生在任意两条机器指令之间**。

以缓冲池计数器 `count` 的“生产增一 / 消费减一”为例：高级语言写成 `count++` 与 `count--`，编译为机器指令后均拆成“取入寄存器 → 运算 → 存回内存”三步：

```text
count++  ──►  R1 = count;   R1 = R1 + 1;   count = R1;
count--  ──►  R2 = count;   R2 = R2 - 1;   count = R2;
```

设初值 `count = 5`，生产者与消费者一放一取，正确结果理应仍为 `5`。但若指令流按如下次序交错执行：

| 时刻 | 生产者指令 | 消费者指令 | 寄存器状态 | 内存中的 `count` |
| --- | --- | --- | --- | --- |
| ① | `R1 = count` | — | `R1 = 5` | 5 |
| ② | — | `R2 = count` | `R1 = 5, R2 = 5` | 5 |
| ③ | `R1 = R1 + 1` | — | `R1 = 6, R2 = 5` | 5 |
| ④ | — | `R2 = R2 - 1` | `R1 = 6, R2 = 4` | 5 |
| ⑤ | `count = R1` | — | `R1 = 6, R2 = 4` | **6** |
| ⑥ | — | `count = R2` | `R1 = 6, R2 = 4` | **4**（写覆盖！） |

由于在“读取旧值”与“写回新值”之间的缝隙里插入了另一进程的操作，⑤ 写入的 `6` 被 ⑥ 写入的 `4` 直接抹掉（若 ⑤⑥ 对调则最终变为 `6`）。这种**多个并发执行流访问和修改同一共享数据，导致最终结果取决于指令交错时序的缺陷**，称为**竞态条件（Race Condition）**。

> **★考点**：如何系统分析真题中的“并发指令流输出取值”问题（如 `11#32`）？
> **实战三步法**：① **先给各进程内每条基础语句/机器指令编号**（例：`P1` 的判条件为 ①、`n++` 为 ②、`printf` 为 ③；`P2` 对应为 ④⑤⑥）；② 列出常见无交错顺序基线；③ **重点构造“刚好停在判定之后或写回之前”的跨进程断点**。
>
> **经典例题（循环计数交错）**：共享变量 `n = 0`，`P1` 与 `P2` 均执行 `while (n < 5) n++; printf("%d", n);`。不考虑打印先后，可能输出几组值？
> - 正常跑完一方再跑另一方，输出 `(5, 5)`；
> - 若 `P1` 在 `n = 4` 时执行完 `n < 5` 准备执行 `n++` 前被切走，`P2` 跑完将 `n` 增至 `5` 并打印 `5`，再切回 `P1` 顺着断点执行 `n++` 变成 `6` 后跳出循环，输出 **`(5, 6)`**（对称亦可得 `(6, 5)`）；
> - 若 `n = 4` 时 `P1` 与 `P2` **先后通过 `n < 5` 判定**并双双停在各自 `n++` 前，随后先后执行 `n++` 将 `n` 推至 `6`，则两者都将打印 **`(6, 6)`**！

再如共享变量 `x` 的两段赋值运算（$P_1$：`x = 1; y = 2; z = x + y; print(z);`；$P_2$：`x = 3; c = x * x; print(c);`），因为 $y$ 恒为 $2$ 而 $x$ 只能取 $1$ 或 $3$，故 $z \in \{3, 5\}$ 不可能为 $1$；而 $c = x \times x$ 在读两次 $x$ 时甚至可能或取同一值 $1, 9$（具体取决于硬件寄存器缓存或两次访存交错能否取到 $1 \times 3 = 3$）。考研客观题专挑此类交错边界设问。

#### 3.1.2 Bernstein 条件（并发可再现性的形式化判据）

在无需额外同步原语的前提下，两个进程 $P$ 与 $Q$ 能够安全并发执行（满足顺序无关性与结果可再现性）的充要条件称为 **Bernstein 条件**（`26#27` 重点考查）。记 $R(P)$ 为进程 $P$ 的读变量集合，$W(P)$ 为写变量集合，则三对交集必须全为空集：

$$
R(P) \cap W(Q) = \varnothing, \quad W(P) \cap R(Q) = \varnothing, \quad W(P) \cap W(Q) = \varnothing
$$

> **注意**：**$R(P) \cap R(Q)$ 不必为空**！多个进程同时只读同一共享变量不会引发任何冲突，真正产生竞态危害的只有“**读–写**”、“**写–读**”与“**写–写**”三类碰撞。

<figure class="cpd-figure not-content" id="os-c3-fig-1">
  <svg viewBox="0 0 720 310" role="img" aria-label="并发执行指令流交错引发竞态条件与更新丢失过程及 Bernstein 并发条件判据">
    <defs>
      <marker id="os-c3-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="414" height="190" rx="8"/>
    <rect class="fig-box-subtle" x="442" y="16" width="262" height="190" rx="8"/>
    <rect class="fig-box-accent" x="16" y="218" width="688" height="76" rx="8"/>
    <rect class="fig-box-blue" x="28" y="46" width="156" height="20" rx="4"/>
    <rect class="fig-box" x="204" y="46" width="60" height="20" rx="4"/>
    <rect class="fig-box-orange" x="280" y="70" width="142" height="20" rx="4"/>
    <rect class="fig-box" x="204" y="70" width="60" height="20" rx="4"/>
    <rect class="fig-box-blue" x="28" y="94" width="156" height="20" rx="4"/>
    <rect class="fig-box" x="204" y="94" width="60" height="20" rx="4"/>
    <rect class="fig-box-orange" x="280" y="118" width="142" height="20" rx="4"/>
    <rect class="fig-box" x="204" y="118" width="60" height="20" rx="4"/>
    <rect class="fig-box-red" x="28" y="142" width="156" height="20" rx="4"/>
    <rect class="fig-box" x="204" y="142" width="60" height="20" rx="4"/>
    <rect class="fig-box-red" x="280" y="166" width="142" height="20" rx="4"/>
    <rect class="fig-box-red" x="198" y="166" width="68" height="20" rx="4"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="202" y1="56" x2="186" y2="56" marker-end="url(#os-c3-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="266" y1="80" x2="278" y2="80" marker-end="url(#os-c3-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="186" y1="152" x2="202" y2="152" marker-end="url(#os-c3-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="280" y1="176" x2="268" y2="176" marker-end="url(#os-c3-arr-1)"/>
    <rect class="fig-box-green" x="456" y="48" width="234" height="30" rx="5"/>
    <rect class="fig-box-red" x="456" y="84" width="234" height="30" rx="5"/>
    <rect class="fig-box-red" x="456" y="120" width="234" height="30" rx="5"/>
    <rect class="fig-box-red" x="456" y="156" width="234" height="30" rx="5"/>
    <text class="fig-title" x="223" y="36" font-size="12" text-anchor="middle">竞态条件：count++ 与 count-- 交错（初值 count = 5）</text>
    <text class="fig-blue" x="106" y="60" font-size="10.5" text-anchor="middle">① R1 = count (R1=5)</text>
    <text class="fig-label" x="234" y="60" font-size="10.5" text-anchor="middle">count=5</text>
    <text class="fig-orange" x="351" y="84" font-size="9.5" text-anchor="middle">② R2 = count (R2=5)</text>
    <text class="fig-muted" x="234" y="84" font-size="10.5" text-anchor="middle">count=5</text>
    <text class="fig-blue" x="106" y="108" font-size="10.5" text-anchor="middle">③ R1 = R1+1 (R1=6)</text>
    <text class="fig-muted" x="234" y="108" font-size="10.5" text-anchor="middle">count=5</text>
    <text class="fig-orange" x="351" y="132" font-size="9.5" text-anchor="middle">④ R2 = R2-1 (R2=4)</text>
    <text class="fig-muted" x="234" y="132" font-size="10.5" text-anchor="middle">count=5</text>
    <text class="fig-red" x="106" y="156" font-size="10.5" text-anchor="middle">⑤ count = R1 (写回 6)</text>
    <text class="fig-label" x="234" y="156" font-size="10.5" text-anchor="middle">count=6</text>
    <text class="fig-red" x="351" y="180" font-size="9.4" text-anchor="middle">⑥ count = R2 (写回 4)</text>
    <text class="fig-red" x="232" y="180" font-size="8.6" text-anchor="middle">4 (丢更新)</text>
    <text class="fig-title" x="573" y="36" font-size="12" text-anchor="middle">Bernstein 并发判据（★ 26#27）</text>
    <text class="fig-green" x="573" y="67" font-size="11" text-anchor="middle">R(P) ∩ R(Q) 可非空（读读不冲突）</text>
    <text class="fig-red" x="573" y="103" font-size="11" text-anchor="middle">R(P) ∩ W(Q) = ∅（读写必互斥）</text>
    <text class="fig-red" x="573" y="139" font-size="11" text-anchor="middle">W(P) ∩ R(Q) = ∅（写读必互斥）</text>
    <text class="fig-red" x="573" y="175" font-size="11" text-anchor="middle">W(P) ∩ W(Q) = ∅（写写必互斥）</text>
    <text class="fig-accent" x="360" y="240" font-size="11.5" text-anchor="middle">根因：高级语句拆成多条机器指令，调度可在“读”与“写”之间切入导致相互覆盖</text>
    <text class="fig-label" x="360" y="261" font-size="11" text-anchor="middle">对策：将“读–改–写”缝隙打包成逻辑不可被打断的临界区（进入区加锁 + 退出区解锁）</text>
    <text class="fig-muted" x="360" y="280" font-size="10.5" text-anchor="middle">记忆要点：破坏可再现性的是并发读写/写写交叉；读读同时进行天然安全</text>
  </svg>
  <figcaption>图 3-1　并发执行指令流交错引发“更新丢失”的微观过程与 Bernstein 安全并发四项判据</figcaption>
</figure>

#### 3.1.3 进程同步 vs 进程互斥、临界资源与临界区

在并发环境中，多进程之间的交互约束分为两类：

| 对比维度 | 进程互斥（Mutual Exclusion） | 进程同步（Synchronization） |
| --- | --- | --- |
| **制约类型** | **间接制约关系**（源于资源独占性） | **直接制约关系**（源于任务协作次序） |
| **核心诉求** | 同一时刻至多一个进程访问特定资源，**不关心谁先谁后** | 多个进程必须按**约定先后顺序**推进（先 A 后 B） |
| **判断金句** | **打乱执行次序结果照样正确**，但不能同时在里面 | **打乱执行次序结果必定出错**（等待事件发生） |
| **典型场景** | 多进程共享一台打印机打印不同文件；多进程读写同一共享变量 | 输入进程完成后通知计算进程读取；生产者放入后再由消费者取 |

> **注意**：广义上讲，“互斥”可看作“同步”的一种特殊情况（强制并发执行流在时间上排成互不重叠的先后序列），许多教材将本章统称为“进程同步”。但在写 PV 大题时，**必须明确区分争资源的互斥信号量与等事件的同步信号量**。

为解决互斥问题，引入两个严格绑定的概念（`16#25`）：

1. **临界资源（Critical Resource）**：**一次仅允许一个进程使用的共享资源**（如打印机、会被多个执行流修改的共享变量/缓冲池）。
   - **重要区分**：**共享资源不一定是临界资源**！例如多个进程同时只读同一个只读数组或代码段，不会冲突，因此不是临界资源；**只有需要互斥访问的共享资源才是临界资源**。
2. **临界区（Critical Section）**：**进程中访问临界资源的那段代码**（即代码区域，而非物理资源本身）。同一份临界资源可能被不同进程中各自不同的代码段访问，**访问同一临界资源的所有临界区必须共用同一把锁**。

为了将临界区保护起来，进程执行流被划分为清晰的四段结构：

```c
while (true) {
    // 1. 进入区（Entry Section）：检查资源是否空闲；若空闲则“上锁”防止他进程进入
    // 2. 临界区（Critical Section）：访问临界资源的最小核心代码段
    // 3. 退出区（Exit Section）：清除“上锁”标志并唤醒等待进程
    // 4. 剩余区（Remainder Section）：与该临界资源无关的其他业务代码
}
```

> **注意**：**互斥是一种逻辑约束，并不意味着进程在执行临界区代码期间不会发生中断或切换**（`16#30` 核心陷阱）。在采用软件互斥、互斥锁或信号量时，进程 A 在临界区内完全可能因时间片耗尽而被切换出去；但只要“上锁”标志有效，进程 B 哪怕获得了 CPU 调度，也会在“进入区”检查失败并被拦住，从而仍保住了“同一时刻至多一个进程处于临界区内”的逻辑互斥。

#### 3.1.4 临界区互斥的四大准则（分层标尺）★

评价任何一种互斥实现方法是否正确高效，都必须用四条准则去度量。**这四条准则并不在同一层级**（`20#32`, `18#32` 高频考点）：

| 层次 | 准则名称 | 严格定义 | 不满足会导致的后果 | 必须遵循？ |
| --- | --- | --- | --- | --- |
| **正确性底线** | **① 空闲让进** | 当临界区空闲时，应允许一个请求进入临界区的进程立即进入 | 资源明明闲着却没人进得去（如永远阻拦、僵持死等） | **是（必须）** |
| **正确性底线** | **② 忙则等待** | 已有进程进入临界区时，其他试图进入的进程必须等待 | 两进程同时修改临界资源，导致竞态覆写（互斥失效） | **是（必须）** |
| **可用性保障** | **③ 有限等待** | 应保证等待进入的进程能在有限时间内进入，以免陷入“死等” | 某些进程长期被插队或无限推迟，发生“饥饿（死等）” | **是（必须）** |
| **性能改善** | **④ 让权等待** | 不能进入临界区时应立即释放处理机，以免陷入“忙等” | 等待者霸占 CPU 原地空转（`while` 循环），浪费处理机资源 | **否（改善性）** |

> **★考点**：
> 1. **“必须遵循”的准则只有前三条**（`20#32`）：**空闲让进、忙则等待、有限等待**；**“让权等待”属于改善性要求**——只倒在第四条上的方案（如 Peterson 算法、TSL 指令、Swap 指令、自旋锁）在逻辑上**依然是正确的**，代价仅仅是浪费 CPU 空转。
> 2. **“死等” vs “忙等”**：**死等**是指永远等不到机会进入（违背有限等待或发生死锁）；**忙等**是指未能进入临界区却反复占用 CPU 轮询状态（违背让权等待）。
> 3. **反例构造法（一招判死一个陌生方案）**：若题目给出一个朴素加锁方案：
>    ```c
>    while (busy != 0);   // ① 检查
>    busy = 1;            // ② 上锁
>    // 临界区
>    busy = 0;            // ③ 解锁
>    ```
>    只要将“检查 `busy`”和“置位 `busy = 1`”之间的缝隙撑开：进程 A 读到 `busy == 0` 跳出 `while` 后切换给进程 B，B 也读到 `busy == 0` 跳出 `while`，随后双方先后执行 `busy = 1` 并**双双进入临界区**——立即判否：**违背“忙则等待”**！

<figure class="cpd-figure not-content" id="os-c3-fig-2">
  <svg viewBox="0 0 720 288" role="img" aria-label="临界区四段代码执行闭环结构与互斥四大准则分层判据">
    <defs>
      <marker id="os-c3-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="260" height="256" rx="8"/>
    <rect class="fig-box-subtle" x="290" y="16" width="414" height="256" rx="8"/>
    <line class="fig-line-accent" x1="142" y1="86" x2="142" y2="100" marker-end="url(#os-c3-arr-2)"/>
    <line class="fig-line-accent" x1="142" y1="140" x2="142" y2="154" marker-end="url(#os-c3-arr-2)"/>
    <line class="fig-line-accent" x1="142" y1="194" x2="142" y2="208" marker-end="url(#os-c3-arr-2)"/>
    <path class="fig-line" d="M 242 229 L 260 229 L 260 67 L 245 67" marker-end="url(#os-c3-arr-2)"/>
    <rect class="fig-box-blue" x="42" y="48" width="200" height="38" rx="5"/>
    <rect class="fig-box-red" x="42" y="102" width="200" height="38" rx="5"/>
    <rect class="fig-box-green" x="42" y="156" width="200" height="38" rx="5"/>
    <rect class="fig-box" x="42" y="210" width="200" height="38" rx="5"/>
    <rect class="fig-box-red" x="304" y="48" width="386" height="72" rx="6"/>
    <rect class="fig-box-orange" x="304" y="128" width="386" height="58" rx="6"/>
    <rect class="fig-box-blue" x="304" y="194" width="386" height="66" rx="6"/>
    <text class="fig-title" x="146" y="36" font-size="12" text-anchor="middle">进程访问临界资源的四段结构</text>
    <text class="fig-blue" x="142" y="64" font-size="11.5" text-anchor="middle">1. 进入区（Entry Section）</text>
    <text class="fig-muted" x="142" y="79" font-size="10" text-anchor="middle">检查临界区状态并加锁</text>
    <text class="fig-red" x="142" y="118" font-size="11.5" text-anchor="middle">2. 临界区（Critical Section）</text>
    <text class="fig-muted" x="142" y="133" font-size="10" text-anchor="middle">访问临界资源的最小代码段</text>
    <text class="fig-green" x="142" y="172" font-size="11.5" text-anchor="middle">3. 退出区（Exit Section）</text>
    <text class="fig-muted" x="142" y="187" font-size="10" text-anchor="middle">解锁并唤醒阻塞等待者</text>
    <text class="fig-label" x="142" y="226" font-size="11.5" text-anchor="middle">4. 剩余区（Remainder）</text>
    <text class="fig-muted" x="142" y="241" font-size="10" text-anchor="middle">无关共享资源代码（放锁外）</text>
    <text class="fig-title" x="497" y="36" font-size="12" text-anchor="middle">临界区互斥四大准则分层判据（★ 20#32 / 18#32）</text>
    <text class="fig-red" x="318" y="67" font-size="11.5">第 1 层 · 正确性底线（必须遵循）</text>
    <text class="fig-label" x="318" y="88" font-size="10.5">① 空闲让进：无人使用时应允许请求者立即进入</text>
    <text class="fig-label" x="318" y="106" font-size="10.5">② 忙则等待：已有进程在内时其他请求必须等待</text>
    <text class="fig-orange" x="318" y="147" font-size="11.5">第 2 层 · 可用性保证（必须遵循）</text>
    <text class="fig-label" x="318" y="169" font-size="10.5">③ 有限等待：保证等待有界，避免进程“死等”（饥饿）</text>
    <text class="fig-blue" x="318" y="212" font-size="11.5">第 3 层 · 性能改善要求（非必须但影响 CPU 效率）</text>
    <text class="fig-label" x="318" y="232" font-size="10.5">④ 让权等待：进不去时释放 CPU，避免“忙等”空转</text>
    <text class="fig-muted" x="678" y="250" font-size="9.5" text-anchor="end">Peterson / TSL / Swap 均倒在此条</text>
  </svg>
  <figcaption>图 3-2　临界区四段结构循环图与互斥四大准则的三层判定模型（前三条决定正确性，第四条决定是否忙等）</figcaption>
</figure>

---

### 3.2 进程互斥的软件实现方法（四步修补链）

软件互斥方法不依赖特殊 CPU 指令或内核原语，仅依靠普通共享变量与分支轮询代码实现两进程互斥。这四种方案并非孤立并列，而是一条清晰的**四步修补链**，其核心矛盾始终围绕<strong>“检查与置位谁在前”</strong>展开——设置在后漏互斥，设置在前易僵持。

#### 3.2.1 第一步：单标志法（`turn`）

设置公用整型变量 `turn`，指示“当前允许进入临界区的进程编号”：

```c
int turn = 0;  // 初值决定谁先有权进入

// 进程 P0                           // 进程 P1
while (turn != 0);                  while (turn != 1);
临界区;                              临界区;
turn = 1;  // 把进入权交给对方         turn = 0;  // 把进入权交给对方
剩余区;                              剩余区;
```

- **机制分析**：任一时刻 `turn` 只能取 `0` 或 `1`，两个 `while` 条件不可能同时为假，因此**绝对保证互斥（满足忙则等待）**。
- **致命缺陷**：进入权只能由“对方”用完后交还。若 `P0` 退出临界区后将 `turn` 置为 `1`，而 `P1` 根本不想进临界区，则 `P0` 再次请求时将被永久挡在门外——强制要求两个进程**严格交替进入**。
- **准则判定**：**违背“空闲让进”**（且违背“让权等待”）。

#### 3.2.2 第二步：双标志先检查法（先判后置）

为消除严格交替，给每个进程各设一个布尔意愿标志 `flag[i]`（`true` 表示想进），进门前先看对方是否举手，没人举手再把自己的旗子升起来：

```c
bool flag[2] = {false, false};

// 进程 P0                           // 进程 P1
while (flag[1]);       // ① 检查      while (flag[0]);       // ③ 检查
flag[0] = true;        // ② 置位      flag[1] = true;        // ④ 置位
临界区;                              临界区;
flag[0] = false;                     flag[1] = false;
```

- **机制分析**：只要 `P1` 没请求进入，`P0` 可连续多次进入，解决了“强制交替”。
- **致命缺陷**：若按 **`① → ③ → ② → ④`** 的顺序交错执行，`P0` 读到 `flag[1] == false` 后未及时置位就被切换，`P1` 也读到 `flag[0] == false`，随后双方各自置 `true` 并**双双闯入临界区**。原因在于“读对方状态”和“立自己标志”是两条分离指令，存在打断空隙。
- **准则判定**：**违背“忙则等待”**（互斥失效，最严重缺陷）与“让权等待”。

#### 3.2.3 第三步：双标志后检查法（先置后判）

既然先查后置会在缝隙里让别人看见“false”，那就先把自己的标志升起来表达意愿，再回头看对方：

```c
bool flag[2] = {false, false};

// 进程 P0                           // 进程 P1
flag[0] = true;        // ① 先置位    flag[1] = true;        // ③ 先置位
while (flag[1]);       // ② 后检查    while (flag[0]);       // ④ 后检查
临界区;                              临界区;
flag[0] = false;                     flag[1] = false;
```

- **机制分析**：无论怎样交错，任何一方在进入临界区前都已亮明 `flag = true`，彻底堵死了双双进入的漏洞，**保住了互斥（忙则等待）**。
- **致命缺陷**：若按 **`① → ③ → ② → ④`** 交错执行，双方都把旗子升成了 `true`，随后都卡死在 `while` 循环里相互观望，而降旗语句在临界区之后谁也走不到——临界区明明空着却**双方死等（违背空闲让进与有限等待）**。
- **问题根源**：**完全对称**。两人状态完全一样，系统缺乏一个“仲裁人”决定僵持时谁该先行。

#### 3.2.4 第四步：Peterson 算法 ★

Peterson 算法把前两类思想合二为一：**用 `flag[]` 表达个人意愿，再用单变量 `turn` 做出“谦让仲裁”打破对称**（`10#27`, `23#45` 常考）。

```c
bool flag[2] = {false, false};
int turn = 0;

// 进程 P0                                 // 进程 P1
flag[0] = true;      // ① 我想进           flag[1] = true;      // ④ 我想进
turn = 1;            // ② 但我谦让给 P1    turn = 0;            // ⑤ 但我谦让给 P0
while (flag[1] && turn == 1);  // ③       while (flag[0] && turn == 0);  // ⑥
临界区;                                    临界区;
flag[0] = false;                           flag[1] = false;
```

**严谨性质验证**：

1. **互斥性（忙则等待）**：假设 `P0` 与 `P1` 同时在临界区中，必有 `flag[0] == true` 且 `flag[1] == true`。此时 `P0` 能跳出 `while` 说明 `turn != 1`（即 `turn == 0`），`P1` 能跳出 `while` 说明 `turn != 0`（即 `turn == 1`）。但 `turn` 是单个整型变量，同一时刻不可能既为 `0` 又为 `1`，矛盾！故绝不可能同时进入临界区。
2. **空闲让进与有限等待（不会死等）**：若 `P0` 被卡在 `while`，说明此时 `flag[1] == true` 且 `turn == 1`。在此瞬间，`P1` 的等待条件 `flag[0] && turn == 0` 必然为假，因此 `P1` 一定能顺利进入并执行完临界区，在退出区执行 `flag[1] = false`，立即打破 `P0` 的阻塞。所以 `P0` 至多等待 `P1` 一次临界区。
3. **让权等待缺口**：仍使用 `while` 空转自旋等待，**不满足让权等待**。此外，原生算法**仅直接适用于双进程**。

> **★考点**：Peterson 算法记忆铁律：**「`turn` 归属谁，谁就得等」**（`turn = 对方` 才是谦让）。若考试伪代码误写为 `turn = 自己`（即 `P0` 写 `turn = 0`），**互斥当场失效**！
> 反例只需 4 拍：① `P0` 置 `flag[0] = true; turn = 0;` → ② `P0` 见 `flag[1] == false` 直接进入临界区 → ③ 切换至 `P1` 置 `flag[1] = true; turn = 1;` → ④ `P1` 判 `turn == 0` 为假，**直接放行自己也进入临界区**！可见，写出 `turn = 对方` 才是让“后写 `turn` 者覆盖前值并把自己拦住”的核心机制。

| 软件互斥方法 | 空闲让进 | 忙则等待 | 有限等待 | 让权等待 | 同一坏交错 $a_1 \to b_1 \to a_2 \to b_2$ 后果 |
| --- | --- | --- | --- | --- | --- |
| **单标志法** | **❌**（强制交替） | ✅ | **❌**（对方不来即死等） | ❌ | — |
| **双标志先检查法** | ✅ | **❌**（缝隙漏洞） | ✅（无阻拦机制） | ❌ | 双双读到 `false`，双双进临界区 |
| **双标志后检查法** | **❌**（双向卡死） | ✅ | **❌**（双方僵持饥饿） | ❌ | 双双置 `true`，双双死锁于 `while` |
| **Peterson 算法** ★ | **✅** | **✅** | **✅** | **❌**（忙等自旋） | `turn` 仅存一值，后写者自拦，放行先写者 |

<figure class="cpd-figure not-content" id="os-c3-fig-3">
  <svg viewBox="0 0 720 310" role="img" aria-label="进程互斥软件实现四步修补演进链与各自失守准则对比">
    <defs>
      <marker id="os-c3-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-orange" x="16" y="16" width="314" height="126" rx="8"/>
    <rect class="fig-box-red" x="390" y="16" width="314" height="126" rx="8"/>
    <rect class="fig-box-orange" x="390" y="168" width="314" height="126" rx="8"/>
    <rect class="fig-box-green" x="16" y="168" width="314" height="126" rx="8"/>
    <line class="fig-line-accent" x1="330" y1="79" x2="387" y2="79" marker-end="url(#os-c3-arr-3)"/>
    <line class="fig-line-accent" x1="547" y1="142" x2="547" y2="165" marker-end="url(#os-c3-arr-3)"/>
    <line class="fig-line-accent" x1="390" y1="231" x2="333" y2="231" marker-end="url(#os-c3-arr-3)"/>
    <rect class="fig-box" x="336" y="54" width="48" height="18" rx="3"/>
    <rect class="fig-box" x="555" y="145" width="76" height="18" rx="3"/>
    <rect class="fig-box" x="336" y="206" width="48" height="18" rx="3"/>
    <text class="fig-orange" x="173" y="38" font-size="12" text-anchor="middle">① 单标志法（turn）</text>
    <text class="fig-label" x="28" y="60" font-size="10.2">核心：while (turn != i); [CS] turn = 1-i;</text>
    <text class="fig-green" x="28" y="82" font-size="10.2">✅ 满足忙则等待（turn 单值保证互斥）</text>
    <text class="fig-red" x="28" y="102" font-size="10.2">❌ 违背空闲让进（进入权被对方把持）</text>
    <text class="fig-muted" x="28" y="124" font-size="9.8">症状：强制严格交替，一方不去另一方无法再进</text>
    <text class="fig-muted" x="360" y="66" font-size="9.5" text-anchor="middle">各设旗</text>
    <text class="fig-red" x="547" y="38" font-size="12" text-anchor="middle">② 双标志先检查法（先判后置）</text>
    <text class="fig-label" x="402" y="60" font-size="10.2">核心：while (flag[j]); [缝隙] flag[i] = true;</text>
    <text class="fig-green" x="402" y="82" font-size="10.2">✅ 消除强制交替（满足空闲让进）</text>
    <text class="fig-red" x="402" y="102" font-size="10.2">❌ 违背忙则等待（检查与置位可被切开）</text>
    <text class="fig-muted" x="402" y="124" font-size="9.8">症状：交错 ①→③→②→④ 导致双双入临界区</text>
    <text class="fig-muted" x="593" y="157" font-size="9.5" text-anchor="middle">提前置位</text>
    <text class="fig-orange" x="547" y="190" font-size="12" text-anchor="middle">③ 双标志后检查法（先置后判）</text>
    <text class="fig-label" x="402" y="212" font-size="10.2">核心：flag[i] = true; [缝隙] while (flag[j]);</text>
    <text class="fig-green" x="402" y="234" font-size="10.2">✅ 堵住并发闯入（满足忙则等待）</text>
    <text class="fig-red" x="402" y="254" font-size="10.2">❌ 违背空闲让进 &amp; 有限等待</text>
    <text class="fig-muted" x="402" y="276" font-size="9.8">症状：对称同时举手后互等，死锁饥饿</text>
    <text class="fig-muted" x="360" y="218" font-size="8.8" text-anchor="middle">加 turn</text>
    <text class="fig-green" x="173" y="190" font-size="12" text-anchor="middle">④ Peterson 算法（flag[] + turn）★</text>
    <text class="fig-label" x="26" y="212" font-size="9.4">核心：flag[i]=T; turn=j; while(flag[j]&amp;&amp;turn==j);</text>
    <text class="fig-green" x="28" y="234" font-size="10.2">✅ 满足空闲让进、忙则等待、有限等待</text>
    <text class="fig-orange" x="28" y="254" font-size="10.2">❌ 仍违背让权等待（while 原地空转忙等）</text>
    <text class="fig-muted" x="28" y="276" font-size="9.8">本质：turn 单值打破对称，后写谦让先写进</text>
  </svg>
  <figcaption>图 3-3　软件互斥四步修补链演进图：检查与置位先后调换反复暴露漏洞，最终靠 flag 与 turn 组合收束</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c3-fig-4">
  <svg viewBox="0 0 720 296" role="img" aria-label="Peterson 算法正确写法 8 拍互谦裁决过程与误写 turn 为自己 4 拍互斥崩溃反例">
    <rect class="fig-box-subtle" x="16" y="16" width="372" height="264" rx="8"/>
    <rect class="fig-box-subtle" x="400" y="16" width="304" height="264" rx="8"/>
    <rect class="fig-box" x="26" y="46" width="352" height="22" rx="4"/>
    <rect class="fig-box-accent" x="26" y="138" width="352" height="22" rx="4"/>
    <rect class="fig-box-green" x="26" y="161" width="352" height="22" rx="4"/>
    <rect class="fig-box-green" x="26" y="230" width="352" height="22" rx="4"/>
    <line class="fig-divider" x1="26" y1="91" x2="378" y2="91"/>
    <line class="fig-divider" x1="26" y1="114" x2="378" y2="114"/>
    <line class="fig-divider" x1="26" y1="137" x2="378" y2="137"/>
    <line class="fig-divider" x1="26" y1="184" x2="378" y2="184"/>
    <line class="fig-divider" x1="26" y1="207" x2="378" y2="207"/>
    <rect class="fig-box" x="412" y="52" width="280" height="40" rx="5"/>
    <rect class="fig-box-blue" x="412" y="100" width="280" height="40" rx="5"/>
    <rect class="fig-box" x="412" y="148" width="280" height="40" rx="5"/>
    <rect class="fig-box-red" x="412" y="196" width="280" height="46" rx="5"/>
    <text class="fig-title" x="202" y="36" font-size="11.5" text-anchor="middle">正确写法：turn = 对方（8 拍裁决，互斥有效）</text>
    <text class="fig-label" x="44" y="61" font-size="10" text-anchor="middle">拍</text>
    <text class="fig-label" x="148" y="61" font-size="10" text-anchor="middle">并发执行流动作</text>
    <text class="fig-label" x="298" y="61" font-size="10" text-anchor="middle">flag[0,1]</text>
    <text class="fig-label" x="357" y="61" font-size="10" text-anchor="middle">turn</text>
    <text class="fig-muted" x="44" y="84" font-size="10" text-anchor="middle">1</text>
    <text class="fig-label" x="62" y="84" font-size="10">P0: flag[0] = true</text>
    <text class="fig-muted" x="298" y="84" font-size="10" text-anchor="middle">[T, F]</text>
    <text class="fig-muted" x="357" y="84" font-size="10" text-anchor="middle">–</text>
    <text class="fig-muted" x="44" y="107" font-size="10" text-anchor="middle">2</text>
    <text class="fig-label" x="62" y="107" font-size="10">P1: flag[1] = true</text>
    <text class="fig-muted" x="298" y="107" font-size="10" text-anchor="middle">[T, T]</text>
    <text class="fig-muted" x="357" y="107" font-size="10" text-anchor="middle">–</text>
    <text class="fig-muted" x="44" y="130" font-size="10" text-anchor="middle">3</text>
    <text class="fig-label" x="62" y="130" font-size="10">P0: turn = 1（让 P1）</text>
    <text class="fig-muted" x="298" y="130" font-size="10" text-anchor="middle">[T, T]</text>
    <text class="fig-muted" x="357" y="130" font-size="10" text-anchor="middle">1</text>
    <text class="fig-accent" x="44" y="153" font-size="10" text-anchor="middle">4</text>
    <text class="fig-accent" x="62" y="153" font-size="10">P1: turn = 0（覆盖！让 P0）</text>
    <text class="fig-accent" x="298" y="153" font-size="10" text-anchor="middle">[T, T]</text>
    <text class="fig-accent" x="357" y="153" font-size="10" text-anchor="middle">0</text>
    <text class="fig-green" x="44" y="176" font-size="10" text-anchor="middle">5</text>
    <text class="fig-green" x="62" y="176" font-size="10">P0 判 turn==1 假 → 进入 CS</text>
    <text class="fig-green" x="298" y="176" font-size="10" text-anchor="middle">[T, T]</text>
    <text class="fig-green" x="357" y="176" font-size="10" text-anchor="middle">0</text>
    <text class="fig-muted" x="44" y="199" font-size="10" text-anchor="middle">6</text>
    <text class="fig-orange" x="62" y="199" font-size="9.4">P1 判 flag[0]&amp;&amp;turn==0 真 → 自旋</text>
    <text class="fig-muted" x="298" y="199" font-size="10" text-anchor="middle">[T, T]</text>
    <text class="fig-muted" x="357" y="199" font-size="10" text-anchor="middle">0</text>
    <text class="fig-muted" x="44" y="222" font-size="10" text-anchor="middle">7</text>
    <text class="fig-label" x="62" y="222" font-size="10">P0 出 CS: flag[0] = false</text>
    <text class="fig-muted" x="298" y="222" font-size="10" text-anchor="middle">[F, T]</text>
    <text class="fig-muted" x="357" y="222" font-size="10" text-anchor="middle">0</text>
    <text class="fig-green" x="44" y="245" font-size="10" text-anchor="middle">8</text>
    <text class="fig-green" x="62" y="245" font-size="10">P1 判 flag[0] 假 → 进入 CS</text>
    <text class="fig-green" x="298" y="245" font-size="10" text-anchor="middle">[F, T]</text>
    <text class="fig-green" x="357" y="245" font-size="10" text-anchor="middle">0</text>
    <text class="fig-muted" x="202" y="269" font-size="10" text-anchor="middle">★ 枢纽：第 4 拍后写者覆盖 turn 把自己挡下</text>
    <text class="fig-title" x="552" y="36" font-size="11.5" text-anchor="middle">错写陷阱：turn = 自己，4 拍即破！（10#27）</text>
    <text class="fig-label" x="424" y="68" font-size="10.5">拍 1：P0 置 flag[0]=T; turn=0;</text>
    <text class="fig-muted" x="424" y="84" font-size="10">状态：flag=[T, F]，turn = 0</text>
    <text class="fig-blue" x="424" y="116" font-size="10.5">拍 2：P0 判 flag[1]==F（未举手）</text>
    <text class="fig-blue" x="424" y="132" font-size="10">→ P0 直接进入临界区！</text>
    <text class="fig-label" x="424" y="164" font-size="10.5">拍 3：切换 P1 置 flag[1]=T; turn=1;</text>
    <text class="fig-muted" x="424" y="180" font-size="10">状态：flag=[T, T]，turn = 1</text>
    <text class="fig-red" x="424" y="213" font-size="10.5">拍 4：P1 判 turn==0 为假（turn==1）</text>
    <text class="fig-red" x="424" y="230" font-size="10.5">→ P1 也直接进入临界区（双双入内！）</text>
    <text class="fig-red" x="552" y="269" font-size="10" text-anchor="middle">根因：后写者把自己 while 条件推假放行自己</text>
  </svg>
  <figcaption>图 3-4　Peterson 算法正确“互谦”裁决逐拍时序与错写 turn = 自己 4 拍破产反例对比</figcaption>
</figure>

---

### 3.3 进程互斥的硬件实现方法与锁机制 ★

软件方法受限于普通访存指令的“读与写分离”，不得不引入精巧而脆弱的变量博弈。硬件方法的思路则直接得多：**由 CPU 指令集直接提供一条不可中断的原子指令，将“检查锁”与“上锁”合并为一个不可分割的硬件动作**（`2.4.2`）。

#### 3.3.1 中断屏蔽方法（关中断 / 开中断）

```c
关中断;       // CLI：屏蔽可屏蔽中断，禁止当前 CPU 响应时钟/外部中断
临界区;
开中断;       // STI：恢复中断响应
```

- **原理**：在单处理机上，进程切换必须依靠中断（如时钟中断触发调度程序）进入内核态完成。关中断后当前 CPU 不会响应任何切换信号，确保进程一气呵成跑完临界区。
- **三大致命缺点（`21#45` 常考）**：
  1. **不适用于多处理机（SMP）系统**：`CLI` 指令**只屏蔽执行该指令的那一颗 CPU 的中断**，而另一颗 CPU 核无需抢占本核即可完全并行地执行同一个临界区代码，互斥彻底失效！
  2. **只能用于内核进程，用户进程无权使用**：开/关中断是高危**特权指令**，仅能在内核态下由操作系统调用；若开放给用户态，用户进程忘开中断或死循环将直接卡死整台机器。
  3. **影响系统效率**：关中断时间过长会限制处理机并发响应与实时性。

#### 3.3.2 TestAndSet（TS / TSL）指令与 Swap（XCHG）指令 ★

这两条指令由硬件总线锁或缓存一致性协议保证整体**原子执行（不可被打断）**，均利用一个初值为 `false`（空闲）的全局共享布尔锁 `lock` 来保护临界区：

**1. TestAndSet（Test-and-Set-Lock，TS / TSL）指令**

```c
// 硬件原子逻辑等价描述（由硬件一气呵成完成，绝不会被打断）
bool TestAndSet(bool *lock) {
    bool old = *lock;    // 读出锁的旧状态
    *lock = true;        // 无论之前是否为 true，强制上锁
    return old;          // 返回上锁前的旧值
}

// 进程调用代码
while (TestAndSet(&lock));   // 进入区：若返回旧值为 true 说明已上锁，自旋重试；为 false 则占锁进入
临界区;
lock = false;                // 退出区：解锁
```

- **解析**：若 `lock` 原为 `false`，`TestAndSet` 在返回 `false` 放行当前进程的同时，已瞬间将 `*lock` 改写为 `true`；后续任何其他进程再调用 `TestAndSet` 都将读回旧值 `true` 并陷入 `while` 自旋。

**2. Swap（Exchange / XCHG）指令（`23#45` 大题原型）**

```c
// 硬件原子逻辑等价描述：原子交换两个指针指向的布尔变量值
void Swap(bool *a, bool *b) {
    bool temp = *a;
    *a = *b;
    *b = temp;
}

// 进程调用代码（lock 为全局共享变量，初值 false）
bool key = true;             // 每个进程私有的局部变量
do {
    Swap(&lock, &key);       // 把 TRUE 换给 lock，把 lock 的原状态换回私有 key
} while (key);               // 若换回 key == true，说明锁早已被占，继续交换忙等
临界区;
lock = false;                // 退出区：释放锁
```

- **等价性与共同缺陷**：`TSL` 与 `Swap` **能力完全等价、可互相模拟**（`TSL(&lock)` 等价于 `key = true; Swap(&lock, &key); return key;`），差别仅在 `TSL` 固定写回 `true` 作返回值，而 `Swap` 借私有变量 `key` 交换两值。现代 CPU 还广泛提供 **CAS（Compare-and-Swap）** 指令，先比较 `*lock == expected` 再原子替换为 `new_val`。
- **适用性与最大短板（`16#27`, `18#32`）**：
  - **优点**：实现极简，且借助硬件原子总线/缓存锁机制，**完全适用于多处理机（SMP）系统**。
  - **缺点**：**不满足“让权等待”**！当锁已被占用时，后续尝试进入的进程只能在 `while` 循环中不停执行 `TSL` 或 `Swap` 占用 CPU 空转（**忙等**）。原因是硬件只卖给了我们“原子性”，没有卖给我们“把自己挂起到等待队列”的 `block()` 操作系统原语。

| 实现机制 | 互斥能力与适用核数 | 空闲让进 | 忙则等待 | 有限等待 | 让权等待 |
| --- | --- | --- | --- | --- | --- |
| **软件：Peterson 算法** | 仅双进程（单/多核需内存屏障） | ✅ | ✅ | ✅ | **❌（忙等）** |
| **硬件：中断屏蔽法** | 仅单处理机 + **仅内核态** | ✅ | ✅ | ✅（单核极短区） | 不涉及等待队列 |
| **硬件：TSL / Swap / CAS** | 单核（易死旋）/ **多核（SMP）** | ✅ | ✅ | ❌/视调度（极端饥饿风险） | **❌（忙等）** |
| **OS 原语：互斥锁 / 记录型信号量** | 单核 / 多核皆适用，全场景通用 | ✅ | ✅ | ✅（队列 FIFO 唤醒） | **✅（block 让权）** |

<figure class="cpd-figure not-content" id="os-c3-fig-5">
  <svg viewBox="0 0 720 278" role="img" aria-label="TSL 与 Swap 原子硬件指令机制示意图及中断屏蔽法在多核下失效对比">
    <defs>
      <marker id="os-c3-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="246" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="246" rx="8"/>
    <rect class="fig-box-blue" x="28" y="48" width="312" height="92" rx="6"/>
    <rect class="fig-box" x="40" y="76" width="112" height="32" rx="4"/>
    <rect class="fig-box" x="178" y="76" width="150" height="32" rx="4"/>
    <line class="fig-line-accent" x1="152" y1="92" x2="175" y2="92" marker-end="url(#os-c3-arr-5)"/>
    <rect class="fig-box-purple" x="28" y="152" width="312" height="98" rx="6"/>
    <rect class="fig-box" x="40" y="182" width="110" height="34" rx="4"/>
    <rect class="fig-box" x="210" y="182" width="118" height="34" rx="4"/>
    <line class="fig-line-accent" x1="153" y1="199" x2="207" y2="199" marker-start="url(#os-c3-arr-5)" marker-end="url(#os-c3-arr-5)"/>
    <rect class="fig-box-red" x="380" y="48" width="312" height="98" rx="6"/>
    <rect class="fig-box" x="392" y="78" width="132" height="54" rx="4"/>
    <rect class="fig-box-red" x="548" y="78" width="132" height="54" rx="4"/>
    <line class="fig-line-dashed" x1="536" y1="74" x2="536" y2="136"/>
    <rect class="fig-box-orange" x="380" y="158" width="312" height="92" rx="6"/>
    <text class="fig-title" x="184" y="36" font-size="11.5" text-anchor="middle">硬件原子指令：消除“读”与“锁”间的缝隙</text>
    <text class="fig-blue" x="40" y="66" font-size="11">1. TestAndSet(&amp;lock) 不可分割原子执行</text>
    <text class="fig-label" x="96" y="96" font-size="10.5" text-anchor="middle">old = *lock</text>
    <text class="fig-label" x="253" y="96" font-size="10" text-anchor="middle">*lock = T; ret old</text>
    <text class="fig-muted" x="184" y="128" font-size="10" text-anchor="middle">old == false → 上锁并进入；old == true → 自旋等待</text>
    <text class="fig-purple" x="40" y="170" font-size="11">2. Swap(&amp;lock, &amp;key) 原子交换（初始 key=T）</text>
    <text class="fig-label" x="95" y="196" font-size="10" text-anchor="middle">lock（全局）</text>
    <text class="fig-muted" x="95" y="210" font-size="9.5" text-anchor="middle">初值 false</text>
    <text class="fig-label" x="269" y="196" font-size="10" text-anchor="middle">key（私有）</text>
    <text class="fig-muted" x="269" y="210" font-size="9.5" text-anchor="middle">初值 true</text>
    <text class="fig-muted" x="180" y="193" font-size="9.5" text-anchor="middle">原子</text>
    <text class="fig-muted" x="180" y="213" font-size="9.5" text-anchor="middle">互换</text>
    <text class="fig-muted" x="184" y="236" font-size="10" text-anchor="middle">交换后 key == false 说明原锁开 → 进临界区</text>
    <text class="fig-title" x="536" y="36" font-size="11.5" text-anchor="middle">多核环境（SMP）下的互斥有效性对比</text>
    <text class="fig-red" x="392" y="66" font-size="11">中断屏蔽法：仅挡本核中断，多核必失效 ❌</text>
    <text class="fig-label" x="458" y="99" font-size="10.5" text-anchor="middle">CPU 核 0（CLI）</text>
    <text class="fig-muted" x="458" y="117" font-size="9.5" text-anchor="middle">本核不响应切换 ✅</text>
    <text class="fig-red" x="614" y="99" font-size="10.5" text-anchor="middle">CPU 核 1（照常跑）</text>
    <text class="fig-red" x="614" y="117" font-size="9.5" text-anchor="middle">可同时进临界区 ❌</text>
    <text class="fig-orange" x="392" y="180" font-size="11">TSL / Swap 多核有效，但欠缺让权等待 ★</text>
    <text class="fig-green" x="392" y="203" font-size="10.5">✅ 依赖总线锁 / Cache 一致性跨核同步原子性</text>
    <text class="fig-red" x="392" y="223" font-size="10.5">❌ 硬件无 block() 原语，等锁者占住核死等空转</text>
    <text class="fig-muted" x="392" y="241" font-size="9.5">与“单核下自旋无意义”构成对称考点（21#45 / 16#27）</text>
  </svg>
  <figcaption>图 3-5　TSL 与 Swap 硬件原子指令机制、中断屏蔽的多核失效原因以及让权等待缺口对照</figcaption>
</figure>

#### 3.3.3 锁机制：自旋锁 vs 互斥锁与锁粒度 ★

2026 年 408 大纲将<strong>“锁（Lock）”</strong>单列为一个独立考点。需要清醒认识的是：**锁并非一种脱离软硬件基础的新理论，而是对“进入区（`acquire`）”和“退出区（`release`）”的工程封装**。锁的底层可以用 TSL/Swap 实现，也可以用信号量实现；前文的互斥四准则同样适用于评估锁的优劣。

```c
acquire(lock);     // 获取锁（进入区）
临界区;
release(lock);     // 释放锁（退出区）
```

根据“**抢不到锁时是否主动让出处理机**”这一唯一分界线，锁分为两大类别：

**1. 自旋锁（Spinlock）—— 忙等**

基于硬件原子指令实现（如 `while (TestAndSet(&lock));`），拿不到锁时在原地死循环测试（“自旋”），**不放弃 CPU、不进入阻塞态**，故不满足让权等待。

> **注意**：
> - **单核自旋锁陷阱**：**在单处理机（不可抢占内核或非时分立刻切换视角）上，自旋锁毫无意义**（汤小丹 10.4.2 节明文指出，单 CPU 且不可抢占内核下自旋锁操作直接退化为空操作）。因为持锁的进程此刻一定被自旋进程挤下了 CPU，自旋进程死占着唯一一颗 CPU 原地打转，等的是一个当前绝不可能被释放的锁，只会白白耗尽整个时间片！只有多核（SMP）系统中，持锁者正在另一颗核心上并行推进并在数微秒内释放锁时，自旋才比睡眠切换划算。
> - **多核缓存失效优化（Test-and-Test-and-Set）**：若每圈循环都直接调用 `TSL(&lock)` 写内存，会持续引发跨核 Cache 缓存行失效（总线风暴）。工程中改用先只读本地缓存自旋、看到变为 `false` 再抢锁：`while (true) { while (*lock); if (!TestAndSet(lock)) return; }`。

**2. 互斥锁（Mutex）—— 阻塞让权**

```c
void acquire(mutex_lock *L) {
    if (L->locked) {
        将该进程 PCB 加入 L->wait_queue;
        block();            // 主动让出处理机，从运行态切入阻塞态
    }
    L->locked = true;
}

void release(mutex_lock *L) {
    L->locked = false;
    if (!empty(L->wait_queue))
        wakeup(L->wait_queue.front);   // 唤醒队首移入就绪队列
}
```

> **★考点**：**互斥锁 vs 自旋锁的选型与信号量区别**
> - **选型成本比较**：阻塞再唤醒需要付出**两次上下文切换代价**（不仅保存/恢复寄存器，还会导致 CPU 高速缓存 Cache 与快表 TLB 内容失效、恢复后需重新预热）。因此：**临界区执行极短（短于两次上下文切换开销）、多核环境、或禁止睡眠的中断处理程序上下文**选用**自旋锁**；**临界区较长（如涉及 I/O）、单核环境或普通进程上下文**选用**互斥锁**。
> - **互斥锁与信号量的本质差别（高频选项）**：互斥锁在功能上等价于**初值为 1 的信号量**，但**互斥锁带有严格“所有权（Ownership）”**——谁加锁就必须由谁解锁（同一进程成对调用 `acquire`/`release`）。而同步问题往往需要“进程 A 做完事情唤醒进程 B”，解锁者与加锁者不是同一个执行流，故**互斥锁只能实现互斥，无法替代信号量实现进程同步**！

**3. 锁的粒度（Granularity）**：粗粒度（整个哈希表/数据结构一把大锁）实现简单且不易死锁，但并发度低；细粒度（每个桶或每行独立一把锁）并发度高，但单次操作往往要连续申请多把锁——**多把锁若不规定统一的固定加锁顺序，就会极易产生“循环等待”死锁**。

<figure class="cpd-figure not-content" id="os-c3-fig-6">
  <svg viewBox="0 0 720 264" role="img" aria-label="自旋锁与互斥锁在等待行为、开销成本、适用场景与所有权上的对比图">
    <defs>
      <marker id="os-c3-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-orange" x="16" y="16" width="336" height="156" rx="8"/>
    <rect class="fig-box-green" x="368" y="16" width="336" height="156" rx="8"/>
    <rect class="fig-box" x="28" y="48" width="96" height="32" rx="4"/>
    <rect class="fig-box" x="148" y="48" width="188" height="32" rx="4"/>
    <line class="fig-line-accent" x1="124" y1="64" x2="145" y2="64" marker-end="url(#os-c3-arr-6)"/>
    <rect class="fig-box" x="380" y="48" width="96" height="32" rx="4"/>
    <rect class="fig-box" x="498" y="48" width="192" height="32" rx="4"/>
    <line class="fig-line-accent" x1="476" y1="64" x2="495" y2="64" marker-end="url(#os-c3-arr-6)"/>
    <rect class="fig-box-accent" x="16" y="184" width="688" height="64" rx="8"/>
    <text class="fig-orange" x="184" y="36" font-size="12" text-anchor="middle">自旋锁（Spinlock）：原地忙等不让出核</text>
    <text class="fig-label" x="76" y="68" font-size="10.5" text-anchor="middle">锁被占用</text>
    <text class="fig-orange" x="242" y="68" font-size="10.5" text-anchor="middle">while(TSL) 占住 CPU 空转</text>
    <text class="fig-green" x="28" y="102" font-size="10.5">✅ 零上下文切换、不破坏 Cache/TLB 热度</text>
    <text class="fig-red" x="28" y="122" font-size="10.5">❌ 不满足让权等待；单处理机上自旋无意义</text>
    <text class="fig-muted" x="28" y="142" font-size="10">适用：多核（SMP）+ 极短临界区 + 中断处理上下文</text>
    <text class="fig-muted" x="28" y="159" font-size="9.5">优化：先只读缓存自旋，再抢写锁（减少总线风暴）</text>
    <text class="fig-green" x="536" y="36" font-size="12" text-anchor="middle">互斥锁（Mutex）：睡眠阻塞满足让权</text>
    <text class="fig-label" x="428" y="68" font-size="10.5" text-anchor="middle">锁被占用</text>
    <text class="fig-green" x="594" y="68" font-size="10.5" text-anchor="middle">block() 入等待队列让出核</text>
    <text class="fig-green" x="380" y="102" font-size="10.5">✅ 满足全部四准则（唯一包含让权等待的锁）</text>
    <text class="fig-red" x="380" y="122" font-size="10.5">❌ 需付出 2 次上下文切换 + 缓存预热损耗</text>
    <text class="fig-muted" x="380" y="142" font-size="10">适用：临界区较长 / 单核 / 可睡眠的普通进程环境</text>
    <text class="fig-accent" x="380" y="159" font-size="9.5">★ 有严格所有权（加锁者解锁）→ 只能互斥不能同步</text>
    <text class="fig-accent" x="360" y="207" font-size="11.5" text-anchor="middle">选型决策界限：自旋等待耗费（T_临界区） vs  睡眠阻塞代价（2 × T_上下文切换）</text>
    <text class="fig-label" x="360" y="230" font-size="11" text-anchor="middle">能力演进序：互斥锁（仅互斥，有所有权） &lt; 信号量（互斥 + 同步，无所有权） &lt; 管程（编译自动互斥 + 条件变量）</text>
  </svg>
  <figcaption>图 3-6　自旋锁与互斥锁的核心分界、选型开销权衡公式及同步原语能力层级图</figcaption>
</figure>


---

### 3.4 信号量机制与 PV 操作基础模型 ★

锁（`acquire`/`release`）和硬件指令已经解决了互斥问题，但它们仍然无法优雅地表达“**进程 A 做完后通知进程 B 开始**”这种同步协作（因为锁具备所有权约束）。1965 年 Dijkstra 提出的**信号量（Semaphore）机制**，用一个简单的整型计数与一对原子操作原语，将**进程互斥**、**进程同步**与**多资源管控**统一到了同一套框架下。

#### 3.4.1 整型信号量与记录型信号量（S.value 与 S.L）★

**1. 整型信号量（仍未满足让权等待）**

整型信号量直接定义一个表示资源数目的整型量 $S$ ，除初始化外，仅允许通过两个标准原子操作 `wait(S)`（即 **P 操作**，源自荷兰语 `proberen` 测试）和 `signal(S)`（即 **V 操作**，源自 `verhogen` 增加）来访问：

```c
void wait(int S) {            // 相当于 P(S)
    while (S <= 0) ;          // 资源不足时死循环空转（忙等！）
    S--;
}

void signal(int S) {          // 相当于 V(S)
    S++;
}
```

- **特点**：由于 `wait(S)` 整体是原子的，“判断 `S > 0`”和“执行 `S--`”之间不再存在缝隙，互斥完全可靠；但当 `S <= 0` 时，进程在 `while` 上不断测试占着 CPU 不放，因此**整型信号量不满足“让权等待”**。

> **★考点**：**2021 统考大题（21#45）整型信号量与开关中断剖析**
> 给出上述 `wait(S)`/`signal(S)` 伪代码，考查三个深度细节：
> 1. **为何对信号量 `S` 的访问（`wait` 和 `signal`）必须互斥执行？** 信号量 `S` 是被多个并发进程共享的变量，若 `S--` 与 `S++` 的“读–改–写”过程被打断交错（例如 `P` 刚读出 `S` 准备减 1 时切换去执行 `V` 将 `S` 加 1，切回后再覆盖写回），信号量计数值将发生错乱，破坏同步互斥语义。
> 2. **若采用关中断保护 `wait(S)` 内部：方法一直接把关中断放在 `while(S<=0);` 外侧，方法二在 `while` 循环体内短暂开中断再关中断，哪一个正确？**
>    **方法一死锁，方法二正确！** 因为进程调度切换依赖时钟等中断唤醒内核调度器。若在方法一中带着关中断陷入 `while(S <= 0);`，由于中断被长期屏蔽，CPU 无法响应时钟中断切换给其他进程，导致永远无人能执行 `signal(S)` 将 `S` 改为正值，当前核将永久死循环！方法二在 `while` 循环体内短暂开中断，才允许调度切换至他进程释放资源。
> 3. **用户程序能否通过直接调用开/关中断指令实现临界区互斥？** **不能**。开/关中断属于特权指令，仅内核态下操作系统有权执行，用户态执行会触发非法指令异常。

**2. 记录型信号量（引入等待队列，正式实现让权等待）★**

为消除忙等，给信号量增加一个指向阻塞进程控制块（PCB）的等待队列指针 `L`（或 `list`），构成**记录型信号量**：

```c
typedef struct {
    int value;          // 信号量计数（资源数 / 排队状态）
    struct PCB *L;      // 指向因等待该信号量而阻塞的进程链表
} semaphore;

void wait(semaphore *S) {     // P(S) 原语：申请资源
    S->value--;
    if (S->value < 0) {
        block(S->L);          // 自我阻塞，放弃处理机，PCB 挂入等待队列 S->L
    }
}

void signal(semaphore *S) {   // V(S) 原语：释放资源
    S->value++;
    if (S->value <= 0) {
        wakeup(S->L);         // 从阻塞队列 S->L 唤醒队首进程，移入就绪队列
    }
}
```

> **★考点**：**`S.value` 物理意义铁律与反推公式（`10#25`, `18#32`, `26#26`）**
> 1. **为何记录型信号量满足“让权等待”？** 因为它在 `S.value < 0` 时调用了操作系统原语 `block(S.L)` 主动交出处理机进入阻塞态（而非那条链表本身自动让出 CPU）。
> 2. **`S.value` 的三种取值物理意义**：
>    - **`S.value > 0`**：当前**剩余可用资源数量**为 `S.value` 份，阻塞队列为空；
>    - **`S.value == 0`**：可用资源已**恰好分配完毕**，阻塞队列为空；
>    - **`S.value < 0`**：资源耗尽，**`|S.value|` 表示当前在阻塞队列 `S.L` 中排队等待该资源的进程总数**（此性质仅对记录型信号量成立！整型信号量 `S` 不可能为负）。
> 3. **操作次数反推公式**：设信号量初值为 $I$ ，当前值为 $C$ ，每执行一次 `V` 使值加 1，每执行一次 `P` 使值减 1，必有：$V_{\text{次数}} - P_{\text{次数}} = C - I$。
>    **真题算例**：若某信号量初值 $I = 3$ ，当前值 $C = 1$ （`10#25`），则 $V_{\text{次数}} - P_{\text{次数}} = 1 - 3 = -2$ ，表明完成的 `P` 操作比 `V` 操作多 **2 次**；若某资源信号量初值为 $k$ ，共 $8$ 个进程并发申请且均未释放（`26#26` 考法），则最多 $k$ 个进程同时使用，其余 $8 - k$ 个进程阻塞在队列中，此时 `S.value = k - 8`。

<figure class="cpd-figure not-content" id="os-c3-fig-7">
  <svg viewBox="0 0 720 296" role="img" aria-label="记录型信号量原语语义、S.value 物理意义三分界以及四步入队与出队动态演化图">
    <defs>
      <marker id="os-c3-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="268" height="140" rx="8"/>
    <rect class="fig-box-subtle" x="296" y="16" width="408" height="140" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="168" width="688" height="112" rx="8"/>
    <rect class="fig-box-green" x="308" y="46" width="384" height="30" rx="4"/>
    <rect class="fig-box-orange" x="308" y="81" width="384" height="30" rx="4"/>
    <rect class="fig-box-red" x="308" y="116" width="384" height="32" rx="4"/>
    <rect class="fig-box" x="28" y="200" width="146" height="68" rx="5"/>
    <rect class="fig-box-orange" x="198" y="200" width="146" height="68" rx="5"/>
    <rect class="fig-box-red" x="368" y="200" width="146" height="68" rx="5"/>
    <rect class="fig-box-green" x="538" y="200" width="154" height="68" rx="5"/>
    <line class="fig-line-accent" x1="174" y1="234" x2="195" y2="234" marker-end="url(#os-c3-arr-7)"/>
    <line class="fig-line-accent" x1="344" y1="234" x2="365" y2="234" marker-end="url(#os-c3-arr-7)"/>
    <line class="fig-line-accent" x1="514" y1="234" x2="535" y2="234" marker-end="url(#os-c3-arr-7)"/>
    <text class="fig-title" x="150" y="36" font-size="11.5" text-anchor="middle">记录型信号量（P / V 原语）</text>
    <text class="fig-label" x="28" y="56" font-size="10">struct { int value; PCB *L; } S;</text>
    <text class="fig-blue" x="28" y="78" font-size="10.5">P(S)：S.value--;</text>
    <text class="fig-label" x="28" y="95" font-size="10">  if (S.value &lt; 0) block(S.L);</text>
    <text class="fig-green" x="28" y="118" font-size="10.5">V(S)：S.value++;</text>
    <text class="fig-label" x="28" y="135" font-size="10">  if (S.value &lt;= 0) wakeup(S.L);</text>
    <text class="fig-muted" x="28" y="150" font-size="9.5">★ 靠 block() 实现让权等待（18#32）</text>
    <text class="fig-title" x="500" y="36" font-size="11.5" text-anchor="middle">S.value 物理意义三分界（★ 10#25 / 26#26）</text>
    <text class="fig-green" x="320" y="65" font-size="10.5">S.value &gt; 0 ：尚余可用资源数为 S.value 份，L 为空</text>
    <text class="fig-orange" x="320" y="100" font-size="10.5">S.value == 0：资源恰好分完，无空闲也无进程在等</text>
    <text class="fig-red" x="320" y="136" font-size="10.5">S.value &lt; 0 ：资源已空，|S.value| = 队列 L 中阻塞人数</text>
    <text class="fig-title" x="360" y="188" font-size="11.5" text-anchor="middle">动态队列推演（设初值 S.value = 1，三进程 P1、P2、P3 并发申请后 P1 释放）</text>
    <text class="fig-label" x="101" y="218" font-size="10.5" text-anchor="middle">① P1 执行 P(S)</text>
    <text class="fig-blue" x="101" y="237" font-size="10" text-anchor="middle">S.value: 1 → 0</text>
    <text class="fig-muted" x="101" y="256" font-size="9.5" text-anchor="middle">L: [空]（P1 获得资源）</text>
    <text class="fig-orange" x="271" y="218" font-size="10.5" text-anchor="middle">② P2 执行 P(S)</text>
    <text class="fig-orange" x="271" y="237" font-size="10" text-anchor="middle">S.value: 0 → -1</text>
    <text class="fig-muted" x="271" y="256" font-size="9.5" text-anchor="middle">L: [P2]（1 人阻塞）</text>
    <text class="fig-red" x="441" y="218" font-size="10.5" text-anchor="middle">③ P3 执行 P(S)</text>
    <text class="fig-red" x="441" y="237" font-size="10" text-anchor="middle">S.value: -1 → -2</text>
    <text class="fig-muted" x="441" y="256" font-size="9.5" text-anchor="middle">L: [P2, P3]（2 人阻塞）</text>
    <text class="fig-green" x="615" y="218" font-size="10.5" text-anchor="middle">④ P1 执行 V(S)</text>
    <text class="fig-green" x="615" y="237" font-size="10" text-anchor="middle">S.value: -2 → -1</text>
    <text class="fig-muted" x="615" y="256" font-size="9.5" text-anchor="middle">L: [P3]（唤醒队首 P2!）</text>
  </svg>
  <figcaption>图 3-7　记录型信号量结构与 P/V 原语语义、S.value 物理意义判据及阻塞队列动态出/入队演化</figcaption>
</figure>

#### 3.4.2 AND 型信号量与信号量集（拓展了解）

当一个进程需要**同时持有两个或以上临界资源**才能继续推进时，如果用普通记录型信号量逐个 `P` 申请，极易在两次 `P` 的间隙里“各自拿着一个资源等对方手里的另一个”，触发死锁。例如进程 A 执行 `P(D); P(E);` 而进程 B 执行 `P(E); P(D);`，交叉执行后双双阻塞。

1. **AND 型信号量**：将多资源的多次申请合成为**一次性全分配或全不分配**的原子操作，消灭死锁的“请求并保持”条件：
   ```c
   Swait(S1, S2, ..., Sn)    // 若所有 Si >= 1，则全部 Si--；否则一个都不减，直接阻塞在第一个不足的 Si 队列上
   Ssignal(S1, S2, ..., Sn)  // 所有 Si++，并唤醒各队列上的阻塞进程
   ```
2. **一般信号量集**：在 AND 基础上进一步引入**下限测试阈值 $t_i$** 与**单次申请消耗量 $d_i$**（仅当所有 $S_i \ge t_i$ 时才执行 $S_i = S_i - d_i$）：
   $$
   \text{Swait}(S_1, t_1, d_1, \dots, S_n, t_n, d_n) \qquad \text{Ssignal}(S_1, d_1, \dots, S_n, d_n)
   $$
   其三个特例将此前所有机制收束统一：
   - **`Swait(S, d, d)`**：每次向单个信号量申请 $d$ 个单位，不足 $d$ 个时不予分配；
   - **`Swait(S, 1, 1)`**：退化为普通的记录型信号量或互斥信号量；
   - **`Swait(S, 1, 0)`（可控开关 ★）**：当 $d = 0$ 时**只检测 $S \ge 1$ 而并不扣除资源**！$S \ge 1$ 时允许任意多进程同时通过，$S = 0$ 时拦住所有进程——这是普通信号量绝无可能表达的语义。

#### 3.4.3 PV 操作的四大基本应用模型 ★

不论题面怎样变化，信号量的基本用法归根结底只有以下四种模型，核心区分在于<strong>“一开始有几份该资源可用”</strong>：

1. **模型一：实现进程互斥（初值 `mutex = 1`）**
   - 同一进程内部成对夹住临界区代码：`P(mutex); 临界区; V(mutex);`。
   - `mutex` 取值范围恒为 $\{-1, 0, 1\}$（若有 $k$ 个进程竞争同一临界区，则最小可达 $1 - k$）。
   - **最佳实践**：把无关代码移至剩余区，令临界区尽可能短。
2. **模型二：实现进程同步（初值 `S = 0`）**
   - 协调两个不同进程的严格先后关系（例如必须先在 `P1` 执行操作 `A`，才能在 `P2` 执行操作 `B`）。
   - **口诀「前 V 后 P」**：先完成动作的进程在动作之后执行 `V(S)`（宣布“事件 A 已完成，生产 1 份许可”）；等待的进程在动作之前执行 `P(S)`（“消费 1 份许可，若尚未发生则阻塞等待”）。
   - 同步信号量成对跨进程分布，通常初值为 `0`（表示初始时刻该前置事件尚未发生）。
3. **模型三：多资源并发数控制（初值 `S = n`）**
   - 限制至多 $n$ 个进程同时访问某类有限多份资源（如 $n$ 格缓冲空位、$n$ 台打印机、某程序段允许至多 2 人进入、博物馆容积 500 人）。
   - **真题实战（`13#45` 博物馆参观）**：某博物馆最多容纳 500 人同时参观，仅有一个出入口且每次只允许通过 1 人。设互斥信号量 `door = 1` 保护出入口，资源信号量 `empty = 500` 管控馆内余位：
     ```c
     semaphore empty = 500, door = 1;
     visitor() {
         P(empty);       // ① 先领馆内名额（同步/资源 P 在前！）
         P(door);        // ② 再互斥过门（互斥 P 在后！）
         进门;
         V(door);
         参观;
         P(door);
         出门;
         V(door);
         V(empty);       // 归还馆内名额
     }
     ```
   - **基础练习**：3 个进程共享某程序段，每次至多允许 2 个进程进入。设 `S = 2`，则全部 3 个进程先后申请时 `S` 的取值范围为 `2, 1, 0, -1`（`-1` 表示第 3 个进程已阻塞排队）。

<figure class="cpd-figure not-content" id="os-c3-fig-8">
  <svg viewBox="0 0 720 260" role="img" aria-label="PV 操作实现进程互斥同进程夹紧模板与实现进程同步跨进程前 V 后 P 模板对比">
    <defs>
      <marker id="os-c3-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="228" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="228" rx="8"/>
    <rect class="fig-box" x="30" y="50" width="144" height="142" rx="6"/>
    <rect class="fig-box" x="194" y="50" width="144" height="142" rx="6"/>
    <rect class="fig-box-blue" x="42" y="76" width="120" height="26" rx="4"/>
    <rect class="fig-box-red" x="42" y="112" width="120" height="32" rx="4"/>
    <rect class="fig-box-green" x="42" y="154" width="120" height="26" rx="4"/>
    <rect class="fig-box-blue" x="206" y="76" width="120" height="26" rx="4"/>
    <rect class="fig-box-red" x="206" y="112" width="120" height="32" rx="4"/>
    <rect class="fig-box-green" x="206" y="154" width="120" height="26" rx="4"/>
    <rect class="fig-box" x="382" y="50" width="136" height="142" rx="6"/>
    <rect class="fig-box" x="554" y="50" width="136" height="142" rx="6"/>
    <rect class="fig-box-blue" x="394" y="84" width="112" height="34" rx="4"/>
    <rect class="fig-box-green" x="394" y="138" width="112" height="34" rx="4"/>
    <rect class="fig-box-orange" x="566" y="84" width="112" height="34" rx="4"/>
    <rect class="fig-box-purple" x="566" y="138" width="112" height="34" rx="4"/>
    <path class="fig-line-green" d="M 506 155 L 536 155 L 536 101 L 563 101" marker-end="url(#os-c3-arr-8)"/>
    <rect class="fig-box" x="518" y="118" width="36" height="18" rx="3"/>
    <text class="fig-title" x="184" y="36" font-size="12" text-anchor="middle">模型一：实现互斥（初值 mutex = 1）</text>
    <text class="fig-label" x="102" y="68" font-size="11" text-anchor="middle">进程 P1</text>
    <text class="fig-blue" x="102" y="93" font-size="10.5" text-anchor="middle">P(mutex); // 上锁</text>
    <text class="fig-red" x="102" y="132" font-size="10.5" text-anchor="middle">临界区代码</text>
    <text class="fig-green" x="102" y="171" font-size="10.5" text-anchor="middle">V(mutex); // 解锁</text>
    <text class="fig-label" x="266" y="68" font-size="11" text-anchor="middle">进程 P2</text>
    <text class="fig-blue" x="266" y="93" font-size="10.5" text-anchor="middle">P(mutex); // 上锁</text>
    <text class="fig-red" x="266" y="132" font-size="10.5" text-anchor="middle">临界区代码</text>
    <text class="fig-green" x="266" y="171" font-size="10.5" text-anchor="middle">V(mutex); // 解锁</text>
    <text class="fig-accent" x="184" y="213" font-size="10.5" text-anchor="middle">★ 成对在“同一进程内”，紧夹临界区</text>
    <text class="fig-muted" x="184" y="231" font-size="10" text-anchor="middle">2 进程竞争时取值范围：-1, 0, 1</text>
    <text class="fig-title" x="536" y="36" font-size="12" text-anchor="middle">模型二：实现同步（初值 S = 0）</text>
    <text class="fig-label" x="450" y="68" font-size="11" text-anchor="middle">前驱进程 P1</text>
    <text class="fig-blue" x="450" y="105" font-size="10.5" text-anchor="middle">先执行：操作 A</text>
    <text class="fig-green" x="450" y="159" font-size="10.5" text-anchor="middle">V(S); // 通知完成</text>
    <text class="fig-label" x="622" y="68" font-size="11" text-anchor="middle">后继进程 P2</text>
    <text class="fig-orange" x="622" y="105" font-size="10.5" text-anchor="middle">P(S); // 等待 A</text>
    <text class="fig-purple" x="622" y="159" font-size="10.5" text-anchor="middle">后执行：操作 B</text>
    <text class="fig-green" x="536" y="130" font-size="9.5" text-anchor="middle">唤醒</text>
    <text class="fig-accent" x="536" y="213" font-size="10.5" text-anchor="middle">★ 口诀「前 V 后 P」：成对分布于不同进程</text>
    <text class="fig-muted" x="536" y="231" font-size="10" text-anchor="middle">初值 0 表示事件尚未发生；V 永不阻塞</text>
  </svg>
  <figcaption>图 3-8　PV 操作实现互斥（同进程成对包围）与同步（跨进程“前 V 后 P”）通用模板对比</figcaption>
</figure>

4. **模型四：实现前驱关系（有向无环图 DAG 通法）★**
   - **通法规则**：当多个并发程序段或操作构成有向无环图（DAG），边 $u \to v$ 表示 $u$ 必须在 $v$ 开始前完成时：
     1. **数边设量**：为图中**每一条直接前驱边**配备一个独立的同步信号量，**初值全设为 `0`**（忽略可通过传递性推导的间接边）。
     2. **入 P 出 V**：每个节点的代码模板严格固定为：
        `[对所有直接前驱入边的信号量执行 P 操作];  执行本节点操作;  [对所有直接后继出边的信号量执行 V 操作];`
     3. **三项自检**：设定的信号量总数 $=$ 边数；每个节点前的 `P` 个数 $=$ 该节点入度；每个节点后的 `V` 个数 $=$ 该节点出度。

   - **经典实例（6 节点 7 边前驱图）**：如左图 3-9 所示，`S1 → S2, S1 → S3, S2 → S4, S2 → S5, S3 → S6, S4 → S6, S5 → S6` 共 7 条直接边，故设 7 个初值为 0 的信号量 `s12, s13, s24, s25, s36, s46, s56`。则 `S1` 结束后执行 `V(s12); V(s13);`，`S2` 先 `P(s12)` 再 `V(s24); V(s25);`，`S6` 前置三个等待 `P(s36); P(s46); P(s56);`。

   - **★ 真题精讲 A（2020#45 统考前驱图）**：有 `A, B, C, D, E` 五个并发操作，满足 `C` 必须在 `A` 和 `B` 之后执行、`E` 必须在 `C` 和 `D` 之后执行。直接前驱边共 4 条（`A→C, B→C, C→E, D→E`），对应设 4 个初值为 `0` 的信号量 `s_ac, s_bc, s_ce, s_de`：`A` 后 `V(s_ac)`、`B` 后 `V(s_bc)`、`C` 前 `P(s_ac); P(s_bc)` 且后 `V(s_ce)`、`D` 后 `V(s_de)`、`E` 前 `P(s_ce); P(s_de)`。

   - **★ 真题精讲 B（2022#46 统考真题：线程内合并与跨线程同步优化）**：
     某进程有 `A, B, C, D, E, F` 共 6 个操作，分别由**两个线程**并发执行：线程 `T1` 执行 `{A, E, F}`，线程 `T2` 执行 `{B, C, D}`。约束为：`C` 在 `A` 与 `B` 后执行；`D` 与 `E` 在 `C` 后执行；`F` 在 `E` 后执行。
     - **核心陷阱与精简技巧**：同一线程内部的操作顺序（`B→C`、`C→D`、`E→F`）已由代码指令的先后顺序天然保证，**不必**额外设置信号量！**真正需要用信号量约束的只有跨越两个线程的同步边**：① `A → C`（设 `S_ac = 0`）；② `C → E`（设 `S_ce = 0`）。（注：若按通用边数法全设 5 个信号量在逻辑上亦等价正确，但考场上仅设 2 个跨线程信号量最简洁清晰、最受阅卷青睐！）
     ```c
     semaphore S_ac = 0, S_ce = 0;

     void T1() {
         执行操作 A;
         V(S_ac);      // 通知 T2：A 已完成
         P(S_ce);      // 等待 T2：C 完成
         执行操作 E;
         执行操作 F;   // 同线程在 E 之后自然顺序执行
     }

     void T2() {
         执行操作 B;   // 同线程在 C 之前自然顺序执行
         P(S_ac);      // 等待 T1：A 完成
         执行操作 C;
         V(S_ce);      // 通知 T1：C 已完成
         执行操作 D;   // 同线程在 C 之后自然顺序执行
     }
     ```

<figure class="cpd-figure not-content" id="os-c3-fig-9">
  <svg viewBox="0 0 720 300" role="img" aria-label="DAG 前驱图信号量通用映射法与 2022 年 408 统考真题跨线程同步双泳道图">
    <defs>
      <marker id="os-c3-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="332" height="268" rx="8"/>
    <rect class="fig-box-subtle" x="364" y="16" width="340" height="268" rx="8"/>
    <line class="fig-line-accent" x1="74" y1="128" x2="115" y2="97" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="74" y1="144" x2="115" y2="176" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="154" y1="86" x2="203" y2="71" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="154" y1="98" x2="203" y2="122" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="154" y1="181" x2="285" y2="145" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="242" y1="74" x2="285" y2="125" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line-accent" x1="242" y1="128" x2="285" y2="135" marker-end="url(#os-c3-arr-9)"/>
    <rect class="fig-box-blue" x="38" y="122" width="36" height="28" rx="5"/>
    <rect class="fig-box-green" x="118" y="78" width="36" height="28" rx="5"/>
    <rect class="fig-box-green" x="118" y="170" width="36" height="28" rx="5"/>
    <rect class="fig-box-orange" x="206" y="54" width="36" height="28" rx="5"/>
    <rect class="fig-box-orange" x="206" y="112" width="36" height="28" rx="5"/>
    <rect class="fig-box-purple" x="288" y="122" width="36" height="28" rx="5"/>
    <rect class="fig-box-blue" x="378" y="52" width="312" height="72" rx="6"/>
    <rect class="fig-box-green" x="378" y="158" width="312" height="76" rx="6"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="582" y1="94" x2="617" y2="94" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="448" y1="186" x2="473" y2="186" marker-end="url(#os-c3-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="524" y1="186" x2="581" y2="186" marker-end="url(#os-c3-arr-9)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.6" d="M 425 108 L 425 142 L 490 142 L 490 170" marker-end="url(#os-c3-arr-9)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.6" d="M 510 172 L 510 142 L 558 142 L 558 111" marker-end="url(#os-c3-arr-9)"/>
    <rect class="fig-box" x="400" y="80" width="46" height="28" rx="4"/>
    <rect class="fig-box" x="536" y="80" width="46" height="28" rx="4"/>
    <rect class="fig-box" x="620" y="80" width="46" height="28" rx="4"/>
    <rect class="fig-box" x="400" y="172" width="46" height="28" rx="4"/>
    <rect class="fig-box" x="476" y="172" width="46" height="28" rx="4"/>
    <rect class="fig-box" x="584" y="172" width="46" height="28" rx="4"/>
    <rect class="fig-box-red" x="394" y="133" width="60" height="18" rx="3"/>
    <rect class="fig-box-orange" x="530" y="133" width="60" height="18" rx="3"/>
    <text class="fig-title" x="182" y="36" font-size="11.5" text-anchor="middle">通用 DAG 前驱图（每边 1 个初值 0 信号量）</text>
    <text class="fig-blue" x="56" y="140" font-size="11" text-anchor="middle">S1</text>
    <text class="fig-green" x="136" y="96" font-size="11" text-anchor="middle">S2</text>
    <text class="fig-green" x="136" y="188" font-size="11" text-anchor="middle">S3</text>
    <text class="fig-orange" x="224" y="72" font-size="11" text-anchor="middle">S4</text>
    <text class="fig-orange" x="224" y="130" font-size="11" text-anchor="middle">S5</text>
    <text class="fig-purple" x="306" y="140" font-size="11" text-anchor="middle">S6</text>
    <text class="fig-muted" x="78" y="102" font-size="9.5">s12</text>
    <text class="fig-muted" x="76" y="175" font-size="9.5">s13</text>
    <text class="fig-muted" x="174" y="69" font-size="9.5">s24</text>
    <text class="fig-muted" x="166" y="131" font-size="9.5">s25</text>
    <text class="fig-muted" x="220" y="176" font-size="9.5">s36</text>
    <text class="fig-muted" x="273" y="95" font-size="9.5">s46</text>
    <text class="fig-muted" x="252" y="124" font-size="9.5">s56</text>
    <text class="fig-label" x="182" y="232" font-size="10.5" text-anchor="middle">7 条边 → 7 个初值为 0 的信号量</text>
    <text class="fig-muted" x="182" y="253" font-size="10" text-anchor="middle">验证：前置 P 数 = 入度，后置 V 数 = 出度</text>
    <text class="fig-muted" x="182" y="271" font-size="9.5" text-anchor="middle">例：S6(入度 3) → P(s36); P(s46); P(s56);</text>
    <text class="fig-title" x="534" y="36" font-size="11.5" text-anchor="middle">2022 408 真题（22#46）：跨线程同步优化 ★</text>
    <text class="fig-blue" x="390" y="69" font-size="10.5">线程 T1 顺序执行（A → E → F）</text>
    <text class="fig-label" x="423" y="98" font-size="11" text-anchor="middle">A</text>
    <text class="fig-label" x="559" y="98" font-size="11" text-anchor="middle">E</text>
    <text class="fig-label" x="643" y="98" font-size="11" text-anchor="middle">F</text>
    <text class="fig-red" x="424" y="146" font-size="9.5" text-anchor="middle">S_ac = 0</text>
    <text class="fig-orange" x="560" y="146" font-size="9.5" text-anchor="middle">S_ce = 0</text>
    <text class="fig-green" x="390" y="222" font-size="10.5">线程 T2 顺序执行（B → C → D）</text>
    <text class="fig-label" x="423" y="190" font-size="11" text-anchor="middle">B</text>
    <text class="fig-label" x="499" y="190" font-size="11" text-anchor="middle">C</text>
    <text class="fig-label" x="607" y="190" font-size="11" text-anchor="middle">D</text>
    <text class="fig-accent" x="534" y="254" font-size="10.5" text-anchor="middle">★ 同线程内（B→C, C→D, E→F）顺序天然保证</text>
    <text class="fig-muted" x="534" y="271" font-size="10" text-anchor="middle">仅跨线程箭头 A→C 与 C→E 必须设信号量</text>
  </svg>
  <figcaption>图 3-9　有向无环前驱图通用信号量映射法则与 2022 年 408 真题“同线程免设、跨线程必设”优化图</figcaption>
</figure>

---

### 3.5 管程与条件变量（Monitor & Condition Variable）

#### 3.5.1 为何引入管程及其本质特性

虽然信号量机制功能完备，但在工程实践中存在严重缺陷：**`P`、`V` 操作作为散落在各进程伪代码中的裸原语，同步控制逻辑与业务逻辑高度耦合；一旦某处少写一个 `V` 或颠倒了两个 `P` 的次序，编译器完全检查不出来，只能在运行时引发极其隐蔽的死锁或数据破坏**。

1974 年 Hansen 与 Hoare 提出<strong>管程（Monitor）</strong>机制，借用面向对象的**封装**思想：**将共享数据结构与操作这些数据的所有过程集中封装成一个模块，并由编程语言的编译器在编译阶段自动向每个管程过程插入加锁/解锁指令，从机制上保证任何时刻最多只有一个进程在管程内部执行**。

管程由四部分组成：① 管程的名称；② 局部于管程内部的共享数据结构说明；③ 对该数据结构进行操作的一组过程（函数）；④ 对局部共享数据设置初值的语句。

> **★考点**：**管程四大高频考点（`16#32`, `18#28`）**
> 1. **管程是由编程语言支持的进程同步机制**（不同于信号量由 OS 内核直接提供原语），互斥控制代码由**编译器**负责插入。
> 2. **封装性是互斥成立的前提**：**管程中定义的共享变量只能被管程内部的过程访问**，管程外部不能直接读写；否则外部绕过入口直接改写共享数据，互斥立刻失效。
> 3. **任何时刻最多只能有一个进程在管程中执行**（若管程内已有执行者，新调用者将在入口队列等待）。
> 4. **管程不仅能实现互斥，配上条件变量后同样能实现同步**！（`16#32` 错项“管程只能用于实现进程互斥”直接考此结论）。

#### 3.5.2 条件变量（Condition Variable）与信号量的根本分界 ★

仅有“每次只能进一人”的管程互斥还不够：假设消费者进入管程发现缓冲区为空，无法取数据，如果它直接在管程里面死等而不让出管程，那么能够放入产品的生产者进程根本进不了管程，双方立刻死锁！

因此管程内必须引入**条件变量** `condition x, y;`。每个条件变量维护一条阻塞链表，提供两个操作：

- **`x.wait()`**：当前进程因条件 `x` 不满足需要阻塞时，将自身加入条件 `x` 的等待队列，并**主动释放管程使用权**，让其他进程得以进入管程改变条件。
- **`x.signal()`**：当某进程改变共享数据状态后，唤醒一个在条件 `x` 队列上等待的进程；**若此时没有进程在 `x` 上等待，则 `x.signal()` 不产生任何效果（空操作），原进程继续执行**。

> **★考点**：**条件变量 vs 信号量的最本质区别（`18#28` 核心判据）**
> **条件变量没有与之关联的整型计数值（无状态、不累积信号）**！
> - 信号量的 `V(S)` 总是使 `S.value++`，即便当前无人等待，释放的信号也会保留下来供未来 `P(S)` 消费；
> - 条件变量的 **`x.signal()` 在无人等待时等于空操作，发出的唤醒信号直接丢失**！因此使用条件变量时，管程内<strong>必须另外维护普通共享状态变量（如 <code>count</code>）</strong>来显式判断条件。

#### 3.5.3 霍尔管程三种队列与 Hoare vs Mesa 语义 ★

当管程内的进程 `P` 执行 `x.signal()` 唤醒了阻塞在条件 `x` 上的进程 `Q` 时，会出现 `P` 和 `Q` 同时想在管程内运行的冲突，而管程只能容纳一个进程。业界存在三种经典语义处理方案：

1. **Hoare（霍尔）语义（教科书重点剖析）**：**`P` 立即挂起自己让出管程，让被唤醒的 `Q` 立刻接管执行**；直到 `Q` 离开管程或再次 `wait` 阻塞后，`P` 才恢复运行。为此霍尔管程内部共维护**三种等待队列**（基于底层互斥信号量 `mutex = 1`、紧急信号量 `next = 0` 及各自条件队列 `x_sem = 0`）：
   - **入口等待队列（`mutex`）**：外部试图调用管程过程但管程非空时在此排队；
   - **紧急等待队列（`next`）**：存放发出 `signal()` 后暂时让出管程的进程，**离开管程时唤醒优先级高于入口队列**（`if (next_count > 0) V(next); else V(mutex);`）；
   - **条件变量等待队列（`x_sem`）**：因对应条件不满足而调用 `wait()` 的进程队列。
   - **关键推论**：在 Hoare 语义下，因为管程使用权是**原地直接移交**给 `Q` 的，中间没有任何第三方能够插手改写共享状态，故 `Q` 醒来时也不用再 `P(mutex)`，且**条件在醒来后必然依然成立，只需使用 `if` 语句检查即可**。
2. **Hansen 语义（折中方案）**：规定 `x.signal()` 必须是管程过程体的**最后一条语句**，发完信号立即退出管程并把接力棒交给 `Q`。
3. **Mesa 语义（现代 OS、POSIX `pthread_cond_wait`、Java `wait/notify` 实际采用）★**：`P` 发出 `signal()` 后**继续占有管程直到自己退出或 wait**，而唤醒的 `Q` 只是进入就绪态重新竞争管程锁。等到 `Q` 终于抢回管程执行权时，刚才的条件可能已被第三个抢先进入管程的进程改坏！因此，**Mesa 语义下绝对禁止用 `if`，必须使用 `while` 循环重新检查条件**！

```c
// Mesa 管程风格生产者-消费者示例（Java / POSIX 实战铁律：必用 while 重检条件！）
Monitor ProducerConsumer {
    item buffer[N];
    int in = 0, out = 0, count = 0;   // 共享数据，由封装保证互斥
    condition notFull, notEmpty;      // 两个条件变量（仅作阻塞/唤醒通道，无计数）

public:
    void put(item x) {
        while (count >= N)            // Hoare 可用 if；Mesa 必须用 while 防止虚假唤醒/插队
            notFull.wait();           // 阻塞并释放管程锁
        buffer[in] = x;
        in = (in + 1) % N;
        count++;
        notEmpty.signal();            // 唤醒可能等待的消费者（无人等待则丢弃）
    }

    item get() {
        while (count <= 0)
            notEmpty.wait();
        item x = buffer[out];
        out = (out + 1) % N;
        count--;
        notFull.signal();
        return x;
    }
}
```

可以看到，管程方案中程序员**既不用写 `P(mutex)`/`V(mutex)`，也不存在“把互斥 P 写在同步 P 之前导致持锁死锁”的顺序风险**（`wait()` 自动释放管程锁，机制级杜绝持锁睡眠）。

<figure class="cpd-figure not-content" id="os-c3-fig-10">
  <svg viewBox="0 0 720 290" role="img" aria-label="霍尔管程内部封装结构、三种等待队列与使用权原地移交机制示意图">
    <defs>
      <marker id="os-c3-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="688" height="258" rx="8"/>
    <rect class="fig-box-blue" x="28" y="48" width="146" height="206" rx="6"/>
    <rect class="fig-box" x="44" y="84" width="114" height="32" rx="4"/>
    <rect class="fig-box" x="44" y="126" width="114" height="32" rx="4"/>
    <rect class="fig-box" x="44" y="168" width="114" height="32" rx="4"/>
    <rect class="fig-box-accent" x="196" y="42" width="282" height="218" rx="8"/>
    <rect class="fig-box" x="208" y="70" width="258" height="46" rx="5"/>
    <rect class="fig-box-green" x="208" y="124" width="258" height="58" rx="5"/>
    <rect class="fig-box-orange" x="208" y="190" width="258" height="58" rx="5"/>
    <rect class="fig-box-purple" x="546" y="48" width="146" height="206" rx="6"/>
    <rect class="fig-box" x="556" y="82" width="126" height="56" rx="4"/>
    <rect class="fig-box" x="556" y="150" width="126" height="56" rx="4"/>
    <line class="fig-line-accent" x1="174" y1="150" x2="193" y2="150" marker-end="url(#os-c3-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="478" y1="136" x2="543" y2="112" marker-end="url(#os-c3-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="546" y1="174" x2="481" y2="162" marker-end="url(#os-c3-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="337" y1="182" x2="337" y2="188" marker-end="url(#os-c3-arr-10)"/>
    <rect class="fig-box" x="492" y="92" width="38" height="16" rx="3"/>
    <rect class="fig-box" x="492" y="182" width="40" height="16" rx="3"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">霍尔（Hoare）管程架构与三种等待队列（★ 16#32 / 18#28）</text>
    <text class="fig-blue" x="101" y="70" font-size="11" text-anchor="middle">① 入口队列 (mutex)</text>
    <text class="fig-label" x="101" y="104" font-size="10.5" text-anchor="middle">等待线程 T3</text>
    <text class="fig-label" x="101" y="146" font-size="10.5" text-anchor="middle">等待线程 T4</text>
    <text class="fig-label" x="101" y="188" font-size="10.5" text-anchor="middle">等待线程 T5</text>
    <text class="fig-muted" x="101" y="232" font-size="9.5" text-anchor="middle">仅管程空闲时竞争进入</text>
    <text class="fig-accent" x="337" y="60" font-size="9.6" text-anchor="middle">管程边界（同一时刻至多 1 进程执行，编译器自动插锁）</text>
    <text class="fig-label" x="337" y="88" font-size="10.2" text-anchor="middle">共享数据：buffer[N], in, out, count</text>
    <text class="fig-muted" x="337" y="105" font-size="9.2" text-anchor="middle">封装铁律：仅允许管程内过程读写（互斥成立前提）</text>
    <text class="fig-green" x="337" y="142" font-size="10.2" text-anchor="middle">管程过程：put() / get() [当前运行进程 T1]</text>
    <text class="fig-muted" x="337" y="160" font-size="8.6" text-anchor="middle">进过程前 P(mutex)；出过程先查 next_count&gt;0 再唤醒</text>
    <text class="fig-muted" x="337" y="174" font-size="9.2" text-anchor="middle">★ 含条件变量后同时支持“互斥 + 同步”</text>
    <text class="fig-orange" x="337" y="208" font-size="9.4" text-anchor="middle">② 紧急等待队列（next）— 优先级高于入口队列 ★</text>
    <text class="fig-muted" x="337" y="226" font-size="8.8" text-anchor="middle">进程发出 x.signal() 唤醒阻塞者后，自身让权暂挂此处</text>
    <text class="fig-muted" x="337" y="241" font-size="8.8" text-anchor="middle">实现管程控制权在“唤醒者”与“被唤醒者”间原地移交</text>
    <text class="fig-purple" x="619" y="70" font-size="10.2" text-anchor="middle">③ 条件变量队列 (x_sem)</text>
    <text class="fig-label" x="619" y="102" font-size="9.2" text-anchor="middle">notFull 队列：[T6, T7]</text>
    <text class="fig-muted" x="619" y="122" font-size="9" text-anchor="middle">满时 wait() 阻塞并让出锁</text>
    <text class="fig-label" x="619" y="170" font-size="9.2" text-anchor="middle">notEmpty 队列：[T8]</text>
    <text class="fig-muted" x="619" y="190" font-size="9" text-anchor="middle">空时 wait() 阻塞并让出锁</text>
    <text class="fig-red" x="619" y="226" font-size="9.2" text-anchor="middle">无计数值：无人等时</text>
    <text class="fig-red" x="619" y="241" font-size="9.2" text-anchor="middle">signal() 信号直接丢失！</text>
    <text class="fig-purple" x="511" y="103" font-size="8.8" text-anchor="middle">wait</text>
    <text class="fig-green" x="512" y="193" font-size="8.5" text-anchor="middle">signal</text>
  </svg>
  <figcaption>图 3-10　霍尔管程内部结构、入口/紧急/条件三种等待队列及控制权交接机制</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c3-fig-11">
  <svg viewBox="0 0 720 248" role="img" aria-label="Hoare 管程与 Mesa 管程在执行 signal 后的调度时序与 if 对 while 检查对比">
    <defs>
      <marker id="os-c3-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-green" x="16" y="16" width="336" height="216" rx="8"/>
    <rect class="fig-box-orange" x="368" y="16" width="336" height="216" rx="8"/>
    <rect class="fig-box" x="30" y="50" width="308" height="32" rx="4"/>
    <rect class="fig-box" x="30" y="96" width="308" height="32" rx="4"/>
    <rect class="fig-box" x="30" y="142" width="308" height="32" rx="4"/>
    <rect class="fig-box-accent" x="30" y="186" width="308" height="34" rx="4"/>
    <line class="fig-line-accent" x1="184" y1="82" x2="184" y2="94" marker-end="url(#os-c3-arr-11)"/>
    <line class="fig-line-accent" x1="184" y1="128" x2="184" y2="140" marker-end="url(#os-c3-arr-11)"/>
    <rect class="fig-box" x="382" y="50" width="308" height="32" rx="4"/>
    <rect class="fig-box-red" x="382" y="96" width="308" height="32" rx="4"/>
    <rect class="fig-box" x="382" y="142" width="308" height="32" rx="4"/>
    <rect class="fig-box-accent" x="382" y="186" width="308" height="34" rx="4"/>
    <line class="fig-line-accent" x1="536" y1="82" x2="536" y2="94" marker-end="url(#os-c3-arr-11)"/>
    <line class="fig-line-accent" x1="536" y1="128" x2="536" y2="140" marker-end="url(#os-c3-arr-11)"/>
    <text class="fig-green" x="184" y="36" font-size="11.5" text-anchor="middle">Hoare 语义（信号与控制权原地移交）</text>
    <text class="fig-label" x="184" y="70" font-size="10.5" text-anchor="middle">① P 执行 x.signal() 唤醒阻塞者 Q</text>
    <text class="fig-label" x="184" y="116" font-size="10.5" text-anchor="middle">② P 立即退出让权，进紧急等待队列 next</text>
    <text class="fig-green" x="184" y="162" font-size="10.5" text-anchor="middle">③ Q 立即无缝接管（中间无第三方插队）</text>
    <text class="fig-accent" x="184" y="207" font-size="10.5" text-anchor="middle">条件必仍满足 → 可写 if (count &gt;= N) wait();</text>
    <text class="fig-orange" x="536" y="36" font-size="11.5" text-anchor="middle">Mesa 语义（POSIX / Java 实战模型 ★）</text>
    <text class="fig-label" x="536" y="70" font-size="10.5" text-anchor="middle">① P 执行 x.signal()，仅将 Q 移入入口就绪态</text>
    <text class="fig-red" x="536" y="116" font-size="10.5" text-anchor="middle">② P 跑完后，第三方 R 可能先抢进并改坏条件！</text>
    <text class="fig-orange" x="536" y="162" font-size="10.5" text-anchor="middle">③ Q 迟后才抢到管程锁恢复运行</text>
    <text class="fig-accent" x="536" y="207" font-size="10.5" text-anchor="middle">条件可能已变假 → 必写 while (count &gt;= N) wait();</text>
  </svg>
  <figcaption>图 3-11　Hoare 语义与 Mesa 语义在唤醒后执行流切换及条件重检写法（if vs while）的根本差异</figcaption>
</figure>

---

### 3.6 ★ PV 操作大题通用解题方法论与避坑铁律

408 历年考研大题中，PV 同步互斥设计题出现频率极高且给分慷慨。面对任何陌生生活或系统场景，按照以下**四步标准化解题流**推进即可稳拿高分甚至满分：

1. **第一步：读题抽象角色与循环结构**
   - 找出题中有几**类**并发进程/线程（如生产者、消费者；爸爸、儿子、女儿；顾客、营业员），切勿把同一类进程的不同个体强行拆成多套代码。
   - 若行为反复发生，每个函数体套 `while (true) { ... }`；若是一次性执行任务（如 `2020#45`、`2022#46` 前驱图），无需循环。并建议在总体外侧或末尾用 `cobegin ... coend` 标出各进程并发执行（即便略去通常也不扣分，但写上更规范）。
2. **第二步：拆解“互斥关系”与“同步/资源约束”**
   - **找互斥**：凡多个进程会同时读写修改同一份临界资源（如缓冲池、盘子、银行取号机、出入口大门、共享计数器），设置互斥信号量（命名推荐 `mutex`），**初值为 `1`**。
   - **找同步与资源约束**：
     - 凡存在“A 操作必须先于 B 操作发生”的先后次序（事件触发），设置同步信号量（如 `full`、`odd`、`apple`、`service`），**初值为 `0`**（“件事初始尚未发生”）。
     - 凡存在“缓冲区空位数、座位数、馆内人数上限”等有限容量约束，设置资源计数信号量（如 `empty`、`seat`），**初值为初始可用资源份数 $N$**。
     - **特例化简**：当某资源容量恰好只有 `1`（如单格盘子、桌子），此时代表该资源的信号量初值为 `1`，它自身已足以保证同一时刻最多一个进程操作该资源，**可省略 `mutex`**！但容量 $N > 1$ 时**绝对不可省去 `mutex`**。
3. **第三步：先写业务骨架，再“先互斥夹紧，后同步前 V 后 P”填 PV**
   - 先用简练伪代码或中文动作描述写出各进程的核心行为序列。
   - **填互斥**：用 `P(mutex); ... V(mutex);` 紧夹访问临界资源的那几行语句。尽量把“生产产品”、“消费产品”、“抽烟”、“思考”等不涉及临界区的耗时操作留在 `V(mutex)` 之外。
   - **填同步（前 V 后 P）**：在先发生的事件动作完成**之后**放 `V`，在后发生的依赖动作开始**之前**放 `P`。
4. **第四步：三条死锁与扣分自检红线**
   - **★ 红线一（致命死锁检查）**：若同一进程内连续出现多个 `P` 操作，**申请同步/资源信号量的 `P` 必须在申请互斥信号量 `P(mutex)` 之前**（即“**同步 P 在前，互斥 P 放最后**”）。绝对禁止“抱着 `mutex` 锁去等资源”！`V` 操作永不阻塞，顺序可调（习惯上先 `V(mutex)` 尽快释放锁，再 `V(同步)`）。
   - **★ 红线二（成对与方向检查）**：每个互斥信号量的 `P`/`V` 是否成对包在同一进程内？每个同步信号量的 `V` 是否在“生产/通知方”、`P` 是否在“消费/等待方”？
   - **★ 红线三（多类队列定向唤醒与排队功能）**：若存在多种不同消费者等待不同产品（如奇数/偶数、苹果/橘子、三类烟民），**不能共用同一个 `full` 信号量**，必须按消费对象分别设信号量定向通知；若题目隐含“先来先服务排队叫号”（如 `2011#45`），切记利用信号量“阻塞队列 FIFO 唤醒”特性专门设等待信号量。

> **注意**：阅卷给分要点：**① 信号量定义清晰、初值准确（且在注释里写明每个信号量的物理意义）；② 各进程伪代码逻辑完整且 `P`/`V` 次序无死锁**。即便个别边缘分支遗漏，只要抓住了核心的互斥与主干同步信号量，408 大题依然能拿到绝大部分分数。


---

### 3.7 经典同步互斥问题模型与 408 真题精讲 ★

几乎所有 408 真题与现实并发场景，都可以归约到以下五大经典模型及其变体。掌握它们的骨架与变形规律，等于打通了 PV 大题的“任督二脉”。

#### 3.7.1 生产者–消费者问题及多类变形 ★

**1. 标准模型（容量为 $N$ 的环形缓冲区）**

一组生产者向大小为 $N$ 的有界环形缓冲区 `buffer[N]` 放入数据，一组消费者从中取出数据。设写入指针 `in` 与读取指针 `out`：

- **互斥**：缓冲区为临界资源（若两个生产者同时选到同一个空位写数据会导致相互覆盖），设 `mutex = 1`。
- **同步（注意这两对信号量数的是同一批格子的两种状态！）**：`empty = N`（空闲格子数）、`full = 0`（已有产品数）。

```c
int in = 0, out = 0;
item buffer[N];
semaphore mutex = 1, empty = N, full = 0;

void producer() {
    while (true) {
        produce an item nextp;        // ① 生产动作放在临界区之外，缩短加锁时间
        P(empty);                     // ② 必须先申请同步资源（空缓冲区）
        P(mutex);                     // ③ 再申请互斥锁进入临界区
        buffer[in] = nextp;
        in = (in + 1) % N;
        V(mutex);                     // ④ 释放互斥锁
        V(full);                      // ⑤ 通知消费者产品数 +1
    }
}

void consumer() {
    while (true) {
        P(full);                      // ① 必须先申请同步资源（满缓冲区）
        P(mutex);                     // ② 再申请互斥锁进入临界区
        nextc = buffer[out];
        out = (out + 1) % N;
        V(mutex);                     // ③ 释放互斥锁
        V(empty);                     // ④ 通知生产者空位数 +1
        consume the item in nextc;    // ⑤ 消费动作放在临界区之外
    }
}
```

> **★考点**：**为何 `P(empty)` 与 `P(mutex)`（或 `P(full)` 与 `P(mutex)`）绝对不能颠倒？**
> 若生产者在缓冲区已满（`empty = 0`）时执行颠倒后的 `P(mutex); P(empty);`，它会先成功拿走 `mutex = 0`，随后在 `P(empty)` 上**抱着 `mutex` 锁阻塞睡眠**。此时唯一能够调用 `V(empty)` 腾出空间的消费者在执行 `P(mutex)` 时被拦在门外——双方相互等待对方释放自己所需的资源，**立即死锁**！
> 反之，**两个 `V` 操作顺序可以交换**（`V` 永不阻塞，但推荐先 `V(mutex)` 尽早放锁）；“生产/消费”放在锁外是为提高并发度（放在锁内逻辑没错，但性能低）。

<figure class="cpd-figure not-content" id="os-c3-fig-12">
  <svg viewBox="0 0 720 306" role="img" aria-label="生产者-消费者环形缓冲池结构、正确 PV 骨架与颠倒 P 顺序导致死锁序列对照">
    <defs>
      <marker id="os-c3-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="346" height="274" rx="8"/>
    <rect class="fig-box-subtle" x="374" y="16" width="330" height="274" rx="8"/>
    <rect class="fig-box" x="34" y="54" width="50" height="32" rx="3"/>
    <rect class="fig-box" x="86" y="54" width="50" height="32" rx="3"/>
    <rect class="fig-box-blue" x="138" y="54" width="50" height="32" rx="3"/>
    <rect class="fig-box-blue" x="190" y="54" width="50" height="32" rx="3"/>
    <rect class="fig-box-blue" x="242" y="54" width="50" height="32" rx="3"/>
    <rect class="fig-box" x="294" y="54" width="50" height="32" rx="3"/>
    <line class="fig-line-accent" x1="163" y1="104" x2="163" y2="89" marker-end="url(#os-c3-arr-12)"/>
    <line class="fig-line-accent" x1="319" y1="104" x2="319" y2="89" marker-end="url(#os-c3-arr-12)"/>
    <rect class="fig-box-blue" x="28" y="128" width="142" height="148" rx="6"/>
    <rect class="fig-box-green" x="206" y="128" width="142" height="148" rx="6"/>
    <path class="fig-line" stroke="var(--sl-color-green)" d="M 170 248 L 188 248 L 188 158 L 203 158" marker-end="url(#os-c3-arr-12)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 206 248 L 194 248 L 194 282 L 18 282 L 18 158 L 25 158" marker-end="url(#os-c3-arr-12)"/>
    <rect class="fig-box" x="388" y="52" width="302" height="40" rx="5"/>
    <rect class="fig-box-orange" x="388" y="102" width="302" height="44" rx="5"/>
    <rect class="fig-box-red" x="388" y="156" width="302" height="44" rx="5"/>
    <rect class="fig-box-red" x="388" y="210" width="302" height="44" rx="5"/>
    <line class="fig-line-accent" x1="539" y1="92" x2="539" y2="100" marker-end="url(#os-c3-arr-12)"/>
    <line class="fig-line-accent" x1="539" y1="146" x2="539" y2="154" marker-end="url(#os-c3-arr-12)"/>
    <line class="fig-line-accent" x1="539" y1="200" x2="539" y2="208" marker-end="url(#os-c3-arr-12)"/>
    <text class="fig-title" x="189" y="36" font-size="11.5" text-anchor="middle">正确骨架：同步 P 在前，互斥 P 在后（N=6 缓冲）</text>
    <text class="fig-muted" x="59" y="74" font-size="10" text-anchor="middle">0 [空]</text>
    <text class="fig-muted" x="111" y="74" font-size="10" text-anchor="middle">1 [空]</text>
    <text class="fig-blue" x="163" y="74" font-size="10" text-anchor="middle">2 [满]</text>
    <text class="fig-blue" x="215" y="74" font-size="10" text-anchor="middle">3 [满]</text>
    <text class="fig-blue" x="267" y="74" font-size="10" text-anchor="middle">4 [满]</text>
    <text class="fig-muted" x="319" y="74" font-size="10" text-anchor="middle">5 [空]</text>
    <text class="fig-accent" x="163" y="117" font-size="9.5" text-anchor="middle">out=2（取）</text>
    <text class="fig-accent" x="319" y="117" font-size="9.5" text-anchor="middle">in=5（写）</text>
    <text class="fig-blue" x="99" y="145" font-size="10.5" text-anchor="middle">生产者 Producer</text>
    <text class="fig-label" x="38" y="164" font-size="10">P(empty);   // 先同步</text>
    <text class="fig-label" x="38" y="183" font-size="10">P(mutex);   // 后互斥</text>
    <text class="fig-muted" x="38" y="203" font-size="10">buffer[in] = nextp;</text>
    <text class="fig-muted" x="38" y="222" font-size="10">in = (in + 1) % N;</text>
    <text class="fig-label" x="38" y="241" font-size="10">V(mutex);</text>
    <text class="fig-green" x="38" y="260" font-size="10">V(full);    // 唤醒消费</text>
    <text class="fig-green" x="277" y="145" font-size="10.5" text-anchor="middle">消费者 Consumer</text>
    <text class="fig-label" x="216" y="164" font-size="10">P(full);    // 先同步</text>
    <text class="fig-label" x="216" y="183" font-size="10">P(mutex);   // 后互斥</text>
    <text class="fig-muted" x="216" y="203" font-size="10">nextc = buffer[out];</text>
    <text class="fig-muted" x="216" y="222" font-size="10">out = (out + 1) % N;</text>
    <text class="fig-label" x="216" y="241" font-size="10">V(mutex);</text>
    <text class="fig-blue" x="216" y="260" font-size="10">V(empty);   // 唤醒生产</text>
    <text class="fig-title" x="539" y="36" font-size="11.5" text-anchor="middle">致命反例：P(mutex) 写在 P(empty) 前 → 死锁 ★</text>
    <text class="fig-label" x="539" y="70" font-size="9.8" text-anchor="middle">前提：缓冲池已满（empty = 0, full = N, mutex = 1）</text>
    <text class="fig-muted" x="539" y="85" font-size="9.5" text-anchor="middle">此时生产者尝试放入新产品，且先执行 P(mutex)</text>
    <text class="fig-orange" x="539" y="121" font-size="10.5" text-anchor="middle">① 生产者执行 P(mutex) 成功 → mutex = 0</text>
    <text class="fig-muted" x="539" y="137" font-size="9.5" text-anchor="middle">生产者此时手里攥着互斥锁继续往下走</text>
    <text class="fig-red" x="539" y="175" font-size="10.5" text-anchor="middle">② 生产者执行 P(empty) → empty = -1，阻塞！</text>
    <text class="fig-muted" x="539" y="191" font-size="9.5" text-anchor="middle">关键：它是“抱着 mutex 锁”睡过去的！</text>
    <text class="fig-red" x="539" y="229" font-size="10.5" text-anchor="middle">③ 消费者执行 P(mutex) → mutex = -1，阻塞！</text>
    <text class="fig-muted" x="539" y="245" font-size="9.5" text-anchor="middle">唯一能 V(empty) 救人的消费者拿不到锁，死锁！</text>
    <text class="fig-accent" x="539" y="274" font-size="10" text-anchor="middle">铁律：连续多 P 时，互斥信号量必须放在最内层（最后 P）</text>
  </svg>
  <figcaption>图 3-12　生产者–消费者环形缓冲同步骨架与 P(mutex) 提前导致持锁阻塞死锁反例推演</figcaption>
</figure>

**2. 经典变形 A：单格水果盘 vs 多格水果盘（容量决定是否可省 `mutex`）★**

桌上有一只盘子，爸爸向盘放苹果，妈妈向盘放橘子；女儿专吃苹果，儿子专吃橘子：
- **当盘子容量 $N = 1$（只能放 1 个水果）时**：设 `plate = 1, apple = 0, orange = 0`。由于 `plate` 初值为 `1`，任意时刻至多允许一名父亲或母亲放入水果，且未放好执行 `V(apple)`/`V(orange)` 前儿女不可能进入取水果，故 **`plate` 本身已经充当了互斥角色，可以省略 `mutex`**！
- **当盘子容量 $N = 10$（如容积为 10 的水果盘，或爸爸同时随机放苹果和橘子）时**：此时 `empty = 10`，多个进程可能同时在盘内放/取水果，**必须增设 `mutex = 1` 互斥访问盘子**！完整代码骨架如下：

```c
semaphore empty = 10, mutex = 1, apple = 0, orange = 0;

void Dad() {
    while (true) {
        prepare fruit;
        P(empty);              // 等盘中有空位
        P(mutex);              // 互斥访问盘子（不可写在 P(empty) 之前！）
        put fruit in plate;
        V(mutex);
        if (fruit == orange) V(orange);
        else                 V(apple);
    }
}

void Son() {
    while (true) {
        P(orange); P(mutex); take orange; V(mutex); V(empty);
        eat orange;
    }
}

void Daughter() {
    while (true) {
        P(apple); P(mutex); take apple; V(mutex); V(empty);
        eat apple;
    }
}
```

**3. 经典变形 B：吸烟者问题（多类消费者 + 单缓冲定向唤醒）**

系统有 1 名供应者 `agent` 和 3 名吸烟者。抽一支烟需要烟草、纸、胶水三种材料：1 号烟民无限拥有烟草，2 号拥有纸，3 号拥有胶水。供应者每次随机放另外两样到桌上，缺这第三样的烟民取走材料卷烟，抽完通知供应者继续放下一组。

- **设计核心**：① 缓冲区容量为 `1`，故 `finish = 1` 兼作桌子的互斥与空桌许可信号（**初值必为 `1`，若错设 `0` 则全员第一步即卡死**）；② 必须设置**三个不同的定向同步信号量 `offer1 = 0, offer2 = 0, offer3 = 0`** 分别唤醒对应吸烟者，否则一个信号量会唤醒错误对象；③ “抽烟”不占用桌子，放在 `V(finish)` 之后并发度更高。

```c
semaphore offer1 = 0, offer2 = 0, offer3 = 0, finish = 1;

void agent() {
    while (true) {
        P(finish);
        随机选 i ∈ {1, 2, 3} 并将对应两样材料放上桌;
        if (i == 1) V(offer1);
        else if (i == 2) V(offer2);
        else V(offer3);
    }
}

void smoker_i() {          // i = 1, 2, 3
    while (true) {
        P(offer_i);        // 等属于自己的那组材料
        从桌取走两样材料并卷烟;
        V(finish);         // 尽早归还空桌
        抽烟;              // 临界区外
    }
}
```

<figure class="cpd-figure not-content" id="os-c3-fig-13">
  <svg viewBox="0 0 720 278" role="img" aria-label="多缓冲家庭水果盘同步互斥模型与吸烟者问题单缓冲定向唤醒关系图">
    <defs>
      <marker id="os-c3-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="346" height="246" rx="8"/>
    <rect class="fig-box-subtle" x="374" y="16" width="330" height="246" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="138" y1="80" x2="237" y2="80" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="138" y1="192" x2="237" y2="192" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-dashed" x1="138" y1="100" x2="159" y2="122" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-dashed" x1="138" y1="172" x2="159" y2="152" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-dashed" x1="240" y1="100" x2="225" y2="122" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-dashed" x1="240" y1="172" x2="225" y2="152" marker-end="url(#os-c3-arr-13)"/>
    <rect class="fig-box-blue" x="28" y="54" width="110" height="52" rx="5"/>
    <rect class="fig-box-orange" x="28" y="166" width="110" height="52" rx="5"/>
    <rect class="fig-box-accent" x="158" y="110" width="68" height="52" rx="6"/>
    <rect class="fig-box-green" x="240" y="54" width="110" height="52" rx="5"/>
    <rect class="fig-box-purple" x="240" y="166" width="110" height="52" rx="5"/>
    <rect class="fig-box-accent" x="386" y="92" width="110" height="94" rx="6"/>
    <rect class="fig-box-blue" x="556" y="52" width="134" height="46" rx="5"/>
    <rect class="fig-box-green" x="556" y="114" width="134" height="46" rx="5"/>
    <rect class="fig-box-orange" x="556" y="176" width="134" height="46" rx="5"/>
    <line class="fig-line-accent" x1="496" y1="116" x2="553" y2="78" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-accent" x1="496" y1="138" x2="553" y2="138" marker-end="url(#os-c3-arr-13)"/>
    <line class="fig-line-accent" x1="496" y1="160" x2="553" y2="198" marker-end="url(#os-c3-arr-13)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" d="M 623 222 L 623 236 L 441 236 L 441 189" marker-end="url(#os-c3-arr-13)"/>
    <text class="fig-title" x="189" y="36" font-size="11.5" text-anchor="middle">家庭水果盘问题（N=10 必设 mutex）</text>
    <text class="fig-blue" x="83" y="75" font-size="10.5" text-anchor="middle">爸爸（放苹果）</text>
    <text class="fig-muted" x="83" y="94" font-size="8.2" text-anchor="middle">P(empty); P(mutex);</text>
    <text class="fig-orange" x="83" y="187" font-size="10.5" text-anchor="middle">妈妈（放橘子）</text>
    <text class="fig-muted" x="83" y="206" font-size="8.2" text-anchor="middle">P(empty); P(mutex);</text>
    <text class="fig-accent" x="192" y="132" font-size="10" text-anchor="middle">盘子</text>
    <text class="fig-muted" x="192" y="149" font-size="9" text-anchor="middle">empty=10</text>
    <text class="fig-green" x="295" y="75" font-size="10.5" text-anchor="middle">女儿（吃苹果）</text>
    <text class="fig-muted" x="295" y="94" font-size="8.2" text-anchor="middle">P(apple); P(mutex);</text>
    <text class="fig-purple" x="295" y="187" font-size="10.5" text-anchor="middle">儿子（吃橘子）</text>
    <text class="fig-muted" x="295" y="206" font-size="8.2" text-anchor="middle">P(orange); P(mutex);</text>
    <text class="fig-blue" x="189" y="71" font-size="9.5" text-anchor="middle">V(apple)</text>
    <text class="fig-orange" x="189" y="183" font-size="9.5" text-anchor="middle">V(orange)</text>
    <text class="fig-muted" x="189" y="246" font-size="9.5" text-anchor="middle">空位归还均执行 V(empty)；若 N=1 则 plate=1 可省 mutex</text>
    <text class="fig-title" x="539" y="36" font-size="11.5" text-anchor="middle">吸烟者问题（多类定向同步 + 容量 1）</text>
    <text class="fig-accent" x="441" y="114" font-size="10.5" text-anchor="middle">供应者 Agent</text>
    <text class="fig-label" x="441" y="134" font-size="10" text-anchor="middle">P(finish);</text>
    <text class="fig-muted" x="441" y="152" font-size="9.5" text-anchor="middle">随机放两样材料</text>
    <text class="fig-muted" x="441" y="170" font-size="9.5" text-anchor="middle">V(offer_i);</text>
    <text class="fig-blue" x="623" y="71" font-size="10" text-anchor="middle">吸烟者 1（有烟草）</text>
    <text class="fig-muted" x="623" y="88" font-size="8.2" text-anchor="middle">P(offer1) 卷烟 V(finish)</text>
    <text class="fig-green" x="623" y="133" font-size="10" text-anchor="middle">吸烟者 2（有纸）</text>
    <text class="fig-muted" x="623" y="150" font-size="8.2" text-anchor="middle">P(offer2) 卷烟 V(finish)</text>
    <text class="fig-orange" x="623" y="195" font-size="10" text-anchor="middle">吸烟者 3（有胶水）</text>
    <text class="fig-muted" x="623" y="212" font-size="8.2" text-anchor="middle">P(offer3) 卷烟 V(finish)</text>
    <text class="fig-muted" x="516" y="85" font-size="9" text-anchor="middle">offer1</text>
    <text class="fig-muted" x="524" y="131" font-size="9" text-anchor="middle">offer2</text>
    <text class="fig-muted" x="516" y="196" font-size="9" text-anchor="middle">offer3</text>
    <text class="fig-green" x="532" y="249" font-size="9.5" text-anchor="middle">V(finish) 释放空桌（finish 初值为 1）</text>
  </svg>
  <figcaption>图 3-13　水果盘问题（单/多缓冲区分）与吸烟者问题（按目标定向唤醒）同步依赖关系</figcaption>
</figure>

**4. 生产者–消费者 408 历年真题集群实战**

- **① 2009#45（奇偶数分离缓冲与统计）**：缓冲池含 $N$ 个单元。$P_1$ 调用 `produce()` 生成正整数并调用 `put()` 放入空单元；$P_2$ 调用 `getodd()` 取出奇数并用 `countodd()` 统计；$P_3$ 调用 `geteven()` 取出偶数并用 `counteven()` 统计。
  - 设 `empty = N, odd = 0, even = 0, mutex = 1`（两个消费者共用同一个缓冲池，故共享一个 `empty` 与 `mutex`，按奇偶各自设一个 `odd`/`even` 同步信号量！）。
  - $P_1$：`x = produce(); P(empty); P(mutex); put(); V(mutex); if(x % 2 == 1) V(odd); else V(even);`。
  - $P_2$：`P(odd); P(mutex); getodd(); V(mutex); V(empty); countodd();`（$P_3$ 对称换为 `even`）。

- **② 2011#45（银行叫号系统 — 容易漏掉的 2 分满分细节 ★）**：某银行 1 个服务窗口、10 个顾客座位。顾客进门若有空座则去取号机（每次仅允许 1 人操作）取号，坐下等待叫号；营业员空闲时叫号服务。
  - **常规 3 信号量骨架**：`empty = 10`（空座）、`full = 0`（已就座顾客）、`mutex = 1`（取号机互斥）。顾客：`P(empty); P(mutex); 取号; V(mutex); V(full); ...`；营业员：`P(full); V(empty); 叫号服务;`。
  - **满分隐藏第 4 个信号量 `service = 0`（解决按号顺序叫号！）**：若顾客一下来了 10 人把 `full` 连 `V` 到 10，没有 `service` 同步约束时，顾客自己并没有“等待叫号”的阻塞动作，营业员任选唤醒谁或顾客提前冲向窗口会导致**叫号失去顺序意义**。增设 `service = 0`，让顾客在 `V(full)` 后紧接着执行 **`P(service)`** 排队挂在等待队列上；营业员执行 `P(full); V(empty); 叫号;` 后再执行 **`V(service)`** 按阻塞队列先来先服务顺序精确唤醒下一位顾客获得服务！

- **③ 2014#47（消费者连续取 10 件产品）**：缓冲池容量 1000，要求某消费者一旦开始从缓冲区取产品，就必须**连续取出 10 件**后才允许其他消费者取。
  - **借鉴哲学家连续夹锁思想**：在标准 `mutex = 1, empty = 1000, full = 0` 基础上，为消费者之间再外包一层独占取货权的互斥锁 `special = 1`：
    ```c
    // 消费者伪代码核心段
    P(special);                     // 抢占连续取 10 次的独占权（仅消费者之间竞争）
    for (int i = 0; i < 10; i++) {
        P(full);                    // 等待产品
        P(mutex);                   // 互斥动缓冲区
        取走 1 件产品;
        V(mutex);
        V(empty);
        消费产品;
    }
    V(special);                     // 连续 10 次取完才释放，换下一位消费者
    ```
  - **深度思考**：为什么外层 `P(special)` 后内层又 `P(full)` **不会死锁**？因为生产者**并不需要申请 `special`**！即便当前消费者拿着 `special` 在某次 `P(full)` 阻塞，生产者照常可以 `P(empty); P(mutex); 放货; V(mutex); V(full);` 把它唤醒继续凑齐 10 件。

- **④ 2015#45（双信箱辩论对称模型）**：A、B 两人各有容量 $M$（初始 $X$ 封信）和 $N$（初始 $Y$ 封信）的信箱。A 从 A 信箱取信回答后提出新问题放入 B 信箱；B 对称执行。
  - 各自既当生产者又当消费者，共设 6 个信号量（对称镜像）：`emptyA = M - X, fullA = X, mutexA = 1, emptyB = N - Y, fullB = Y, mutexB = 1`。
  - A 的骨架：`P(fullA); P(mutexA); 从 A 取信; V(mutexA); V(emptyA); 回答并提新问题; P(emptyB); P(mutexB); 放入 B; V(mutexB); V(fullB);`（B 与之完全镜像互换 `A/B`）。

#### 3.7.2 读者–写者问题（半互斥与三大策略对比）★

允许多个<strong>读者（Reader）</strong>同时读取同一共享文件或数据库，但<strong>写者（Writer）</strong>必须独占访问（**读–读不互斥，读–写与写–写互斥**）。普通单个信号量只有“允许 1 个/不允许”两档，无法表达“同伙并行”。破局思想是**让“整群读者”作为统一主体去和写者抢 `rw` 锁——第一个读者负责上锁，最后一个读者负责解锁**。

| 策略名称 | 核心思想与新增信号量 | 关键机制说明 | 优缺点与饥饿情况 |
| --- | --- | --- | --- |
| **① 读者优先** | `rw = 1, mutex = 1, readcount = 0`（无闸门） | 只要已有读者在读，后到的读者不经 `P(rw)` 直接加入阅读 | 读并发最高；**写者可能饥饿**（若读者络绎不绝） |
| **② 读写公平** | 新增公共排队信号量 **`w = 1`** | 读写均先 `P(w)` 排队；写者在 `w` 上排上队时挡住后来新读者 | **读者、写者均不饥饿**，严格先到先服务（408 常用公平写法） |
| **③ 写者优先** | 新增 `writecount = 0, mutexW = 1, readTry = 1` | 首个写者一到立即 `P(readTry)` 关闭读者闸门，已有读者读完后全写完再放开读者 | 保证写实时性；**读者可能饥饿** |

```c
// ① 读者优先（408 基准模型）                 // ② 读写公平方案（加公共排队闸门 w = 1）
semaphore rw = 1, mutex = 1;                 semaphore rw = 1, mutex = 1, w = 1;
int readcount = 0;                           int readcount = 0;

void reader() {                              void reader_fair() {
    while (true) {                               while (true) {
        P(mutex);  // 保护 readcount                 P(w);       // 与写者在同一队列公平排队
        if (readcount == 0) P(rw);                   P(mutex);
        readcount++;                                 if (readcount == 0) P(rw);
        V(mutex);                                    readcount++;
                                                     V(mutex);
        perform read; // ★ 必须在 mutex 外!          V(w);       // 立即放行后续同行读者或排队的写者
                                                     perform read;
        P(mutex);                                    P(mutex);
        readcount--;                                 readcount--;
        if (readcount == 0) V(rw);                   if (readcount == 0) V(rw);
        V(mutex);                                    V(mutex);
    }                                            }
}                                            }

void writer() {                              void writer_fair() {
    while (true) {                               while (true) {
        P(rw);                                       P(w);       // 先抢闸门挡住后来新读者
        perform write;                               P(rw);      // 再等当前这批读者退出
        V(rw);                                       perform write;
    }                                                V(rw);
}                                                    V(w);
                                                 }
                                             }
```

> **注意**：写读者优先代码时的**两处必考易错点**：
> 1. **`readcount++` 与 `if (readcount == 0) P(rw)` 必须整体夹在 `P(mutex)...V(mutex)` 内**！若拆出 `mutex` 外，两个同时到达的读者可能都测到 `readcount == 0` 并双双去 `P(rw)` 导致第二人阻塞死锁。
> 2. **读操作 `perform read` 绝对不能放进 `mutex` 内部**，否则多名读者退化为串行读，失去了“多读者并发”的根本意义！
> - **绝对写者优先补充**：若需强写者优先，为写者再增计数器 `writecount = 0` 与 `mutexW = 1` 保护 `readTry = 1`：首写者 `P(readTry)`、末写者 `V(readTry)`，而读者在 `P(readTry); ... V(readTry);` 外包裹进入统计区（写者写完才还闸门，新写者可直接连续插队读前）。
> - **信号量集限制至多 $RN$ 个读者并发**：`Swait(L, 1, 1); Swait(mx, 1, 0);`（读者占名额且只测 `mx>=1` 不扣除）；写者 `Swait(mx, 1, 1; L, RN, 0);`（占 `mx` 且等待 `L` 回满为 `RN` 即全部读者退场）。

> **★考点**：**2017#46 统考真题（隐蔽的多变量读写互斥）**
> 三个线程共享全局变量 `x, y, z`：`T1` 执行计算需读 `x` 和 `y`；`T2` 需读 `y` 和 `z`；`T3` 需**读改写 `z`** 并**读改写 `y`**。
> - **拆解关系**：`x` 仅被 `T1` 读，**无需互斥信号量**；`z` 被 `T2` 读、`T3` 写，属一对读写互斥（设 `mutex_z = 1`）；`y` 被 `T1, T2` 同时读（**读读不互斥！**），但分别与 `T3` 写 `y` 冲突！
> - **满分写法**：设 `mutex_y1 = 1`（保护 `T1` 读 `y` 与 `T3` 写 `y`）、`mutex_y2 = 1`（保护 `T2` 读 `y` 与 `T3` 写 `y`）、`mutex_z = 1`（保护 `T2` 读 `z` 与 `T3` 写 `z`）。这样 `T1` 和 `T2` 可以真正**并发读 `y`**，而 `T3` 写 `y` 时需用 `P(mutex_y1); P(mutex_y2); 写 y; V(mutex_y2); V(mutex_y1);` 同时挡住双方（因仅有 `T3` 同时申领两把锁，故绝无环路死锁；若直接设单把 `mutex_y = 1` 虽然牺牲了一点读并发，但也能正确保证互斥不出错）。

<figure class="cpd-figure not-content" id="os-c3-fig-14">
  <svg viewBox="0 0 720 302" role="img" aria-label="读者-写者问题三种策略：读者优先、读写公平与写者优先闸门队列机制对比图">
    <defs>
      <marker id="os-c3-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-blue" x="16" y="16" width="220" height="270" rx="8"/>
    <rect class="fig-box-green" x="250" y="16" width="220" height="270" rx="8"/>
    <rect class="fig-box-orange" x="484" y="16" width="220" height="270" rx="8"/>
    <rect class="fig-box" x="28" y="48" width="196" height="44" rx="5"/>
    <rect class="fig-box" x="28" y="102" width="196" height="72" rx="5"/>
    <rect class="fig-box-red" x="28" y="236" width="196" height="36" rx="4"/>
    <rect class="fig-box" x="262" y="48" width="196" height="44" rx="5"/>
    <rect class="fig-box" x="262" y="102" width="196" height="72" rx="5"/>
    <rect class="fig-box-accent" x="262" y="236" width="196" height="36" rx="4"/>
    <rect class="fig-box" x="496" y="48" width="196" height="44" rx="5"/>
    <rect class="fig-box" x="496" y="102" width="196" height="72" rx="5"/>
    <rect class="fig-box-red" x="496" y="236" width="196" height="36" rx="4"/>
    <text class="fig-blue" x="126" y="36" font-size="11.5" text-anchor="middle">① 读者优先（基准方案）</text>
    <text class="fig-label" x="126" y="66" font-size="10" text-anchor="middle">信号量：rw=1, mutex=1</text>
    <text class="fig-muted" x="126" y="83" font-size="9.5" text-anchor="middle">共享整型：readcount = 0</text>
    <text class="fig-label" x="40" y="122" font-size="10">首读者：if(rc==0) P(rw);</text>
    <text class="fig-label" x="40" y="142" font-size="10">末读者：if(rc==0) V(rw);</text>
    <text class="fig-muted" x="40" y="162" font-size="9.5">新读者：无闸门阻拦，直接进！</text>
    <text class="fig-label" x="30" y="196" font-size="9.5">★ 必错：读操作必须放 mutex 外</text>
    <text class="fig-label" x="30" y="216" font-size="9.5">★ 必错：改计数+判断整体放 mutex 内</text>
    <text class="fig-red" x="126" y="258" font-size="10.5" text-anchor="middle">后果：写者可能无限期饥饿 ❌</text>
    <text class="fig-green" x="360" y="36" font-size="11.5" text-anchor="middle">② 读写公平（加队列闸门 w）</text>
    <text class="fig-label" x="360" y="66" font-size="10" text-anchor="middle">新增信号量：公共排队闸门 w = 1</text>
    <text class="fig-muted" x="360" y="83" font-size="9.5" text-anchor="middle">读者、写者先到先排队</text>
    <text class="fig-label" x="268" y="122" font-size="9.2">读者：P(w)→改计数→V(w)→读</text>
    <text class="fig-label" x="268" y="142" font-size="9.2">写者：P(w)→P(rw)→写→V(rw)→V(w)</text>
    <text class="fig-muted" x="268" y="162" font-size="9.2">写者排 w 时新读者挡在 P(w)</text>
    <text class="fig-label" x="264" y="196" font-size="9.5">读者改完计数早放 V(w)，不挡同伴</text>
    <text class="fig-label" x="264" y="216" font-size="9.5">写者写完再放 V(w)，保独占写权</text>
    <text class="fig-accent" x="360" y="258" font-size="10.5" text-anchor="middle">结果：FIFO 相对公平，均不饥饿 ✅</text>
    <text class="fig-orange" x="594" y="36" font-size="11.5" text-anchor="middle">③ 写者优先（readTry 闸门）</text>
    <text class="fig-label" x="594" y="66" font-size="9.2" text-anchor="middle">writecount, mutexW, readTry=1</text>
    <text class="fig-muted" x="594" y="83" font-size="9.2" text-anchor="middle">写者群共同关断/放开读者闸门</text>
    <text class="fig-label" x="503" y="122" font-size="9.5">首写者：P(readTry); 封堵新读者</text>
    <text class="fig-label" x="503" y="142" font-size="9.5">末写者：V(readTry); 放行读者</text>
    <text class="fig-muted" x="594" y="162" font-size="8.4" text-anchor="middle">读者：P(readTry) 过闸门即 V(readTry)</text>
    <text class="fig-label" x="498" y="196" font-size="9.5">只要尚有写者在等，新读者全阻塞</text>
    <text class="fig-label" x="498" y="216" font-size="9.5">保障配置/写更新的最高实时性</text>
    <text class="fig-red" x="594" y="258" font-size="10.5" text-anchor="middle">后果：读者可能无限期饥饿 ❌</text>
  </svg>
  <figcaption>图 3-14　读者–写者问题三种经典策略的信号量闸门位置、排队机制与饥饿隐患对比</figcaption>
</figure>

#### 3.7.3 哲学家进餐问题与 2019 统考加碗真题 ★

5 位哲学家围坐圆桌，每两人间放 1 只筷子（共 5 只，编号 `0～4`，第 $i$ 位哲学家左手筷为 `chopstick[i]`，右手筷为 `chopstick[(i+1)%5]`），必须**同时拿到左右两只筷子**方能进餐。

- **朴素方案死锁根因**：若每位哲学家都执行“先拿左筷 `P(chopstick[i])`，再拿右筷 `P(chopstick[(i+1)%5])`”，一旦 5 人同时饥饿并各自抓起左筷后切走，便会出现**全章最经典的单一死锁状态：5 人每人手里死握 1 根筷子、同时请求右手那根筷子（同时满足“请求并保持”与“循环等待”）**。

> **★考点**：**破环统一判据与四大解法对比**
> 只要<strong>“同时只握 1 根筷子”的人数上限</strong>严格小于哲学家总数 $n$（$< 5$），环路就永远无法闭合！四种常见解法对比如下（注：**四种解法受物理筷子数 $\lfloor 5/2 \rfloor = 2$ 限制，最大同时进餐人数均固定为 2**，不可用于比较优劣）：
>
> | 方案 | 具体实现策略 | 破坏的死锁条件 | 最大“只握一根”人数 |
> | --- | --- | --- | --- |
> | **① 限制人数** | 增设信号量 `limit = 4`（$n - 1$），至多 $n - 1$ 人同时上桌取筷 | **循环等待** | 4（$< 5$） |
> | **② 奇偶非对称破环** | 奇数号先左后右、偶数号先右后左（或前 $n - 1$ 人先左后右、最后 1 人先右后左），**无需额外信号量** | **循环等待** | 3（$< 5$） |
> | **③ `mutex` 互斥取筷** | 增设 `mutex = 1` 包住左右两次 `P`：`P(mutex); P(left); P(right); V(mutex);` | **请求并保持** | 1（$< 5$） |
> | **④ AND 型信号量** | `Swait(chopstick[i], chopstick[(i+1)%5]);` 两根筷子原子共申共放 | **请求并保持** | 0（$< 5$） |

> **★考点**：**2019 统考大题（19#43）$n$ 名哲学家 + $m$ 个碗真题深析**
> 圆桌边坐着 $n$ 名（$n \ge 3$）哲学家，桌中心有 **$m$ 个（$m \ge 1$）碗**，每名哲学家必须取得 **1 个碗和左右两根筷子**方能进餐。要求最大化并发度且绝对避免死锁。
> - **易错陷阱**：千万不要照抄课本的常数 `4`！总数已参数化为 $n$ 。
> - **核心推导（分情况或一招收束）**：
>   - 死锁隐患仍在于“所有人同时拿碗后并排拿左筷导致筷子环路死锁”。要阻止筷子成环，同时拿碗进餐区竞争筷子的人数上限绝对不能超过 **$n - 1$**；同时受限于物理碗的总数只有 $m$ 个，允许进入的总人数也不能超过 **$m$**。
>   - **标准优雅满分写法**：将控制同时入桌取筷与拿碗的信号量初值直接取二者的较小值 **`bowl = min(n - 1, m)`**（或拆开设 `bowl = m` 配合 `limit = n - 1`，先 `P(limit); P(bowl);` 再拿左右筷子！）：
>     ```c
>     semaphore chopstick[n] = {1, 1, ..., 1};
>     semaphore bowl = min(n - 1, m);   // 若另设 limit = n-1 与 bowl = m 则先 P(limit) 后 P(bowl)
>
>     void philosopher(int i) {
>         while (true) {
>             think();
>             P(bowl);                         // 限制同时参与竞争筷子的人数 <= n-1 且 <= m
>             P(chopstick[i]);                 // 拿左筷
>             P(chopstick[(i + 1) % n]);       // 拿右筷
>             eat();
>             V(chopstick[i]);                 // 放左筷
>             V(chopstick[(i + 1) % n]);       // 放右筷
>             V(bowl);                         // 归还碗与名额
>         }
>     }
>     ```
>   - **为何绝对不死锁（必写得分理由）**：因为最多只允许 $\min(n - 1, m) \le n - 1$ 名哲学家同时进入取筷流程，即使极端情况下他们全都各自抓起了左筷，桌面至少还剩余 1 根空闲筷子；必然存在某一位持有碗和左筷的哲学家能够抓起右手空筷完成就餐并释放所有资源，环路永远无法闭合！

<figure class="cpd-figure not-content" id="os-c3-fig-15">
  <svg viewBox="0 0 720 300" role="img" aria-label="哲学家进餐圆桌五人各握左筷环路死锁图与四种防死锁策略及 2019 真题解法对比">
    <defs>
      <marker id="os-c3-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="292" height="268" rx="8"/>
    <rect class="fig-box-subtle" x="322" y="16" width="382" height="268" rx="8"/>
    <circle class="fig-box" cx="162" cy="148" r="46"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 182 80 A 74 74 0 0 1 224 114" marker-end="url(#os-c3-arr-15)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 236 142 A 74 74 0 0 1 218 194" marker-end="url(#os-c3-arr-15)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 186 212 A 74 74 0 0 1 138 212" marker-end="url(#os-c3-arr-15)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 106 194 A 74 74 0 0 1 88 142" marker-end="url(#os-c3-arr-15)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 100 114 A 74 74 0 0 1 142 80" marker-end="url(#os-c3-arr-15)"/>
    <rect class="fig-box-red" x="138" y="60" width="48" height="26" rx="5"/>
    <rect class="fig-box-red" x="214" y="116" width="48" height="26" rx="5"/>
    <rect class="fig-box-red" x="184" y="198" width="48" height="26" rx="5"/>
    <rect class="fig-box-red" x="92" y="198" width="48" height="26" rx="5"/>
    <rect class="fig-box-red" x="62" y="116" width="48" height="26" rx="5"/>
    <rect class="fig-box-blue" x="334" y="46" width="358" height="42" rx="5"/>
    <rect class="fig-box-green" x="334" y="94" width="358" height="42" rx="5"/>
    <rect class="fig-box-orange" x="334" y="142" width="358" height="42" rx="5"/>
    <rect class="fig-box-purple" x="334" y="190" width="358" height="42" rx="5"/>
    <rect class="fig-box-red" x="334" y="238" width="358" height="36" rx="5"/>
    <text class="fig-title" x="162" y="36" font-size="11.5" text-anchor="middle">朴素写法唯一死锁态（5 人循环等待）</text>
    <text class="fig-label" x="162" y="145" font-size="10.5" text-anchor="middle">圆桌</text>
    <text class="fig-muted" x="162" y="160" font-size="9.5" text-anchor="middle">5 筷各被占</text>
    <text class="fig-red" x="162" y="77" font-size="10.5" text-anchor="middle">P0(C0)</text>
    <text class="fig-red" x="238" y="133" font-size="10.5" text-anchor="middle">P1(C1)</text>
    <text class="fig-red" x="208" y="215" font-size="10.5" text-anchor="middle">P2(C2)</text>
    <text class="fig-red" x="116" y="215" font-size="10.5" text-anchor="middle">P3(C3)</text>
    <text class="fig-red" x="86" y="133" font-size="10.5" text-anchor="middle">P4(C4)</text>
    <text class="fig-muted" x="218" y="92" font-size="9">等 C1</text>
    <text class="fig-muted" x="252" y="176" font-size="9">等 C2</text>
    <text class="fig-muted" x="162" y="238" font-size="9" text-anchor="middle">等 C3</text>
    <text class="fig-muted" x="86" y="176" font-size="9" text-anchor="end">等 C4</text>
    <text class="fig-muted" x="106" y="90" font-size="9" text-anchor="end">等 C0</text>
    <text class="fig-red" x="162" y="264" font-size="10" text-anchor="middle">判据：只要“只握 1 根筷子”人数 &lt; n，环必不闭合</text>
    <text class="fig-title" x="513" y="36" font-size="11.5" text-anchor="middle">四种防死锁破环方案（最大同时吃皆为 2）</text>
    <text class="fig-blue" x="346" y="63" font-size="10.5">① 限制人数 ≤ n-1（压至 4 人）→ 破“循环等待”</text>
    <text class="fig-muted" x="346" y="79" font-size="9.5">设 limit = n-1；先 P(limit) 再拿左右筷</text>
    <text class="fig-green" x="346" y="111" font-size="10.5">② 奇偶非对称顺序（压至 3 人）→ 破“循环等待”</text>
    <text class="fig-muted" x="346" y="127" font-size="9.5">奇数先左偶先右；零额外信号量开销，最优雅</text>
    <text class="fig-orange" x="346" y="159" font-size="10.5">③ mutex 夹住取两筷（压至 1 人）→ 破“请求并保持”</text>
    <text class="fig-muted" x="346" y="175" font-size="9.5">P(mutex); 拿左筷; 拿右筷; V(mutex);（取筷串行）</text>
    <text class="fig-purple" x="346" y="207" font-size="10.5">④ AND 型信号量 Swait（压至 0 人）→ 破“请求并保持”</text>
    <text class="fig-muted" x="346" y="223" font-size="9.5">两根同时原子申请，要么全给要么一根不拿</text>
    <text class="fig-red" x="513" y="260" font-size="10.5" text-anchor="middle">★ 2019#43（n 人 + m 碗）：初值设为 min(n-1, m)！</text>
  </svg>
  <figcaption>图 3-15　哲学家进餐环路死锁状态图、四大防死锁机制比较与 2019 年 408 加碗真题核心边界</figcaption>
</figure>

#### 3.7.4 睡眠理发师问题（Sleeping Barber Problem）

理发店有 1 名理发师、1 把理发椅和 $N$ 把供顾客等候的椅子：没有顾客时理发师坐在理发椅上睡觉；顾客进门时，若理发师在睡则唤醒他，若理发师在忙且尚有空等候椅则入座等待，**若 $N$ 把等候椅均满则顾客直接离开（不排队死等！）**。

- **信号量设置**：
  - `customers = 0`：正在等候理发的顾客数（同步信号量：用于顾客通知唤醒睡觉的理发师）；
  - `barbers = 0`：空闲就绪的理发师数（同步信号量：用于理发师通知一位等候顾客开始理发）；
  - `mutex = 1`：互斥保护共享整数变量 `waiting`（初值 `0`，记录当前坐着等候的顾客数，确保同时只有一人修改 `waiting`）。

```c
#define N 5                             // N 把等候椅
int waiting = 0;                        // 正在等候的顾客数
semaphore customers = 0, barbers = 0, mutex = 1;

void barber() {
    while (true) {
        P(customers);                   // 没有顾客时理发师睡眠（阻塞）
        P(mutex);                       // 互斥修改 waiting 计数
        waiting--;
        V(barbers);                     // 通知 1 名顾客来理发
        V(mutex);
        cut_hair();                     // 正在理发（锁外执行）
    }
}

void customer() {
    P(mutex);
    if (waiting < N) {                  // 还有空余等候椅
        waiting++;
        V(customers);                   // 唤醒（或登记）通知理发师有客
        V(mutex);
        P(barbers);                     // 等待理发师就绪（若忙则阻塞挂起）
        get_haircut();                  // 坐上理发椅享受理发
    } else {
        V(mutex);                       // ★ 椅子全满，释放锁后直接离开（绝不阻塞！）
    }
}
```

> **注意**：理发师问题之所以不用 `semaphore empty = N;` 去控制等候椅，是因为如果用了 `P(empty)`，第 $N + 1$ 位顾客就会被阻塞在门外死等而无法执行“看见椅满即离开”的分支。只有用 `mutex` 保护的 `if (waiting < N)` 判断分支，才能准确刻画“**有限排队、满员立即拒客退出**”这一工程流控特征（常见于操作系统线程池任务队列、网络服务器连接拒绝模型）。

<figure class="cpd-figure not-content" id="os-c3-fig-16">
  <svg viewBox="0 0 720 268" role="img" aria-label="睡眠理发师问题空间结构与顾客理发师双向同步流转及满员拒客机制">
    <defs>
      <marker id="os-c3-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="308" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="336" y="16" width="368" height="236" rx="8"/>
    <rect class="fig-box-blue" x="28" y="50" width="130" height="68" rx="5"/>
    <rect class="fig-box-green" x="168" y="50" width="144" height="68" rx="5"/>
    <rect class="fig-box-red" x="28" y="130" width="284" height="52" rx="5"/>
    <rect class="fig-box-accent" x="28" y="194" width="284" height="44" rx="5"/>
    <rect class="fig-box" x="346" y="50" width="160" height="188" rx="5"/>
    <rect class="fig-box" x="538" y="50" width="154" height="188" rx="5"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" d="M 538 128 L 522 128 L 522 90 L 509 90" marker-end="url(#os-c3-arr-16)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.6" x1="506" y1="158" x2="535" y2="158" marker-end="url(#os-c3-arr-16)"/>
    <text class="fig-title" x="170" y="36" font-size="11.5" text-anchor="middle">睡眠理发师问题：空间模型与流控特点</text>
    <text class="fig-blue" x="93" y="70" font-size="10.5" text-anchor="middle">1 张理发椅</text>
    <text class="fig-muted" x="93" y="88" font-size="9.2" text-anchor="middle">barbers = 0（就绪）</text>
    <text class="fig-muted" x="93" y="104" font-size="9.2" text-anchor="middle">无客在 P(customers) 睡</text>
    <text class="fig-green" x="240" y="70" font-size="10.5" text-anchor="middle">N 把等候椅</text>
    <text class="fig-muted" x="240" y="88" font-size="9.2" text-anchor="middle">waiting = 0..N</text>
    <text class="fig-muted" x="240" y="104" font-size="9.2" text-anchor="middle">mutex = 1 保护修改</text>
    <text class="fig-red" x="170" y="150" font-size="10.2" text-anchor="middle">★ 满员不阻塞：if (waiting &lt; N)</text>
    <text class="fig-muted" x="170" y="170" font-size="9.2" text-anchor="middle">waiting == N 时，顾客 V(mutex) 后直接离店</text>
    <text class="fig-accent" x="170" y="213" font-size="9.4" text-anchor="middle">提示：不设空椅信号量 empty=N，防满客死等门口</text>
    <text class="fig-muted" x="170" y="229" font-size="9.2" text-anchor="middle">对应线程池“队列满直接拒绝策略（AbortPolicy）”</text>
    <text class="fig-title" x="520" y="36" font-size="11.5" text-anchor="middle">理发师与顾客双向对称唤醒流程</text>
    <text class="fig-blue" x="426" y="68" font-size="10.8" text-anchor="middle">理发师 Barber()</text>
    <text class="fig-label" x="356" y="94" font-size="9.3">P(customers); // 无客睡</text>
    <text class="fig-label" x="356" y="122" font-size="9.3">P(mutex);</text>
    <text class="fig-muted" x="356" y="140" font-size="9.3">waiting--;</text>
    <text class="fig-blue" x="356" y="161" font-size="9.3">V(barbers);  // 叫顾客</text>
    <text class="fig-label" x="356" y="182" font-size="9.3">V(mutex);</text>
    <text class="fig-muted" x="356" y="205" font-size="9.3">cut_hair();</text>
    <text class="fig-green" x="615" y="68" font-size="10.8" text-anchor="middle">顾客 Customer()</text>
    <text class="fig-label" x="546" y="90" font-size="9.2">P(mutex);</text>
    <text class="fig-label" x="546" y="109" font-size="9.2">if (waiting &lt; N) {</text>
    <text class="fig-green" x="546" y="131" font-size="9">  waiting++; V(customers);</text>
    <text class="fig-blue" x="546" y="161" font-size="9.2">  V(mutex); P(barbers);</text>
    <text class="fig-muted" x="546" y="182" font-size="9.2">  get_haircut();</text>
    <text class="fig-red" x="546" y="205" font-size="9">} else V(mutex); // 离开</text>
    <text class="fig-green" x="522" y="76" font-size="9" text-anchor="middle">唤醒</text>
    <text class="fig-blue" x="522" y="175" font-size="9" text-anchor="middle">放行</text>
  </svg>
  <figcaption>图 3-16　睡眠理发师问题非对称队列模型：用互斥保护条件分支实现“椅满即离开”与双向唤醒</figcaption>
</figure>

---

### 3.8 本章 408 历年真题考法全景与高频错题排查表

#### 3.8.1 历年真题考法汇总（2009–2026）

| 真题年份/题号 | 所属知识点 | 核心命题原型与必拿分要点 |
| --- | --- | --- |
| **`09#45`** | 生产者–消费者多分支 | $P_1$ 产整数放入共享缓冲，$P_2$ 取奇数统计、$P_3$ 取偶数统计；共享 `empty=N` 与 `mutex=1`，分设 `odd=0, even=0` |
| **`10#25` / `26#26`** | 信号量数值反推 | 由初值 $I$ 与当前值 $C$ 反推 $V - P = C - I$；由进程总数反推并发数与阻塞排队数 |
| **`10#27` / `23#45`** | 软件/硬件互斥实现 | `10#27` 考 Peterson 算法（注意 `turn = 对方` 与不满足让权）；`23#45` 大题考 `Swap` 指令与布尔变量写进入/退出区及四准则评价 |
| **`11#32` / `26#27`** | 并发指令流与 Bernstein | `11#32` 考交错指令写覆盖取值；`26#27` 考 Bernstein 三对不相交条件（读读不冲突） |
| **`11#45`** | 银行叫号排队系统 | `empty=10, full=0, mutex=1` 之外，必须增设 `service=0` 利用信号量队列实现有序排队叫号 |
| **`13#45`** | 资源上限 + 通道互斥 | 博物馆 500 人容量与单一出入口互斥；`P(empty)` 必须在 `P(door)` 之前 |
| **`14#47`** | 连续批量消费锁定 | 消费者连续取 10 件产品才允许下位消费者取；外层加锁 `special=1` 包住 `for` 循环，不阻塞生产者 |
| **`15#45`** | 双缓冲对称交互 | A、B 双信箱辩论；各设 `empty, full, mutex` 共 6 个信号量，一人既消费又生产 |
| **`16#25/27/30/32`** | 概念辨析大合集 | `16#25` 临界资源概念；`16#27` TSL 忙等不让权；`16#30` 临界区允许被切换，互斥是逻辑约束；`16#32` 管程也可同步 |
| **`17#46`** | 隐形读写问题 | 三线程共享 `x,y,z`；仅 `T1,T2` 读 `y` 不互斥，分别设 `mutex_y1, mutex_y2, mutex_z` 对抗 `T3` 的写操作 |
| **`18#28` / `18#32`** | 条件变量与让权机制 | `18#28` 条件变量语义；`18#32` 唯一可实现“让权等待”的是信号量机制（`block()` 原语） |
| **`19#43`** | 哲学家进餐变形 | $n$ 位哲学家 + $m$ 个碗；限制人数初值取 $\min(n-1, m)$ 破环防死锁 |
| **`20#32` / `20#45`** | 四准则与纯同步前驱图 | `20#32` 必须遵循的仅前三条准则（让权非必须）；`20#45` 纯前驱图设 4 个初值 `0` 同步信号量 |
| **`21#45`** | 整型信号量与开关中断 | 分析 `wait`/`signal` 需互斥访问 `S`、关中断罩住 `while` 忙等会致死锁、用户态禁用特权开关中断 |
| **`22#46`** | 跨线程同步前驱图 | 6 操作分派给两线程 `T1/T2`；仅跨线程箭头 `A→C` 与 `C→E` 需设 `S_ac=0, S_ce=0` |
| **`24#46` / `25#45`** | 工序协作与综合 PV | 围绕“工序完成事件（同步初值 0）+ 有限工具/工位资源（互斥 1 或资源数 $N$）”构建多进程协作流（如 `25#45` 三人植树多工序协同），按四步解题法稳步拆解即可命中全部核心得分点 |

#### 3.8.2 高频易错点终极避坑清单

1. **混淆互斥与同步判据**：打乱先后顺序结果仍然正确（只是不能同时进入）是**互斥**（初值 1）；打乱先后顺序结果必然错误是**同步**（初值 0）。
2. **误把让权等待当作必须条件**：临界区互斥**必须遵循的是前三条**（空闲让进、忙则等待、有限等待）；不满足“让权等待”（如 Peterson、TSL、Swap、自旋锁）依然逻辑正确，只是 CPU 忙等。
3. **误判单核自旋与多核关中断**：**单核**上自旋锁无意义（持锁者没在跑，自旋纯浪费）；**多核**上关中断只挡本核挡不住他核，互斥失效。
4. **Peterson 把 `turn` 写反**：牢记 **`turn = 对方`**（“`turn` 归属谁，谁就得等”）；写成 `turn = 自己` 四拍即破。
5. **颠倒多个 `P` 操作顺序**：连续执行多个 `P` 时，**同步/资源信号量 `P` 在前，互斥 `P(mutex)` 在最后**；颠倒立刻导致“抱着锁等资源”死锁；`V` 顺序一般无约束。
6. **在容量为 1 时多写 `mutex` 或容量大于 1 时漏写 `mutex`**：`N = 1` 时 `empty = 1` 本身即可兼顾互斥，可省 `mutex`；`N > 1` 时必设 `mutex = 1`。
7. **混淆条件变量与信号量**：信号量的 `V` 会累加计数，不会丢信号；**条件变量的 `signal()` 在无人等待时直接丢弃**，必须配合额外共享变量判断，且在 Mesa 语义下必用 **`while`** 重检条件。
8. **哲学家题目照抄常数 `4`**：面对 $n$ 名哲学家题型，限制信号量必须写成 $n - 1$（含碗约束时取 $\min(n - 1, m)$），说明不死锁原因时务必答到“**同时只握 1 根筷子的人数上限小于 $n$ ，无法构成循环等待环路**”。

## 第4章 处理机调度与死锁

在多道程序系统中，内存里往往同时驻留着数十乃至上百个就绪进程，而物理 CPU 的核心数却屈指可数。从底层操作系统设计哲学看，OS 之所以能用极少数物理处理器编织出“每个程序都在独占一台机器”的完美错觉（CPU 虚拟化），靠的正是三大核心机制的精密配合：**时钟中断**（强制夺回 CPU 控制权）、**处理机调度**（决定下一个把 CPU 交给谁）以及**上下文切换**（完成执行现场的无缝接力）。

然而，资源有限不仅会引发“下一个轮到谁”的调度博弈，还可能在并发进程相互争抢不可抢占资源或消息时，演变成谁也无法向前推进的僵局——**死锁**。本章围绕“**CPU 怎么分（处理机调度）**”与“**资源卡死怎么办（死锁处理）**”两大核心主题展开，这既是 408 历年选择题与综合大题的超级高频阵地，也是操作系统资源管理思想的集大成者。

---

### 4.1 处理机调度的概念、层次与底层机制

#### 4.1.1 调度的三个层次 ★

一个作业从用户提交到执行结束，中间并非只经过一次挑选，而是依据**资源层级**与**时间尺度**划分为三个层次的调度。三者频率相差几个数量级，而频率直接决定了各层允许使用的算法复杂度上限。

| 调度层次 | 别名 | 调度对象与空间流转 | 典型频率 | 核心任务与对进程状态的影响 |
| --- | --- | --- | --- | --- |
| **高级调度** | **作业调度**、长程调度 | **外存后备队列 → 内存**（面向作业） | 极低（几分钟一次） | 按策略从外存后备队列挑选作业调入内存，**为其创建进程（建立 PCB）并分配内存与 I/O 等资源**；作业完成时撤消 PCB。每个作业只调入一次、调出一次（无 → 创建 → 就绪） |
| **中级调度** | **内存调度**、中程调度 | **内存 ↔ 外存对换区**（面向进程映像） | 中等（介于两者之间） | 当内存紧张时，将暂时不能运行的进程整体换出到外存，使其进入**挂起（静止）态**；待内存空闲且条件具备时再换回内存。旨在**提高内存利用率与系统吞吐量**（就绪 ↔ 就绪挂起、阻塞 ↔ 阻塞挂起） |
| **低级调度** | **进程调度**、短程调度 | **内存就绪队列 → CPU**（面向进程或内核级线程） | 极高（10～100 ms 一次） | 按某种调度算法从就绪队列选出最合适的进程（或内核级线程），**将处理机控制权分配给它**。是多道并发的最基本调度，算法必须**简单快速**（就绪 → 运行） |

> **★考点**：
> 1. **必须配置的层次**：**低级调度（进程调度）是所有多道操作系统必备的**；高级调度主要存在于多道批处理系统，分时和实时系统通常直接创建进程而不设作业调度；中级调度只在需要改善内存利用率时引入。因此现实中既有“三级调度模型”，也有“两级调度模型”。
> 2. **挂起态与阻塞态的本质区别**：处于阻塞态的进程，其**进程映像仍在内存中**，等待事件就绪即可恢复；处于挂起态（静止就绪 / 静止阻塞）的进程，其**进程映像已被对换到外存**，必须先由中级调度重新调入内存才可能被低级调度选中。

<figure class="cpd-figure not-content" id="os-c4-fig-1">
  <svg viewBox="0 0 720 342" role="img" aria-label="处理机三级调度与进程七状态流转全景配合图">
    <defs>
      <marker id="os-c4-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 区域底框 -->
    <rect class="fig-box-subtle" x="16" y="16" width="166" height="270" rx="8"/>
    <rect class="fig-box-subtle" x="196" y="16" width="218" height="270" rx="8"/>
    <rect class="fig-box-subtle" x="476" y="16" width="228" height="270" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="296" width="688" height="32" rx="6"/>
    <!-- 连线（先画线，留空防穿字） -->
    <!-- 高级调度：后备队列 -> 创建态 -->
    <line class="fig-line-accent" x1="166" y1="74" x2="210" y2="74" stroke-width="1.8" marker-end="url(#os-c4-arr-1)"/>
    <!-- 创建态 -> 就绪态 -->
    <line class="fig-line" x1="274" y1="100" x2="324" y2="146" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 创建态 -> 就绪挂起 (内存不足时) -->
    <line class="fig-line-dashed" x1="234" y1="100" x2="152" y2="146" stroke-width="1.4" marker-end="url(#os-c4-arr-1)"/>
    <!-- 中级调度：就绪挂起 <-> 就绪态 -->
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="166" y1="168" x2="288" y2="168" stroke-width="1.6" marker-end="url(#os-c4-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="288" y1="186" x2="166" y2="186" stroke-width="1.6" marker-end="url(#os-c4-arr-1)"/>
    <!-- 中级调度：阻塞挂起 <-> 阻塞态 -->
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="166" y1="242" x2="288" y2="242" stroke-width="1.6" marker-end="url(#os-c4-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="288" y1="260" x2="166" y2="260" stroke-width="1.6" marker-end="url(#os-c4-arr-1)"/>
    <!-- 阻塞挂起 -> 就绪挂起 -->
    <line class="fig-line" x1="98" y1="224" x2="98" y2="200" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 低级调度：就绪态 -> 运行态 -->
    <line class="fig-line-accent" x1="404" y1="166" x2="482" y2="166" stroke-width="2" marker-end="url(#os-c4-arr-1)"/>
    <!-- 运行态 -> 就绪态 (时间片到/抢占) -->
    <line class="fig-line" x1="484" y1="188" x2="406" y2="188" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 运行态 -> 阻塞态 -->
    <path class="fig-line" d="M 541 198 L 541 250 L 406 250" fill="none" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 阻塞态 -> 就绪态 -->
    <line class="fig-line" x1="347" y1="224" x2="347" y2="200" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 运行态 -> 终止态 -->
    <line class="fig-line" x1="598" y1="172" x2="612" y2="172" stroke-width="1.5" marker-end="url(#os-c4-arr-1)"/>
    <!-- 运行态 -> 就绪挂起 (部分系统支持) -->
    <path class="fig-line-dashed" d="M 541 144 L 541 118 L 116 118 L 116 144" fill="none" stroke-width="1.2" marker-end="url(#os-c4-arr-1)"/>
    <!-- 前景节点框 -->
    <rect class="fig-box-orange" x="30" y="48" width="136" height="52" rx="6"/>
    <rect class="fig-box-purple" x="30" y="146" width="136" height="52" rx="6"/>
    <rect class="fig-box-purple" x="30" y="224" width="136" height="52" rx="6"/>
    <rect class="fig-box-blue" x="212" y="48" width="124" height="52" rx="6"/>
    <rect class="fig-box-green" x="290" y="146" width="114" height="52" rx="6"/>
    <rect class="fig-box-red" x="290" y="224" width="114" height="52" rx="6"/>
    <rect class="fig-box-accent" x="484" y="146" width="114" height="52" rx="6"/>
    <rect class="fig-box" x="614" y="146" width="76" height="52" rx="6"/>
    <!-- 垫字小框防穿线 -->
    <rect class="fig-box" x="172" y="54" width="34" height="16" rx="3"/>
    <rect class="fig-box" x="196" y="158" width="62" height="16" rx="3"/>
    <rect class="fig-box" x="196" y="178" width="62" height="16" rx="3"/>
    <rect class="fig-box" x="196" y="232" width="62" height="16" rx="3"/>
    <rect class="fig-box" x="196" y="252" width="62" height="16" rx="3"/>
    <rect class="fig-box" x="421" y="146" width="46" height="16" rx="3"/>
    <!-- 标题与节点文字 -->
    <text class="fig-title" x="99" y="34" font-size="12" text-anchor="middle">外存区域（后备/对换）</text>
    <text class="fig-title" x="313" y="34" font-size="12" text-anchor="middle">内存区域（进程常驻）</text>
    <text class="fig-title" x="574" y="34" font-size="12" text-anchor="middle">CPU 与生命周期终点</text>
    <text class="fig-orange" x="98" y="70" font-size="11.5" text-anchor="middle">外存后备队列</text>
    <text class="fig-muted" x="98" y="88" font-size="10" text-anchor="middle">已提交的静止作业</text>
    <text class="fig-purple" x="98" y="168" font-size="11.5" text-anchor="middle">就绪挂起 (静止就绪)</text>
    <text class="fig-muted" x="98" y="186" font-size="10" text-anchor="middle">映像在外存·待激活</text>
    <text class="fig-purple" x="98" y="246" font-size="11.5" text-anchor="middle">阻塞挂起 (静止阻塞)</text>
    <text class="fig-muted" x="98" y="264" font-size="10" text-anchor="middle">映像在外存·等事件</text>
    <text class="fig-blue" x="274" y="70" font-size="11.5" text-anchor="middle">创建态 (建 PCB)</text>
    <text class="fig-muted" x="274" y="88" font-size="10" text-anchor="middle">资源初始化完成</text>
    <text class="fig-green" x="347" y="168" font-size="10.8" text-anchor="middle">就绪态 (活动就绪)</text>
    <text class="fig-muted" x="347" y="186" font-size="9.5" text-anchor="middle">仅缺 CPU 即可运行</text>
    <text class="fig-red" x="347" y="246" font-size="10.8" text-anchor="middle">阻塞态 (活动阻塞)</text>
    <text class="fig-muted" x="347" y="264" font-size="9.5" text-anchor="middle">等 I/O 或同步信号</text>
    <text class="fig-accent" x="541" y="168" font-size="11.5" text-anchor="middle">运行态 ★</text>
    <text class="fig-muted" x="541" y="186" font-size="9.8" text-anchor="middle">占用 CPU 执行指令</text>
    <text class="fig-label" x="652" y="168" font-size="11.5" text-anchor="middle">终止态</text>
    <text class="fig-muted" x="652" y="186" font-size="10" text-anchor="middle">释放 PCB</text>
    <!-- 连线标注 -->
    <text class="fig-accent" x="189" y="66" font-size="9.8" text-anchor="middle">高级</text>
    <text class="fig-muted" x="189" y="90" font-size="9.5" text-anchor="middle">建进程</text>
    <text class="fig-purple" x="227" y="170" font-size="9.8" text-anchor="middle">中级·激活</text>
    <text class="fig-purple" x="227" y="190" font-size="9.8" text-anchor="middle">中级·挂起</text>
    <text class="fig-purple" x="227" y="244" font-size="9.8" text-anchor="middle">中级·激活</text>
    <text class="fig-purple" x="227" y="264" font-size="9.8" text-anchor="middle">中级·挂起</text>
    <text class="fig-muted" x="56" y="216" font-size="9.8" text-anchor="middle">事件发生</text>
    <text class="fig-accent" x="444" y="158" font-size="9.8" text-anchor="middle">低级★</text>
    <text class="fig-muted" x="444" y="203" font-size="9.2" text-anchor="middle">时间片到/抢占</text>
    <text class="fig-muted" x="526" y="264" font-size="9.5" text-anchor="middle">申请 I/O / P 操作</text>
    <text class="fig-muted" x="339" y="215" font-size="9.2" text-anchor="end">唤醒 (I/O 完成)</text>
    <text class="fig-muted" x="376" y="110" font-size="9.5" text-anchor="middle">运行→就绪挂起</text>
    <text class="fig-label" x="360" y="316" font-size="11" text-anchor="middle">★ 频率与算法约束：高级调度（分钟级，可复杂） ≪ 中级调度（秒级，换入换出） ≪ 低级调度（10～100 ms，必须极简快速）</text>
  </svg>
  <figcaption>图 4-1　处理机三级调度与进程七状态转换流转全景（区分驻留内存的活动态与换出外存的挂起态）</figcaption>
</figure>

#### 4.1.2 调度的实现、上下文切换与内核机制

许多教材将负责调度的模块称为“调度程序”，初学者容易误以为它是一个独立跑在系统里的用户进程。实际上，在现代操作系统内核（如 Unix/Linux 与 xv6）中，**调度器（`scheduler()`）本质上是内核内部的一段特权函数**，依附于时钟中断、系统调用陷入（Trap）或内核线程上下文触发执行。完整调度与切换机制由四大逻辑部件驱动：

1. **排队器**：每当有进程转为就绪态（新创建、I/O 唤醒、时间片用完），排队器负责将它插入对应的就绪队列。只管组织队列，不做选择决策。
2. **调度程序（Scheduler）**：按照预定调度算法从就绪队列中**选出**下一个占用 CPU 的进程——只做“选谁”的决策，不直接操作寄存器。
3. **分派程序（Dispatcher）**：负责执行调度决策——将选中进程从就绪队列摘下、驱动上下文切换器完成现场替换、切换回用户态并跳转到新进程断点恢复执行。
4. **上下文切换器（Context Switcher）**：负责将当前进程的 CPU 现场保存进其 PCB，并将新进程 PCB 中的现场装入 CPU 寄存器。教材指出，由于分派程序自身也是一段需占用寄存器执行的代码，严格意义上一次完整调度包含**两对上下文切换**（先切入内核分派程序，再由分派程序切入目标用户进程）。

**分派延迟（Dispatch Latency）**：从停止旧进程（或选定新进程）到新进程真正执行第一条用户指令之间的纯时间开销 $\delta$ 。它由直接开销 $\delta_d$ 与间接开销 $\delta_i$ 两部分构成：

| 上下文分层 / 开销维度 | 包含内容与存放位置 | 上下文切换时的处理方式与开销特征 |
| --- | --- | --- |
| **用户级上下文** | 代码段、数据段、共享内存区、用户栈（进程虚存空间） | **不搬动物理数据**，仅修改页表基址寄存器使 CPU 映射到另一套虚存空间 |
| **寄存器上下文** | `PSW`（程序状态字）、`PC`（指令计数器）、`SP`（栈指针）、通用寄存器 | **必须逐个保存与恢复**，CPU 仅有一套寄存器，由**硬件中断隐指令**（保护 `PC/PSW`）与**内核软件代码**（搬运通用寄存器入 **PCB**）协作完成 |
| **系统级上下文** | PCB、页表/段表管理信息、核心栈（内核空间） | 切换内核栈指针与页表基址寄存器；**全系统共用的信息（如内核中断向量表基址寄存器）不需要保存和切换** |
| **直接开销 $\delta_d$** | 保存/恢复寄存器上下文（约上千条指令）、更新 PCB、重排就绪队列 | 可直接测量，通常只有几微秒 |
| **间接开销 $\delta_i$ ★** | 新进程上线后遭遇 **TLB 冷启动（全部失效）** 与 **CPU Cache 冷启动（大量未命中）** | **通常远大于直接开销**！这也是同进程内线程切换比进程切换快得多的根本原因（不切页表、TLB 不失效） |

> **★考点**：
> 1. **为什么现场必须存进 PCB 而不能存进用户栈？** 第一，存在循环依赖——“恢复用户栈指针 `SP` 前必须先知道现场存放在哪个 `SP` 地址”；第二，一旦进程被中级调度换出至外存，OS 在内核中直接读取其常驻内存的 PCB 远比跨地址空间访问安全可靠。
> 2. **硬件与软件的切换分工**：“头尾由硬件原子完成，中间由软件完成”——进入内核时，软件执行任何指令都会立刻覆盖 `PC` 与 `PSW`，因此必须由硬件**中断隐指令**原子保存旧进程的 `PC`、`PSW`；退出时同理需由**中断返回指令**原子恢复。
> 3. **发生调度 ≠ 必然发生上下文切换**：若调度程序经评估后选中的仍是原进程（例如优先级仍最高），则无需进行上下文切换；但反之**发生上下文切换前必定执行了调度**（2025 年 408 第 23 题亦直接考查页式虚存上下文切换不需要改变“内核中断向量表基址寄存器”）。

#### 4.1.3 进程调度的时机与临界区陷阱 ★

判断某个时刻“能否进行进程调度”，只需要盯住一条总纲：**调度动作本身要读写修改就绪队列、PCB 链与 CPU 现场；凡是内核数据结构正处于“半成品”或原子边界不可打断的时刻，绝对禁止调度。**

| 分类 | 具体场景 | 深层原因与考点辨析 |
| --- | --- | --- |
| **可以调度的时机** | ① 当前进程主动放弃 CPU：运行结束、异常终止、或申请 I/O / 执行 `wait()` 阻塞<br>② 当前进程时间片耗尽（时钟中断）<br>③ 阻塞进程被唤醒或创建新进程，就绪队列改变（抢占式）<br>④ **中断处理程序结束 / 系统调用完成准备返回用户态前** | 第 ① 类无论抢占与否均必然调度；第 ②③④ 类在抢占式下触发重新决策，检查是否需要换人 |
| **绝对不能调度的时机** | ① **正在处理中断的过程中**<br>② **进程处于操作系统内核临界区中**<br>③ **正在执行原子操作（原语，如 `P/V`、阻塞/唤醒原语）过程中** | ① 中断现场尚未完全理顺或正处理硬件交互；② **内核临界区正修改就绪队列/PCB 链等调度器自己依赖的数据结构**，强行调度将破坏内核一致性；③ 原语本身通过关中断实现，不可分割 |

> **注意（★高频经典易错坑）**：**“进程处于临界区时不能进行进程调度”这一说法是错误的！**
> 必须严格区分**内核临界区**与**普通（用户）临界区**：
> - 当进程正在访问打印机或修改用户态共享变量（处于**普通临界区**）时，它锁住的是用户资源，并不会破坏操作系统的就绪队列或内核数据结构；此时完全允许发生时钟中断并将它调度走，别的进程也进不去那把用户锁（最多阻塞等待），所以**普通临界区中完全可以进行进程调度**（真题 `12#30`、`21#27` 考点）。
> - 只有当进程持有的是**内核临界区锁**（如修改进程控制块队列、或如 4.3 节所述的多核自旋锁保护的内核区）时，调度切换才会被禁止！

<figure class="cpd-figure not-content" id="os-c4-fig-2">
  <svg viewBox="0 0 720 318" role="img" aria-label="调度器与上下文切换链路及临界区调度边界对比图">
    <defs>
      <marker id="os-c4-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 上半区：调度与切换流程 -->
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="148" rx="8"/>
    <line class="fig-line-accent" x1="146" y1="68" x2="170" y2="68" stroke-width="1.8" marker-end="url(#os-c4-arr-2)"/>
    <line class="fig-line-accent" x1="316" y1="68" x2="340" y2="68" stroke-width="1.8" marker-end="url(#os-c4-arr-2)"/>
    <line class="fig-line-accent" x1="534" y1="68" x2="558" y2="68" stroke-width="1.8" marker-end="url(#os-c4-arr-2)"/>
    <rect class="fig-box" x="28" y="42" width="118" height="52" rx="5"/>
    <rect class="fig-box-blue" x="172" y="42" width="144" height="52" rx="5"/>
    <rect class="fig-box-accent" x="342" y="42" width="192" height="52" rx="5"/>
    <rect class="fig-box-green" x="560" y="42" width="132" height="52" rx="5"/>
    <rect class="fig-box-orange" x="28" y="106" width="664" height="44" rx="5"/>
    <text class="fig-title" x="360" y="32" font-size="12" text-anchor="middle">一、内核调度与两阶段上下文切换执行链（中断隐指令 → 软件切换 → 中断返回）</text>
    <text class="fig-label" x="87" y="64" font-size="11.5" text-anchor="middle">① 排队器</text>
    <text class="fig-muted" x="87" y="81" font-size="10" text-anchor="middle">组织入就绪队列</text>
    <text class="fig-blue" x="244" y="64" font-size="11.5" text-anchor="middle">② 调度程序 Scheduler</text>
    <text class="fig-muted" x="244" y="81" font-size="10" text-anchor="middle">选出目标进程(不碰寄存器)</text>
    <text class="fig-accent" x="438" y="64" font-size="11.5" text-anchor="middle">③ 分派程序 + 上下文切换器</text>
    <text class="fig-muted" x="438" y="81" font-size="9.5" text-anchor="middle">存现场入 PCB · 换 PTBR · 装新现场</text>
    <text class="fig-green" x="626" y="64" font-size="11.5" text-anchor="middle">④ 新进程执行</text>
    <text class="fig-muted" x="626" y="81" font-size="10" text-anchor="middle">中断返回切用户态</text>
    <text class="fig-orange" x="360" y="124" font-size="11" text-anchor="middle">★ 分派延迟总开销 δ = δ_d(保存/恢复寄存器、换 PTBR) + δ_i(TLB 与 Cache 冷启动损失，后者往往更大)</text>
    <text class="fig-muted" x="360" y="140" font-size="10" text-anchor="middle">不需要换：全系统唯一的中断向量表基址寄存器(25#23) ｜ 必须换：PC、PSW、通用寄存器、SP、页表基址寄存器(PTBR)</text>
    <!-- 下半区：能调度 vs 不能调度 -->
    <rect class="fig-box-red" x="16" y="174" width="336" height="130" rx="8"/>
    <rect class="fig-box-green" x="368" y="174" width="336" height="130" rx="8"/>
    <text class="fig-red" x="184" y="196" font-size="11.5" text-anchor="middle">✕ 绝对禁止调度的三大禁区（内核半成品状态）</text>
    <text class="fig-label" x="28" y="218" font-size="10.2">1. 中断处理过程中：现场未完整整理或交互尚未完成</text>
    <text class="fig-label" x="28" y="239" font-size="10.2">2. 内核临界区中：正修改就绪队列、PCB 链等调度数据结构</text>
    <text class="fig-label" x="28" y="260" font-size="10.2">3. 原子操作 / 原语中：关中断保原子性（如 P/V 原语）</text>
    <text class="fig-muted" x="28" y="286" font-size="10">★ 统一准则：若此刻强行换人，调度器读到的内核状态不一致</text>
    <text class="fig-green" x="536" y="196" font-size="11.5" text-anchor="middle">✓ 可以调度的常见时机（含普通临界区）</text>
    <text class="fig-label" x="380" y="218" font-size="10.2">1. 普通（用户）临界区中：访问打印机或用户态互斥锁 ★</text>
    <text class="fig-label" x="380" y="239" font-size="10.2">2. 当前进程终止或主动阻塞（I/O 请求、wait 阻塞）</text>
    <text class="fig-label" x="380" y="260" font-size="10.2">3. 时间片用完 / 更高优先级就绪 / 中断完毕返回前</text>
    <text class="fig-muted" x="380" y="286" font-size="10">★ 说明：用户锁与调度器数据结构无关，切走后安全不破坏系统</text>
  </svg>
  <figcaption>图 4-2　调度器与上下文切换完整链路及“内核临界区禁调度 vs 普通临界区可调度”核心边界（12#30、21#27、25#23）</figcaption>
</figure>

#### 4.1.4 调度方式、闲逛进程与两类线程的调度

根据是否允许在进程尚未完成或阻塞时强行夺走 CPU，进程调度分为两种截然不同的方式：

- **非抢占式（非剥夺方式）**：一旦将 CPU 分配给某进程，就让它一直运行到自然结束或主动阻塞（如请求 I/O、执行 `Block` 原语）才重新调度。实现简单、无额外时钟抢占开销，适合早期批处理系统，但无法保证交互性与实时截止期。
- **抢占式（剥夺方式）**：允许调度程序依据特定原则暂停正在运行的进程，将其从运行态拉回就绪态，把 CPU 改分给其他进程。抢占必须依靠**时钟中断**等硬件机制强行将控制权交还操作系统，主要依据三项原则：**优先权原则**（高优先级抢占低优先级）、**短进程优先原则**（更短剩余时间抢占）与**时间片原则**（时间片到强制轮换）。适合分时与实时系统。

**闲逛进程（Idle Process）**：当就绪队列为空时，由于 CPU 取指周期从不停止，必须安排一个“永远不会阻塞的兜底进程”在 CPU 上运行（在 Linux 中为 `PID = 0` 的 `swapper / idle task`，在 Windows 中为 `System Idle Process`）。它的全部六条性质均可由其定位直接推出：
1. **优先级最低**：只要有任何一个真实就绪进程出现，就立刻让出 CPU。
2. **不占用除 CPU 以外的任何资源**：不申请内存、不做 I/O，否则一旦自己缺资源就会导致“就绪队列空且闲逛进程也阻塞”的死局。
3. **永远不会被阻塞**：不等待任何外部事件。
4. **执行期间必须开中断（响应中断）**：否则外设 I/O 完成中断进不来，处于阻塞态的用户进程永远无法被唤醒，系统彻底僵死！
5. **常执行零地址指令或停机节能指令（如 x86 的 `HLT`）**：不访存、不读寄存器，使 CPU 在空转等待中断期间进入低功耗状态。

**线程调度视角差异**：若系统仅支持**用户级线程（ULT）**，内核完全感知不到线程存在，**调度仍以进程为单位**；一个线程发起阻塞系统调用将牵连**整个进程阻塞**，且无法利用多核并行。若系统支持**内核级线程（KLT）**，内核为每个线程建立 TCB 并直接以其作为**处理机调度的基本单位**（进程仅作资源分配单位）；单线程阻塞不影响同进程其他线程，且线程数越多的进程获得的总 CPU 时间通常越多（真题常考二者区别）。

<figure class="cpd-figure not-content" id="os-c4-fig-3">
  <svg viewBox="0 0 720 272" role="img" aria-label="非抢占式与抢占式调度对比时序及闲逛进程工作状态机">
    <defs>
      <marker id="os-c4-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 上区：抢占 vs 非抢占对比 -->
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="148" rx="8"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">非抢占式 vs 抢占式核心分水岭（例：P1 于 t=0 到达需 8、低优先级；P2 于 t=3 到达需 4、高优先级）</text>
    <!-- 时刻虚线 -->
    <line class="fig-line-dashed" x1="238" y1="46" x2="238" y2="129"/>
    <!-- 非抢占时间轴 -->
    <text class="fig-label" x="28" y="68" font-size="11.5">非抢占式：</text>
    <rect class="fig-box-blue" x="118" y="50" width="320" height="28" rx="4"/>
    <rect class="fig-box-green" x="438" y="50" width="160" height="28" rx="4"/>
    <text class="fig-blue" x="278" y="68" font-size="11.5" text-anchor="middle">P1 一直运行 (0–8)</text>
    <text class="fig-green" x="518" y="68" font-size="11.5" text-anchor="middle">P2 (8–12)</text>
    <text class="fig-muted" x="610" y="68" font-size="10">P2 被晾等 5 单位</text>
    <!-- 抢占式时间轴 -->
    <text class="fig-label" x="28" y="114" font-size="11.5">抢占式：</text>
    <rect class="fig-box-blue" x="118" y="96" width="120" height="28" rx="4"/>
    <rect class="fig-box-green" x="238" y="96" width="160" height="28" rx="4"/>
    <rect class="fig-box-blue" x="398" y="96" width="200" height="28" rx="4"/>
    <text class="fig-blue" x="178" y="114" font-size="11" text-anchor="middle">P1 (0–3)</text>
    <text class="fig-green" x="318" y="114" font-size="11.5" text-anchor="middle">P2 立即抢占 (3–7)</text>
    <text class="fig-blue" x="498" y="114" font-size="11" text-anchor="middle">P1 恢复续跑 (7–12)</text>
    <text class="fig-muted" x="610" y="114" font-size="10">P2 响应为 0</text>
    <!-- 刻度数字 -->
    <text class="fig-accent" x="238" y="144" font-size="10.5" text-anchor="middle">t=3: P2 到达引发检查</text>
    <text class="fig-muted" x="118" y="144" font-size="10" text-anchor="middle">0</text>
    <text class="fig-muted" x="398" y="144" font-size="10" text-anchor="middle">7</text>
    <text class="fig-muted" x="438" y="144" font-size="10" text-anchor="middle">8</text>
    <text class="fig-muted" x="598" y="144" font-size="10" text-anchor="middle">12</text>
    <!-- 下区：闲逛进程状态与性质 -->
    <rect class="fig-box-subtle" x="16" y="172" width="688" height="86" rx="8"/>
    <line class="fig-line-accent" x1="208" y1="222" x2="254" y2="222" stroke-width="1.6" marker-end="url(#os-c4-arr-3)"/>
    <line class="fig-line-accent" x1="454" y1="222" x2="500" y2="222" stroke-width="1.6" marker-end="url(#os-c4-arr-3)"/>
    <rect class="fig-box" x="28" y="200" width="178" height="44" rx="5"/>
    <rect class="fig-box-purple" x="256" y="200" width="196" height="44" rx="5"/>
    <rect class="fig-box-green" x="502" y="200" width="188" height="44" rx="5"/>
    <text class="fig-title" x="360" y="191" font-size="11.5" text-anchor="middle">闲逛进程 (Idle Process / PID=0) 兜底流转：永不阻塞 · 优先级最低 · 始终开中断</text>
    <text class="fig-label" x="117" y="218" font-size="11" text-anchor="middle">就绪队列为空</text>
    <text class="fig-muted" x="117" y="234" font-size="9.8" text-anchor="middle">无用户/系统任务可调度</text>
    <text class="fig-purple" x="354" y="218" font-size="11" text-anchor="middle">执行 Idle (HLT 节能指令)</text>
    <text class="fig-muted" x="354" y="234" font-size="9.8" text-anchor="middle">零地址指令 · 随时可被中断</text>
    <text class="fig-green" x="596" y="218" font-size="11" text-anchor="middle">I/O 或时钟中断唤醒</text>
    <text class="fig-muted" x="596" y="234" font-size="9.8" text-anchor="middle">立即让出 CPU 给新就绪进程</text>
  </svg>
  <figcaption>图 4-3　非抢占与抢占式调度直观分水岭及闲逛进程（Idle Process）的兜底切换流转</figcaption>
</figure>

---

### 4.2 ★调度目标与五大性能评价指标

不同类型操作系统的调度目标存在天然冲突，不能同时达到最优：
- **批处理系统**：无用户坐等终端交互，追求**平均周转时间短**、**系统吞吐量高**与**处理机利用率高**。注意“吞吐量高”倾向于多运行**短作业**，“CPU 利用率高”却倾向于多运行**计算密集型作业**，二者本身也会打架，需要平衡。
- **分时系统**：用户在终端前等待反馈，首要追求**响应时间快**与**均衡性**（响应时间快慢应与请求复杂度相适应）。
- **实时系统**：首要保证**截止时间（Deadline）满足**与**高度可预测性**，哪怕整体平均速度慢也绝不允许单次超时。

为统一后续各调度算法的计算标准，设系统中共有 $n$ 个进程（或作业），对第 $i$ 个进程：令其到达时刻为 $A_i$ ，需要的服务时间（CPU 总运行时间）为 $S_i$ ，实际完成时刻为 $C_i$ ，首次获得 CPU 开始运行的时刻为 $F_i$ 。

#### 1. CPU 利用率与系统吞吐量

$$
\text{CPU 利用率} = \frac{\text{CPU 有效工作时间}}{\text{CPU 有效工作时间} + \text{CPU 空闲等待时间}} \quad , \quad \text{系统吞吐量} = \frac{\text{完成的作业总数}}{\text{总花费时间}}
$$

- **注意**：当多道程序（包含 CPU 计算与 I/O 读写交叠）并发执行时，需画出 CPU 与各 I/O 设备并行甘特图，分别累计“设备忙碌总时间 / 总耗用时间”（如真题 `12#29`：让 CPU 与 I/O 尽可能并行重叠，使总时间最短）。

#### 2. 周转时间、平均周转时间与带权周转时间 ★

- **周转时间（Turnaround Time）**：从作业提交（进程到达）起，到全部执行完毕为止经历的总时间，包含“外存后备等待 + 内存就绪等待 + CPU 执行 + I/O 阻塞”四段之和：

$$
T_i = C_i - A_i \quad , \quad \overline{T} = \frac{1}{n}\sum_{i=1}^{n} T_i
$$

- **带权周转时间（Weighted Turnaround Time）**：周转时间与实际服务时间之比（无量纲，衡量作业所耗费总时间是纯干活时间的多少倍，客观反映短作业在长队列中等待的“委屈度”）：

$$
W_i = \frac{T_i}{S_i} \ge 1 \quad , \quad \overline{W} = \frac{1}{n}\sum_{i=1}^{n} W_i = \frac{1}{n}\sum_{i=1}^{n}\frac{T_i}{S_i}
$$

> **注意（★必考计算大坑）**：计算平均带权周转时间 $\overline{W}$ 时，**必须先分别求出每个进程的 $W_i = T_i / S_i$ ，再取算术平均**！严禁用“$\overline{T} \div \overline{S}$”代替，两者一般不相等！此外 $T_i \ge S_i$ 决定了任何进程（无并行的单核条件下）$W_i \ge 1$ ，周转时间与带权周转时间均是**越小越好**。

#### 3. 等待时间与响应时间 ★

- **等待时间（Waiting Time）**：进程（或作业）处于<strong>等待被服务状态（如在就绪队列等待 CPU 或作业在后备队列等待装入内存）</strong>的累计时间之和，**不含正在被 CPU 或 I/O 设备服务的时间**。
  - 对于纯计算型进程，无论非抢占还是抢占式，**等待时间通用公式**：$\text{等待时间}_i = T_i - S_i$ 。
  - 若进程包含 $I_i$ 时间的 I/O 操作（等待 I/O 期间正在被设备服务，不算排队干等），则 $\text{等待时间}_i = T_i - S_i - I_i$ 。调度算法本身无法改变进程所需的 $S_i$ 与 $I_i$ ，只能通过排序改变等待时间。
- **响应时间（Response Time）**：用户提交请求到系统<strong>首次产生响应（首次被调度上 CPU 执行）</strong>为止的时间间隔：

$$
\text{响应时间}_i = F_i - A_i
$$

> **★考点**：**非抢占式 vs 抢占式下“等待时间”与“响应时间”的分离（`23#29`）**：
> - 在**非抢占式**下，纯计算进程一旦于 $F_i$ 首次上 CPU 就会一跑到底直到 $C_i$ 结束，中间不再重新排队，故**等待时间 $= F_i - A_i =$ 响应时间**（两者数值相等）。
> - 在**抢占式**下，进程可能刚跑到一半在半途被踢回就绪队列再次排队（如后面 SRTF 中 $P_1$ 于 $t=0$ 首次上 CPU 响应时间为 $0$ ，但中途被抢占重排，总等待时间高达 $9$ ），此时**等待时间是所有就绪等待片段的总和（必须用 $T_i - S_i$ 计算），与响应时间彻底分离**！

<figure class="cpd-figure not-content" id="os-c4-fig-4">
  <svg viewBox="0 0 720 236" role="img" aria-label="调度评价指标在进程生命周期时间轴上的几何分解图">
    <defs>
      <marker id="os-c4-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="208" rx="8"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">进程 / 作业生命周期时间轴与五大评价指标精确几何映射（抢占式与含 I/O 场景通用）</text>
    <!-- 时间轴主线 -->
    <line class="fig-line-accent" x1="36" y1="88" x2="684" y2="88" stroke-width="1.6" marker-end="url(#os-c4-arr-4)"/>
    <!-- 分段色块 y=56 h=26 -->
    <rect class="fig-box" x="56" y="56" width="84" height="26" rx="3"/>
    <rect class="fig-box-orange" x="140" y="56" width="84" height="26" rx="3"/>
    <rect class="fig-box-green" x="224" y="56" width="90" height="26" rx="3"/>
    <rect class="fig-box-orange" x="314" y="56" width="80" height="26" rx="3"/>
    <rect class="fig-box-blue" x="394" y="56" width="96" height="26" rx="3"/>
    <rect class="fig-box-green" x="490" y="56" width="120" height="26" rx="3"/>
    <!-- 时刻竖线 -->
    <line class="fig-line-dashed" x1="56" y1="50" x2="56" y2="194"/>
    <line class="fig-line-dashed" x1="224" y1="50" x2="224" y2="152"/>
    <line class="fig-line-dashed" x1="610" y1="50" x2="610" y2="194"/>
    <!-- 时刻圆点 -->
    <circle class="fig-dot" cx="56" cy="88" r="3.5"/>
    <circle class="fig-dot" cx="224" cy="88" r="3.5"/>
    <circle class="fig-dot" cx="610" cy="88" r="3.5"/>
    <!-- 段内文字 -->
    <text class="fig-muted" x="98" y="73" font-size="10" text-anchor="middle">后备队列等</text>
    <text class="fig-orange" x="182" y="73" font-size="10" text-anchor="middle">就绪等 ①</text>
    <text class="fig-green" x="269" y="73" font-size="10" text-anchor="middle">CPU 运行 ①</text>
    <text class="fig-orange" x="354" y="73" font-size="9.5" text-anchor="middle">就绪等 ②(抢)</text>
    <text class="fig-blue" x="442" y="73" font-size="10" text-anchor="middle">I/O 服务 (阻塞)</text>
    <text class="fig-green" x="550" y="73" font-size="10" text-anchor="middle">CPU 运行 ②</text>
    <!-- 关键时刻标 -->
    <text class="fig-accent" x="56" y="48" font-size="10.5" text-anchor="middle">A_i 到达</text>
    <text class="fig-accent" x="224" y="48" font-size="10.5" text-anchor="middle">F_i 首次上CPU</text>
    <text class="fig-accent" x="610" y="48" font-size="10.5" text-anchor="middle">C_i 完成</text>
    <!-- 下方指标线与标注 -->
    <!-- 响应时间 -->
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="58" y1="118" x2="222" y2="118" stroke-width="1.6" marker-start="url(#os-c4-arr-4)" marker-end="url(#os-c4-arr-4)"/>
    <text class="fig-purple" x="140" y="113" font-size="10.5" text-anchor="middle">响应时间 = F_i − A_i</text>
    <!-- 等待时间（不含 I/O） -->
    <rect class="fig-box-orange" x="56" y="130" width="168" height="22" rx="3"/>
    <rect class="fig-box-orange" x="314" y="130" width="80" height="22" rx="3"/>
    <text class="fig-orange" x="140" y="145" font-size="10" text-anchor="middle">等待片段 1 (作业含后备)</text>
    <text class="fig-orange" x="354" y="145" font-size="10" text-anchor="middle">等待片段 2</text>
    <text class="fig-muted" x="410" y="145" font-size="10" text-anchor="start">等待 = T_i − S_i − I_i (排队之和)</text>
    <!-- 周转时间 -->
    <line class="fig-line-accent" x1="58" y1="176" x2="608" y2="176" stroke-width="1.8" marker-start="url(#os-c4-arr-4)" marker-end="url(#os-c4-arr-4)"/>
    <rect class="fig-box" x="224" y="166" width="218" height="20" rx="3"/>
    <text class="fig-accent" x="333" y="180" font-size="11" text-anchor="middle">周转时间 T_i = C_i − A_i ★</text>
    <text class="fig-label" x="360" y="206" font-size="10.8" text-anchor="middle">带权周转 W_i = T_i / S_i ≥ 1（其中 S_i = CPU 运行① + CPU 运行②；平均带权必须先求比值再平均！）</text>
  </svg>
  <figcaption>图 4-4　响应时间、等待时间、服务时间、周转时间与带权周转时间在进程时间轴上的几何关系</figcaption>
</figure>

---

### 4.3 ★经典单处理机与多处理机调度算法全解析

在深入每一种具体调度算法前，掌握一个**通用元规则**可看穿全章所有算法本质：除 RR 外，几乎所有单核调度算法都可看作**优先级调度的特例**——只是各自选用了不同的“比较键（优先级函数）”。判断任意新算法能否具备抢占式版本，只需两问：
1. **比较键在运行期间会不会被后来者超越？** 不会超越就没有抢占式版本（如 FCFS）；会超越才有抢占意义。
2. **超越发生在离散时刻还是连续过程？** 若仅在“新进程到达时刻”产生分歧（如 SRTF、静态优先级），只需在离散到达点检查，开销可控；若在等待过程中连续上升导致必然交越（如 HRRN），则没有固定检查点，工程上只保留非抢占式。

下面除 MLQ 外，其余经典算法均以**同一组标准算例数据**横向跑通以便对照：

| 进程 | 到达时间 $A_i$ | 服务时间 $S_i$ | 优先数（约定：**数值越小优先级越高**） |
| --- | --- | --- | --- |
| `P1` | 0 | 7 | 3 |
| `P2` | 2 | 4 | 1 |
| `P3` | 4 | 1 | 4 |
| `P4` | 5 | 4 | 2 |

#### 4.3.1 先来先服务 (FCFS)

- **规则**：按作业到达后备队列（或进程到达就绪队列）的先后次序（FIFO）分配处理机。
- **抢占性**：**只可能是非抢占式**——因为比较键是“到达时间”，正在运行的进程到达时刻必定早于任何后来者，不可能被超越。
- **优缺点与饥饿**：实现最简单（单一 FIFO 队列），规则直观公平，**不会导致饥饿**（排在前面的进程数只减不增）。缺点是存在严重的**护航效应（Convoy Effect）**：一个 CPU 密集型长作业排在最前面时，会堵住后面一串短作业和 I/O 密集型进程；更深层的系统代价在于，**排在后面的 I/O 密集型进程拿不到 CPU 就发不出 I/O 请求，导致外设长时间跟着闲置**，等它们好不容易拿到 CPU 又马上阻塞去等 I/O，CPU 转而空转。因此准确评价是<strong>“对 CPU 密集型有利、对 I/O 密集型不利”</strong>，通常仅用于批处理作业调度或作为多级队列中的子队列策略。
- **基准算例手算**：调度顺序 `P1(0–7) → P2(7–11) → P3(11–12) → P4(12–16)`。各指标见表：
  - $T$: $P_1=7,\; P_2=9,\; P_3=8,\; P_4=11 \implies \overline{T} = 8.75$ ；
  - $W$: $P_1=1.00,\; P_2=2.25,\; P_3=\mathbf{8.00},\; P_4=2.75 \implies \overline{W} = 3.50$ （注意 $P_3$ 仅需 $1$ 单位服务却等了 $7$ 单位，带权周转飙至 $8.00$ ，量化了护航效应）；
  - $\text{等待} = \text{响应} = (0+5+7+7)/4 = 4.75$ 。

#### 4.3.2 ★短作业优先 (SJF / SPF) 与最短剩余时间优先 (SRTF / SRTN)

- **规则与变体**：
  - **非抢占式 SJF / SPF**：从**当前已到达且未完成**的就绪集合中挑选要求服务时间 $S_i$ 最短的进程；若时长相同，则先到达者优先。
  - **抢占式 SRTF / SRTN（最短剩余时间优先）**：将比较键改为“**剩余服务时间**”。每当有**新进程到达**就绪队列时，比较新进程总服务时间与当前运行者的剩余时间，若更短则立即抢占。运行者的剩余时间只减而等待者的不变，差距不断拉大，故**手算 SRTF 只需在每个新进程到达的离散时刻检查一次抢占**，其余时刻绝不会发生超越！
- **★最优性证明与严格前提（易考坑）**：
  - 设所有进程**同时到达**，若序列中存在相邻对 $(X,Y)$ 满足服务时间 $a > b$ ，将二者对调后，排在它们前面的等待不变，排在后面的因总完成时刻 $P+a+b$ 不变也不受影响，而 $X,Y$ 两者的等待时间之和从 $2P+a$ 严格降至 $2P+b$ （减少了 $a-b > 0$ ）。故反复交换直到按服务时间升序即得最小总等待时间。
  - **注意（常见严谨性考题陷阱）**：教材常泛称“SJF 平均等待时间、平均周转时间最少”，这一结论**必须以“所有进程同时到达（或几乎同时到达）”为前提**！当进程不同时到达时，非抢占 SJF 并不一定最优（见基准算例对比：非抢占 SJF $\overline{T}=8.00$ ，而抢占式 SRTF 可压至 $\overline{T}=7.00$ ）；**无前提下平均等待与平均周转时间全局最优的是抢占式的 SRTF**。
- **无法预知服务时间的预测法**：真实系统中无法事先准确获知未来 CPU 突发长度，一般利用历史实测值 $t_n$ 与历史预测值 $\tau_n$ 做**指数加权移动平均**：$\tau_{n+1} = \alpha \cdot t_n + (1-\alpha)\cdot \tau_n \quad (\alpha \in [0,1],\;\text{常取 } 1/2)$ 。展开后为 $\tau_{n+1} = \alpha t_n + (1-\alpha)\alpha t_{n-1} + (1-\alpha)^2\alpha t_{n-2} + \cdots$ ，越久远的历史权重按指数衰减，既利用了全部历史又只需维护一个 $\tau$ 变量。当 $\alpha = 0$ 时完全忽略近期实测，当 $\alpha = 1$ 时只看最近一次；它的缺陷是**抗噪但对行为模式突变跟随滞后**。
- **缺点**：**① 可能饥饿**（若源源不断有短作业到达，长作业将永远被插队而“饿死”）；② 必须预知运行时间（用户甚至可能虚报短时间欺骗系统）；③ 未考虑任务紧迫程度，无法用于实时或交互式场景。
- **基准算例手算（`17#23` 提醒：每轮只圈“此刻已到达”的进程！）**：
  - **非抢占 SJF**：$t=0$ 仅 $P_1$ 到达（即使 $P_3$ 只有 $1$ 也不能选！），故 $P_1$ 跑完 $0$ ～ $7$ ；$t=7$ 时 $P_2(4), P_3(1), P_4(4)$ 均到达，选 $P_3(7$ ～ $8)$ ；$t=8$ 时 $P_2$ 与 $P_4$ 同长 $4$ ，先到的 $P_2$ 优先 $(8$ ～ $12)$ ，最后 $P_4(12$ ～ $16)$ 。指标：$\overline{T} = (7+10+4+11)/4 = \mathbf{8.00}$ ，$\overline{W} = (1+2.5+4+2.75)/4 = \mathbf{2.56}$ ，平均等待 $=$ 平均响应 $= \mathbf{4.00}$ 。
  - **抢占 SRTF**：$t=0$ 跑 $P_1(7)$ ；$t=2$ 时 $P_2(4)$ 到，$P_1$ 剩 $5 > 4$ ，**抢占**跑 $P_2$ ；$t=4$ 时 $P_3(1)$ 到，$P_2$ 剩 $2 > 1$ ，**抢占**跑 $P_3$ ；$t=5$ 时 $P_3$ 完且 $P_4(4)$ 到，就绪余 $\{P_1(5), P_2(2), P_4(4)\}$ 选 $P_2(5$ ～ $7)$ ；$t=7$ 选 $P_4(7$ ～ $11)$ ；$t=11$ 跑完 $P_1(11$ ～ $16)$ 。指标：$\overline{T} = (16+5+1+6)/4 = \mathbf{7.00}$ ，$\overline{W} = (16/7+1.25+1+1.5)/4 \approx \mathbf{1.51}$ ；平均等待 $= (9+1+0+2)/4 = \mathbf{3.00}$ ，而平均响应 $= (0+0+0+2)/4 = \mathbf{0.50}$ （$P_1$ 响应为 $0$ 、等待却高达 $9$ ！）。

#### 4.3.3 ★高响应比优先 (HRRN)

- **提出动机**：FCFS 只看等待时间、对短作业不利；SJF 只看服务时间、会饿死长作业。HRRN 同时把两类信息折算进**响应比** $R$ ，在调度时选 $R$ 最大者：

$$
R = \frac{\text{等待时间} + \text{要求服务时间}}{\text{要求服务时间}} = 1 + \frac{W}{S} \ge 1
$$

- **★公式的深层物理含义**：响应比 $R$ 恰好等于“**假设现在就将该非抢占进程调度上 CPU，它跑完后最终得到的带权周转时间**”（周转时间恰好为 $W+S$ ）。选 $R$ 最大即“**优先解救当前已经被相对自身工作量拖累得最狠的进程**”。
- **两大退化与防饥饿机制**：
  - 当各进程**等待时间 $W$ 相同**时，$R$ 单调由 $1/S$ 决定，**退化为 SJF**（短作业优先）。
  - 当各进程**服务时间 $S$ 相同**时，$R$ 单调由 $W$ 决定，**退化为 FCFS**（先来先服务）。
  - **为什么不会饥饿（系统不过载时）？** 新到达进程的 $W=0$ ，故 $R=1$ 是理论最小下界，绝对插不到任何已等待过（$R>1$）的进程前面；长作业随着等待 $W$ 增加，其 $R$ 线性无上界增长，迟早超过后来短作业成为最高者。
- **为什么只有非抢占式？** 运行进程 $R$ 冻结不变，就绪进程随等待增加 $R$ 不断上升，比较键必在连续时间中发生交越，没有离散的抢占检查点，故工程中只采用非抢占式（每次调度需遍历重算所有就绪进程 $R$ ，计算开销略大，且仍需预知服务时间 $S$ ）。真题 `09#24`、`11#23` 考法：“综合考虑等待时间与执行时间 / 满足短任务优先且不饥饿” $\implies$ **HRRN**。
- **基准算例手算**：$t=0$ 跑 $P_1(0$ ～ $7)$ ；$t=7$ 重算：$R_{P2}=(5+4)/4=2.25$ 、$R_{P3}=(3+1)/1=\mathbf{4.00}$ 、$R_{P4}=(2+4)/4=1.50$ ，选 $P_3(7$ ～ $8)$ ；$t=8$ 必须**全部重新计算**：$R_{P2}=(6+4)/4=\mathbf{2.50}$ 、$R_{P4}=(3+4)/4=1.75$ ，选 $P_2(8$ ～ $12)$ ，最后 $P_4(12$ ～ $16)$ 。本例巧合下甘特图与 SJF 相同，但只要把 $P_2$ 服务时间改为 $6$ ，$t=8$ 时 $R_{P2}=(6+6)/6=2.00 > R_{P4}=1.75$ 仍优先运行已等久的 $P_2$ ，而 SJF 则会继续让 $P_4$ 插队。

#### 4.3.4 ★优先级调度与优先级反转

优先级调度沿着两个相互正交的维度划分：**抢占式 vs 非抢占式**，以及**静态优先级 vs 动态优先级**。

- **静态优先级**：创建时确定、运行期间不变（开销小，但**低优先级进程可能发生饥饿**）。赋值三大依据：进程类型、对资源的需求（少者优先以提升并发度）、用户紧急要求。常见通用赋值惯例：
  - **系统进程 $>$ 用户进程**；**交互型进程 $>$ 非交互型进程**；
  - **I/O 密集型进程 $>$ CPU 密集型进程（★真题 `13#31` 高频考点）**——让 I/O 密集型进程先跑一小段 CPU 并尽快把慢速的 I/O 请求发出去，这样 CPU 就能与外设尽早进入**并行工作**状态，显著提高设备与处理器综合利用率！
- **动态优先级与老化（Aging）**：
  - 调整信号：**等待时间越长 $\to$ 优先级升高（这就是“老化 Aging”，是根治饥饿的唯一有效手段，使等待上界受控为 $k\Delta$ ）**；**占用 CPU 时间越长 / 刚用完一个时间片 $\to$ 优先级降低**（真题 `10#26` 考法：降低进程优先级的最合理时机是“**进程刚使用完一个时间片**”，而刚从阻塞变就绪或久在就绪队列则应当提高或维持）。
  - 若所有进程优先级初值相同且仅随等待时间匀速老化，则先到者优先级永远最高，**动态优先级退化为 FCFS**。
  - **注意**：**抢占本身并不能改善最低优先级进程的处境**（只会让高优先级进程更快插队），治饥饿只能靠**老化**（`16#46` 动态优先级大题考点）。
- **做题避坑铁律（`18#24, 22#25, 23#29`）**：动手画优先级调度甘特图前，**必须先在题干圈出三件事**：① **优先数方向**（值越小优先级越高如 Unix `nice` 值 `22#25`，还是值越大优先级越高 `23#29`，每年命题都会换！）；② **抢占还是非抢占**；③ **同优先级按什么排**（通常 FCFS）。
  - 基准算例（优先数小优先）：非抢占得 `P1(0–7) → P2(7–11) → P4(11–15) → P3(15–16)`（$\overline{T}=9.50,\; \overline{W}=4.44$ ）；抢占得 `P1(0–2) → P2(2–6) → P4(6–10) → P1(10–15) → P3(15–16)`（$\overline{T}=9.00,\; \overline{W}=4.10,\; \text{平均等待}=5.00,\; \text{平均响应}=3.00$ ）。

**★进阶陷阱：优先级反转（Priority Inversion）**：指高优先级进程被低优先级进程**间接**无限期阻塞的反常现象。形成链条必须凑齐**三方**（只有高低两方不构成反转，因为 $P_L$ 很快就会跑完临界区放锁）：
> 低优先级进程 $P_L$ 先进入临界区持有一把锁 $\to$ 高优先级 $P_H$ 到达并申请同一把锁，被迫阻塞等 $P_L$ 放锁 $\to$ **不需要该锁的中优先级进程 $P_M$ 到达，凭借优先级高于 $P_L$ 直接抢占了 $P_L$ 的 CPU** $\to$ $P_L$ 拿不到 CPU 无法执行完临界区并放锁 $\to$ 最终变成了 $P_M$ 事实上卡死了最高优先级的 $P_H$ ！

| 解决对策 | 核心机制（改动对象） | 触发时机 | 优缺点与工程权衡 |
| --- | --- | --- | --- |
| **优先级继承** (Priority Inheritance) | 临时修改**持锁进程 $P_L$ 的优先级**，使其继承等待该锁的最高优先级进程 $P_H$ 的级别，出临界区释放锁后恢复原值 | **被动触发**（仅当更高优先级进程真的因等锁而阻塞时才提升） | 不影响无关进程，但若存在多锁嵌套则需沿等待链**传递继承**，实现较复杂；**无法防止死锁**，也无法减少阻塞次数 |
| **优先级天花板** (Priority Ceiling) | 预先修改**锁的属性**：为每把锁设定“天花板优先级”（可能访问该锁的所有进程中的最高优先级）；任何进程一旦获锁，**立即**将自身优先级升至天花板 | **主动触发**（拿锁瞬间就提升，不等 $P_H$ 出现） | 需预先静态分析确定每把锁的访问者集合；即使 $P_H$ 未出现也会短暂阻塞无关的 $P_M$ ；但换来“**每个进程最多被阻塞一次**”且**可有效防止交叉持锁引起的死锁** |

#### 4.3.5 ★时间片轮转 (RR)

- **基本规则**：所有就绪进程按到达顺序排成 FIFO 循环队列，每次调度队首运行一个固定大小的**时间片 $q$**。
  - 若 $q$ 内未完成：由**时钟中断**触发调度程序，将其剥夺 CPU 移回**就绪队列队尾**（状态为**运行态 $\to$ 就绪态，绝非阻塞态！** 真题 `17#27` 考点）。
  - 若在 $q$ 用完前提前完成或因 I/O 阻塞：立即调度新队首并**重新启动一个完整的新时间片 $q$**（绝不沿用上一进程剩下的碎片）。
- **核心交易与定量公式**：RR 完全不比较进程长短或优先级，**用周转时间的恶化换取所有就绪进程响应时间的确定性上界**，且**绝不会发生饥饿**。其硬件实现核心依赖三要素：**时钟中断处理程序**（计时扣减剩余片）、**PCB**（记录剩余时间片）与**进程就绪队列**（**阻塞队列不参与时间片轮转实现**，真题 `21#25`）。
  设一次上下文切换总开销（含直接与间接冷启动损失）为 $\delta = \delta_d + \delta_i$ ，就绪队列共有 $n$ 个进程：

$$
\text{CPU 有效利用率} \approx \frac{q}{q + \delta} \quad , \quad \text{响应时间上界} \approx n(q + \delta)
$$

  - **时间片 $q$ 过大**：切换少、开销极低，但响应变慢；当 $q \ge \max S_i$ 时轮转一次也不会发生，**RR 完全退化为 FCFS**！
  - **时间片 $q$ 过小**：响应极快，但 $q/(q+\delta)$ 急剧下降，CPU 大半时间浪费在上下文切换（如 $q=1\;\text{ms},\;\delta=1\;\text{ms}$ 时利用率仅 50%，更遑论算上间接开销后差距放大数倍）。
  - **工程选型原则**：时间片大小主要受**系统响应时间要求、切换开销、就绪进程数目**三因素影响，通常取**略大于一次典型交互所需处理时间**（使多数交互进程在 1 个时间片内完成，如 $10\text{～}100\;\text{ms}$ ，保证 $q \ge 20\delta$ 时损耗 $<5\%$ ）。

> **注意（★手算 RR 的头号分歧点：`24#30`）**：当同一时刻同时发生“**进程时间片耗尽回队尾**”与“**新进程刚好到达入队**”时，不同教材存在两种约定，**动笔前必须确认且全程只用同一种约定**：
> - **约定 A（新到达者先入队，408 多数教材/模拟器首选）**：$t=2$ 时 $P_2$ 先入队，然后时间片耗尽的 $P_1$ 挂到 $P_2$ 后面（队列 `[P2, P1]`），于是 $P_2$ 立刻上 CPU。算例（$q=2$ ）调度序列为 `P1(0-2) P2(2-4) P1(4-6) P3(6-7) P2(7-9) P4(9-11) P1(11-13) P4(13-15) P1(15-16)`，指标：$\overline{T}=9.00,\; \overline{W}=2.38,\; \text{等待}=5.00,\; \text{响应}=1.50$ 。
> - **约定 B（时间片用完者先入队）**：$t=2$ 时 $P_1$ 先回队尾，然后 $P_2$ 再挂其后（队列 `[P1, P2]`），导致 $P_1$ 连跑两个时间片 `0-4`！算例调度序列变为 `P1(0-4) P2(4-6) P1(6-8) P3(8-9) P4(9-11) P2(11-13) P1(13-14) P4(14-16)`，指标：$\overline{T}=10.25,\; \overline{W}=3.13,\; \text{等待}=6.25,\; \text{响应}=2.50$ 。

#### 4.3.6 多级队列调度 (MLQ) 与 ★多级反馈队列调度 (MLFQ)

- **多级队列调度 (MLQ)**：单一队列无法同时兼顾性质迥异的进程，于是将就绪队列拆分为多个独立子队列（如系统进程队列用 FCFS、交互队列用 RR、批处理队列用 FCFS/SJF），各队列间采用“**固定优先级**（高队列不空不调低队列，低队列可能饥饿）”或“**按队列划分时间片比例**”调度。其最大局限（**也是它与 MLFQ 的唯一根本分界线**）在于：**进程被永久性静态分配到某一队列且不能在队列间移动**，必须事先知道进程所属类型。
- **★多级反馈队列调度 (MLFQ)**：既无需事先预知服务时间（像 SJF 那样难实现），也无需预先分类（像 MLQ 那样僵硬），是目前公认综合性能极优的通用调度算法——核心思想是<strong>“先全当成短作业放进第一队列，让进程通过自身运行行为暴露长短并自动降级”</strong>。设计 MLFQ 需确定四要素：**就绪队列数量、各队列优先级、各队列内部算法、进程在队列间迁移条件**（`20#26`）。

**MLFQ 五条标准运行规则（配合 3 级算例 $Q_1: q=1,\; Q_2: q=2,\; Q_3: \text{FCFS}$ ）**：
1. 设置多级就绪队列 $Q_1, Q_2, \dots, Q_k$ ，**队列优先级从高到低（$Q_1$ 最高），而时间片却从小到大（常呈倍增，如 $10, 20, 40\;\text{ms}$ ）**。
   - **为什么要从小到大？** 高优先级给小时间片能让真正的短作业与交互任务快速响应并直接做完退出；能一路降到第 $i$ 级的进程“长作业证据不断累积”，给更大的时间片能显著摊薄切换开销 $q/(q+\delta)$ ！
2. 队列内部一般按 FCFS 排序；**新到达进程一律先放入最高级队列 $Q_1$ 的末尾**。
3. **仅当第 $1$ ～ $(i-1)$ 级队列全部为空时，才允许调度第 $i$ 级队列中的进程**。
4. **耗尽时间片降级**：进程在 $Q_i$ 跑满一个完整时间片 $q_i$ 仍未完成，证明它比本级更长，**降级移至下一级队列 $Q_{i+1}$ 的末尾**（已在最低级 $Q_k$ 则按 RR 回 $Q_k$ 队尾）。
5. **★被高优先级抢占不降级（手算最易错点！`19#27`）**：若某进程正于 $Q_i$ 运行，此时更高优先级队列 $Q_j\;(j<i)$ 有新进程到达（或 I/O 阻塞唤醒进入高级队列），则立即抢占它，**并将其放回原队列 $Q_i$ 的末尾（级别不变！下次调度再给完整 $q_i$ ）**——因为外部抢占只能证明别人来了，无法证明当前进程长短！

> **注意（防饥饿补丁）**：在基本规则下，若高优先级队列不断涌入新进程，沉入底部的长作业**仍然可能发生饥饿**！工程上常外挂<strong>老化（Aging）</strong>补丁（等待超阈值 $\Theta$ 提升一级或周期性全部提回 $Q_1$ ）。若队列数 $k=1$ 或时间片倍率趋近 $1$ 或老化周期过小，MLFQ 都会退化回普通 RR。
>
> **基准算例 MLFQ（$Q_1:q=1, Q_2:q=2, Q_3:\text{FCFS}$）逐步推演**：
> $0\text{～}1$: $P_1$ 在 $Q_1$ 跑满 $1$ 降入 $Q_2$ ；$1\text{～}2$: $P_1$ 在 $Q_2$ 刚跑 $1$ ，$t=2$ 时 $P_2$ 入 $Q_1$ 发生**抢占**，$P_1$ **回 $Q_2$ 队尾（不降级！剩 $5$ ）**；$2\text{～}3$: $P_2$ 在 $Q_1$ 跑满 $1$ 降入 $Q_2$ ；$3\text{～}4$: $P_1$ 在 $Q_2$ 跑 $1$ 又被 $t=4$ 到达的 $P_3$ 抢占再**回 $Q_2$ 队尾**（剩 $4$ ）；$4\text{～}5$: $P_3$ 在 $Q_1$ 跑 $1$ 完成；$5\text{～}6$: $P_4$ 在 $Q_1$ 跑 $1$ 降入 $Q_2$ ；$6\text{～}8$: $P_2$ 在 $Q_2$ 跑满 $2$ 降入 $Q_3$ ；$8\text{～}10$: $P_1$ 在 $Q_2$ 跑满 $2$ 降入 $Q_3$ ；$10\text{～}12$: $P_4$ 在 $Q_2$ 跑满 $2$ 降入 $Q_3$ ；$12\text{～}16$: $Q_3$ 内按 FCFS 依次跑完 $P_2(1)$ 、$P_1(2)$ 、$P_4(1)$ 。本例中四个进程**平均响应时间低至** $0.00$ ，且无需任何事先预测！

<figure class="cpd-figure not-content" id="os-c4-fig-5">
  <svg viewBox="0 0 720 358" role="img" aria-label="同一组基准进程下六种经典调度算法的甘特图与四大评价指标全景对比">
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="330" rx="8"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">同一组基准进程 P1(0,7) P2(2,4) P3(4,1) P4(5,4) 在六种经典调度算法下的甘特图与指标对比</text>
    <!-- 刻度线 x0=116, step=28, x16=564 -->
    <line class="fig-line-dashed" x1="116" y1="50" x2="116" y2="284"/>
    <line class="fig-line-dashed" x1="172" y1="50" x2="172" y2="284"/>
    <line class="fig-line-dashed" x1="228" y1="50" x2="228" y2="284"/>
    <line class="fig-line-dashed" x1="256" y1="50" x2="256" y2="284"/>
    <line class="fig-line-dashed" x1="312" y1="50" x2="312" y2="284"/>
    <line class="fig-line-dashed" x1="340" y1="50" x2="340" y2="284"/>
    <line class="fig-line-dashed" x1="424" y1="50" x2="424" y2="284"/>
    <line class="fig-line-dashed" x1="452" y1="50" x2="452" y2="284"/>
    <line class="fig-line-dashed" x1="564" y1="50" x2="564" y2="284"/>
    <!-- 1. FCFS y=52 -->
    <text class="fig-label" x="26" y="70" font-size="11">1. FCFS</text>
    <rect class="fig-box-blue" x="116" y="52" width="196" height="24" rx="3"/>
    <rect class="fig-box-green" x="312" y="52" width="112" height="24" rx="3"/>
    <rect class="fig-box-orange" x="424" y="52" width="28" height="24" rx="3"/>
    <rect class="fig-box-purple" x="452" y="52" width="112" height="24" rx="3"/>
    <text class="fig-blue" x="214" y="68" font-size="10.5" text-anchor="middle">P1 (0–7)</text>
    <text class="fig-green" x="368" y="68" font-size="10.5" text-anchor="middle">P2 (7–11)</text>
    <text class="fig-orange" x="438" y="68" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-purple" x="508" y="68" font-size="10.5" text-anchor="middle">P4 (12–16)</text>
    <text class="fig-muted" x="574" y="68" font-size="10">T=8.75 W=3.50 R=4.75</text>
    <!-- 2. SJF y=92 -->
    <text class="fig-label" x="26" y="110" font-size="11">2. SJF (非)</text>
    <rect class="fig-box-blue" x="116" y="92" width="196" height="24" rx="3"/>
    <rect class="fig-box-orange" x="312" y="92" width="28" height="24" rx="3"/>
    <rect class="fig-box-green" x="340" y="92" width="112" height="24" rx="3"/>
    <rect class="fig-box-purple" x="452" y="92" width="112" height="24" rx="3"/>
    <text class="fig-blue" x="214" y="108" font-size="10.5" text-anchor="middle">P1 (0–7)</text>
    <text class="fig-orange" x="326" y="108" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-green" x="396" y="108" font-size="10.5" text-anchor="middle">P2 (8–12)</text>
    <text class="fig-purple" x="508" y="108" font-size="10.5" text-anchor="middle">P4 (12–16)</text>
    <text class="fig-muted" x="574" y="108" font-size="10">T=8.00 W=2.56 R=4.00</text>
    <!-- 3. SRTF y=132 -->
    <text class="fig-accent" x="26" y="150" font-size="11">3. SRTF ★</text>
    <rect class="fig-box-blue" x="116" y="132" width="56" height="24" rx="3"/>
    <rect class="fig-box-green" x="172" y="132" width="56" height="24" rx="3"/>
    <rect class="fig-box-orange" x="228" y="132" width="28" height="24" rx="3"/>
    <rect class="fig-box-green" x="256" y="132" width="56" height="24" rx="3"/>
    <rect class="fig-box-purple" x="312" y="132" width="112" height="24" rx="3"/>
    <rect class="fig-box-blue" x="424" y="132" width="140" height="24" rx="3"/>
    <text class="fig-blue" x="144" y="148" font-size="10" text-anchor="middle">P1</text>
    <text class="fig-green" x="200" y="148" font-size="10" text-anchor="middle">P2</text>
    <text class="fig-orange" x="242" y="148" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-green" x="284" y="148" font-size="10" text-anchor="middle">P2</text>
    <text class="fig-purple" x="368" y="148" font-size="10.5" text-anchor="middle">P4 (7–11)</text>
    <text class="fig-blue" x="494" y="148" font-size="10.5" text-anchor="middle">P1 (11–16)</text>
    <text class="fig-accent" x="574" y="148" font-size="10">T=7.00 W=1.51 R=0.50</text>
    <!-- 4. HRRN y=172 -->
    <text class="fig-label" x="26" y="190" font-size="11">4. HRRN (非)</text>
    <rect class="fig-box-blue" x="116" y="172" width="196" height="24" rx="3"/>
    <rect class="fig-box-orange" x="312" y="172" width="28" height="24" rx="3"/>
    <rect class="fig-box-green" x="340" y="172" width="112" height="24" rx="3"/>
    <rect class="fig-box-purple" x="452" y="172" width="112" height="24" rx="3"/>
    <text class="fig-blue" x="214" y="188" font-size="10.5" text-anchor="middle">P1 (0–7)</text>
    <text class="fig-orange" x="326" y="188" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-green" x="396" y="188" font-size="10.5" text-anchor="middle">P2 (8–12)</text>
    <text class="fig-purple" x="508" y="188" font-size="10.5" text-anchor="middle">P4 (12–16)</text>
    <text class="fig-muted" x="574" y="188" font-size="10">T=8.00 W=2.56 R=4.00</text>
    <!-- 5. 优先级(抢) y=212 -->
    <text class="fig-label" x="26" y="230" font-size="11">5. 优先级(抢)</text>
    <rect class="fig-box-blue" x="116" y="212" width="56" height="24" rx="3"/>
    <rect class="fig-box-green" x="172" y="212" width="112" height="24" rx="3"/>
    <rect class="fig-box-purple" x="284" y="212" width="112" height="24" rx="3"/>
    <rect class="fig-box-blue" x="396" y="212" width="140" height="24" rx="3"/>
    <rect class="fig-box-orange" x="536" y="212" width="28" height="24" rx="3"/>
    <text class="fig-blue" x="144" y="228" font-size="10" text-anchor="middle">P1</text>
    <text class="fig-green" x="228" y="228" font-size="10.5" text-anchor="middle">P2 (2–6)</text>
    <text class="fig-purple" x="340" y="228" font-size="10.5" text-anchor="middle">P4 (6–10)</text>
    <text class="fig-blue" x="466" y="228" font-size="10.5" text-anchor="middle">P1 (10–15)</text>
    <text class="fig-orange" x="550" y="228" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-muted" x="574" y="228" font-size="10">T=9.00 W=4.10 R=3.00</text>
    <!-- 6. RR(q=2) y=252 -->
    <text class="fig-label" x="26" y="270" font-size="11">6. RR (q=2)</text>
    <rect class="fig-box-blue" x="116" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-green" x="172" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-blue" x="228" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-orange" x="284" y="252" width="28" height="24" rx="3"/>
    <rect class="fig-box-green" x="312" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-purple" x="368" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-blue" x="424" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-purple" x="480" y="252" width="56" height="24" rx="3"/>
    <rect class="fig-box-blue" x="536" y="252" width="28" height="24" rx="3"/>
    <text class="fig-blue" x="144" y="268" font-size="10" text-anchor="middle">P1</text>
    <text class="fig-green" x="200" y="268" font-size="10" text-anchor="middle">P2</text>
    <text class="fig-blue" x="256" y="268" font-size="10" text-anchor="middle">P1</text>
    <text class="fig-orange" x="298" y="268" font-size="9.5" text-anchor="middle">P3</text>
    <text class="fig-green" x="340" y="268" font-size="10" text-anchor="middle">P2</text>
    <text class="fig-purple" x="396" y="268" font-size="10" text-anchor="middle">P4</text>
    <text class="fig-blue" x="452" y="268" font-size="10" text-anchor="middle">P1</text>
    <text class="fig-purple" x="508" y="268" font-size="10" text-anchor="middle">P4</text>
    <text class="fig-blue" x="550" y="268" font-size="9.5" text-anchor="middle">P1</text>
    <text class="fig-muted" x="574" y="268" font-size="10">T=9.00 W=2.38 R=1.50</text>
    <!-- 刻度文字 -->
    <text class="fig-muted" x="116" y="302" font-size="10" text-anchor="middle">0</text>
    <text class="fig-muted" x="172" y="302" font-size="10" text-anchor="middle">2</text>
    <text class="fig-muted" x="228" y="302" font-size="10" text-anchor="middle">4</text>
    <text class="fig-muted" x="256" y="302" font-size="10" text-anchor="middle">5</text>
    <text class="fig-muted" x="312" y="302" font-size="10" text-anchor="middle">7</text>
    <text class="fig-muted" x="340" y="302" font-size="10" text-anchor="middle">8</text>
    <text class="fig-muted" x="424" y="302" font-size="10" text-anchor="middle">11</text>
    <text class="fig-muted" x="452" y="302" font-size="10" text-anchor="middle">12</text>
    <text class="fig-muted" x="564" y="302" font-size="10" text-anchor="middle">16</text>
    <text class="fig-label" x="360" y="330" font-size="10.8" text-anchor="middle">结论：SRTF 平均周转与带权最优；RR(约定A:新 arrival 先入队)大幅压低响应时间；总完工时刻只要 CPU 不白闲均恒为 16</text>
  </svg>
  <figcaption>图 4-5　同一组进程下六大调度算法甘特图（Gantt）与平均周转（T）、带权周转（W）、平均响应（R）全景对照</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c4-fig-6">
  <svg viewBox="0 0 720 248" role="img" aria-label="SJF 指数加权移动平均预测跟随滞后曲线与 RR 时间片大小双边界权衡曲线">
    <defs>
      <marker id="os-c4-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左图：指数移动平均预测 -->
    <rect class="fig-box-subtle" x="16" y="14" width="336" height="220" rx="8"/>
    <text class="fig-title" x="184" y="34" font-size="11.5" text-anchor="middle">SJF 指数加权移动平均 τ_(n+1) = 0.5t_n + 0.5τ_n</text>
    <line class="fig-line" x1="52" y1="184" x2="332" y2="184" marker-end="url(#os-c4-arr-6)"/>
    <line class="fig-line" x1="52" y1="184" x2="52" y2="48" marker-end="url(#os-c4-arr-6)"/>
    <!-- 网格与数值点：n=1..7, x=72+38×(i-1), y=184 - val×6.6 -->
    <polyline class="fig-line" stroke="var(--sl-color-blue)" stroke-width="2" fill="none" points="72,144 110,158 148,144 186,158 224,98 262,98 300,98"/>
    <polyline class="fig-line" stroke="var(--sl-color-orange)" stroke-width="2" stroke-dasharray="5 3" fill="none" points="72,118 110,131 148,144 186,144 224,151 262,125 300,111"/>
    <circle class="fig-dot" cx="224" cy="98" r="3"/>
    <circle class="fig-dot" cx="224" cy="151" r="3"/>
    <text class="fig-blue" x="78" y="54" font-size="9.5">── 实测值 t_n (6,4,6,4 → 13)</text>
    <text class="fig-orange" x="78" y="69" font-size="9.5">- - - 预测值 τ_n (抗噪但跟随滞后)</text>
    <text class="fig-muted" x="42" y="102" font-size="9.5" text-anchor="end">13</text>
    <text class="fig-muted" x="42" y="148" font-size="9.5" text-anchor="end">6</text>
    <text class="fig-muted" x="72" y="198" font-size="9.5" text-anchor="middle">1</text>
    <text class="fig-muted" x="186" y="198" font-size="9.5" text-anchor="middle">4</text>
    <text class="fig-muted" x="224" y="198" font-size="9.5" text-anchor="middle">5</text>
    <text class="fig-muted" x="300" y="198" font-size="9.5" text-anchor="middle">7</text>
    <text class="fig-label" x="184" y="218" font-size="10.2" text-anchor="middle">步数 n（第 5 次突变时预测只能逐步逼近）</text>
    <!-- 右图：RR 时间片大小权衡 -->
    <rect class="fig-box-subtle" x="368" y="14" width="336" height="220" rx="8"/>
    <text class="fig-title" x="536" y="34" font-size="11.5" text-anchor="middle">RR 时间片 q 大小与效率 / 响应的双边界权衡</text>
    <line class="fig-line" x1="404" y1="184" x2="684" y2="184" marker-end="url(#os-c4-arr-6)"/>
    <line class="fig-line" x1="404" y1="184" x2="404" y2="48" marker-end="url(#os-c4-arr-6)"/>
    <!-- 推荐区间阴影框 -->
    <rect class="fig-box-green" x="514" y="68" width="76" height="112" rx="4"/>
    <!-- 切换开销占比曲线（随q大而降）与响应时间曲线（随q大线性升） -->
    <path class="fig-line" stroke="var(--sl-color-red)" stroke-width="2" fill="none" d="M 414 70 C 442 146, 504 172, 664 179"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" stroke-width="2" x1="414" y1="176" x2="664" y2="70"/>
    <line class="fig-line-dashed" x1="612" y1="68" x2="612" y2="184"/>
    <text class="fig-red" x="416" y="60" font-size="9.8" text-anchor="start">切换损耗 δ/(q+δ)</text>
    <text class="fig-purple" x="678" y="60" font-size="9.8" text-anchor="end">响应上界 n(q+δ)</text>
    <text class="fig-green" x="552" y="138" font-size="10.5" text-anchor="middle">推荐区间</text>
    <text class="fig-muted" x="552" y="153" font-size="9.5" text-anchor="middle">略大于典型交互</text>
    <text class="fig-muted" x="618" y="140" font-size="9.3" text-anchor="start">q ≥ max S_i</text>
    <text class="fig-muted" x="618" y="154" font-size="9.3" text-anchor="start">退化为 FCFS</text>
    <text class="fig-label" x="536" y="218" font-size="10.2" text-anchor="middle">时间片大小 q（过小切换爆炸 · 过大退化为 FCFS）</text>
  </svg>
  <figcaption>图 4-6　SJF 预测值跟随滞后规律与时间片轮转（RR）时间片大小的效率-响应双边界制约</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c4-fig-7">
  <svg viewBox="0 0 720 274" role="img" aria-label="优先级反转三方阻塞链形成与优先级继承及天花板破局对比">
    <defs>
      <marker id="os-c4-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 上区：三方反转过程 -->
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="122" rx="8"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">优先级反转（必须凑齐 P_L、P_H、P_M 三方才构成间接无限期阻塞）</text>
    <line class="fig-line" x1="34" y1="92" x2="686" y2="92" marker-end="url(#os-c4-arr-7)"/>
    <rect class="fig-box-green" x="48" y="64" width="108" height="28" rx="4"/>
    <rect class="fig-box-red" x="156" y="64" width="114" height="28" rx="4"/>
    <rect class="fig-box-orange" x="270" y="64" width="212" height="28" rx="4"/>
    <rect class="fig-box-green" x="482" y="64" width="76" height="28" rx="4"/>
    <rect class="fig-box-red" x="558" y="64" width="114" height="28" rx="4"/>
    <text class="fig-green" x="102" y="82" font-size="10.5" text-anchor="middle">P_L 拿锁运行</text>
    <text class="fig-red" x="213" y="82" font-size="10.5" text-anchor="middle">P_H 要锁 → 阻塞</text>
    <text class="fig-orange" x="376" y="82" font-size="10.5" text-anchor="middle">P_M(不需此锁)抢占 P_L 并长跑 ★</text>
    <text class="fig-green" x="520" y="82" font-size="10.5" text-anchor="middle">P_L 放锁</text>
    <text class="fig-red" x="615" y="82" font-size="10.5" text-anchor="middle">P_H 终于运行</text>
    <text class="fig-muted" x="360" y="118" font-size="10.5" text-anchor="middle">因果链：P_M 优先级虽低于 P_H，却因抢占了持锁的 P_L，间接将最高优先级 P_H 长期阻塞在锁外</text>
    <!-- 下区：两大对策 -->
    <rect class="fig-box-blue" x="16" y="148" width="336" height="112" rx="8"/>
    <rect class="fig-box-purple" x="368" y="148" width="336" height="112" rx="8"/>
    <text class="fig-blue" x="184" y="170" font-size="12" text-anchor="middle">对策一：优先级继承（被动 · 改进程属性）</text>
    <text class="fig-label" x="32" y="192" font-size="10.8">• 触发：仅当 P_H 因等锁阻塞时，P_L 临时继承 H 级</text>
    <text class="fig-label" x="32" y="212" font-size="10.8">• 效果：P_M 抢不动 P_L，促使 P_L 尽快出临界区放锁</text>
    <text class="fig-muted" x="32" y="234" font-size="10">• 局限：需处理传递继承链；不能防止死锁与多重阻塞</text>
    <text class="fig-purple" x="536" y="170" font-size="12" text-anchor="middle">对策二：优先级天花板（主动 · 改锁属性）</text>
    <text class="fig-label" x="384" y="192" font-size="10.8">• 触发：进程一拿到锁，立刻升至该锁预设最高访问优先级</text>
    <text class="fig-label" x="384" y="212" font-size="10.8">• 效果：全程免疫 P_M 抢占，每进程最多阻塞 1 次且防死锁</text>
    <text class="fig-muted" x="384" y="234" font-size="10">• 局限：需静态预知用锁进程；P_H 未到达时也会拦住 P_M</text>
  </svg>
  <figcaption>图 4-7　优先级反转三方阻塞链形成过程及优先级继承与天花板机制对比</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c4-fig-8">
  <svg viewBox="0 0 720 334" role="img" aria-label="多级反馈队列三级结构降级规则与被高优先级抢占不降级对比图">
    <defs>
      <marker id="os-c4-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="238" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="262" width="688" height="58" rx="6"/>
    <!-- 队列框 -->
    <rect class="fig-box-green" x="128" y="48" width="242" height="42" rx="5"/>
    <rect class="fig-box-blue" x="128" y="110" width="242" height="42" rx="5"/>
    <rect class="fig-box-purple" x="128" y="172" width="242" height="42" rx="5"/>
    <!-- CPU 框 -->
    <rect class="fig-box-accent" x="458" y="96" width="128" height="68" rx="6"/>
    <!-- 队列连线 -->
    <line class="fig-line-accent" x1="36" y1="69" x2="124" y2="69" stroke-width="1.8" marker-end="url(#os-c4-arr-8)"/>
    <line class="fig-line" x1="370" y1="69" x2="456" y2="112" stroke-width="1.5" marker-end="url(#os-c4-arr-8)"/>
    <line class="fig-line" x1="370" y1="131" x2="456" y2="131" stroke-width="1.5" marker-end="url(#os-c4-arr-8)"/>
    <line class="fig-line" x1="370" y1="193" x2="456" y2="150" stroke-width="1.5" marker-end="url(#os-c4-arr-8)"/>
    <!-- 时间片用完降级虚线/实线 -->
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 522 96 L 522 62 L 414 62 L 414 120 L 372 120" fill="none" stroke-width="1.4" marker-end="url(#os-c4-arr-8)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 522 166 L 522 193 L 374 193" fill="none" stroke-width="1.4" marker-end="url(#os-c4-arr-8)"/>
    <!-- 被抢占回原队列（走下方安全空道） -->
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 488 166 L 488 238 L 414 238 L 414 144 L 372 144" fill="none" stroke-width="1.4" marker-end="url(#os-c4-arr-8)"/>
    <!-- 老化提升 -->
    <path class="fig-line-dashed" stroke="var(--sl-color-green)" d="M 124 193 L 78 193 L 78 69 L 124 69" fill="none" stroke-width="1.5" marker-end="url(#os-c4-arr-8)"/>
    <!-- 结束输出 -->
    <line class="fig-line" x1="586" y1="130" x2="646" y2="130" stroke-width="1.5" marker-end="url(#os-c4-arr-8)"/>
    <rect class="fig-box" x="66" y="96" width="24" height="76" rx="3"/>
    <rect class="fig-box" x="424" y="53" width="88" height="18" rx="3"/>
    <rect class="fig-box" x="280" y="228" width="176" height="18" rx="3"/>
    <!-- 文字 -->
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">多级反馈队列（MLFQ）三级队列晋升/降级与抢占流转模型</text>
    <text class="fig-label" x="78" y="59" font-size="10.5" text-anchor="middle">新进程入 Q1</text>
    <text class="fig-green" x="249" y="66" font-size="11.5" text-anchor="middle">Q1 (最高优先级 · q1 = 10 ms)</text>
    <text class="fig-muted" x="249" y="82" font-size="9.8" text-anchor="middle">FCFS · 短作业与交互任务快速完成</text>
    <text class="fig-blue" x="249" y="128" font-size="11.5" text-anchor="middle">Q2 (中优先级 · q2 = 20 ms)</text>
    <text class="fig-muted" x="249" y="144" font-size="9.8" text-anchor="middle">仅当 Q1 全空时调度</text>
    <text class="fig-purple" x="249" y="190" font-size="11.5" text-anchor="middle">Q3 (最低优先级 · q3 = 40 ms / RR)</text>
    <text class="fig-muted" x="249" y="206" font-size="9.8" text-anchor="middle">时间片大以摊薄切换开销</text>
    <text class="fig-accent" x="522" y="126" font-size="12" text-anchor="middle">CPU 执行</text>
    <text class="fig-muted" x="522" y="144" font-size="10" text-anchor="middle">抢占优先级调度</text>
    <text class="fig-label" x="676" y="134" font-size="10.5" text-anchor="middle">完成退出</text>
    <text class="fig-orange" x="468" y="65" font-size="9.5" text-anchor="middle">时间片用完降级</text>
    <text class="fig-orange" x="468" y="187" font-size="9.8" text-anchor="middle">用完 q2 降级</text>
    <text class="fig-red" x="368" y="241" font-size="9.8" text-anchor="middle">★ 被 Q1 抢占：回原 Q2 队尾</text>
    <text class="fig-green" x="78" y="134" font-size="9.8" text-anchor="middle" writing-mode="tb">老化防饥饿</text>
    <!-- 底部注释框 -->
    <text class="fig-accent" x="360" y="282" font-size="11" text-anchor="middle">★ 核心判别：时间片用完证明长短 → 降入下一级；被高级队列新进程抢占是外部原因 → 回原队列队尾（下次重获完整 q_i）</text>
    <text class="fig-muted" x="360" y="302" font-size="10.2" text-anchor="middle">设计四要素（20#26）：队列数量 + 各队列优先级 + 各队列内部调度算法 + 进程在队列间的迁移条件</text>
  </svg>
  <figcaption>图 4-8　多级反馈队列调度（MLFQ）运行全规则、时间片倍增结构与“降级 vs 抢占”关键分支</figcaption>
</figure>

#### 4.3.7 基于公平原则的调度：公平分享、彩票调度与 Linux CFS 思路

传统算法承诺“执行**次序**”（先来、短作业、高优先），而公平类调度器改为直接承诺“CPU 时间**份额**”。

1. **保证调度（对进程公平）**：为系统中的 $n$ 个进程各承诺获得约 $1/n$ 的 CPU 时间。运行时跟踪自创建以来的已获 CPU 时间，并计算应获时间 $(t - t_{\text{创建}})/n$ ，每次选择**公平比率（实际时间 $\div$ 应得时间）最小**的进程投入运行（直至其比率超过最接近它的进程）。
   - **精妙机制**：分母随时间单调增大，故长期未跑的进程比率自动跌破 $1$ 并不断减小，**无需外挂老化补丁即天然不饥饿**（老化已内建进比较键）。
2. **公平分享调度（对用户公平）**：保证调度若遇用户 A 开 $4$ 个进程而用户 B 仅开 $1$ 个进程，用户 A 将夺走 $80\%$ 的 CPU——**对进程公平并不等于对用户公平**！公平分享改以**用户**为分配单元，设周期 $L = \sum w_u$ ，每周期用户 $u$ 获得 $w_u$ 个时间片，用户内部各进程跨周期连续做 RR（例如权重 $2:1$ 且用户 1 有 A,B,C,D 四个进程、用户 2 有 E，序列为 `A B E C D E ...`）。
3. **彩票调度（Lottery Scheduling，比例份额思想）**：为系统发行若干张“彩票”，进程掌握的彩票数与其应得份额成正比（例如 A 占 75 张、B 占 25 张）。每次调度随机抽取一张中奖号码，持该彩票的进程上 CPU。支持**彩票转让**（客户进程将彩票临时交给服务端加速处理）、**彩票货币**与**通胀**，实现极简、无需全局复杂状态，但在短周期内存在随机波动（其确定性改进版为**步长调度 Stride Scheduling**）。
4. **Linux CFS（Completely Fair Scheduler，完全公平调度器）**：放弃传统固定时间片，为每个进程引入**虚拟运行时间** `vruntime` 。进程实际在 CPU 运行 $\Delta t$ 后，按其优先级权重 $w_i$ 累计虚拟运行时间 $\Delta \text{vruntime}_i = \Delta t \times \frac{\text{NICE\_0\_LOAD}}{w_i}$ ：
   - 优先级高（`nice` 值小、权重 $w_i$ 大）的进程，`vruntime` **涨得慢**；普通进程涨得快。
   - 所有可运行进程按 `vruntime` 从小到大组织为一棵**红黑树（Red-Black Tree）**，**调度器每次只需 $O(1)$ 直接拾取最左下角节点（`rb_leftmost`，即当前 `vruntime` 最小、被系统亏欠最多的进程）投入运行**，切换或更新后以 $O(\log n)$ 重新插回红黑树，既兼顾对权重敏感的公平性，又天然杜绝饥饿。

<figure class="cpd-figure not-content" id="os-c4-fig-9">
  <svg viewBox="0 0 720 272" role="img" aria-label="公平原则调度演变与 Linux CFS 红黑树虚拟运行时间调度机制图">
    <defs>
      <marker id="os-c4-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左栏：保证/公平分享/彩票思路 -->
    <rect class="fig-box-subtle" x="16" y="14" width="320" height="244" rx="8"/>
    <text class="fig-title" x="176" y="34" font-size="11.5" text-anchor="middle">份额公平家族：从“承诺次序”转向“承诺份额”</text>
    <rect class="fig-box-blue" x="30" y="48" width="292" height="58" rx="5"/>
    <rect class="fig-box-green" x="30" y="118" width="292" height="58" rx="5"/>
    <rect class="fig-box-orange" x="30" y="188" width="292" height="58" rx="5"/>
    <text class="fig-blue" x="42" y="67" font-size="11">① 保证调度（按进程：公平比率 = 实得 / 应得）</text>
    <text class="fig-muted" x="42" y="85" font-size="9.8">分母随时间自增 → 比率跌破 1 必被选中，天然免老化</text>
    <text class="fig-muted" x="42" y="99" font-size="9.5">缺陷：用户 A 开 4 进程、用户 B 开 1 进程时 A 拿 80%</text>
    <text class="fig-green" x="42" y="137" font-size="11">② 公平分享调度（按用户加权 RR）</text>
    <text class="fig-muted" x="42" y="155" font-size="9.8">周期 L = ∑w_u；用户份额与所开进程数无关</text>
    <text class="fig-muted" x="42" y="169" font-size="9.5">例：权重 2:1 且 U1={A..D}, U2={E} → A B E C D E…</text>
    <text class="fig-orange" x="42" y="207" font-size="11">③ 彩票调度（概率比例份额）</text>
    <text class="fig-muted" x="42" y="225" font-size="9.8">75 张 vs 25 张彩票随机抽奖；支持转让与货币转换</text>
    <text class="fig-muted" x="42" y="239" font-size="9.5">确定性步长改进版按 步长 ∝ 1/票数 选最小通行证</text>
    <!-- 右栏：Linux CFS 红黑树 -->
    <rect class="fig-box-subtle" x="350" y="14" width="354" height="244" rx="8"/>
    <text class="fig-title" x="527" y="34" font-size="11.5" text-anchor="middle">Linux CFS 完全公平调度器（红黑树按 vruntime 排序）</text>
    <!-- 树枝连线 -->
    <line class="fig-line" x1="527" y1="78" x2="452" y2="112"/>
    <line class="fig-line" x1="527" y1="78" x2="602" y2="112"/>
    <line class="fig-line" x1="452" y1="138" x2="404" y2="168"/>
    <line class="fig-line" x1="452" y1="138" x2="496" y2="168"/>
    <line class="fig-line" x1="602" y1="138" x2="648" y2="168"/>
    <!-- 从最左节点到CPU运行回插 -->
    <path class="fig-line-accent" d="M 404 198 L 404 226 L 467 226" fill="none" stroke-width="1.6" marker-end="url(#os-c4-arr-9)"/>
    <!-- 树节点 -->
    <rect class="fig-box" x="488" y="52" width="78" height="28" rx="14"/>
    <rect class="fig-box" x="414" y="110" width="76" height="28" rx="14"/>
    <rect class="fig-box" x="564" y="110" width="76" height="28" rx="14"/>
    <rect class="fig-box-green" x="364" y="164" width="80" height="34" rx="17"/>
    <rect class="fig-box" x="458" y="166" width="76" height="28" rx="14"/>
    <rect class="fig-box" x="610" y="166" width="76" height="28" rx="14"/>
    <text class="fig-label" x="527" y="70" font-size="10.5" text-anchor="middle">vr = 25</text>
    <text class="fig-label" x="452" y="128" font-size="10.5" text-anchor="middle">vr = 14</text>
    <text class="fig-label" x="602" y="128" font-size="10.5" text-anchor="middle">vr = 38</text>
    <text class="fig-green" x="404" y="179" font-size="10.5" text-anchor="middle">vr = 6 ★</text>
    <text class="fig-muted" x="404" y="192" font-size="9" text-anchor="middle">rb_leftmost</text>
    <text class="fig-label" x="496" y="184" font-size="10.5" text-anchor="middle">vr = 19</text>
    <text class="fig-label" x="648" y="184" font-size="10.5" text-anchor="middle">vr = 45</text>
    <!-- 说明 -->
    <rect class="fig-box-accent" x="470" y="206" width="222" height="40" rx="5"/>
    <text class="fig-accent" x="581" y="222" font-size="10" text-anchor="middle">O(1) 取最左节点运行 → 涨 vruntime</text>
    <text class="fig-muted" x="581" y="238" font-size="9.5" text-anchor="middle">nice 小(权重大)者 vr 涨得慢，多拿 CPU</text>
  </svg>
  <figcaption>图 4-9　基于公平原则的算法家族（保证/公平分享/彩票）与 Linux CFS 红黑树调度思路</figcaption>
</figure>

#### 4.3.8 多处理机调度（2026 大纲二(二)5）

当系统拥有多个 CPU 核心时，架构首先划分出两条分界线：**对称多处理（SMP）vs 非对称多处理（主从式）**（非对称由一台主处理机包揽全部调度，面临**系统瓶颈**与**单点失效**致命隐患，现代多核普遍采用 SMP）；**UMA（均匀访存）vs NUMA（非均匀访存）**（NUMA 下跨节点访存存在高昂的远程延迟）。

1. **多处理机调度方式的演进链**：**自调度**（共享公共就绪队列，简单但锁竞争成瓶颈、Cache 命中率低、合作线程难同时跑；值得一提的是，自调度下线程粒度的 FCFS 性能意外优于复杂优先级算法） $\to$ **成组调度**（将互相合作的一组线程同时分派到一组核心上同时运行，大幅降低切换与阻塞；按“总线程数比例”分时比“按应用均分”处理机浪费率更低） $\to$ **专用处理机分配**（每线程独占一核，零切换但利用率受限，建议并发总线程数不超过物理核数） $\to$ **动态调度**（进程执行期动态调整线程数，OS 与应用协同决策）。
2. **队列组织与两大对抗力量**：
   - **全局队列 vs 每核私有队列**：全局队列天然负载均衡但存在严酷互斥锁竞争、且完全破坏 Cache 亲和性；每核私有队列消除了抢锁并保持亲和性，但需额外引入跨核 **Push（忙核推走）/ Pull（闲核拉取）** 负载均衡。
   - **★处理器亲和性（CPU Affinity） vs 负载均衡（Load Balancing）**：前者希望线程**留在上次运行的核心**，从而保留 **L1/L2 Cache 热数据、TLB 页表项拷贝以及 NUMA 本地内存就近性**；后者希望把长队列的线程**迁到空闲核心**。迁移划算的充要权衡准则为：**迁移省下的排队等待收益 $>$ Cache 重建 $+$ TLB 重填代价（NUMA 下还需加上远程访存延迟增量）**。
3. **★多核调度与同步的耦合陷阱**：单处理机上自旋锁无意义，而在多核 SMP 下，若在核 A 上**持有自旋锁的线程因时间片到或高优先级抢占而被调度换出**，那么在核 B、核 C 上忙等该锁的线程将会**成倍地满负荷空转烧掉整个时间片**，直到持锁者重新被调度！应对办法：调度层用成组调度/专用分配；同步层则在**自旋锁保护的内核临界区内严格禁止抢占**。

<figure class="cpd-figure not-content" id="os-c4-fig-10">
  <svg viewBox="0 0 720 264" role="img" aria-label="SMP 多处理机私有队列下的 CPU 亲和性与负载均衡迁移权衡图">
    <defs>
      <marker id="os-c4-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 核0 -->
    <rect class="fig-box-subtle" x="16" y="14" width="246" height="178" rx="8"/>
    <rect class="fig-box-blue" x="30" y="46" width="218" height="36" rx="5"/>
    <rect class="fig-box-orange" x="30" y="92" width="218" height="44" rx="5"/>
    <rect class="fig-box-green" x="30" y="146" width="218" height="34" rx="5"/>
    <!-- 核1 -->
    <rect class="fig-box-subtle" x="458" y="14" width="246" height="178" rx="8"/>
    <rect class="fig-box-blue" x="472" y="46" width="218" height="36" rx="5"/>
    <rect class="fig-box" x="472" y="92" width="218" height="44" rx="5"/>
    <rect class="fig-box-green" x="472" y="146" width="218" height="34" rx="5"/>
    <!-- 中间权衡连线 -->
    <line class="fig-line-accent" x1="252" y1="106" x2="468" y2="106" stroke-width="1.8" marker-end="url(#os-c4-arr-10)"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-green)" x1="468" y1="126" x2="252" y2="126" stroke-width="1.6" marker-end="url(#os-c4-arr-10)"/>
    <rect class="fig-box" x="276" y="88" width="168" height="48" rx="5"/>
    <!-- 底部提示框 -->
    <rect class="fig-box-red" x="16" y="202" width="688" height="48" rx="6"/>
    <!-- 文字 -->
    <text class="fig-title" x="139" y="34" font-size="11.5" text-anchor="middle">Core 0（过载私有队列）</text>
    <text class="fig-blue" x="139" y="68" font-size="11" text-anchor="middle">正在运行：T1（持自旋锁禁用抢占）</text>
    <text class="fig-orange" x="139" y="110" font-size="11" text-anchor="middle">就绪队列：[ T2, T3, T4, T5 ]</text>
    <text class="fig-muted" x="139" y="126" font-size="9.8" text-anchor="middle">排队拥挤，等待时间飙升</text>
    <text class="fig-green" x="139" y="167" font-size="10" text-anchor="middle">L1/L2 Cache + TLB (含 T2 热数据)</text>
    <text class="fig-title" x="581" y="34" font-size="11.5" text-anchor="middle">Core 1（空闲私有队列）</text>
    <text class="fig-blue" x="581" y="68" font-size="11" text-anchor="middle">正在运行：Idle 闲逛进程</text>
    <text class="fig-muted" x="581" y="118" font-size="11" text-anchor="middle">就绪队列：[ 空 ]</text>
    <text class="fig-green" x="581" y="167" font-size="10.8" text-anchor="middle">本地 Cache + TLB（无 T2 映射）</text>
    <text class="fig-accent" x="360" y="106" font-size="10.2" text-anchor="middle">Push 推 / Pull 拉负载均衡</text>
    <text class="fig-green" x="360" y="126" font-size="10.2" text-anchor="middle">处理器亲和性拉力（尽量别动）</text>
    <text class="fig-red" x="360" y="222" font-size="11" text-anchor="middle">★ 迁移决策：节省等待收益 &gt; Cache 重建 + TLB 重填 (+ NUMA 远程访存增量) 才迁；</text>
    <text class="fig-muted" x="360" y="239" font-size="10" text-anchor="middle">多核同步铁律：持自旋锁线程在临界区内禁止被抢占换出，否则其他等待核心会成倍满载空转</text>
  </svg>
  <figcaption>图 4-10　SMP 每核私有队列下的处理器亲和性与 Push/Pull 负载均衡迁移权衡（含自旋锁禁抢占防空转）</figcaption>
</figure>

#### 4.3.9 ★处理机调度算法全景对比汇总表

| 算法 | 抢占性 | 是否饥饿 | 需预知服务时间 | 核心优点 | 主要缺点与考法陷阱 | 典型适用场景 |
| --- | --- | --- | --- | --- | --- | --- |
| **FCFS** | **仅非抢占** | 不会 | 否 | 实现最简、规则公平 | **护航效应**（I/O 设备连带闲置）；对短作业/I/O 密集不利 | 批处理作业调度、MLQ 子队列 |
| **SJF (非)** | 非抢占 | **会**（长作业） | **是**（或预测） | 同时到达时平均等待/周转最小 | 到达时间不同时**非最优**；对长作业不公平；不能保紧迫性 | 批处理（短作业为主） |
| **SRTF (抢)** | **抢占** | **会**（长作业） | **是** | **无前提**下平均等待/周转全局最优 | 切换开销增；无法预知服务时间；长作业饥饿；抢占查到达点 | 理论性能标杆 |
| **HRRN** | **仅非抢占** | 不会（不过载时） | **是** | 折中 FCFS 与 SJF；$R$ 即期望带权周转；不饥饿 | 每次调度需遍历重算 $R$ ；仍需预知时间（`09#24, 11#23`） | 批处理系统 |
| **优先级调度** | 皆可 | 静态会 / 动态(老化)不会 | 否 | 灵活区分紧迫度；支持实时需求 | **优先级反转**（三方条件）；务必审题方向（`22#25` vs `23#29`） | 通用系统、实时系统（抢占） |
| **RR** | **抢占**（时钟） | 不会 | 否 | 公平、**响应时间有上界** $n(q+\delta)$ | 切换开销大；$q \ge \max S_i$ 退化 FCFS；留意入队冲突约定（`24#30`） | **分时系统、交互式终端** |
| **MLQ** | 队列间视策略 | 固定优先级会 | 需预知类型 | 不同队列用不同最优算法；选人 $O(k)$ | 进程**不可在队列间移动**，必须事先静态分类 | 进程类别固定分明的系统 |
| **MLFQ** | **抢占** | **会**（需靠老化补丁） | **否** | 不需预知时间自动识别长短；响应极佳 | 实现复杂；**被抢占回原队尾不降级**，用完 $q_i$ 才降级（`19#27`） | **现代通用操作系统主流模型** |
| **保证 / 公平分享** | 抢占 | 不会（内建老化） | 否 | 保证时间份额而非仅次序；抗多开进程作弊 | 比率计算与维护开销较大 | 多用户公平共享系统 |
| **Linux CFS** | 抢占 | 不会 | 否 | 红黑树 $O(1)$ 取最小 `vruntime`；按权重平滑分配 | 极端频繁短交互需微调延迟与唤醒抢占 | 现代 Linux 内核默认调度器 |

---

### 4.4 死锁的基本概念、成因与最小资源数定理

#### 4.4.1 死锁定义与死锁 / 饥饿 / 死循环辨析 ★

**死锁（Deadlock）定义**：如果一组并发进程中的**每一个进程都在等待仅由该组进程中的其他进程才能引发的事件**（通常是等待对方所持有的资源释放，或等待对方发送通信消息），且在未得到所需资源之前均不释放自己已持有的资源，那么这组进程就处于死锁状态，所有相关进程将永久阻塞而无法向前推进。

> **★考点（资源分类与致死前提）**：
> - **可抢占性资源**（如 **CPU、主存**）**不会引起死锁**——因为操作系统可以直接把它们从当前持有者强行剥夺转分他人。
> - 会引起死锁的是**不可抢占性资源**（打印机、刻录机、磁带机、打开的文件锁）以及**可消耗性资源**（进程间通信的消息、信号量令牌）。

在考研选择题中，**死锁、饥饿、死循环**常放在一起考查辨析，三者皆表现为程序无法正常前进，但成因、进程状态与责任归属截然不同：

| 辨析维度 | 死锁（Deadlock） | 饥饿（Starvation） | 死循环（Endless Loop） |
| --- | --- | --- | --- |
| **涉及进程数** | **一组并发进程（至少 2 个）** | 单个进程即可发生 | 单个进程 |
| **进程所处状态** | 全部处于**阻塞态** | 多处于**就绪态**（或阻塞态，总排不上） | 处于**运行态**（或就绪-运行轮转） |
| **是否占用 CPU** | **不占用 CPU**（已全部阻塞） | **不占用 CPU**（轮不到自己） | **占满 CPU**（一直在执行空转代码） |
| **等待环路特征** | 资源分配图中**必存在循环等待环** | **无等待环** | **无等待环** |
| **直接成因与责任方** | OS 资源分配冲突（互持互等不可抢占资源） | OS 调度/分配策略不公（如 SJF 遇连续短作业、静态低优先级、读者优先下的写者） | **用户程序自身逻辑错误**（循环跳出条件永不为假） |
| **OS 能否检测发现** | **能**（可通过死锁检测算法/资源分配图判定） | 难（“等多久算饿死”无客观统一阈值） | **不能**（OS 无法区分是有意服务循环还是 Bug） |

<figure class="cpd-figure not-content" id="os-c4-fig-11">
  <svg viewBox="0 0 720 228" role="img" aria-label="死锁、饥饿与死循环三维特征辨析对比图">
    <rect class="fig-box-red" x="16" y="14" width="220" height="200" rx="8"/>
    <rect class="fig-box-orange" x="250" y="14" width="220" height="200" rx="8"/>
    <rect class="fig-box-purple" x="484" y="14" width="220" height="200" rx="8"/>
    <!-- 死锁 -->
    <text class="fig-red" x="126" y="38" font-size="12.5" text-anchor="middle">① 死锁 (Deadlock)</text>
    <line class="fig-divider" x1="30" y1="48" x2="222" y2="48"/>
    <text class="fig-label" x="30" y="70" font-size="11">• 进程数：至少 2 个进程</text>
    <text class="fig-label" x="30" y="92" font-size="11">• 状态：全部陷入阻塞态</text>
    <text class="fig-label" x="30" y="114" font-size="11">• 占 CPU：否（完全释放 CPU）</text>
    <text class="fig-label" x="30" y="136" font-size="11">• 依赖环：存在循环等待链 ★</text>
    <text class="fig-label" x="30" y="158" font-size="11">• OS 检测：可以精确检测</text>
    <text class="fig-muted" x="30" y="186" font-size="10">例：P1 持 R1 等 R2，P2 持 R2 等 R1</text>
    <text class="fig-muted" x="30" y="201" font-size="10">成因：资源竞争与推进顺序不当</text>
    <!-- 饥饿 -->
    <text class="fig-orange" x="360" y="38" font-size="12.5" text-anchor="middle">② 饥饿 (Starvation)</text>
    <line class="fig-divider" x1="264" y1="48" x2="456" y2="48"/>
    <text class="fig-label" x="264" y="70" font-size="11">• 进程数：单个进程即可发生</text>
    <text class="fig-label" x="264" y="92" font-size="11">• 状态：长期就绪（或阻塞）</text>
    <text class="fig-label" x="264" y="114" font-size="11">• 占 CPU：否（一直排不到）</text>
    <text class="fig-label" x="264" y="136" font-size="11">• 依赖环：没有循环等待环</text>
    <text class="fig-label" x="264" y="158" font-size="11">• OS 检测：无客观界限，难检测</text>
    <text class="fig-muted" x="264" y="186" font-size="10">例：SJF 长作业 / 读者优先写者</text>
    <text class="fig-muted" x="264" y="201" font-size="10">成因：调度或资源分配策略不公</text>
    <!-- 死循环 -->
    <text class="fig-purple" x="594" y="38" font-size="12.5" text-anchor="middle">③ 死循环 (Endless Loop)</text>
    <line class="fig-divider" x1="498" y1="48" x2="690" y2="48"/>
    <text class="fig-label" x="498" y="70" font-size="11">• 进程数：单个进程</text>
    <text class="fig-label" x="498" y="92" font-size="11">• 状态：处于运行态（活奔乱跳）</text>
    <text class="fig-label" x="498" y="114" font-size="11">• 占 CPU：是（占满处理器跑）</text>
    <text class="fig-label" x="498" y="136" font-size="11">• 依赖环：无（程序指令自环）</text>
    <text class="fig-label" x="498" y="158" font-size="11">• OS 检测：无法判别是否为 Bug</text>
    <text class="fig-muted" x="498" y="186" font-size="10">例：while(1) 退出条件永不成立</text>
    <text class="fig-muted" x="498" y="201" font-size="10">成因：用户程序自身逻辑设计错误</text>
  </svg>
  <figcaption>图 4-11　死锁、饥饿与死循环三大“停滞”现象的三维判别卡片</figcaption>
</figure>

#### 4.4.2 死锁的三类成因与四个必要条件 ★

1. **产生死锁的三类直接成因**：
   - **竞争不可抢占性资源**：系统不可抢占资源数量不足（如仅有一份文件锁 $F_1, F_2$ ），$P_1$ 先 `open(F1)` 后申请 $F_2$ ，$P_2$ 先 `open(F2)` 后申请 $F_1$ ，交叉执行时形成无限期僵持。
   - **竞争可消耗性资源**：进程间通过消息通信协作，若 $P_1, P_2, P_3$ 均编写成“先 `receive` 后 `send`”，则三个进程将**永久阻塞在 `receive` 上，等待一条永远不会被发出的消息**。
   - **进程推进顺序不当**：在共享同一台打印机 $R_1$ 与同一台磁带机 $R_2$ 时，由于并发异步性，若调度轨迹使系统越过安全边界进入“$P_1$ 占 $R_1$、$P_2$ 占 $R_2$”的**不安全区域**，后续必撞入死锁。

2. **★死锁产生的四个必要条件（缺一不可，必须同时满足）**：

| 必要条件 | 精确定义 | 核心通俗理解 |
| --- | --- | --- |
| **1. 互斥条件**（Mutual Exclusion） | 进程对其所分配到的资源进行排他性使用，某段时间内某种资源仅允许被一个进程占用；其他请求者必须阻塞等待释放 | 资源不能同时共享 |
| **2. 请求和保持条件**（Hold and Wait，又称占有并等待） | 进程已经保持了至少一个资源，但又提出了新的资源请求，而新资源已被其他进程占有；此时请求进程阻塞，但**对自己已获得的资源保持不放** | 吃着碗里的、看着锅里的 |
| **3. 不可抢占条件**（No Preemption，又称非抢占） | 进程已获得的资源在未使用完之前，**不能被其他进程强行夺走**，只能在使用完毕后由持有进程主动自愿释放 | 拿到手里就夺不走 |
| **4. 循环等待条件**（Circular Wait） | 存在一个进程—资源的闭合循环等待链 $\{P_0, P_1, \dots, P_n\}$ ：$P_0$ 等待 $P_1$ 占有的资源，$P_1$ 等待 $P_2$ 占有的资源…… $P_n$ 等待 $P_0$ 占有的资源 | 等待关系首尾闭合 |

> **注意（逻辑关系辨析）**：上述四条是死锁发生的**必要条件而非充分条件**！只要有任何一条不满足，死锁就绝对不会发生；但四条全满足时，死锁也未必真的发生（例如当同类资源实例数足够打破局部闭环，或有只需其中一种资源的“单需求进程”先行完工释放资源时，循环等待可自动解开）。

#### 4.4.3 ★死锁最小资源数定理与高频计算模板

这是 408 选择题高频计算送分模板（真题 `09#25`、`14#24`、`21#31`、`16#25` 均直接套用本定理）：

- **问题模型一（同构进程求最少资源数）**：系统有 $m$ 个并发进程共享同一类不可抢占资源，每个进程最多需要 $k$ 个该类资源（$k \ge 1$）。为确保系统在任何推进顺序下**绝不发生死锁**，系统中至少应配备多少个该类资源？
  - **极值抽屉原理推导**：发生死锁时最惨烈的临界资源占用状态，是**每个进程都恰好差 $1$ 个资源就凑齐（即各占 $k-1$ 个）**，此时共占用 $m(k-1)$ 个资源而系统空余量为 $0$ ，全体卡死。只要系统中再额外多出 **$1$ 个空闲资源**，无论分给哪个进程都能让它凑够 $k$ 个顺利跑完并归还全部 $k$ 个资源，进而接力盘活所有其余进程！

$$
R_{\min} = m(k - 1) + 1
$$

- **问题模型二（已知资源总数 $R$ 求不死锁的最大进程数 $m_{\max}$ ，`09#25`）**：利用同一不等式反向求解即可：

$$
m(k - 1) + 1 \le R \implies m_{\max} = \left\lfloor \frac{R - 1}{k - 1} \right\rfloor
$$

  - **真题示例（`09#25`）**：8 台打印机，每个进程最多用 3 台，求确保不死锁的最大进程数 $K$ 。代入 $2m + 1 \le 8 \implies m \le 3.5$ ，故最多允许 **$3$ 个进程**并发执行。
- **问题模型三（异构需求推广，各进程最大需求 $k_i$ 不同）**：设各进程最多各需 $k_1, k_2, \dots, k_m$ 个同类资源，同理每人都差 $1$ 个时最坏消耗 $\sum (k_i - 1)$ ，再加 $1$ 即永不死锁：

$$
R_{\min} = \sum_{i=1}^{m}(k_i - 1) + 1
$$

- **模型四（多类资源构成循环等待最少进程数，`16#25`）**：环路至少需要 $2$ 个进程首尾相接；若有 $c$ 类资源（每类 1 个实例）且每进程每次最多占用或申请固定数量，需判断形成“最简闭合循环等待链”最少需几个进程（如各拿 1 个再等另一个，最少 2 个进程即可成环）。

<figure class="cpd-figure not-content" id="os-c4-fig-12">
  <svg viewBox="0 0 720 268" role="img" aria-label="进程推进轨迹平面图与死锁最小资源数抽屉极值原理图">
    <defs>
      <marker id="os-c4-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左图：进程推进轨迹平面图 -->
    <rect class="fig-box-subtle" x="16" y="14" width="346" height="240" rx="8"/>
    <text class="fig-title" x="189" y="34" font-size="11.5" text-anchor="middle">进程推进轨迹平面（P1 与 P2 共享 R1、R2）</text>
    <!-- 坐标轴 -->
    <line class="fig-line" x1="66" y1="214" x2="342" y2="214" marker-end="url(#os-c4-arr-12)"/>
    <line class="fig-line" x1="66" y1="214" x2="66" y2="44" marker-end="url(#os-c4-arr-12)"/>
    <!-- 辅助刻度虚线 -->
    <line class="fig-line-dashed" x1="122" y1="174" x2="122" y2="214"/>
    <line class="fig-line-dashed" x1="174" y1="174" x2="174" y2="214"/>
    <line class="fig-line-dashed" x1="226" y1="174" x2="226" y2="214"/>
    <line class="fig-line-dashed" x1="278" y1="174" x2="278" y2="214"/>
    <line class="fig-line-dashed" x1="66" y1="174" x2="122" y2="174"/>
    <line class="fig-line-dashed" x1="66" y1="136" x2="122" y2="136"/>
    <line class="fig-line-dashed" x1="66" y1="98" x2="122" y2="98"/>
    <line class="fig-line-dashed" x1="66" y1="66" x2="122" y2="66"/>
    <!-- L/阶梯形禁区（R1互斥 ∪ R2互斥）与凹角不安全区 D -->
    <path class="fig-box-red" d="M 122 136 L 122 66 L 226 66 L 226 98 L 278 98 L 278 174 L 174 174 L 174 136 Z"/>
    <rect class="fig-box-orange" x="122" y="136" width="52" height="38"/>
    <!-- 轨迹线 -->
    <!-- 合法安全轨（P2 先完成并释放 R1/R2，上方绕过禁区） -->
    <path class="fig-line-green" d="M 66 214 L 66 56 L 306 56" fill="none" stroke-width="2" marker-end="url(#os-c4-arr-12)"/>
    <!-- 非法死锁轨（进入凹角 D 必撞死锁墙） -->
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 66 214 L 148 214 L 148 164" fill="none" stroke-width="1.8" stroke-dasharray="4 3" marker-end="url(#os-c4-arr-12)"/>
    <!-- 刻度文字 -->
    <text class="fig-muted" x="122" y="227" font-size="8.5" text-anchor="middle">Req R1</text>
    <text class="fig-muted" x="174" y="227" font-size="8.5" text-anchor="middle">Req R2</text>
    <text class="fig-muted" x="226" y="227" font-size="8.5" text-anchor="middle">Rel R1</text>
    <text class="fig-muted" x="278" y="227" font-size="8.5" text-anchor="middle">Rel R2</text>
    <text class="fig-label" x="328" y="227" font-size="9.5" text-anchor="middle">P1</text>
    <text class="fig-muted" x="60" y="177" font-size="8.5" text-anchor="end">Req R2</text>
    <text class="fig-muted" x="60" y="139" font-size="8.5" text-anchor="end">Req R1</text>
    <text class="fig-muted" x="60" y="101" font-size="8.5" text-anchor="end">Rel R2</text>
    <text class="fig-muted" x="60" y="69" font-size="8.5" text-anchor="end">Rel R1</text>
    <text class="fig-label" x="48" y="51" font-size="9.5" text-anchor="middle">P2</text>
    <text class="fig-red" x="200" y="114" font-size="10.2" text-anchor="middle">禁止同时进入区</text>
    <text class="fig-muted" x="200" y="129" font-size="8.5" text-anchor="middle">(R1 ∪ R2 互斥禁区)</text>
    <text class="fig-orange" x="148" y="151" font-size="8.2" text-anchor="middle">不安全区 D</text>
    <text class="fig-green" x="200" y="50" font-size="9.5" text-anchor="middle">安全轨迹（P2 先释放绕行）</text>
    <!-- 右图：最小资源数定理 -->
    <rect class="fig-box-subtle" x="378" y="14" width="326" height="240" rx="8"/>
    <text class="fig-title" x="541" y="34" font-size="10.4" text-anchor="middle">最小资源数定理：R_min = m(k − 1) + 1 (例 m=3, k=4)</text>
    <!-- 3个进程各自占 3 个 -->
    <rect class="fig-box-orange" x="394" y="52" width="90" height="72" rx="5"/>
    <rect class="fig-box-orange" x="496" y="52" width="90" height="72" rx="5"/>
    <rect class="fig-box-orange" x="598" y="52" width="90" height="72" rx="5"/>
    <!-- 底部+1救命资源 -->
    <rect class="fig-box-green" x="394" y="160" width="294" height="44" rx="6"/>
    <line class="fig-line-accent" x1="541" y1="160" x2="444" y2="128" stroke-width="1.8" marker-end="url(#os-c4-arr-12)"/>
    <!-- 小资源圆点 -->
    <circle class="fig-dot-muted" cx="416" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="436" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="456" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="518" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="538" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="558" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="620" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="640" cy="86" r="5"/>
    <circle class="fig-dot-muted" cx="660" cy="86" r="5"/>
    <circle class="fig-green-fill" cx="416" cy="182" r="7"/>
    <!-- 文字 -->
    <text class="fig-orange" x="439" y="68" font-size="9.6" text-anchor="middle">P1 (占 3 缺 1)</text>
    <text class="fig-muted" x="439" y="112" font-size="9.5" text-anchor="middle">差 1 个凑齐 4</text>
    <text class="fig-orange" x="541" y="68" font-size="9.6" text-anchor="middle">P2 (占 3 缺 1)</text>
    <text class="fig-muted" x="541" y="112" font-size="9.5" text-anchor="middle">差 1 个凑齐 4</text>
    <text class="fig-orange" x="643" y="68" font-size="9.6" text-anchor="middle">P3 (占 3 缺 1)</text>
    <text class="fig-muted" x="643" y="112" font-size="9.5" text-anchor="middle">差 1 个凑齐 4</text>
    <text class="fig-green" x="556" y="179" font-size="11" text-anchor="middle">+ 1 个关键救命资源（总数 10）</text>
    <text class="fig-muted" x="556" y="195" font-size="9.6" text-anchor="middle">任给其一 → 凑齐 4 个跑完释放 → 接力盘活</text>
    <text class="fig-accent" x="541" y="232" font-size="10.5" text-anchor="middle">★ 只剩 9 个时可能各占 3 死锁；有 10 个则必不死锁</text>
  </svg>
  <figcaption>图 4-12　进程推进轨迹平面（合法安全轨 vs 必死锁区 D）与最小资源数公式极值原理</figcaption>
</figure>

---

### 4.5 ★死锁的处理策略与银行家算法

#### 4.5.1 死锁预防：分别破坏四个必要条件

死锁处理的四种策略沿“**预防 $\to$ 避免 $\to$ 检测 $\to$ 解除**”排列，呈现出鲜明的单调权衡规律：**对死锁的事前防范严格度单调递减，而系统资源利用率与并发度则单调递增**。其中**死锁预防**是在系统设计阶段施加限制条件，破坏四个必要条件之一（**注意**：互斥是非共享物理设备的固有属性，不仅不能随便破坏，甚至必须保证；故工程上主要破坏后三个条件）：

| 被破坏的条件 | 具体破坏手段与协议 | 主要代价、缺陷与适用范围 |
| --- | --- | --- |
| **1. 破坏互斥条件** | 采用虚拟化技术（如 **SPOOLing 假脱机技术**）将独占物理设备改造为逻辑上可同时访问的共享设备 | 仅对少数能缓冲虚拟化的设备有效（如打印机可以，刻录机/普通互斥锁不行），且需额外管理缓冲开销 |
| **2. 破坏请求和保持条件** | **协议一（静态全量分配）**：进程运行前必须**一次性申请完**全部所需资源，不全满足不启动<br>**协议二（分阶段申请释放）**：允许只持初期所需资源开跑，用完即释放后再申下一批（如“磁带→磁盘→打印”两段式） | **协议一**：实现最简，但资源被闲置浪费极严重，且个别紧缺资源易引发**进程饥饿**<br>**协议二**：缓解浪费与饥饿，但需程序本身具备清晰阶段性 |
| **3. 破坏不可抢占条件** | ① 进程请求新资源遭拒时，必须**主动释放已持有的全部资源**，日后重新申请<br>② 高优先级进程可直接剥夺低优先级进程手中的资源 | 实现复杂；频繁释放再申请导致**前功尽弃、开销大、吞吐下降与饥饿**；**仅适用于状态易保存与恢复的资源（如 CPU 寄存器、内存）**，绝不能中途剥夺打印机或刻录机 |
| **4. 破坏循环等待条件 ★** | **资源有序分配法**（按序编号分配）：为全系统所有资源类型线性编号 $F(R_i)$ （如 `F(磁带机)=1, F(磁盘机)=5, F(打印机)=12`），规定**进程必须按序号严格递增顺序申请资源**；若已持高号资源再想要低号资源，**必须先释放所有相同和更高序号的资源** | **实用性最好、利用率与吞吐明显高于前几类**；局限在于：① 增减新设备需重编号，扩充困难；② 进程实际用资源顺序若与编号相反，仍需提前占用暂不用的低号资源导致浪费；③ **限制用户编程自主性** |

> **★考点（资源有序分配法反证无环）**：为何按编号递增申请绝不会产生环路？假设存在循环等待环 $P_0 \to P_1 \to \dots \to P_k \to P_0$ ，其中 $P_i$ 已占资源 $r_i$ 并等待 $P_{i+1}$ 所占的 $r_{i+1}$ 。按规则“先占小编号再求大编号”可得 $F(r_0) < F(r_1) < \dots < F(r_k) < F(r_0)$ ，推出 $F(r_0) < F(r_0)$ 的绝对矛盾！从另一方面看，任一时刻必有某进程所持有的资源编号在全系统中最大，它后续要请求的编号只会更大——那些大号资源必定空闲无人占，故该进程必能率先跑完！前章中的细粒度加锁规范与哲学家进餐的奇偶策略均属于该方法。

<figure class="cpd-figure not-content" id="os-c4-fig-13">
  <svg viewBox="0 0 720 256" role="img" aria-label="死锁预防破坏四个必要条件的方法比较与资源有序分配法反证无环示意图">
    <defs>
      <marker id="os-c4-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 上半区：四张破坏手段卡片 -->
    <rect class="fig-box" x="16" y="14" width="164" height="114" rx="6"/>
    <rect class="fig-box-orange" x="190" y="14" width="164" height="114" rx="6"/>
    <rect class="fig-box-purple" x="364" y="14" width="164" height="114" rx="6"/>
    <rect class="fig-box-green" x="538" y="14" width="166" height="114" rx="6"/>
    <text class="fig-title" x="98" y="34" font-size="11" text-anchor="middle">① 破坏互斥</text>
    <text class="fig-label" x="26" y="54" font-size="10">手段：SPOOLing 假脱机</text>
    <text class="fig-muted" x="26" y="72" font-size="9.5">将独占打印机虚拟共享</text>
    <text class="fig-muted" x="26" y="90" font-size="9.5">✕ 大多数临界资源物理</text>
    <text class="fig-muted" x="26" y="106" font-size="9.5">性质决定了不能破坏互斥</text>
    <text class="fig-orange" x="272" y="34" font-size="11" text-anchor="middle">② 破坏请求和保持</text>
    <text class="fig-label" x="200" y="54" font-size="10">协议1：静态一次性申全</text>
    <text class="fig-label" x="200" y="72" font-size="10">协议2：分阶段用完即放</text>
    <text class="fig-muted" x="200" y="90" font-size="9.5">✕ 资源利用率极低、易饿</text>
    <text class="fig-muted" x="200" y="106" font-size="9.5">✕ 需预知全部或阶段需求</text>
    <text class="fig-purple" x="446" y="34" font-size="11" text-anchor="middle">③ 破坏不可抢占</text>
    <text class="fig-label" x="374" y="54" font-size="10">手段1：被拒自愿全释放</text>
    <text class="fig-label" x="374" y="72" font-size="10">手段2：高优先级剥夺</text>
    <text class="fig-muted" x="374" y="90" font-size="9.5">✕ 仅限 CPU/内存等易恢复</text>
    <text class="fig-muted" x="374" y="106" font-size="9.5">✕ 前功尽弃、开销大易饥饿</text>
    <text class="fig-green" x="621" y="34" font-size="11" text-anchor="middle">④ 破坏循环等待 ★</text>
    <text class="fig-label" x="548" y="54" font-size="10">手段：资源有序分配法</text>
    <text class="fig-label" x="548" y="72" font-size="10">严格按 F(R) 递增申请</text>
    <text class="fig-muted" x="548" y="90" font-size="9.5">✓ 最实用，吞吐利用率较好</text>
    <text class="fig-muted" x="548" y="106" font-size="9.5">✕ 增新设备难、限制编程</text>
    <!-- 下半区：资源有序分配反证无环 -->
    <rect class="fig-box-subtle" x="16" y="140" width="688" height="102" rx="8"/>
    <text class="fig-title" x="360" y="160" font-size="11.5" text-anchor="middle">资源有序分配法为何必无环？（反证推导：F(磁带)=1 &lt; F(磁盘)=5 &lt; F(打印机)=12）</text>
    <rect class="fig-box-blue" x="36" y="176" width="144" height="36" rx="5"/>
    <rect class="fig-box-blue" x="232" y="176" width="144" height="36" rx="5"/>
    <rect class="fig-box-blue" x="428" y="176" width="144" height="36" rx="5"/>
    <rect class="fig-box-red" x="596" y="176" width="96" height="36" rx="5"/>
    <line class="fig-line-accent" x1="180" y1="194" x2="228" y2="194" stroke-width="1.6" marker-end="url(#os-c4-arr-13)"/>
    <line class="fig-line-accent" x1="376" y1="194" x2="424" y2="194" stroke-width="1.6" marker-end="url(#os-c4-arr-13)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" x1="572" y1="194" x2="594" y2="194" stroke-width="1.6" marker-end="url(#os-c4-arr-13)"/>
    <text class="fig-blue" x="108" y="198" font-size="10.5" text-anchor="middle">P0 持 1 求 5</text>
    <text class="fig-blue" x="304" y="198" font-size="10.5" text-anchor="middle">P1 持 5 求 12</text>
    <text class="fig-blue" x="500" y="198" font-size="10.5" text-anchor="middle">P2 持 12 禁求 1</text>
    <text class="fig-red" x="644" y="198" font-size="10.5" text-anchor="middle">12 &lt; 1 矛盾✕</text>
    <text class="fig-muted" x="360" y="232" font-size="10" text-anchor="middle">推论：任一时刻持最大编号资源的进程后续只会申请更大编号（必空闲），因此必能率先完成释放</text>
  </svg>
  <figcaption>图 4-13　死锁预防四条件破坏策略横向比较及“资源有序分配法”反证无环机制</figcaption>
</figure>

#### 4.5.2 死锁避免：安全状态与 ★银行家算法（408 超级高频大题/选择）

死锁避免**不破坏任何必要条件**，而是在每次动态分配前预先推演：如果批准这次请求，系统是否仍处于**安全状态**。

- **安全状态（Safe State）与安全序列**：若系统能按某种进程推进顺序 $\langle P_{k_1}, P_{k_2}, \dots, P_{k_n}\rangle$ 为每个进程分配其尚需资源，直至满足最大需求使所有进程都顺利完成，则称系统处于**安全状态**，该序列称为**安全序列**（通常**不唯一**）。
- **★安全状态 vs 不安全状态 vs 死锁状态（概念辨析必考，`13#32`）**：
  - 系统若处于**安全状态** $\implies$ **一定不会发生死锁**；
  - 系统若处于**不安全状态** $\implies$ **不一定立即死锁，只是存在演变为死锁的风险**（例如进程最终实际未申请到当初声明的 `Max` 即提前释放了部分资源，仍可侥幸逃脱）；反之，**死锁状态必定是不安全状态的真子集**！
  - 银行家算法是一种**偏保守的乐观预防前哨**：只要分配后陷入不安全状态就拒绝试探分配（宁可误伤部分不会真死锁的请求，也绝不允许系统踏出安全区）。

<figure class="cpd-figure not-content" id="os-c4-fig-14">
  <svg viewBox="0 0 720 242" role="img" aria-label="系统状态空间韦恩图（安全状态、不安全状态与死锁状态包含关系）与四大死锁策略光谱">
    <defs>
      <marker id="os-c4-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左图：韦恩包含关系 -->
    <rect class="fig-box-subtle" x="16" y="14" width="356" height="214" rx="8"/>
    <text class="fig-title" x="194" y="34" font-size="11.5" text-anchor="middle">系统状态空间精确包含关系（不安全 ≠ 死锁）</text>
    <!-- 安全状态半区 + 不安全半区 -->
    <rect class="fig-box-green" x="28" y="48" width="154" height="134" rx="8"/>
    <rect class="fig-box-orange" x="204" y="48" width="156" height="134" rx="8"/>
    <!-- 死锁嵌套真子集 -->
    <rect class="fig-box-red" x="224" y="116" width="118" height="58" rx="8"/>
    <!-- 跨边界拒绝箭头 -->
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 156 91 L 214 91" stroke-width="1.8" stroke-dasharray="4 3" marker-end="url(#os-c4-arr-14)"/>
    <rect class="fig-box" x="150" y="72" width="70" height="15" rx="3"/>
    <text class="fig-green" x="105" y="68" font-size="11.5" text-anchor="middle">安全状态 (Safe)</text>
    <text class="fig-muted" x="105" y="114" font-size="10" text-anchor="middle">存在至少一条</text>
    <text class="fig-muted" x="105" y="129" font-size="10" text-anchor="middle">安全序列，保证</text>
    <text class="fig-green" x="105" y="146" font-size="10.5" text-anchor="middle">绝不会发生死锁</text>
    <text class="fig-orange" x="282" y="68" font-size="11.5" text-anchor="middle">不安全状态 (Unsafe)</text>
    <text class="fig-muted" x="282" y="105" font-size="9.5" text-anchor="middle">可能侥幸不死，但有风险</text>
    <text class="fig-red" x="283" y="139" font-size="11" text-anchor="middle">死锁状态 ★</text>
    <text class="fig-muted" x="283" y="157" font-size="9.5" text-anchor="middle">Deadlock ⊂ Unsafe</text>
    <text class="fig-red" x="185" y="83" font-size="8.6" text-anchor="middle">拒绝试分配!</text>
    <text class="fig-label" x="194" y="206" font-size="10.2" text-anchor="middle">银行家算法守门规则：只允许系统在绿色区域内转移</text>
    <!-- 右图：四大策略权衡光谱 -->
    <rect class="fig-box-subtle" x="386" y="14" width="318" height="214" rx="8"/>
    <text class="fig-title" x="545" y="34" font-size="11.5" text-anchor="middle">死锁四大策略防范强度 vs 资源利用率单调谱</text>
    <rect class="fig-box" x="398" y="50" width="258" height="30" rx="4"/>
    <rect class="fig-box-blue" x="398" y="88" width="258" height="30" rx="4"/>
    <rect class="fig-box-orange" x="398" y="126" width="258" height="30" rx="4"/>
    <rect class="fig-box-red" x="398" y="164" width="258" height="30" rx="4"/>
    <line class="fig-line-accent" x1="674" y1="190" x2="674" y2="54" stroke-width="1.6" marker-end="url(#os-c4-arr-14)"/>
    <text class="fig-label" x="406" y="69" font-size="10">1. 死锁预防：破坏条件 · 限制最死 · 利用率最低</text>
    <text class="fig-blue" x="406" y="107" font-size="10">2. 死锁避免：银行家需 Need · 保守不进不安全</text>
    <text class="fig-orange" x="406" y="145" font-size="10">3. 死锁检测：只查 Request · 容忍运行定时化简</text>
    <text class="fig-red" x="406" y="183" font-size="10">4. 死锁解除：发生后抢占或撤消 · 并发度最高</text>
    <text class="fig-accent" x="545" y="212" font-size="10" text-anchor="middle">↑ 事前防范严格度上升 ｜ ↓ 资源利用率与并发度上升</text>
  </svg>
  <figcaption>图 4-14　安全状态、不安全状态与死锁状态韦恩包含关系及四大处理策略的权衡单调规律</figcaption>
</figure>

##### （1）银行家算法四大核心数据结构（设 $n$ 个进程、$m$ 类资源）

- **`Available[m]`**（可利用资源向量）：一维数组，记录目前系统中**每一类资源尚存的空闲数量**。
- **`Max[n][m]`**（最大需求矩阵）：进程进入系统时必须预先申明其整个生命周期对各类资源的最大需求（不得超系统资源总量）。
- **`Allocation[n][m]`**（分配矩阵）：当前已分配给每个进程的各类资源数量。
- **`Need[n][m]`**（需求矩阵）：每个进程**尚需**多少资源才能完成任务，恒有：

$$
Need[i][j] = Max[i][j] - Allocation[i][j]
$$

> **★做题准备铁律（`11#27, 12#27, 18#26, 20#27, 22#26`）**：试卷通常只给出总资源数以及 `Max` 和 `Allocation`（或仅给出 `Allocation` 和 `Need`），动笔前第一步永远是先在表旁补齐**需求矩阵**（`Need = Max - Allocation`）并核算出**可用向量**（`Available = 总量 - ∑Allocation`）！

##### （2）安全性算法与贪心等价性

1. 初始化工作向量 `Work = Available`（代表演练过程中动态回收后手头的当前可用资源），以及完成标志向量 `Finish[i] = false`（$i = 0, 1, \dots, n-1$ ）。
2. 从进程集合中寻找一个同时满足下列两个条件的进程 $P_i$ ：
   - `Finish[i] == false`；
   - **`Need[i][j] <= Work[j]`**（对所有资源类 $j$ 均成立。**注意：此处比较的是 `Need`，绝不是 `Request`！**）。
3. 若找到，模拟让 $P_i$ 跑完并归还它占用的全部资源：
   - **`Work[j] = Work[j] + Allocation[i][j]`**（**注意：加回的是 `Allocation`，绝不是 `Need`！**）；
   - `Finish[i] = true` ，将 $P_i$ 追加进安全序列，返回第 2 步继续寻找。
4. 若所有进程的 `Finish[i]` 均为 `true` ，则系统处于**安全状态**，记下的顺序即为一条安全序列；否则若在某一轮遍历所有未完成进程均无法推进，则系统处于**不安全状态**。

> **★考点（贪心不漏解与末态自检铁律）**：
> - **为什么贪心挑任意一个可满足的进程不会漏掉安全序列？** 因为在整个推演中 `Allocation` 非负，使得 `Work` 向量只增不减！只要 $P_i$ 此刻已经满足 $Need_i \le Work$ ，那么不管先推其他谁，后续 $Work$ 只会更大，$P_i$ 在更晚的时刻也依然满足——提前运行它不会剥夺任何进程的机会。所以**只要贪心走死胡同，穷举全部 $n!$ 种排列也必死胡同**！
> - **算完自检绝招**：若成功找出完整安全序列，**最终结束时的 `Work` 必须一分不差地等于系统的原始资源总量**！

##### （3）银行家算法资源请求三道关

当进程 $P_i$ 发出请求向量 `Request_i[m]` 时，系统依次检查三道关（顺序不可颠倒）：
1. **第一关（合法性检查）**：若对所有 $j$ 均有 $Request_i[j] \le Need[i][j]$ ，转第 2 步；否则认为出错（申请超过了最初申明的最大需求上限）。
2. **第二关（物理可用性检查）**：若对所有 $j$ 均有 $Request_i[j] \le Available[j]$ ，转第 3 步；否则说明系统当下库存不足，**直接阻塞 $P_i$ 等待**（不试探分配、不跑安全性检查）。
3. **第三关（试探分配 + 安全性检查）**：假定先把资源分配给 $P_i$ ，同步更新三组数据：$Available = Available - Request_i$ 、$Allocation_i = Allocation_i + Request_i$ 、$Need_i = Need_i - Request_i$ ，随后调用**安全性算法**检测新状态是否安全：
   - 若存在安全序列 $\implies$ **正式分配生效**；
   - 若不安全 $\implies$ **立即作废本次试探分配，全部回滚恢复原状态**，并让 $P_i$ 阻塞等待。

##### （4）完整双态演练算例（408 经典 5 进程模型 + 失败回滚对比）

设系统共有 3 类资源 $A, B, C$ ，总量为 $(10, 5, 7)$ ，$T_0$ 时刻 5 个进程状态如下表（已分配合计 $(7, 2, 5)$ ，故 $Available = (10, 5, 7) - (7, 2, 5) = (3, 3, 2)$ ）：

| 进程 | `Max (A, B, C)` | `Allocation (A, B, C)` | `Need = Max - Allocation` | 初始 `Available` |
| --- | --- | --- | --- | --- |
| `P0` | `7, 5, 3` | `0, 1, 0` | **`7, 4, 3`** | `(3, 3, 2)` |
| `P1` | `3, 2, 2` | `2, 0, 0` | **`1, 2, 2`** | |
| `P2` | `9, 0, 2` | `3, 0, 2` | **`6, 0, 0`** | |
| `P3` | `2, 2, 2` | `2, 1, 1` | **`0, 1, 1`** | |
| `P4` | `4, 3, 3` | `0, 0, 2` | **`4, 3, 1`** | |

- **情形 1：进程 $P_1$ 发出请求** `Request_1 = (1, 0, 2)`
  - 第 ① 关：$(1, 0, 2) \le Need_{P1}(1, 2, 2)$ ✓ ；第 ② 关：$(1, 0, 2) \le Available(3, 3, 2)$ ✓ 。
  - 第 ③ 关试探修改：$Available \to (2, 3, 0)$ 、$Allocation_{P1} \to (3, 0, 2)$ 、$Need_{P1} \to (0, 2, 0)$ 。
  - 运行安全性算法：初始 `Work = (2, 3, 0)` $\to$ 选 `P1`（$Need(0,2,0) \le (2,3,0)$），归还后 `Work = (2,3,0)+(3,0,2) = (5, 3, 2)` $\to$ 选 `P3`（$Need(0,1,1) \le (5,3,2)$），归还后 `Work = (7, 4, 3)` $\to$ 选 `P4`（$Need(4,3,1) \le (7,4,3)$），归还后 `Work = (7, 4, 5)` $\to$ 选 `P0`（$Need(7,4,3) \le (7,4,5)$），归还后 `Work = (7, 5, 5)` $\to$ 选 `P2`（$Need(6,0,0) \le (7,5,5)$），归还后 `Work = (10, 5, 7)` $=$ **资源总量 ✓**！安全序列为 $\langle P_1, P_3, P_4, P_0, P_2\rangle$ （亦有多解如 $\langle P_1, P_3, P_0, P_2, P_4\rangle$ ），**批准本次请求**！
- **情形 2：若随后 $P_0$ 在 $(2, 3, 0)$ 下请求** `Request_0 = (0, 2, 0)`
  - 第 ① ② 关均通过；试探分配后 `Available` 跌为 $(2, 1, 0)$ ，`P1` 尚需 `(0,2,0)`、其余进程需 `B ≥ 1` 或 `C ≥ 1`——首轮竟找不到任何一个满足 $Need \le (2,1,0)$ 的进程！立即判定**不安全**，**撤销试探分配并阻塞 $P_0$**。

<figure class="cpd-figure not-content" id="os-c4-fig-15">
  <svg viewBox="0 0 720 332" role="img" aria-label="银行家算法三道关检验流程与五进程安全性检查步进推演矩阵图">
    <defs>
      <marker id="os-c4-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左区：三道关流程 -->
    <rect class="fig-box-subtle" x="16" y="14" width="234" height="304" rx="8"/>
    <text class="fig-title" x="133" y="34" font-size="11.5" text-anchor="middle">银行家算法“三道关”流程</text>
    <line class="fig-line-accent" x1="133" y1="76" x2="133" y2="94" stroke-width="1.5" marker-end="url(#os-c4-arr-15)"/>
    <line class="fig-line-accent" x1="133" y1="132" x2="133" y2="150" stroke-width="1.5" marker-end="url(#os-c4-arr-15)"/>
    <line class="fig-line-accent" x1="133" y1="188" x2="133" y2="206" stroke-width="1.5" marker-end="url(#os-c4-arr-15)"/>
    <line class="fig-line-accent" x1="133" y1="252" x2="133" y2="270" stroke-width="1.5" marker-end="url(#os-c4-arr-15)"/>
    <rect class="fig-box" x="48" y="46" width="170" height="30" rx="5"/>
    <rect class="fig-box-blue" x="28" y="96" width="210" height="36" rx="5"/>
    <rect class="fig-box-orange" x="28" y="152" width="210" height="36" rx="5"/>
    <rect class="fig-box-purple" x="28" y="208" width="210" height="44" rx="5"/>
    <rect class="fig-box-green" x="28" y="272" width="210" height="36" rx="5"/>
    <text class="fig-label" x="133" y="65" font-size="10.5" text-anchor="middle">收到 Request_i 请求</text>
    <text class="fig-blue" x="133" y="112" font-size="10.5" text-anchor="middle">① Request_i ≤ Need_i ?</text>
    <text class="fig-muted" x="133" y="126" font-size="9.2" text-anchor="middle">否 → 越界报错(超最大声明)</text>
    <text class="fig-orange" x="133" y="168" font-size="10.5" text-anchor="middle">② Request_i ≤ Available ?</text>
    <text class="fig-muted" x="133" y="182" font-size="9.2" text-anchor="middle">否 → 库存不足，直接阻塞等待</text>
    <text class="fig-purple" x="133" y="226" font-size="10.2" text-anchor="middle">③ 试探更新 Avail/Alloc/Need</text>
    <text class="fig-muted" x="133" y="242" font-size="9.2" text-anchor="middle">调用右方安全性算法检查</text>
    <text class="fig-green" x="133" y="288" font-size="10.2" text-anchor="middle">安全 → 正式分配 ✓</text>
    <text class="fig-red" x="133" y="302" font-size="9.2" text-anchor="middle">不安全 → 全额回滚并阻塞 Pi ✕</text>
    <!-- 右区：安全性检查步进推演矩阵 -->
    <rect class="fig-box-subtle" x="262" y="14" width="442" height="304" rx="8"/>
    <text class="fig-title" x="483" y="34" font-size="11.5" text-anchor="middle">安全性检查步进推演矩阵（P1 申请 (1,0,2) 试分配后）</text>
    <!-- 表头 -->
    <rect class="fig-box" x="274" y="46" width="418" height="24" rx="4"/>
    <text class="fig-title" x="304" y="62" font-size="10" text-anchor="middle">轮次</text>
    <text class="fig-title" x="372" y="62" font-size="10" text-anchor="middle">当前 Work</text>
    <text class="fig-title" x="468" y="62" font-size="10" text-anchor="middle">选中且 Need ≤ Work</text>
    <text class="fig-title" x="608" y="62" font-size="10" text-anchor="middle">归还后 Work += Alloc</text>
    <!-- 5 行步进 -->
    <rect class="fig-box-green" x="274" y="76" width="418" height="32" rx="4"/>
    <rect class="fig-box-green" x="274" y="114" width="418" height="32" rx="4"/>
    <rect class="fig-box-green" x="274" y="152" width="418" height="32" rx="4"/>
    <rect class="fig-box-green" x="274" y="190" width="418" height="32" rx="4"/>
    <rect class="fig-box-green" x="274" y="228" width="418" height="32" rx="4"/>
    <text class="fig-label" x="304" y="96" font-size="10.2" text-anchor="middle">第 1 轮</text>
    <text class="fig-label" x="372" y="96" font-size="10.2" text-anchor="middle">(2, 3, 0)</text>
    <text class="fig-green" x="468" y="96" font-size="10.2" text-anchor="middle">P1: Need(0,2,0) ✓</text>
    <text class="fig-accent" x="608" y="96" font-size="10.2" text-anchor="middle">+(3,0,2) = (5, 3, 2)</text>
    <text class="fig-label" x="304" y="134" font-size="10.2" text-anchor="middle">第 2 轮</text>
    <text class="fig-label" x="372" y="134" font-size="10.2" text-anchor="middle">(5, 3, 2)</text>
    <text class="fig-green" x="468" y="134" font-size="10.2" text-anchor="middle">P3: Need(0,1,1) ✓</text>
    <text class="fig-accent" x="608" y="134" font-size="10.2" text-anchor="middle">+(2,1,1) = (7, 4, 3)</text>
    <text class="fig-label" x="304" y="172" font-size="10.2" text-anchor="middle">第 3 轮</text>
    <text class="fig-label" x="372" y="172" font-size="10.2" text-anchor="middle">(7, 4, 3)</text>
    <text class="fig-green" x="468" y="172" font-size="10.2" text-anchor="middle">P4: Need(4,3,1) ✓</text>
    <text class="fig-accent" x="608" y="172" font-size="10.2" text-anchor="middle">+(0,0,2) = (7, 4, 5)</text>
    <text class="fig-label" x="304" y="210" font-size="10.2" text-anchor="middle">第 4 轮</text>
    <text class="fig-label" x="372" y="210" font-size="10.2" text-anchor="middle">(7, 4, 5)</text>
    <text class="fig-green" x="468" y="210" font-size="10.2" text-anchor="middle">P0: Need(7,4,3) ✓</text>
    <text class="fig-accent" x="608" y="210" font-size="10.2" text-anchor="middle">+(0,1,0) = (7, 5, 5)</text>
    <text class="fig-label" x="304" y="248" font-size="10.2" text-anchor="middle">第 5 轮</text>
    <text class="fig-label" x="372" y="248" font-size="10.2" text-anchor="middle">(7, 5, 5)</text>
    <text class="fig-green" x="468" y="248" font-size="10.2" text-anchor="middle">P2: Need(6,0,0) ✓</text>
    <text class="fig-accent" x="608" y="248" font-size="10.2" text-anchor="middle">+(3,0,2) = (10,5,7) ★</text>
    <!-- 底部提示 -->
    <rect class="fig-box-red" x="274" y="268" width="418" height="40" rx="5"/>
    <text class="fig-red" x="483" y="284" font-size="9.4" text-anchor="middle">★ 两处必避大坑：判条件比 Need (非 Request)；归还加 Allocation (非 Need)</text>
    <text class="fig-muted" x="483" y="300" font-size="9.8" text-anchor="middle">自检规律：全部 Finish=true 后末态 Work=(10,5,7) 必严格等于系统资源总量</text>
  </svg>
  <figcaption>图 4-15　银行家算法请求三道关检验流与经典五进程安全性检查步进矩阵推演</figcaption>
</figure>

---

### 4.6 ★死锁的检测与解除

如果系统既未采取死锁预防措施、也未运行需要预先知道最大需求的银行家算法，则允许死锁发生，转而通过**死锁检测**定位死锁并调用**死锁解除**恢复系统。

#### 4.6.1 资源分配图 (RAG) 与死锁定理 ★

**资源分配图（Resource Allocation Graph, RAG）** $G = (N, E)$ 是描述当前进程与资源占求关系的有向二部图：
- **两类节点**：**圆圈**代表进程 $P_i$ ；**方框**代表一类资源 $R_j$ ，方框内部的**小圆点**代表该类资源所包含的具体实例数目。
- **两类有向边（画法规范务必准确！）**：
  - **请求边** $(P_i \to R_j)$ ：从进程圆圈指向**资源方框的外框本身**，表示 $P_i$ 申请该类资源中的一个实例（只要是此类资源，哪个实例都行）。
  - **分配边** $(R_j \to P_i)$ ：必须始于**资源方框内部的某一个具体实例小圆点**，指向进程圆圈，表示该具体实例已分配给 $P_i$ 。

> **★考点（单实例 vs 多实例资源图的环路判别铁律）**：
> - **如果每种资源类仅包含 $1$ 个实例**：RAG 中存在有向环 $\iff$ 系统**必然死锁**（充要条件，此时可将图等价简化为仅含进程节点的“等待图 Wait-for Graph”用 DFS 找环）。
> - **如果至少存在一种资源包含多个实例**：RAG 中存在有向环只是死锁的**必要不充分条件**！因为环上所争抢的多实例资源可能还有其余空闲实例（或由环外无阻塞进程占用的实例在完工后释放），必须通过**化简算法**才能定夺！

<figure class="cpd-figure not-content" id="os-c4-fig-16">
  <svg viewBox="0 0 720 264" role="img" aria-label="资源分配图边画法规范及单实例与多实例环路死锁判别对比图">
    <defs>
      <marker id="os-c4-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左区：单实例环路必死锁 -->
    <rect class="fig-box-subtle" x="16" y="14" width="320" height="236" rx="8"/>
    <text class="fig-title" x="176" y="34" font-size="11.5" text-anchor="middle">单实例资源：有环 ⇔ 必然死锁</text>
    <!-- R1, R2 方框 -->
    <rect class="fig-box" x="148" y="54" width="56" height="36" rx="4"/>
    <rect class="fig-box" x="148" y="168" width="56" height="36" rx="4"/>
    <!-- P1, P2 圆形节点 -->
    <circle class="fig-box-red" cx="76" cy="129" r="22"/>
    <circle class="fig-box-red" cx="276" cy="129" r="22"/>
    <!-- 资源点 -->
    <circle class="fig-dot" cx="176" cy="72" r="5"/>
    <circle class="fig-dot" cx="176" cy="186" r="5"/>
    <!-- 边：分配边从点出，请求边落方框外缘 -->
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 171 72 L 92 110" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 94 143 L 146 178" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 181 186 L 260 147" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 258 115 L 206 78" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <text class="fig-muted" x="176" y="48" font-size="10" text-anchor="middle">R1 (1 实例)</text>
    <text class="fig-muted" x="176" y="218" font-size="10" text-anchor="middle">R2 (1 实例)</text>
    <text class="fig-red" x="76" y="133" font-size="11.5" text-anchor="middle">P1</text>
    <text class="fig-red" x="276" y="133" font-size="11.5" text-anchor="middle">P2</text>
    <text class="fig-blue" x="116" y="82" font-size="9.5" text-anchor="middle">分配边</text>
    <text class="fig-red" x="82" y="179" font-size="9.5" text-anchor="middle">请求边(指方框)</text>
    <text class="fig-label" x="176" y="238" font-size="10.2" text-anchor="middle">分配边始于框内实例点，请求边指向方框本身</text>
    <!-- 右区：多实例有环未必死锁 -->
    <rect class="fig-box-subtle" x="350" y="14" width="354" height="236" rx="8"/>
    <text class="fig-title" x="527" y="34" font-size="11.5" text-anchor="middle">多实例资源：有环只是必要条件（本图无死锁！）</text>
    <!-- R1(2点), R2(2点) -->
    <rect class="fig-box" x="494" y="54" width="66" height="36" rx="4"/>
    <rect class="fig-box" x="494" y="168" width="66" height="36" rx="4"/>
    <circle class="fig-dot" cx="514" cy="72" r="4.5"/>
    <circle class="fig-dot" cx="540" cy="72" r="4.5"/>
    <circle class="fig-dot" cx="514" cy="186" r="4.5"/>
    <circle class="fig-dot" cx="540" cy="186" r="4.5"/>
    <!-- 4 个进程 -->
    <circle class="fig-box-orange" cx="426" cy="129" r="20"/>
    <circle class="fig-box-orange" cx="628" cy="129" r="20"/>
    <circle class="fig-box-green" cx="400" cy="64" r="18"/>
    <circle class="fig-box-green" cx="654" cy="194" r="18"/>
    <!-- 内部环 P1->R2->P3->R1->P1 -->
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 540 77 L 444 116" stroke-width="1.5" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 444 140 L 492 178" stroke-width="1.5" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 514 181 L 610 140" stroke-width="1.5" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" d="M 610 118 L 562 78" stroke-width="1.5" marker-end="url(#os-c4-arr-16)"/>
    <!-- 环外无请求可消边：R1左边点->P2, R2右边点->P4 -->
    <path class="fig-line-green" d="M 509 72 L 420 64" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <path class="fig-line-green" d="M 545 186 L 634 194" stroke-width="1.6" marker-end="url(#os-c4-arr-16)"/>
    <text class="fig-muted" x="527" y="48" font-size="10" text-anchor="middle">R1 (2 实例)</text>
    <text class="fig-muted" x="527" y="218" font-size="10" text-anchor="middle">R2 (2 实例)</text>
    <text class="fig-orange" x="426" y="133" font-size="11" text-anchor="middle">P1</text>
    <text class="fig-orange" x="628" y="133" font-size="11" text-anchor="middle">P3</text>
    <text class="fig-green" x="400" y="68" font-size="10.5" text-anchor="middle">P2</text>
    <text class="fig-green" x="654" y="198" font-size="10.5" text-anchor="middle">P4</text>
    <text class="fig-green" x="527" y="238" font-size="10.2" text-anchor="middle">P2、P4 无请求 → 率先消去释放实例 → 打破环路！</text>
  </svg>
  <figcaption>图 4-16　资源分配图（RAG）标准边画法及单实例（充要）与多实例（必要不充分）环路判别对比</figcaption>
</figure>

**★资源分配图化简规则与死锁定理**：
1. 在 RAG 中找出一个**既不阻塞**（它所申请的各类资源数量均小于或等于系统当前剩余空闲实例数）**又非独立**（尚连着分配边或请求边）的进程节点 $P_i$ ；
2. 消去 $P_i$ 的所有**请求边与分配边**，使其成为孤立节点，同时把 $P_i$ 原先占用的资源归还系统（对应方框空闲实例数增加）；
3. 重复上述步骤直至再也找不到满足条件的可化简节点为止。

**死锁定理**：系统状态 $S$ 为死锁状态的充分必要条件是——**当且仅当状态 $S$ 的资源分配图是不可完全简化的**！而且可以证明，无论先消去哪一个可简化进程，最终剩余的不可简化图（即**死锁进程集合**）是**唯一确定**的。

#### 4.6.2 死锁检测算法（矩阵法）与银行家算法的唯一分界 ★

程序实现时，资源分配图化简算法可机械地等价为矩阵迭代（与银行家安全性算法形态几乎相同）：
- 设 `Available[m]` 为当前空闲资源向量，`Allocation[n][m]` 为已分配矩阵，**请求矩阵** `Request[n][m]` 为每个进程当前实际已提出的请求向量，建立已证实可运行完毕的集合 `L`：
  1. `Work = Available` ；先将所有 `Allocation_i == 0 && Request_i == 0` 的本来孤立节点记入 `L` ；
  2. 寻找满足 $P_i \notin L$ 且 **`Request[i] <= Work`** 的进程，将 `Work += Allocation[i]` 并把 $P_i$ 记入 `L` ；
  3. 反复迭代至找不到满足条件的进程：若最终全集未尽入 `L` ，则未入 `L` 的进程即为死锁进程集！

> **★考点（死锁避免 S1 vs 死锁检测 S2 的唯一核心分水岭，`15#26`）**：
> - **死锁避免（银行家算法）** 比较的是 **`Need <= Work`**（需要预先知道进程整个生命周期的**最大资源总量 `Max`**）；
> - **死锁检测** 比较的是 **`Request <= Work`**（只看当前这一刻已经实际提出的请求，**不需要事先知道总需求 `Max` 或 `Need`**！）。
> - 此外，限制资源申请顺序属于**死锁预防**（资源有序分配法），**避免和检测都不限制进程申请资源的顺序**。

**检测策略的三种调用时机**：① 每次资源请求得不到满足时（实时性最好但 $O(n^2 m)$ 开销极高）；② **定时周期性检测**（折中方案）；③ **当发现 CPU 利用率异常下降（且就绪队列为空/很短）时启动检测**（成因是大量死锁进程阻塞不占 CPU，但要注意 I/O 密集型也会导致 CPU 利用率下降，只是外部征兆而非定论）。

<figure class="cpd-figure not-content" id="os-c4-fig-17">
  <svg viewBox="0 0 720 292" role="img" aria-label="资源分配图机械化简步进对比（可完全简化无死锁 vs 不可完全简化存在死锁）">
    <defs>
      <marker id="os-c4-arr-17" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <!-- 左区：可完全简化 (R1=2, R2=1; P1占1个R1求R2; P2占1个R2求R1; P3占1个R1无请求) -->
    <rect class="fig-box-subtle" x="16" y="14" width="338" height="264" rx="8"/>
    <text class="fig-green" x="185" y="34" font-size="11.5" text-anchor="middle">情形 A：可完全简化 → 无死锁（P3 无请求）</text>
    <rect class="fig-box" x="28" y="46" width="314" height="62" rx="5"/>
    <rect class="fig-box-green" x="28" y="118" width="314" height="44" rx="5"/>
    <rect class="fig-box-green" x="28" y="172" width="314" height="44" rx="5"/>
    <rect class="fig-box-green" x="28" y="226" width="314" height="40" rx="5"/>
    <line class="fig-line-accent" x1="185" y1="108" x2="185" y2="118" stroke-width="1.4" marker-end="url(#os-c4-arr-17)"/>
    <line class="fig-line-accent" x1="185" y1="162" x2="185" y2="172" stroke-width="1.4" marker-end="url(#os-c4-arr-17)"/>
    <line class="fig-line-accent" x1="185" y1="216" x2="185" y2="226" stroke-width="1.4" marker-end="url(#os-c4-arr-17)"/>
    <text class="fig-label" x="185" y="63" font-size="10.2" text-anchor="middle">初始状态：总量 R1=2, R2=1 ｜ 空闲 Work=(0, 0)</text>
    <text class="fig-muted" x="185" y="80" font-size="9.8" text-anchor="middle">Alloc: P1(1,0), P2(0,1), P3(1,0)</text>
    <text class="fig-muted" x="185" y="96" font-size="9.8" text-anchor="middle">Req: P1(0,1), P2(1,0), P3(0,0)</text>
    <text class="fig-green" x="185" y="136" font-size="10.5" text-anchor="middle">第 1 步：选 P3 (Req 0,0 ≤ Work 0,0) → 消边释放</text>
    <text class="fig-muted" x="185" y="152" font-size="9.8" text-anchor="middle">Work 变为 (0,0)+(1,0) = (1, 0)，P3 成孤立点</text>
    <text class="fig-green" x="185" y="190" font-size="10.5" text-anchor="middle">第 2 步：选 P2 (Req 1,0 ≤ Work 1,0) → 消边释放</text>
    <text class="fig-muted" x="185" y="206" font-size="9.8" text-anchor="middle">Work 变为 (1,0)+(0,1) = (1, 1)，撬动最后一环</text>
    <text class="fig-green" x="185" y="250" font-size="10.5" text-anchor="middle">第 3 步：选 P1 (Req 0,1 ≤ 1,1) → 全消完，无死锁 ✓</text>
    <!-- 右区：仅改 P3 请求 R2 -> 不可简化死锁 -->
    <rect class="fig-box-subtle" x="366" y="14" width="338" height="264" rx="8"/>
    <text class="fig-red" x="535" y="34" font-size="11.5" text-anchor="middle">情形 B：不可完全简化 → 死锁（仅增 P3→R2 边）</text>
    <rect class="fig-box" x="378" y="46" width="314" height="62" rx="5"/>
    <rect class="fig-box-red" x="378" y="118" width="314" height="36" rx="5"/>
    <rect class="fig-box-red" x="378" y="160" width="314" height="36" rx="5"/>
    <rect class="fig-box-red" x="378" y="202" width="314" height="36" rx="5"/>
    <rect class="fig-box-orange" x="378" y="244" width="314" height="24" rx="4"/>
    <text class="fig-label" x="535" y="68" font-size="10.2" text-anchor="middle">修改：仅将 P3 改为请求 1 个 R2，其余全同</text>
    <text class="fig-muted" x="535" y="88" font-size="9.8" text-anchor="middle">此时空闲 Work = (0, 0)，逐一核对全部请求：</text>
    <text class="fig-red" x="535" y="140" font-size="10.5" text-anchor="middle">P1：Req (0, 1) &gt; Work (0, 0) → 阻塞 ✕</text>
    <text class="fig-red" x="535" y="182" font-size="10.5" text-anchor="middle">P2：Req (1, 0) &gt; Work (0, 0) → 阻塞 ✕</text>
    <text class="fig-red" x="535" y="224" font-size="10.5" text-anchor="middle">P3：Req (0, 1) &gt; Work (0, 0) → 阻塞 ✕</text>
    <text class="fig-orange" x="535" y="260" font-size="10.2" text-anchor="middle">★ 死锁定理：图不可完全简化，死锁集 = {P1, P2, P3}</text>
  </svg>
  <figcaption>图 4-17　资源分配图（RAG）与检测矩阵法的一正一反机械推演对照</figcaption>
</figure>

#### 4.6.3 死锁解除的四大手段

一旦确认发生死锁，除最原始的人工干预重启（通知操作员手工杀进程）外，系统级自动解除主要围绕以下方式展开：

1. **资源剥夺法（挂起抢占）**：强行将某些死锁进程所占有的资源（如挂起该进程）剥夺出来，转分给其他死锁进程使用。
   - **需解决的三件事**：**抢谁**（最小代价）、**防饥饿**（不能每次死锁都揪住同一个倒霉进程剥夺）与**被抢进程回滚**。
2. **撤销/终止进程法**：强制终止部分或全部死锁进程以释放其占有的全部资源、彻底打破循环等待链。包含两种极端粒度：
   - **全部撤销**：把参与死锁的所有进程一口气全杀掉——最简单粗暴，但代价极惨重（可能让一个即将运行 99% 完成的长计算任务“功亏一篑”）。
   - **逐个撤销**：按某种代价排序规则逐个终止死锁进程。**★注意易错坑**：每撤销一个进程释放出资源后，**都必须重新运行一遍死锁检测算法**，确认环路是否已解开，只有未解除时才继续杀下一个！
   - **挑谁先终止的四条代价依据**：进程优先级低者优先、已执行时间少而还需时间多者优先、已占用资源多且后续还需更多资源者优先、批处理式进程优先于交互式进程。
3. **进程回退法（Rollback）**：让一个或多个死锁进程退回到先前尚未发生资源冲突的一致历史状态，释放回退期间获得的资源后再行重启。回退粒度取决于系统是否建立<strong>检查点（Checkpoint）</strong>机制——若有检查点，只需退回最近一个已落盘稳定存储器的检查点快照；若无检查点，则被迫完全回滚（相当于杀掉重跑）。

<figure class="cpd-figure not-content" id="os-c4-fig-18">
  <svg viewBox="0 0 720 238" role="img" aria-label="死锁核心考点全景对比与 408 命题四大分水岭总结图">
    <rect class="fig-box-subtle" x="16" y="14" width="688" height="210" rx="8"/>
    <text class="fig-title" x="360" y="34" font-size="12" text-anchor="middle">死锁处理全家族核心分水岭与 408 真题命题套路总览</text>
    <!-- 4 张分界线卡片 -->
    <rect class="fig-box-blue" x="28" y="48" width="324" height="76" rx="6"/>
    <rect class="fig-box-green" x="368" y="48" width="324" height="76" rx="6"/>
    <rect class="fig-box-orange" x="28" y="134" width="324" height="76" rx="6"/>
    <rect class="fig-box-purple" x="368" y="134" width="324" height="76" rx="6"/>
    <text class="fig-blue" x="40" y="68" font-size="11.2">分水岭 ①：预防 vs 避免（15#26, 19#30）</text>
    <text class="fig-label" x="40" y="88" font-size="10.2">• 预防：静态破坏四条件之一（仅有序分配最实用）</text>
    <text class="fig-label" x="40" y="106" font-size="10.2">• 避免：不破坏条件、不限申请序，动态防进不安全</text>
    <text class="fig-green" x="380" y="68" font-size="11.2">分水岭 ②：避免(银行家) vs 检测（15#26）</text>
    <text class="fig-label" x="380" y="88" font-size="10.2">• 银行家：事前检查，需总需求 Max/Need（保守）</text>
    <text class="fig-label" x="380" y="106" font-size="10.2">• 检测：事后诊断，只需当前请求 Request（乐观）</text>
    <text class="fig-orange" x="40" y="154" font-size="11.2">分水岭 ③：最小资源数与反推公式（09#25, 21#31）</text>
    <text class="fig-label" x="40" y="174" font-size="10.2">• R_min = m(k−1)+1 或 ∑(k_i−1)+1（抽屉极值）</text>
    <text class="fig-label" x="40" y="192" font-size="10.2">• 反向求最多进程数：m_max = ⌊(R−1)/(k−1)⌋</text>
    <text class="fig-purple" x="380" y="154" font-size="11.2">分水岭 ④：死锁解除关键流程与代价</text>
    <text class="fig-label" x="380" y="174" font-size="10.2">• 逐个终止：每撤消 1 个必重跑一次死锁检测 ★</text>
    <text class="fig-label" x="380" y="192" font-size="10.2">• 剥夺/回退：依赖检查点快照与防饥饿选牺牲品</text>
  </svg>
  <figcaption>图 4-18　死锁策略全家族四大核心分水岭与历年 408 真题常考套路总览</figcaption>
</figure>

> **★考点（本章 408 真题命题地图速览）**：
> - **调度时机与上下文切换**：普通临界区可调度、内核临界区/中断中/原语中禁调度（`12#30, 21#27`）；时间片用完变就绪态（`17#27`）；时间片轮转依赖“时钟中断+PCB+就绪队列”（`21#25`）；页式虚存切换不需要换“内核中断向量表基址寄存器”（`25#23`）。
> - **调度算法计算与概念**：FCFS 与 SJF 须先圈定“当前已到达集合”（`17#23`）；HRRN 是唯一既考虑等待又考虑运行且不饥饿的算法（`09#24, 11#23`）；优先级调度先看数值大小方向再看抢占性（`18#24, 22#25, 23#29`）、I/O 密集型优先级应高于 CPU 密集型（`13#31`）、刚用完时间片应降低优先级（`10#26`）、老化防饥饿（`16#46`）；RR 手算严守同一种冲突入队约定（`24#30`）；MLFQ 区分“用完降级”与“被抢占回原队列队尾”（`19#27, 20#26`）。
> - **死锁定理与银行家**：`m(k-1)+1` 双向正反套算（`09#25, 14#24, 21#31`）；成环进程数与有序分配（`16#25`）；避免需 `Need`、检测仅用 `Request`、限制顺序属预防（`15#26`）；银行家四步手算与“末态 `Work` $=$ 总资源量”自检（`11#27, 12#27, 13#32, 18#26, 20#27, 22#26`）。

## 第5章 内存管理

### 5.1 内存管理概念：从程序装入到地址空间虚拟化 ★

#### 5.1.1 内存虚拟化哲学与五大核心功能

在多道程序系统中，操作系统面对的核心资源矛盾在处理器与主存两端截然不同：CPU 只有一个（或少数核心），可以通过时间片轮转与上下文切换在**时间上复用**；但主存里驻留着进程的代码与数据，动辄数十 MB 至数 GB，不可能在每次进程切换时整体倒腾进出磁盘。因此，内存必须在**空间上同时分给多个进程**，并借助**内存虚拟化**技术编织出“每个进程都独占一片从 0 开始、连续且足够大的私有内存”的完美假象。

从架构层次上看，内存虚拟化由四层协同落地：

1. **抽象（Abstraction）**：为每个进程提供独立的**虚拟地址空间（逻辑地址空间）**，屏蔽物理内存碎片与并发干扰。
2. **接口（Interface）**：向上为程序提供动态申请与释放内存的系统接口（如 C 语言的 `malloc` / `free`、`mmap` / `munmap`，C++ 的 `new` / `delete`）。
3. **机制（Mechanism）**：**操作系统负责制定并维护映射规则（如建立和更新页表）**，**硬件 MMU（内存管理单元）与 TLB 负责在每条访存指令执行时高速完成地址转换与越界检测**——由于访存频率极高，地址翻译绝对不能每次陷入内核用软件完成。
4. **策略（Policy）**：物理内存不足时，由操作系统决定给每个进程分配多少页框、缺页时淘汰哪一页。

一旦多个进程在物理内存中并存，内存管理必须解决相互关联的**五大核心功能**：

| 核心功能 | 解决的核心矛盾 | 典型机制与代表技术 |
|---|---|---|
| **地址变换（重定位）** | 编译期无法预知装入位置，程序只能从 `0` 编址 | 绝对装入、静态重定位、**动态重定位**（基址寄存器 / MMU + 页表） |
| **内存分配与回收** | 有限主存空间需分配给多进程并动态归还合并 | 连续分配（空闲分区表/链）、离散分配（位示图/页表） |
| **内存保护** | 防止某进程越界读写踩坏内核或其他进程数据 | **界地址保护**（基址+界限寄存器）、页/段表越界与读写权限位 |
| **内存共享** | 保护不能一刀切死，共享库与 IPC 需共同访问同一份数据 | **可重入纯代码**、共享段表（`count` 计数）、共享 `mmap` 映射 |
| **内存扩充** | 所有进程需求总和超过实际物理内存容量 | 覆盖技术、交换（对换）技术、**虚拟内存**（请求分页/分段） |

> **★考点**：整章演进受一条清晰的因果链推动——整块连续存放 → 装卸频繁产生**外部碎片** → 改用离散存放（分页/分段/段页式）→ 产生翻译与页表空间开销（TLB + 多级页表）→ 进程依然受限于全部装入 → 引入**虚拟内存**（按需调入 + 页面置换）→ 换页过勤导致**抖动**（工作集 + 页框分配控制）。

---

#### 5.1.2 程序的编译、链接与装入全流程 ★

一个高级语言程序从源代码变成内存中可运行的进程，必须经历**编辑 → 编译 → 链接 → 装入**四个阶段。之所以无法一步到位写出物理地址，根本原因在于**两级位置未知**：

1. **编译期未知模块间拼接位置**：编译器处理单个源文件（如 `a.c`、`b.c`）时，不知道最终还有哪些模块拼在它前面，只能假定**本模块内部从 `0` 开始**编址。
2. **链接期未知内存物理基址**：链接器把多个目标模块首尾相接拼成一个装入模块（可执行文件）时，除第一个模块外，其余模块内部相对地址都要加上前面模块的总长度，同时解析外部符号引用（如 `CALL printf`）；拼好后的装入模块整体仍然从 **`0` 开始**编号——**完整的逻辑地址正是在链接阶段形成**，而非编译阶段。
3. **装入期才确定物理地址**：多道环境下装入模块在物理内存中的起始位置要等装入或运行时才能确定，因此还需进行第二次重定位。

<figure class="cpd-figure not-content" id="os-c5-fig-1">
  <svg viewBox="0 0 720 326" role="img" aria-label="程序编译链接装入两级地址重定位与三种装入方式对比示意图">
    <defs>
      <marker id="os-c5-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="148" rx="6" class="fig-box-subtle"/>
    <rect x="16" y="172" width="336" height="140" rx="6" class="fig-box-subtle"/>
    <rect x="368" y="172" width="336" height="140" rx="6" class="fig-box-subtle"/>
    <line x1="158" y1="78" x2="188" y2="78" class="fig-line" marker-end="url(#os-c5-arr-1)"/>
    <line x1="342" y1="78" x2="372" y2="78" class="fig-line-accent" marker-end="url(#os-c5-arr-1)"/>
    <line x1="538" y1="78" x2="568" y2="78" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-1)"/>
    <rect x="28" y="42" width="130" height="72" rx="5" class="fig-box"/>
    <rect x="190" y="42" width="152" height="72" rx="5" class="fig-box-blue"/>
    <rect x="374" y="42" width="164" height="72" rx="5" class="fig-box-accent"/>
    <rect x="570" y="42" width="122" height="72" rx="5" class="fig-box-green"/>
    <rect x="28" y="122" width="664" height="30" rx="4" class="fig-box"/>
    <rect x="28" y="206" width="312" height="94" rx="5" class="fig-box-orange"/>
    <rect x="380" y="206" width="312" height="94" rx="5" class="fig-box-green"/>
    <text x="360" y="33" text-anchor="middle" font-size="11.5" class="fig-title">从源代码到物理内存的两级重定位流程（第 1 级管模块间，第 2 级管整体入内存）</text>
    <text x="93" y="64" text-anchor="middle" font-size="11" class="fig-title">① 编辑（源程序）</text>
    <text x="93" y="83" text-anchor="middle" font-size="10" class="fig-label">a.c / b.c / c.c</text>
    <text x="93" y="101" text-anchor="middle" font-size="9.5" class="fig-muted">变量名/函数名（符号）</text>
    <text x="266" y="64" text-anchor="middle" font-size="11" class="fig-blue">② 编译（目标模块）</text>
    <text x="266" y="83" text-anchor="middle" font-size="10" class="fig-label">模块 A(0..L) B(0..M)</text>
    <text x="266" y="101" text-anchor="middle" font-size="9.5" class="fig-muted">各自从 0 编址（局部相对）</text>
    <text x="456" y="64" text-anchor="middle" font-size="11" class="fig-accent">③ 链接（装入模块）★</text>
    <text x="456" y="83" text-anchor="middle" font-size="10" class="fig-label">B+L, C+L+M &amp; 库函数</text>
    <text x="456" y="101" text-anchor="middle" font-size="9.5" class="fig-accent">形成完整逻辑地址（0 起）</text>
    <text x="631" y="64" text-anchor="middle" font-size="11" class="fig-green">④ 装入（内存映像）</text>
    <text x="631" y="83" text-anchor="middle" font-size="10" class="fig-label">加装入基址 Base</text>
    <text x="631" y="101" text-anchor="middle" font-size="9.5" class="fig-muted">内核态分配页框/填页表</text>
    <text x="360" y="141" text-anchor="middle" font-size="10" class="fig-label">执行模式考点（26#23）：编辑、编译、链接、命令解释程序均在用户态运行；只有“装入程序”需分配物理内存与建表，在内核态运行</text>
    <text x="184" y="194" text-anchor="middle" font-size="11" class="fig-title">静态重定位（可重定位装入）</text>
    <text x="184" y="226" text-anchor="middle" font-size="10" class="fig-orange">装入时一次性按重定位表 + Base</text>
    <text x="184" y="245" text-anchor="middle" font-size="10" class="fig-label">指令中直接写入最终物理地址（如 12000）</text>
    <text x="184" y="264" text-anchor="middle" font-size="9.5" class="fig-muted">无需硬件支持，但装入后绝对不可移动</text>
    <text x="184" y="283" text-anchor="middle" font-size="9.5" class="fig-muted">必须一次性全部分配、运行期不能再申请内存</text>
    <text x="536" y="194" text-anchor="middle" font-size="11" class="fig-title">动态重定位（动态运行时装入）★</text>
    <text x="536" y="226" text-anchor="middle" font-size="10" class="fig-green">推迟到每次访存时由硬件（MMU）转换</text>
    <text x="536" y="245" text-anchor="middle" font-size="10" class="fig-label">内存中指令仍保留逻辑地址（如 2000）</text>
    <text x="536" y="264" text-anchor="middle" font-size="9.5" class="fig-muted">允许程序搬家：只需改写重定位寄存器值</text>
    <text x="536" y="283" text-anchor="middle" font-size="9.5" class="fig-muted">唯一支持紧凑、对换与部分装入（虚存）的方式</text>
  </svg>
  <figcaption>图 5-1　程序编译—链接—装入两级地址重定位与静/动态装入对比（完整逻辑地址在链接阶段形成）</figcaption>
</figure>

**（1）链接产物的内部构成与链接三件事**

目标模块与链接后的可执行文件（如 ELF）并不只是裸机器码，还包含：**代码段（`.text`）**、**已初始化数据段（`.data`）**、**未初始化数据段说明（`.bss`，只记长度不占文件空间，装入时清零开辟）**、**符号表**（记录本模块定义与引用的外部符号）、**重定位表**（列出需要修正地址的偏移位置）。

链接器把多个目标模块 $A, B, C$（长度分别为 $L, M, N$ ）合并时完成三件事：① **装配库函数**；② **相对地址重编址**（ $B$ 内偏移统一加 $L$ ， $C$ 内偏移统一加 $L + M$ ）；③ **外部符号引用解析**（将 `CALL B`、`CALL C` 等符号名替换为具体逻辑地址 $L$ 、 $L + M$ ）。

**（2）三种链接方式对比**

| 链接方式 | 外部模块拼入时机 | 优点 | 缺点与限制 |
|---|---|---|---|
| **静态链接** | 程序运行前，一次链接成完整装入模块 | 装入即可运行，无运行期链接开销 | 可执行文件体积大；库函数在各程序中重复拷贝；更新某个模块须重链接全部 |
| **装入时动态链接** | 装入内存时，边装入边链接 | 便于模块独立修改更新；**便于多应用共享目标模块** | 装入变慢；运行期间用不到的分支模块（如错误处理）仍被装入占内存 |
| **运行时动态链接** | **执行中真正调用到该模块时**才装入并链接 | 加快启动装入；未执行分支根本不调入，**最节省内存** | 首次调用存在链接延迟；需要操作系统运行期链接支持 |

> **注意**：动态链接库之所以能被多个进程共享，核心前提是库代码必须是**可重入代码（纯代码）**——执行过程中绝对不能修改代码自身，也不在代码段保存跨调用的私有状态。

**（3）三种装入方式对比**

| 比较维度 | 绝对装入 | 静态重定位（可重定位装入） | 动态重定位（动态运行时装入） |
|---|---|---|---|
| **指令中留存的地址** | 物理地址（编译/汇编期确定） | 物理地址（装入期按重定位表改写） | **逻辑地址（装入后一直未改）** |
| **地址转换时机** | 编译/汇编时（或程序员手写） | 装入内存时一次性改写 | **运行时每次访存** |
| **装入后可否移动** | 不可移动 | 不可移动 | **可任意移动**（只需更新重定位寄存器） |
| **一次分配全部内存** | 必须 | 必须（且运行期不能动态扩充） | 无需（支持对换、紧凑与按需调入虚存） |
| **硬件支持** | 无 | 无 | **必需**（重定位寄存器 + 界地址寄存器 / MMU） |
| **适用系统** | 单道程序系统（如早期单片机） | 早期多道系统（固定分区） | 现代操作系统（动态分区、紧凑、虚存） |

> **★考点**：`11#30` 考过“逻辑地址在哪个阶段形成？”——答案是**链接阶段**，不是编译阶段（编译只产生各模块局部相对地址）。`26#23` 考过“编译程序、链接程序、装入程序、命令解释程序哪个在内核态执行？”——答案是**装入程序**（只有它需分配物理页框、建立页表、初始化 PCB 等内核特权操作，其余三者均运行在用户态）。此外，**装入与链接是两项解耦的知识点**，切忌强行将三种链接与三种装入做一对一捆绑。

---

#### 5.1.3 运行时内存映像与地址空间划分 ★

程序装入内存成为运行中的**进程**后，其虚拟地址空间（**进程内存映像**）并非把可执行文件原样搬进主存。以经典 32 位 Linux（按字节编址，$2^{32}\text{ B} = 4\text{ GB}$ ）为例，每个进程都拥有独立、连续的 $0 \sim 4\text{ GB} - 1$ 虚拟地址空间，由体系结构地址位数直接决定，**与实际安装的物理内存及硬盘容量无关**（`23#28` 曾考查此易错点）。

1. **高地址 1 GB 内核空间**（`0xC0000000` ～ `0xFFFFFFFF`）：仅内核态可访问，存放内核代码、内核数据结构、**各进程的 PCB 与内核栈、页表**等。系统物理内存中**只有一份内核**，却映射到每个进程地址空间顶部——原因在于进程随时因中断、异常或系统调用陷入内核，若内核不在当前地址空间内，每次陷入都必须切换整套页表并刷新 TLB，性能代价无法承受；安全性则靠页表项特权级位保证，用户态访问立即触发保护异常。
2. **低地址 3 GB 用户空间**（`0x00000000` ～ `0xBFFFFFFF`），自低地址向高地址依次布局如下：

<figure class="cpd-figure not-content" id="os-c5-fig-2">
  <svg viewBox="0 0 720 342" role="img" aria-label="32位进程运行时虚拟内存映像布局与多进程内核物理共享示意图">
    <defs>
      <marker id="os-c5-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="350" height="314" rx="6" class="fig-box-subtle"/>
    <rect x="382" y="14" width="322" height="176" rx="6" class="fig-box-subtle"/>
    <rect x="382" y="200" width="322" height="128" rx="6" class="fig-box-subtle"/>
    <line x1="250" y1="108" x2="250" y2="126" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-2)"/>
    <line x1="250" y1="180" x2="250" y2="160" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-2)"/>
    <line x1="348" y1="54" x2="544" y2="54" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-2)"/>
    <polyline points="424,146 472,146 472,72 544,72" class="fig-line-dashed" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-2)"/>
    <rect x="32" y="38" width="314" height="38" rx="4" class="fig-box-red"/>
    <rect x="32" y="78" width="314" height="30" rx="4" class="fig-box-blue"/>
    <rect x="32" y="128" width="314" height="30" rx="4" class="fig-box-orange"/>
    <rect x="32" y="180" width="314" height="32" rx="4" class="fig-box-green"/>
    <rect x="32" y="214" width="314" height="30" rx="4" class="fig-box-accent"/>
    <rect x="32" y="246" width="314" height="30" rx="4" class="fig-box-purple"/>
    <rect x="32" y="278" width="314" height="26" rx="4" class="fig-box"/>
    <rect x="546" y="40" width="144" height="50" rx="4" class="fig-box-red"/>
    <rect x="546" y="94" width="144" height="82" rx="4" class="fig-box"/>
    <rect x="394" y="126" width="128" height="48" rx="4" class="fig-box-blue"/>
    <rect x="394" y="212" width="298" height="104" rx="4" class="fig-box-accent"/>
    <text x="190" y="31" text-anchor="middle" font-size="10.2" class="fig-title">进程虚拟地址空间（32 位 = 4 GB，低 3 GB 用户 + 高 1 GB 内核）</text>
    <text x="189" y="54" text-anchor="middle" font-size="10.5" class="fig-red">内核空间（1 GB：0xC0000000–0xFFFFFFFF）★</text>
    <text x="189" y="70" text-anchor="middle" font-size="9.5" class="fig-label">PCB · 页表 · 内核代码/栈 · 仅内核态可访问</text>
    <text x="189" y="97" text-anchor="middle" font-size="10.2" class="fig-blue">用户栈 Stack（局部变量 / 参数 / 返回地址）</text>
    <text x="260" y="121" font-size="9.2" class="fig-blue">向低址增长</text>
    <text x="189" y="147" text-anchor="middle" font-size="10.2" class="fig-orange">共享库（.so/.dll）与 mmap 文件映射区</text>
    <text x="260" y="173" font-size="9.2" class="fig-green">向高址增长</text>
    <text x="189" y="200" text-anchor="middle" font-size="9.8" class="fig-green">堆 Heap（malloc / new，含堆碎片）</text>
    <text x="189" y="233" text-anchor="middle" font-size="9.8" class="fig-accent">BSS（未初始化全局/静态）+ .data（已初始化全局/静态）</text>
    <text x="189" y="265" text-anchor="middle" font-size="9.4" class="fig-purple">只读代码与常量区 .text / .rodata（指令与 const 常变量）</text>
    <text x="189" y="295" text-anchor="middle" font-size="9.5" class="fig-muted">保留区（0x00000000 附近不可访问，防空指针解引用）</text>
    <text x="543" y="31" text-anchor="middle" font-size="11" class="fig-title">物理内存：全机仅一份内核</text>
    <text x="618" y="61" text-anchor="middle" font-size="10.5" class="fig-red">唯一物理内核区</text>
    <text x="618" y="79" text-anchor="middle" font-size="9.5" class="fig-label">所有进程页表共用此区</text>
    <text x="618" y="122" text-anchor="middle" font-size="10" class="fig-label">各进程用户区页框</text>
    <text x="618" y="142" text-anchor="middle" font-size="9.5" class="fig-muted">离散存放代码/数据/堆/栈</text>
    <text x="618" y="160" text-anchor="middle" font-size="9.5" class="fig-muted">彼此隔离</text>
    <text x="458" y="146" text-anchor="middle" font-size="10" class="fig-blue">另一进程 P2</text>
    <text x="458" y="163" text-anchor="middle" font-size="9.5" class="fig-muted">同样共享内核区</text>
    <text x="543" y="232" text-anchor="middle" font-size="10.5" class="fig-accent">C 程序对象定位速查（25#46 真题考点）★</text>
    <text x="406" y="251" font-size="9.5" class="fig-label">• #define X 1024：预编译替换为立即数，隐含在代码指令中</text>
    <text x="406" y="269" font-size="9.5" class="fig-label">• 全局 const 常变量、指令代码：只读代码/常量区</text>
    <text x="406" y="287" font-size="9.2" class="fig-label">• 全局指针 char *ptr; (指向 malloc(100))：ptr 本身在</text>
    <text x="412" y="303" font-size="9" class="fig-red">读写数据段（.data/.bss），所指 100 B 空间在堆区！</text>
  </svg>
  <figcaption>图 5-2　32 位进程运行时虚拟内存映像布局、内核物理共享映射及 C 语言对象定位辨析</figcaption>
</figure>

| 内存区域 | 内容来源与典型 C 对象 | 在可执行文件中是否占空间 | 读写权限与大小变化 |
|---|---|---|---|
| **只读代码/常量区**（`.text` / `.rodata`） | 机器指令、`const` 修饰只读常变量、字符串字面量 | **占**（原样存储） | 只读、可执行；大小固定 |
| **读写数据段**（`.data`） | **已初始化**的全局变量与 `static` 静态变量 | **占**（需存初值） | 可读可写；大小固定 |
| **BSS 段**（`.bss`） | **未初始化**（或初始化为 `0`）的全局/静态变量 | **不占**（仅记总长度） | 可读可写；装入时由 OS 清零开辟 |
| **堆区**（Heap） | `malloc` / `new` 动态申请的空间（非二叉堆数据结构） | 不占（运行时动态分配） | 可读可写；**向高地址增长**，$O(n)$ 链表分配，有碎片 |
| **共享库 / 映射区** | 动态链接库（`.so` / `.dll`）及 `mmap` 映射区 | 不占（只记依赖库名） | 按页表保护位决定 |
| **用户栈区**（Stack） | 函数栈帧（实参、返回地址、上帧帧指针、局部变量） | 不占（调用自动压栈） | 可读可写；**向低地址增长**，LIFO $O(1)$，无碎片 |
| **内核空间** | OS 内核代码与数据、**PCB**、页表、内核栈 | — | 仅内核态可访问 |

> **注意**：三个 408 高频陷阱必须精准辨析——① **宏定义常量 `#define N 1024`** 在预编译阶段直接文本替换，作为**立即数**嵌入机器指令中，不会像 `const` 常变量那样在内存中单独分配数据存储单元；② **`BSS` 段揭示“文件布局 ≠ 内存布局”**：`int arr[1000000];` 在磁盘可执行文件里只占几字节长度描述，运行起来却占满 $4\text{ MB}$ 内存；③ **`25#46` 大题核心分辨点**：全局指针变量 `char *ptr = (char *)malloc(100);` 中，**指针变量 `ptr` 本身存放在读写数据段**，而 **`ptr` 指向的那 $100\text{ B}$ 内存单元在堆区**；函数的局部变量若未驻留寄存器则在**用户栈**；**PCB 在内核空间**。此外，堆与栈在中间空闲区相向增长，是为了在两者大小均不可预知时最大化复用同一块地址空间。

---

#### 5.1.4 内存保护、共享与早期内存扩充技术

**（1）内存保护的两套硬件方案**

| 方案 | 寄存器配置 | 检查对象与判据 | 优缺点与定位 |
|---|---|---|---|
| **上下限（界限）寄存器** | 下限寄存器 = 最小物理地址；上限寄存器 = 最大物理地址 | 检查**变换后的物理地址**：$\text{下限} \le PA \le \text{上限}$ | 先加后查，若越界则已经算出非法物理地址；早期简单系统采用 |
| **基址 + 界地址（限长）寄存器** | 重定位（基址）寄存器 = 起始物理地址；界地址寄存器 = 逻辑地址空间长度 | 检查**变换前的逻辑地址**：$LA < \text{界地址}$，通过后才算 $PA = \text{基址} + LA$ | **越界检查先于地址变换**，越界立即触发异常终止进程，且两者可硬件并行加速；分页（$P < \text{页表长度}$）、分段（$S < \text{段表长度}$）均为其直系后代 |

> **★考点**：`09#26` 明确指出，分区分配内存管理方式的主要保护措施就是**界地址保护**。同时注意**先检查逻辑地址是否越界，再执行重定位加法**（一旦越界硬件立即中断，不存在“算出来的物理地址”）；当进程被换出再换入到新起始物理地址时，只需改写**重定位寄存器**，**界地址寄存器无需修改**（它反映的是进程自身逻辑地址空间的长度）。

<figure class="cpd-figure not-content" id="os-c5-fig-3">
  <svg viewBox="0 0 720 250" role="img" aria-label="内存保护基址加界限寄存器与上下限寄存器硬件校验链路对比图">
    <defs>
      <marker id="os-c5-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="440" height="222" rx="6" class="fig-box-subtle"/>
    <rect x="468" y="14" width="236" height="222" rx="6" class="fig-box-subtle"/>
    <line x1="94" y1="86" x2="140" y2="86" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-3)"/>
    <polyline points="85,128 85,116 164,116 164,108" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-3)"/>
    <line x1="196" y1="106" x2="196" y2="176" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-3)"/>
    <line x1="226" y1="86" x2="294" y2="86" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-3)"/>
    <line x1="316" y1="126" x2="316" y2="108" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-3)"/>
    <line x1="338" y1="86" x2="376" y2="86" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-3)"/>
    <line x1="586" y1="84" x2="586" y2="106" class="fig-line" marker-end="url(#os-c5-arr-3)"/>
    <line x1="586" y1="146" x2="586" y2="168" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-3)"/>
    <rect x="28" y="68" width="66" height="36" rx="4" class="fig-box-blue"/>
    <rect x="142" y="64" width="84" height="42" rx="5" class="fig-box-accent"/>
    <rect x="28" y="128" width="114" height="32" rx="4" class="fig-box"/>
    <rect x="128" y="178" width="112" height="44" rx="4" class="fig-box-red"/>
    <rect x="296" y="64" width="42" height="42" rx="5" class="fig-box-green"/>
    <rect x="264" y="128" width="104" height="32" rx="4" class="fig-box"/>
    <rect x="374" y="68" width="74" height="36" rx="4" class="fig-box-green"/>
    <rect x="264" y="178" width="180" height="44" rx="4" class="fig-box-blue"/>
    <rect x="484" y="48" width="204" height="36" rx="4" class="fig-box"/>
    <rect x="484" y="108" width="204" height="38" rx="4" class="fig-box-orange"/>
    <rect x="484" y="170" width="204" height="52" rx="4" class="fig-box"/>
    <text x="236" y="34" text-anchor="middle" font-size="11.5" class="fig-title">主流方案：基址 + 界地址（限长）寄存器 ★ 先检后加</text>
    <text x="61" y="84" text-anchor="middle" font-size="10" class="fig-blue">CPU 给出</text>
    <text x="61" y="98" text-anchor="middle" font-size="9.5" class="fig-label">逻辑地址 LA</text>
    <text x="184" y="83" text-anchor="middle" font-size="10.5" class="fig-accent">比较器</text>
    <text x="184" y="98" text-anchor="middle" font-size="9.5" class="fig-accent">LA &lt; 限长?</text>
    <text x="85" y="148" text-anchor="middle" font-size="9.5" class="fig-label">界地址寄存器（限长）</text>
    <text x="188" y="168" text-anchor="end" font-size="9.5" class="fig-red">否（≥）</text>
    <text x="184" y="197" text-anchor="middle" font-size="10" class="fig-red">地址越界异常</text>
    <text x="184" y="213" text-anchor="middle" font-size="9.5" class="fig-label">中止变换并终止进程</text>
    <text x="260" y="79" text-anchor="middle" font-size="9.5" class="fig-green">是（合法）</text>
    <text x="317" y="90" text-anchor="middle" font-size="14" class="fig-green">+</text>
    <text x="316" y="148" text-anchor="middle" font-size="9.5" class="fig-label">重定位寄存器（基址）</text>
    <text x="411" y="84" text-anchor="middle" font-size="10" class="fig-green">物理地址</text>
    <text x="411" y="98" text-anchor="middle" font-size="8.4" class="fig-label">PA = Base+LA</text>
    <text x="354" y="197" text-anchor="middle" font-size="10" class="fig-blue">移动搬家时仅改 Base，限长不变</text>
    <text x="354" y="213" text-anchor="middle" font-size="9.5" class="fig-muted">（比较与加法可硬件并行提速）</text>
    <text x="586" y="34" text-anchor="middle" font-size="11.5" class="fig-title">早期方案：上下限寄存器</text>
    <text x="586" y="70" text-anchor="middle" font-size="10" class="fig-label">逻辑地址 → 形成物理地址 PA</text>
    <text x="586" y="131" text-anchor="middle" font-size="10" class="fig-orange">校验：下限 ≤ PA ≤ 上限 ?</text>
    <text x="586" y="192" text-anchor="middle" font-size="10" class="fig-label">校验对象是“变换后的物理地址”</text>
    <text x="586" y="210" text-anchor="middle" font-size="9.5" class="fig-muted">若非法，先算出物理地址再拦截</text>
  </svg>
  <figcaption>图 5-3　两套硬件内存保护链路对比（基址+界地址寄存器先判逻辑地址越界再变换）</figcaption>
</figure>

**（2）早期内存扩充：覆盖技术 vs 交换（对换）技术**

在虚拟内存诞生之前，操作系统和程序员使用过两种方法在逻辑上扩充主存：

| 对比维度 | 覆盖技术（Overlay） | 交换 / 对换技术（Swapping） |
|---|---|---|
| **作用范围** | **同一进程内部**的若干程序段之间 | **不同进程之间**，以**整个进程**为单位换入/换出 |
| **决策者与透明性** | **程序员**在源码中显式划分，**对用户不透明**（属程序设计技术） | **操作系统对换进程**自动执行，**对用户透明**（属**中级调度**） |
| **空间划分** | **常驻固定区** + 若干互斥共用的**覆盖区** | 内存 ↔ 磁盘**连续分配的对换区**（高速 I/O 优先） |
| **内存需求 / 约束** | $\text{所需内存} = \text{固定区} + \sum \text{各覆盖区内最大模块大小}$ | 被换出进程仍要求能**整体装入**才运行；**PCB 常驻内存不换出** |

- **覆盖计算陷阱**：不同覆盖区里的模块之间**不互斥**，可以同时驻留内存，因此总内存需求绝不是“固定区 + 最大的那一个覆盖区”，而是**每个覆盖区分别取其互斥组内最大模块再累加**。例如某程序固定区 `A` 占 $20\text{ KB}$，覆盖区 1 中互斥模块 `B(50 KB)`、`C(30 KB)`，覆盖区 2 中互斥模块 `D(20 KB)`、`E(40 KB)`、`F(60 KB)`，则最少需要 $20 + \max(50, 30) + \max(20, 40, 60) = 130\text{ KB}$ 内存。
- **交换的调度规则**：**换出**时优先挑驻留内存中**处于阻塞/睡眠态且优先级最低**的进程（有时还需考虑已在内存驻留时间，防止“刚换入又换出”抖动）；**换入**时从就绪但已换出（挂起就绪）的进程中挑**在磁盘上等待最久**的进程换入内存。外存对换区采用**连续分配**，其分配与回收合并规则与内存动态分区完全相同。

<figure class="cpd-figure not-content" id="os-c5-fig-4">
  <svg viewBox="0 0 720 250" role="img" aria-label="覆盖技术与交换技术内存扩充机制及计算法则对比图">
    <defs>
      <marker id="os-c5-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="336" height="222" rx="6" class="fig-box-subtle"/>
    <rect x="368" y="14" width="336" height="222" rx="6" class="fig-box-subtle"/>
    <line x1="110" y1="84" x2="110" y2="100" class="fig-line"/>
    <line x1="60" y1="100" x2="160" y2="100" class="fig-line"/>
    <line x1="60" y1="100" x2="60" y2="114" class="fig-line" marker-end="url(#os-c5-arr-4)"/>
    <line x1="160" y1="100" x2="160" y2="114" class="fig-line" marker-end="url(#os-c5-arr-4)"/>
    <line x1="60" y1="146" x2="60" y2="164" class="fig-line"/>
    <line x1="36" y1="164" x2="96" y2="164" class="fig-line"/>
    <line x1="36" y1="164" x2="36" y2="176" class="fig-line" marker-end="url(#os-c5-arr-4)"/>
    <line x1="66" y1="164" x2="66" y2="176" class="fig-line" marker-end="url(#os-c5-arr-4)"/>
    <line x1="96" y1="164" x2="96" y2="176" class="fig-line" marker-end="url(#os-c5-arr-4)"/>
    <line x1="484" y1="90" x2="564" y2="90" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-4)"/>
    <line x1="564" y1="126" x2="484" y2="126" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-4)"/>
    <rect x="76" y="48" width="68" height="34" rx="4" class="fig-box-blue"/>
    <rect x="28" y="116" width="64" height="30" rx="4" class="fig-box-green"/>
    <rect x="128" y="116" width="64" height="30" rx="4" class="fig-box-green"/>
    <rect x="22" y="178" width="28" height="24" rx="3" class="fig-box-orange"/>
    <rect x="52" y="178" width="28" height="24" rx="3" class="fig-box-orange"/>
    <rect x="82" y="178" width="28" height="24" rx="3" class="fig-box-orange"/>
    <rect x="206" y="48" width="134" height="154" rx="5" class="fig-box"/>
    <rect x="216" y="58" width="114" height="32" rx="4" class="fig-box-blue"/>
    <rect x="216" y="96" width="114" height="44" rx="4" class="fig-box-green"/>
    <rect x="216" y="146" width="114" height="46" rx="4" class="fig-box-orange"/>
    <rect x="28" y="208" width="312" height="22" rx="3" class="fig-box-accent"/>
    <rect x="380" y="52" width="102" height="106" rx="5" class="fig-box-blue"/>
    <rect x="566" y="52" width="126" height="106" rx="5" class="fig-box-orange"/>
    <rect x="380" y="168" width="312" height="58" rx="4" class="fig-box"/>
    <text x="184" y="34" text-anchor="middle" font-size="11.5" class="fig-title">覆盖技术（进程内 · 程序员设计 · 不透明）</text>
    <text x="110" y="69" text-anchor="middle" font-size="10" class="fig-blue">A (20K)</text>
    <text x="60" y="135" text-anchor="middle" font-size="9.5" class="fig-green">B(50K)</text>
    <text x="160" y="135" text-anchor="middle" font-size="9.5" class="fig-green">C(30K)</text>
    <text x="36" y="194" text-anchor="middle" font-size="9" class="fig-orange">D20</text>
    <text x="66" y="194" text-anchor="middle" font-size="9" class="fig-orange">E40</text>
    <text x="96" y="194" text-anchor="middle" font-size="9" class="fig-orange">F60</text>
    <text x="273" y="78" text-anchor="middle" font-size="10" class="fig-blue">固定区：A (20K)</text>
    <text x="273" y="114" text-anchor="middle" font-size="9.5" class="fig-green">覆盖区1：B / C</text>
    <text x="273" y="131" text-anchor="middle" font-size="9.5" class="fig-label">max = 50 KB</text>
    <text x="273" y="165" text-anchor="middle" font-size="9.5" class="fig-orange">覆盖区2：D / E / F</text>
    <text x="273" y="182" text-anchor="middle" font-size="9.5" class="fig-label">max = 60 KB</text>
    <text x="184" y="223" text-anchor="middle" font-size="9.5" class="fig-accent">总需求 = 20 + 50 + 60 = 130 KB（非 20+60！）</text>
    <text x="536" y="34" text-anchor="middle" font-size="11.5" class="fig-title">交换技术（进程间 · OS 中级调度 · 透明）</text>
    <text x="431" y="75" text-anchor="middle" font-size="10.5" class="fig-blue">主存（RAM）</text>
    <text x="431" y="96" text-anchor="middle" font-size="9.5" class="fig-label">活跃/就绪进程</text>
    <text x="431" y="116" text-anchor="middle" font-size="9.5" class="fig-red">PCB 常驻不换出</text>
    <text x="431" y="140" text-anchor="middle" font-size="9.5" class="fig-muted">腾出空间提并发</text>
    <text x="524" y="82" text-anchor="middle" font-size="9.5" class="fig-orange">换出（阻塞低优）</text>
    <text x="524" y="143" text-anchor="middle" font-size="9.5" class="fig-green">换入（挂起最久）</text>
    <text x="629" y="75" text-anchor="middle" font-size="10.5" class="fig-orange">磁盘对换区</text>
    <text x="629" y="96" text-anchor="middle" font-size="9.5" class="fig-label">连续分配，IO快</text>
    <text x="629" y="116" text-anchor="middle" font-size="9.5" class="fig-label">整进程映像换出</text>
    <text x="629" y="140" text-anchor="middle" font-size="9.5" class="fig-muted">（挂起态进程）</text>
    <text x="536" y="191" text-anchor="middle" font-size="10" class="fig-label">边界：交换以“整个进程”为单位，仍需完整装入才能运行；</text>
    <text x="536" y="211" text-anchor="middle" font-size="9.5" class="fig-muted">虚存则以“页/段”为单位，允许程序部分装入！</text>
  </svg>
  <figcaption>图 5-4　覆盖技术（进程内分段复用覆盖区）与交换技术（进程间整体对换与中级调度）对比</figcaption>
</figure>

---

### 5.2 连续分配管理方式 ★

连续分配指必须为每个进程分配一整段**连续的物理内存**。这一家族的三代演进，本质上是“缓解内碎片 → 消除内碎片 → 产生并艰难回收外碎片”的矛盾推演。

#### 5.2.1 单一连续分配与固定分区分配

| 连续分配方式 | 分区划分时机 | 分区大小与多道程序度 | 内部碎片 | 外部碎片 | 配套硬件与说明 |
|---|---|---|---|---|---|
| **单一连续分配** | 无须划分（系统区 + 用户区） | 整个用户区归一道程序；多道度 = `1` | **有**（用户区未用满部分） | **无** | 单用户单任务；可用覆盖扩充、绝对装入 |
| **固定分区分配** | **系统启动前**预先划定 | **等大**（适合大小一致的同类任务）或**不等大**（多个小 + 适量中 + 少量大分区）；多道度受分区数限制 | **有**（程序小于分区尺寸） | **无** | 需维护**分区说明表**（分区号、起始地址、大小、状态），多用静态重定位 |
| **动态分区分配** | **进程装入时**按需动态切分 | 分区大小、数量、位置随进程动态变化 | **无**（按需切分；仅余极小边角时不切才算内碎片） | **有** | 维护**空闲分区表 / 空闲分区链**；配合紧凑需**动态重定位** |

> **注意**：分辨**内部碎片**与**外部碎片**的唯一判据——**看这块浪费的空间是否已经分出去了**。已经划给某进程但进程自己没用完的空间是**内部碎片**（出现在单一连续、固定分区、基本分页、段页式、伙伴算法）；还未分配给任何进程、夹在已分配区之间因太小无法利用的空闲区是**外部碎片**（出现在动态分区、基本分段）。

---

#### 5.2.2 动态分区分配的数据结构与四大算法 ★

动态分区常用两种数据结构记账：**空闲分区表**（顺序表，记录分区号、大小、始址）与**空闲分区链**（双向链表，直接利用空闲块自身的头部与尾部存放链指针——**头部存状态位、分区大小、前向指针，尾部存后向指针并重复一遍状态位与大小**）。尾部重复记录是为了回收时通过 `回收区首址 - 1` 直接读取前邻块的大小与状态，以 $O(1)$ 时间定位前驱块，无需全表扫描。

**（1）四大基于顺序搜索的动态分区分配算法**

| 分配算法 | 空闲链排序方式 | 查找起点与选择规则 | 优点与性能 | 缺点与碎片特征 |
|---|---|---|---|---|
| **首次适应（FF）** | **按地址递增** | 每次从<strong>链首（低地址）</strong>顺序找，取第一个满足的空闲区 | **综合性能最好**；保留高地址大空闲区，**分配/回收无需重排** | 低地址端反复被切割，积累大量微小外碎片，每次从头扫增加前期无效查找 |
| **邻近适应（NF）**（循环首次适应） | **按地址递增**（循环链） | 从**上次查找结束的下一个位置**继续循环找，取第一个够大的 | 无需每次从低地址碎片扫起，空闲区分布更均匀，查找开销小 | **高地址大空闲区同样被拆散**，大进程到来时可能无连续大块可用；性能常不优于 FF |
| **最佳适应（BF）** | **按容量递增** | 从链首找到第一个够大的，即**能满足要求的最小空闲区** | 大分区得以保留，单次空间利用率最高 | 每次切完余量最小，产生**最多极难利用的微小外部碎片**；**分配/回收后需重排**，开销大 |
| **最坏适应（WF）** | **按容量递减** | 直接考察链首（**当前最大空闲区**），满足即切分 | 切完剩余块仍较大，不易形成微小外碎片；查找只需看链首 | 迅速消耗系统最大空闲区，后续大进程易分配失败；**分配/回收后需重排**，开销大 |

> **★考点**：`10#28`、`17#25` 考最佳适应手算、`19#32` 考四种算法碎片对比（问最容易产生过多难以利用碎片的是 **最佳适应 BF**）。**衡量碎片严重程度的指标是最大连续空闲块，而不是空闲总量**！手算多步请求时，**每一步分配后都必须在当前最新空闲状态上重算候选集**，切忌拿初始表去算后续请求（例如 `A=20, B=10, C=120, D=60` 依次响应 `15, 30, 50`：BF 第 2 步切走 `D(60)` 剩 `30`，第 3 步 `D` 已不在候选集内）。

**（2）动态分区回收的四种邻接合并情况**

归还一块物理内存时，必须检查其前后是否紧邻（**地址严丝合缝**，即 `前邻末址 + 1 == 回收区首址` 或 `回收区末址 + 1 == 后邻首址`）现有空闲区。按“**表项数变不变、首址改不改**”两个维度可将四类情形完全区分：

| 回收情形 | 前邻空闲 | 后邻空闲 | 表项数变化 | 合并后始址与大小处理 |
|---|---|---|---|---|
| **情况一** | 是（$F_1$） | 否 | **不变** | 保留 $F_1$ 原首址；`F1.size += 回收区大小` |
| **情况二** | 否 | 是（$F_2$） | **不变** | **改首址为回收区首址**；`F2.size += 回收区大小`（**唯一需改首址**） |
| **情况三** | 是（$F_1$） | 是（$F_2$） | **$-1$** | 保留 $F_1$ 原首址；`F1.size += 回收区 + F2.size`；**删除 $F_2$ 表项** |
| **情况四** | 否 | 否 | **$+1$** | 新建表项，填回收区首址与大小，按对应排序规则插入表/链 |

<figure class="cpd-figure not-content" id="os-c5-fig-5">
  <svg viewBox="0 0 720 306" role="img" aria-label="动态分区双向链表结构与内存回收四种邻接合并情况图">
    <defs>
      <marker id="os-c5-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="100" rx="6" class="fig-box-subtle"/>
    <rect x="16" y="124" width="688" height="168" rx="6" class="fig-box-subtle"/>
    <rect x="30" y="42" width="160" height="58" rx="4" class="fig-box-blue"/>
    <rect x="190" y="42" width="220" height="58" rx="4" class="fig-box"/>
    <rect x="410" y="42" width="144" height="58" rx="4" class="fig-box-blue"/>
    <rect x="572" y="42" width="118" height="58" rx="4" class="fig-box-orange"/>
    <line x1="190" y1="62" x2="190" y2="80" class="fig-divider"/>
    <rect x="32" y="156" width="154" height="122" rx="4" class="fig-box"/>
    <rect x="198" y="156" width="154" height="122" rx="4" class="fig-box"/>
    <rect x="364" y="156" width="154" height="122" rx="4" class="fig-box"/>
    <rect x="530" y="156" width="160" height="122" rx="4" class="fig-box"/>
    <rect x="44" y="182" width="64" height="28" rx="2" class="fig-box-blue"/>
    <rect x="108" y="182" width="64" height="28" rx="2" class="fig-box-green"/>
    <rect x="210" y="182" width="64" height="28" rx="2" class="fig-box-green"/>
    <rect x="274" y="182" width="64" height="28" rx="2" class="fig-box-blue"/>
    <rect x="376" y="182" width="44" height="28" rx="2" class="fig-box-blue"/>
    <rect x="420" y="182" width="42" height="28" rx="2" class="fig-box-green"/>
    <rect x="462" y="182" width="44" height="28" rx="2" class="fig-box-blue"/>
    <rect x="546" y="182" width="40" height="28" rx="2" class="fig-box-red"/>
    <rect x="586" y="182" width="48" height="28" rx="2" class="fig-box-green"/>
    <rect x="634" y="182" width="40" height="28" rx="2" class="fig-box-red"/>
    <text x="360" y="33" text-anchor="middle" font-size="11.5" class="fig-title">空闲分区链结构（尾部重复状态位与大小，实现 O(1) 前驱定位）</text>
    <text x="110" y="63" text-anchor="middle" font-size="10" class="fig-blue">头部（3 项）</text>
    <text x="110" y="82" text-anchor="middle" font-size="9.5" class="fig-label">状态(0) | 大小 | 前向指针</text>
    <text x="300" y="65" text-anchor="middle" font-size="10.5" class="fig-label">N 字节可用空闲空间</text>
    <text x="300" y="85" text-anchor="middle" font-size="9.5" class="fig-muted">已分配后头尾指针失效，仅维系状态(1)</text>
    <text x="482" y="63" text-anchor="middle" font-size="10" class="fig-blue">尾部（重复 2 项）</text>
    <text x="482" y="82" text-anchor="middle" font-size="9.5" class="fig-label">后向指针 | 大小 | 状态(0)</text>
    <text x="631" y="63" text-anchor="middle" font-size="10" class="fig-orange">回收探测技巧</text>
    <text x="631" y="83" text-anchor="middle" font-size="9.5" class="fig-label">读 始址-1 即可见</text>
    <text x="360" y="144" text-anchor="middle" font-size="11.5" class="fig-title">动态分区回收时的四种邻接合并情况（“紧邻”要求字节地址严丝合缝）</text>
    <text x="109" y="173" text-anchor="middle" font-size="10" class="fig-title">① 仅与前空闲区邻接</text>
    <text x="76" y="200" text-anchor="middle" font-size="9.5" class="fig-blue">前空闲 F1</text>
    <text x="140" y="200" text-anchor="middle" font-size="9.5" class="fig-green">回收区</text>
    <text x="109" y="232" text-anchor="middle" font-size="9.5" class="fig-label">并入 F1，首址不变</text>
    <text x="109" y="252" text-anchor="middle" font-size="9.5" class="fig-accent">表项数：不变</text>
    <text x="275" y="173" text-anchor="middle" font-size="10" class="fig-title">② 仅与后空闲区邻接</text>
    <text x="242" y="200" text-anchor="middle" font-size="9.5" class="fig-green">回收区</text>
    <text x="306" y="200" text-anchor="middle" font-size="9.5" class="fig-blue">后空闲 F2</text>
    <text x="275" y="232" text-anchor="middle" font-size="9.5" class="fig-red">首址改为回收区始址！</text>
    <text x="275" y="252" text-anchor="middle" font-size="9.5" class="fig-accent">表项数：不变</text>
    <text x="441" y="173" text-anchor="middle" font-size="10" class="fig-title">③ 前后均与空闲区邻接</text>
    <text x="398" y="200" text-anchor="middle" font-size="9" class="fig-blue">F1</text>
    <text x="441" y="200" text-anchor="middle" font-size="9" class="fig-green">回收</text>
    <text x="484" y="200" text-anchor="middle" font-size="9" class="fig-blue">F2</text>
    <text x="441" y="232" text-anchor="middle" font-size="9.5" class="fig-label">三合一用 F1 始址</text>
    <text x="441" y="252" text-anchor="middle" font-size="9.5" class="fig-red">表项数：-1（删 F2）</text>
    <text x="610" y="173" text-anchor="middle" font-size="10" class="fig-title">④ 前后均不邻接空闲区</text>
    <text x="566" y="200" text-anchor="middle" font-size="9" class="fig-red">已用</text>
    <text x="610" y="200" text-anchor="middle" font-size="9" class="fig-green">回收</text>
    <text x="654" y="200" text-anchor="middle" font-size="9" class="fig-red">已用</text>
    <text x="610" y="232" text-anchor="middle" font-size="9.5" class="fig-label">新建独立空闲表项</text>
    <text x="610" y="252" text-anchor="middle" font-size="9.5" class="fig-green">表项数：+1</text>
  </svg>
  <figcaption>图 5-5　空闲分区链头尾复用结构与动态分区回收时的四种邻接合并策略</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c5-fig-6">
  <svg viewBox="0 0 720 296" role="img" aria-label="首次适应邻近适应最佳适应最坏适应四大算法同序列分配与碎片演化对比图">
    <rect x="16" y="14" width="688" height="268" rx="6" class="fig-box-subtle"/>
    <rect x="28" y="42" width="664" height="28" rx="4" class="fig-box"/>
    <rect x="28" y="76" width="112" height="36" rx="3" class="fig-box-blue"/>
    <rect x="144" y="76" width="114" height="36" rx="3" class="fig-box-blue"/>
    <rect x="262" y="76" width="114" height="36" rx="3" class="fig-box-blue"/>
    <rect x="380" y="76" width="114" height="36" rx="3" class="fig-box-blue"/>
    <rect x="498" y="76" width="194" height="36" rx="3" class="fig-box-accent"/>
    <rect x="28" y="118" width="112" height="34" rx="3" class="fig-box"/>
    <rect x="144" y="118" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="262" y="118" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="380" y="118" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="498" y="118" width="194" height="34" rx="3" class="fig-box-red"/>
    <rect x="28" y="156" width="112" height="34" rx="3" class="fig-box"/>
    <rect x="144" y="156" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="262" y="156" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="380" y="156" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="498" y="156" width="194" height="34" rx="3" class="fig-box-green"/>
    <rect x="28" y="194" width="112" height="34" rx="3" class="fig-box"/>
    <rect x="144" y="194" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="262" y="194" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="380" y="194" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="498" y="194" width="194" height="34" rx="3" class="fig-box-green"/>
    <rect x="28" y="232" width="112" height="34" rx="3" class="fig-box"/>
    <rect x="144" y="232" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="262" y="232" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="380" y="232" width="114" height="34" rx="3" class="fig-box"/>
    <rect x="498" y="232" width="194" height="34" rx="3" class="fig-box-red"/>
    <text x="360" y="33" text-anchor="middle" font-size="11.5" class="fig-title">同一序列碎片演化（初始空闲 A=20, B=10, C=120, D=60 KB；依次请求 P1=15, P2=30, P3=50）</text>
    <text x="360" y="60" text-anchor="middle" font-size="10" class="fig-label">注：4 种算法均共分掉 95 KB、均剩总空闲 115 KB，但能否装下第 4 个进程 P4=65 KB 完全取决于“最大连续块”！</text>
    <text x="84" y="98" text-anchor="middle" font-size="10.5" class="fig-blue">算法策略</text>
    <text x="201" y="98" text-anchor="middle" font-size="10" class="fig-blue">第1步 P1=15K</text>
    <text x="319" y="98" text-anchor="middle" font-size="10" class="fig-blue">第2步 P2=30K</text>
    <text x="437" y="98" text-anchor="middle" font-size="10" class="fig-blue">第3步 P3=50K</text>
    <text x="595" y="98" text-anchor="middle" font-size="10" class="fig-accent">最终空闲快照 &amp; 能否接 P4=65K</text>
    <text x="84" y="139" text-anchor="middle" font-size="10" class="fig-title">首次适应 FF</text>
    <text x="201" y="139" text-anchor="middle" font-size="9.5" class="fig-label">A(20) → 剩 5</text>
    <text x="319" y="139" text-anchor="middle" font-size="9.5" class="fig-label">C(120) → 剩 90</text>
    <text x="437" y="139" text-anchor="middle" font-size="9.5" class="fig-label">C(90) → 剩 40</text>
    <text x="595" y="139" text-anchor="middle" font-size="9.5" class="fig-red">[5, 10, 40, 60] max=60 ✗ 失败</text>
    <text x="84" y="177" text-anchor="middle" font-size="10" class="fig-title">邻近适应 NF</text>
    <text x="201" y="177" text-anchor="middle" font-size="9.5" class="fig-label">A(20) → 指针移B</text>
    <text x="319" y="177" text-anchor="middle" font-size="9.5" class="fig-label">C(120) → 指针移D</text>
    <text x="437" y="177" text-anchor="middle" font-size="9.5" class="fig-label">D(60) → 剩 10</text>
    <text x="595" y="177" text-anchor="middle" font-size="9.5" class="fig-green">[5, 10, 90, 10] max=90 ✓ 成功</text>
    <text x="84" y="215" text-anchor="middle" font-size="10" class="fig-title">最佳适应 BF</text>
    <text x="201" y="215" text-anchor="middle" font-size="9.5" class="fig-label">A(20) → 剩 5</text>
    <text x="319" y="215" text-anchor="middle" font-size="9.5" class="fig-label">D(60) → 剩 30</text>
    <text x="437" y="215" text-anchor="middle" font-size="9.5" class="fig-label">C(120) → 剩 70</text>
    <text x="595" y="215" text-anchor="middle" font-size="9.5" class="fig-green">[5, 10, 70, 30] max=70 ✓ 成功</text>
    <text x="84" y="253" text-anchor="middle" font-size="10" class="fig-title">最坏适应 WF</text>
    <text x="201" y="253" text-anchor="middle" font-size="9.5" class="fig-label">C(120) → 剩 105</text>
    <text x="319" y="253" text-anchor="middle" font-size="9.5" class="fig-label">C(105) → 剩 75</text>
    <text x="437" y="253" text-anchor="middle" font-size="9.5" class="fig-label">C(75) → 剩 25</text>
    <text x="595" y="253" text-anchor="middle" font-size="9.5" class="fig-red">[20, 10, 25, 60] max=60 ✗ 失败</text>
  </svg>
  <figcaption>图 5-6　动态分区四大算法在同一序列下的步进分配与外部碎片演化对比</figcaption>
</figure>

---

#### 5.2.3 紧凑技术与伙伴系统（Buddy System）

1. **紧凑（拼接 / Compaction）**：动态分区长期运行后会出现大量外碎片，解决的办法是将内存中已分配的所有进程向同一端搬迁紧邻，从而将分散的小空闲区拼成整块连续大区。**硬前提**：必须采用**动态重定位**（搬迁后仅修改各进程重定位寄存器的基址即可，若采用静态重定位则移动开销不可承受）。紧凑只对消除**外部碎片**有效，且整体搬运数据的时间代价较高。
2. **伙伴系统（Buddy System，`24#27` 高频新考点）**：前述顺序搜索算法在回收合并时需扫描链表判断邻接；伙伴系统属**索引分配算法**（现代 Linux 内核用来管理物理页框组），将可分配区统一划分成大小为 $2^k$ 的幂次空闲块并按阶建立双向空闲链表：
   - **分配过程**：申请大小为 $S$ 的空间时，先计算满足 $2^{i-1} < S \le 2^i$ 的最小整数阶 $i$ ；若 $2^i$ 级链表有空闲块则直接分配；否则向 $2^{i+1}$ 级（或更高阶）查找空闲块，**一劈为二**得到两个互为“伙伴”的块，一半继续劈分或分配，另一半挂入对应阶空闲链表。
   - **回收与伙伴三要素**：一个块在回收时**只允许与其“伙伴”合并**，满足伙伴关系必须**三条同时成立**：① **大小相等**（同为 $2^k$ ）；② **物理相邻**；③ **由同一个 $2^{k+1}$ 父块分割而来**（合并后恰好对齐到 $2^{k+1}$ 边界，起始地址为 $A$ 且大小为 $2^k$ 的块，其唯一伙伴首址为 $A \oplus 2^k$ ）。若伙伴空闲则合并成 $2^{k+1}$ 并递归向上尝试合并。
   - **核心代价**：按 $2^k$ 向上取整分配会**重新引入内部碎片**（例如请求 $33\text{ KB}$ 会分配 $64\text{ KB}$，内部浪费 $31\text{ KB}$ ）。

> **★考点**：`24#27` 考查“回收分区时**仅合并大小相等**的空闲分区的算法是？”——答案是**伙伴算法**（首次/最佳/最坏适应算法的回收规则一律是“前后物理相邻就合并”，与相邻分区大小无关）。

<figure class="cpd-figure not-content" id="os-c5-fig-7">
  <svg viewBox="0 0 720 264" role="img" aria-label="伙伴系统Buddy System按2的幂劈分分配与按位异或伙伴合并示意图">
    <defs>
      <marker id="os-c5-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="236" rx="6" class="fig-box-subtle"/>
    <line x1="176" y1="80" x2="176" y2="96" class="fig-line-accent" marker-end="url(#os-c5-arr-7)"/>
    <line x1="100" y1="130" x2="100" y2="146" class="fig-line-accent" marker-end="url(#os-c5-arr-7)"/>
    <rect x="32" y="44" width="288" height="34" rx="4" class="fig-box"/>
    <rect x="32" y="98" width="138" height="30" rx="4" class="fig-box-blue"/>
    <rect x="182" y="98" width="138" height="30" rx="4" class="fig-box-green"/>
    <rect x="32" y="148" width="66" height="36" rx="4" class="fig-box-accent"/>
    <rect x="104" y="148" width="66" height="36" rx="4" class="fig-box-blue"/>
    <rect x="182" y="148" width="138" height="36" rx="4" class="fig-box-orange"/>
    <rect x="348" y="44" width="340" height="140" rx="5" class="fig-box"/>
    <rect x="32" y="196" width="656" height="42" rx="4" class="fig-box-purple"/>
    <text x="360" y="33" text-anchor="middle" font-size="11.5" class="fig-title">伙伴系统（Buddy System）：连续按 2 的幂劈分与伙伴块合并规则</text>
    <text x="176" y="65" text-anchor="middle" font-size="10.5" class="fig-label">初始空闲块：16 KB（0x0000 – 0x3FFF，16K 链）</text>
    <text x="101" y="117" text-anchor="middle" font-size="9.5" class="fig-blue">左半 8 KB（继续劈分）</text>
    <text x="251" y="117" text-anchor="middle" font-size="9.5" class="fig-green">右半 8 KB（互为伙伴）</text>
    <text x="65" y="164" text-anchor="middle" font-size="9.5" class="fig-accent">分 4 KB</text>
    <text x="65" y="179" text-anchor="middle" font-size="9" class="fig-label">供 3K 用</text>
    <text x="137" y="164" text-anchor="middle" font-size="9.5" class="fig-blue">空闲 4 KB</text>
    <text x="137" y="179" text-anchor="middle" font-size="9" class="fig-muted">挂 4K 链</text>
    <text x="251" y="164" text-anchor="middle" font-size="9.5" class="fig-orange">再分配 5 KB → 取 8 KB</text>
    <text x="251" y="179" text-anchor="middle" font-size="9" class="fig-red">内碎片 = 3 KB！</text>
    <text x="518" y="66" text-anchor="middle" font-size="10.5" class="fig-title">伙伴块合并的三个充分必要条件 ★</text>
    <text x="362" y="88" font-size="10" class="fig-label">① 大小相等：两块必须同为 2ᵏ 字节</text>
    <text x="362" y="108" font-size="10" class="fig-label">② 物理相邻：地址严格连续无缝隙</text>
    <text x="362" y="128" font-size="10" class="fig-accent">③ 同父对齐：由同一 2ᵏ⁺¹ 父块劈成（伙伴地址 = A ⊕ 2ᵏ）</text>
    <text x="362" y="150" font-size="9.5" class="fig-red">反例：第 2 块（4–8K）与第 3 块（8–12K）同大且相邻，</text>
    <text x="362" y="167" font-size="9.5" class="fig-red">但分属不同 8K 父块，绝不合并！</text>
    <text x="360" y="214" text-anchor="middle" font-size="10" class="fig-purple">408 考点（24#27）：只有伙伴算法回收时“仅合并大小相等的空闲伙伴块”；代价是按 2 的幂对齐重新产生内部碎片</text>
    <text x="360" y="231" text-anchor="middle" font-size="9.5" class="fig-muted">（传统 FF/NF/BF/WF 只要物理相邻一律合并，无论大小是否相等）</text>
  </svg>
  <figcaption>图 5-7　伙伴系统劈分与伙伴块合并三要素（同大小、物理相邻、同属一个父块）</figcaption>
</figure>


---

### 5.3 基本分页存储管理 ★

连续分配之所以必须“整块搬家”做紧凑，归根结底只是为了满足“逻辑地址 + 固定基址 = 物理地址”这一简陋的变换要求。**基本分页存储管理**彻底放弃物理空间连续性的要求，从系统的角度将进程和物理内存分别切成等大的小块，用硬件查表代替物理连续，从根本上消除了外部碎片。

#### 5.3.1 分页思想、四组易混概念辨析与页面大小权衡

1. **核心机制**：
   - 将进程的逻辑地址空间划分为若干大小相等的**页（Page）**，从 $0$ 开始编号（$0, 1, 2, \dots$ ）。
   - 将物理内存空间划分为与页**严格等大**的**页框 / 页帧 / 物理块（Frame）**，从 $0$ 开始编号。
   - 进程装入时，各个页可以**离散地**放入内存中任意空闲页框里；操作系统为每个进程建立一张**页表（Page Table）**，记录“逻辑页号 → 物理页框号”的映射关系。

2. **四组核心概念关系辨析（极易混淆！）**：
   - **页与页框**：大小**完全相等**；页是进程逻辑空间切片（像照片），页框是物理内存切片（像相框），一个页恰好装入一个页框。
   - **页框与 Cache 主存块**：虽都是对物理主存的划分，但粒度完全不同！页框是**操作系统视角**下主存与磁盘交换的单位（典型为 $4\text{ KB}$ ）；主存块是 **计组硬件视角**下 Cache 与主存交换的单位（典型为 $32\text{ B}$ 或 $64\text{ B}$ ）。一个 $4\text{ KB}$ 的页框内部包含了成百上千个 Cache 块（如 $4\text{ KB} / 64\text{ B} = 64$ 块）。
   - **页与页表项（PTE）**：页表由一行行页表项组成；**一个进程有多少页，其页表就有多少个页表项**。由于页表按页号从 $0$ 连续排布（本质是数组），**页号是隐含下标，不占页表项存储空间**；页表项长度常对齐到 $2$ 的幂（如 $4\text{ B}$ ），使乘以表项长度退化为左移。
   - **页表与页框**：页表本身也是数据结构，**存放在主存的内核区**（即占据主存的某些页框）！普通单级页表必须**连续存放**，大进程的一张页表可能占上千个连续页框；而在多级页表中，**各级每一张子页表最大只占 1 个页框**。

<figure class="cpd-figure not-content" id="os-c5-fig-8">
  <svg viewBox="0 0 720 296" role="img" aria-label="基本分页地址拆分离散映射及页与页框页表项页表关系图">
    <defs>
      <marker id="os-c5-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="268" rx="6" class="fig-box-subtle"/>
    <line x1="172" y1="78" x2="252" y2="78" class="fig-line-dashed" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-8)"/>
    <line x1="172" y1="110" x2="252" y2="110" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-8)"/>
    <line x1="172" y1="142" x2="252" y2="142" class="fig-line-dashed" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-8)"/>
    <line x1="426" y1="78" x2="486" y2="96" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-8)"/>
    <line x1="426" y1="110" x2="486" y2="184" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-8)"/>
    <line x1="426" y1="142" x2="486" y2="126" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-8)"/>
    <rect x="30" y="62" width="140" height="30" rx="3" class="fig-box-blue"/>
    <rect x="30" y="94" width="140" height="30" rx="3" class="fig-box-green"/>
    <rect x="30" y="126" width="140" height="30" rx="3" class="fig-box-orange"/>
    <rect x="30" y="158" width="140" height="30" rx="3" class="fig-box"/>
    <rect x="254" y="42" width="172" height="148" rx="4" class="fig-box"/>
    <rect x="254" y="64" width="172" height="28" rx="2" class="fig-box-blue"/>
    <rect x="254" y="94" width="172" height="28" rx="2" class="fig-box-green"/>
    <rect x="254" y="124" width="172" height="28" rx="2" class="fig-box-orange"/>
    <rect x="254" y="154" width="172" height="28" rx="2" class="fig-box"/>
    <rect x="488" y="48" width="200" height="32" rx="3" class="fig-box"/>
    <rect x="488" y="82" width="200" height="30" rx="3" class="fig-box-blue"/>
    <rect x="488" y="114" width="200" height="30" rx="3" class="fig-box-orange"/>
    <rect x="488" y="146" width="200" height="24" rx="3" class="fig-box"/>
    <rect x="488" y="172" width="200" height="30" rx="3" class="fig-box-green"/>
    <rect x="30" y="212" width="658" height="58" rx="4" class="fig-box-accent"/>
    <text x="100" y="46" text-anchor="middle" font-size="11" class="fig-title">进程逻辑地址空间（页）</text>
    <text x="100" y="81" text-anchor="middle" font-size="10" class="fig-blue">第 0 页（4 KB）</text>
    <text x="100" y="113" text-anchor="middle" font-size="10" class="fig-green">第 1 页（4 KB）</text>
    <text x="100" y="145" text-anchor="middle" font-size="10" class="fig-orange">第 2 页（4 KB）</text>
    <text x="100" y="177" text-anchor="middle" font-size="9.5" class="fig-muted">第 3 页（末页含内碎片）</text>
    <text x="340" y="34" text-anchor="middle" font-size="11" class="fig-title">进程页表（存主存内核区）</text>
    <text x="340" y="57" text-anchor="middle" font-size="8.8" class="fig-muted">下标 P(隐含) ｜ 页框号 f ｜ 保护位</text>
    <text x="340" y="82" text-anchor="middle" font-size="10" class="fig-blue">P=0（隐含）｜ f = 1 ｜ R/X</text>
    <text x="340" y="112" text-anchor="middle" font-size="10" class="fig-green">P=1（隐含）｜ f = 4 ｜ R/W</text>
    <text x="340" y="142" text-anchor="middle" font-size="10" class="fig-orange">P=2（隐含）｜ f = 2 ｜ R/W</text>
    <text x="340" y="172" text-anchor="middle" font-size="9.5" class="fig-muted">P=3（隐含）｜ f = 7 ｜ R/W</text>
    <text x="588" y="38" text-anchor="middle" font-size="11" class="fig-title">物理主存空间（页框 Frame）</text>
    <text x="588" y="68" text-anchor="middle" font-size="9.5" class="fig-muted">0 号页框（系统内核 / 其他进程）</text>
    <text x="588" y="101" text-anchor="middle" font-size="10" class="fig-blue">1 号页框 ← 装入第 0 页</text>
    <text x="588" y="133" text-anchor="middle" font-size="10" class="fig-orange">2 号页框 ← 装入第 2 页</text>
    <text x="588" y="162" text-anchor="middle" font-size="9.5" class="fig-muted">3 号页框（空闲，记入位示图）</text>
    <text x="588" y="191" text-anchor="middle" font-size="10" class="fig-green">4 号页框 ← 装入第 1 页</text>
    <text x="359" y="233" text-anchor="middle" font-size="10.5" class="fig-accent">逻辑地址拆位公式（页面大小 L = 2ᵏ 字节）：页号 P = ⌊A / L⌋（高位），页内偏移 d = A mod L（低 k 位）</text>
    <text x="359" y="255" text-anchor="middle" font-size="9.5" class="fig-label">页与页框严格等大；页表按 P 连续存储故 P 不占存储字段；每个页框内含多个小主存块（Cache 行，如 64 B）</text>
  </svg>
  <figcaption>图 5-8　基本分页的逻辑页与物理页框离散映射、页表隐含索引及逻辑地址拆位规律</figcaption>
</figure>

3. **页面大小的选择权衡（一分为二看代价）**：

| 页面大小变大时的影响 | 变化趋势 | 本质原因 |
|---|---|---|
| **页表项数与页表体积** | **变少 / 变小** | 总页数 = 进程大小 $\div$ 页面大小 |
| **内部碎片大小** | **变大** | 进程末页平均浪费半个页面，页面越大浪费越多 |
| **缺页率（空间局部性）** | **降低** | 一次调入的连续空间更大，但可能顺带调入暂时不用的数据，单次缺页 I/O 传输耗时变长 |
| **TLB 覆盖范围** | **变大** | 相同 TLB 表项数能映射更大内存区间，TLB 命中率上升 |

现代操作系统普遍采用折中值 **$4\text{ KB}$**（$2^{12}\text{ B}$ ）。

---

#### 5.3.2 地址拆位规则与基本地址变换机构

1. **逻辑地址结构（一维地址空间）**：由于页的大小取 $L = 2^k$ ，硬件自动把逻辑地址 $A$ 切成高位**页号 $P$** 与低 $k$ 位**页内偏移 $d$**（对用户完全透明，用户只感知连续的一维地址）：
   $$
   P = \lfloor A / L \rfloor = A \gg k, \qquad d = A \bmod L
   $$
   - 若页面大小为 $2\text{ KB}$ 还是 $4\text{ KB}$ ，且计算机按字节编址，则低 $k = \log_2 L$ 位十六进制表示时尤需小心（如 $4\text{ KB} = 2^{12}\text{ B}$ 对应十六进制低 $3$ 位；$1\text{ KB} = 2^{10}\text{ B}$ 对应低 $10$ 位，展开二进制后再从低位起切出 $10$ 位）。

2. **基本地址变换机构（无快表时两次访存）**：
   - 系统中仅需设置一个硬件**页表寄存器（PTBR / PTR）**，存放当前运行进程的**页表始址 $F_{\text{表}}$** 与**页表长度 $M$**（注意：$M$ 的单位是**页表项个数**，不是字节数！进程未运行时这两个值保存在该进程的 PCB 中，进程切换时加载进 PTBR）。
   - **完整变换四步**：
     1. 硬件拆出页号 $P$ 与页内偏移 $d$ 。
     2. **越界检查**：比较 $P < M$ （页号从 $0$ 开始，**$P \ge M$ 即越界**，触发地址越界异常）。页内偏移 $d$ 由位数天然限定在 $0 \sim 2^k - 1$ 内，**不可能越界**。
     3. **查页表（第 1 次访存）**：计算页表项物理地址 $\text{PTE\_PA} = F_{\text{表}} + P \times \text{页表项长度}$，访存读出物理页框号 $f$ 。
     4. **拼出物理地址并存取数据（第 2 次访存）**：将页框号 $f$ 左移 $k$ 位拼上页内偏移 $d$ （即 $PA = f \times L + d$ ），按此物理地址再次访存完成指令或数据读写。

<figure class="cpd-figure not-content" id="os-c5-fig-9">
  <svg viewBox="0 0 720 282" role="img" aria-label="基本分页硬件地址变换机构PTBR越界比较与两次访存数据通路图">
    <defs>
      <marker id="os-c5-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="254" rx="6" class="fig-box-subtle"/>
    <line x1="158" y1="60" x2="188" y2="60" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-9)"/>
    <line x1="234" y1="84" x2="234" y2="112" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-9)"/>
    <line x1="278" y1="60" x2="326" y2="60" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-9)"/>
    <line x1="158" y1="158" x2="348" y2="158" class="fig-line" stroke="var(--sl-color-purple)"/>
    <line x1="348" y1="158" x2="348" y2="82" class="fig-line" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-9)"/>
    <line x1="372" y1="60" x2="404" y2="60" class="fig-line-accent" marker-end="url(#os-c5-arr-9)"/>
    <line x1="478" y1="82" x2="478" y2="114" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-9)"/>
    <polyline points="580,174 622,174 622,196" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-9)"/>
    <polyline points="240,224 446,224 446,214 480,214" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-9)"/>
    <rect x="30" y="38" width="126" height="44" rx="4" class="fig-box-blue"/>
    <rect x="190" y="38" width="86" height="44" rx="4" class="fig-box-accent"/>
    <rect x="172" y="114" width="122" height="32" rx="4" class="fig-box-red"/>
    <rect x="24" y="138" width="136" height="42" rx="4" class="fig-box-purple"/>
    <rect x="328" y="38" width="42" height="42" rx="4" class="fig-box"/>
    <rect x="406" y="38" width="144" height="44" rx="4" class="fig-box"/>
    <rect x="394" y="116" width="184" height="78" rx="4" class="fig-box-orange"/>
    <rect x="30" y="206" width="208" height="36" rx="4" class="fig-box-green"/>
    <rect x="482" y="198" width="204" height="50" rx="4" class="fig-box-green"/>
    <text x="360" y="30" text-anchor="middle" font-size="11.5" class="fig-title">基本分页硬件地址变换机构（无快表时恒需 2 次访存）</text>
    <text x="93" y="57" text-anchor="middle" font-size="10" class="fig-blue">逻辑地址 VA</text>
    <text x="93" y="73" text-anchor="middle" font-size="9.5" class="fig-label">页号 P ｜ 偏移 d</text>
    <text x="233" y="57" text-anchor="middle" font-size="10" class="fig-accent">① 越界比较</text>
    <text x="233" y="73" text-anchor="middle" font-size="9.5" class="fig-accent">P &lt; 长度 M ?</text>
    <text x="252" y="103" font-size="9.5" class="fig-red">P ≥ M</text>
    <text x="233" y="134" text-anchor="middle" font-size="9.5" class="fig-red">触发地址越界中断</text>
    <text x="92" y="156" text-anchor="middle" font-size="10" class="fig-purple">页表寄存器 PTBR</text>
    <text x="92" y="172" text-anchor="middle" font-size="8.8" class="fig-muted">始址 F | 长度 M (来自PCB)</text>
    <text x="302" y="53" text-anchor="middle" font-size="9" class="fig-green">合法</text>
    <text x="349" y="64" text-anchor="middle" font-size="12" class="fig-label">+</text>
    <text x="478" y="56" text-anchor="middle" font-size="9.5" class="fig-label">PTE 地址 =</text>
    <text x="478" y="73" text-anchor="middle" font-size="9.5" class="fig-accent">F + P × PTE字节数</text>
    <text x="486" y="135" text-anchor="middle" font-size="10" class="fig-orange">② 主存页表（第1次访存）</text>
    <text x="486" y="154" text-anchor="middle" font-size="9.5" class="fig-label">读出物理页框号 f（+ 权限位）</text>
    <text x="486" y="173" text-anchor="middle" font-size="9.5" class="fig-muted">权限不符则触发存取保护异常</text>
    <text x="134" y="228" text-anchor="middle" font-size="9.5" class="fig-green">低 k 位偏移 d（原样直通不改）</text>
    <text x="584" y="218" text-anchor="middle" font-size="10" class="fig-green">拼接 PA = f &lt;&lt; k | d</text>
    <text x="584" y="236" text-anchor="middle" font-size="9.5" class="fig-label">③ 访问主存数据（第2次访存）</text>
  </svg>
  <figcaption>图 5-9　基本分页硬件地址变换链路与页表寄存器（PTBR）两次访存流程</figcaption>
</figure>

> **★考点**：页表项物理地址求解是 408 大题核心母题模板（见 `13#46`、`20#46`）。把页表看成数组 `PTE[]`，第 $P$ 项的字节物理地址恒为 $\text{页表起始物理地址} + P \times \text{页表项字节数}$ 。同时记住：合成物理地址必须把页框号**左移 $k$ 位**（或乘以页面大小 $L$ ）再加偏移 $d$ ，切勿直接数值相加！

---

#### 5.3.3 快表（TLB）与有效访问时间（EAT）计算 ★

基本分页每次取指令或读写数据都要先访存查一次页表，导致访存速度下降近 50%。根据程序局部性原理，CPU 在地址变换机构中增设了一个高速相联缓冲存储器——**快表（TLB，Translation Lookaside Buffer）**，专门缓存近期用过的页表项。

1. **TLB 结构与工作原理**：
   - TLB 是按内容并行查找的**相联存储器**（也可采用全相联或组相联，组相联时虚拟页号拆分为 `TLB 标记 + TLB 组索引`）。
   - **TLB 项必须同时存页号和页框号**（以及有效位、修改位、ASID 进程号等）：因为 TLB 只缓存局部页表项，不能靠数组下标确定页号（区别于慢表页号隐含）。
   - **查快表过程**：越界检查通过后，先把页号 $P$ 送入 TLB 与所有表项的页号**并行比对**。若命中则直接输出页框号 $f$ ，省去慢表访存；若未命中再去访问主存慢表，取回映射后**写入 TLB**（若 TLB 满则按硬件置换策略淘汰一项）。进程上下文切换时，要么清空 TLB，要么依靠 ASID（地址空间标识符）隔离，避免误命中前一个进程的映射。

2. **有效访问时间（EAT）两种模型对比**：
   设访问一次快表时间为 $\lambda$ ，访问一次主存时间为 $t$ ，TLB 命中率为 $a$ （不考虑缺页与 Cache，单级页表）：

   | 访问模式 | TLB 命中耗时 | TLB 未命中耗时 | 有效访问时间 $EAT$ 公式 |
   |---|---|---|---|
   | **串行查找（默认）** | $\lambda + t$ | $\lambda + t + t = \lambda + 2t$ | $EAT = a(\lambda + t) + (1 - a)(\lambda + 2t) = 2t + \lambda - ta$ |
   | **并行查找**（TLB 与慢表同时启动） | $\lambda + t$ | $2t$ （$\lambda$ 被查慢表的 $t$ 掩盖） | $EAT = a(\lambda + t) + (1 - a) \cdot 2t = 2t + a\lambda - ta$ |

   - 若为 **$n$ 级页表**且串行查找：TLB 命中**恒为 1 次访存**（跳过全部中间级直接给出页框号），耗时 $\lambda + t$ ；TLB 未命中需走完 $n$ 级页表再取数据，共 **$n + 1$ 次访存**，耗时 $\lambda + (n + 1)t$ ，故 $EAT = a(\lambda + t) + (1 - a)[\lambda + (n + 1)t]$ 。

> **注意**：题目未明确说明“快表与慢表并行查询”时，**一律按串行模型计算**！术语“快表具有并行查找能力”指的是**TLB 内部所有表项同时与当前页号比较**，而非 TLB 与主存页表并行访问。

<figure class="cpd-figure not-content" id="os-c5-fig-10">
  <svg viewBox="0 0 720 306" role="img" aria-label="引入快表TLB的地址变换通路与串行并行EAT时序公式对比图">
    <defs>
      <marker id="os-c5-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="176" rx="6" class="fig-box-subtle"/>
    <rect x="16" y="200" width="688" height="92" rx="6" class="fig-box-subtle"/>
    <line x1="128" y1="88" x2="162" y2="88" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-10)"/>
    <polyline points="296,68 416,68 416,96 476,96" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-10)"/>
    <line x1="230" y1="112" x2="230" y2="132" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-10)"/>
    <line x1="308" y1="156" x2="348" y2="156" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-10)"/>
    <polyline points="376,134 376,118 296,118" class="fig-line-dashed" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-10)"/>
    <polyline points="424,156 446,156 446,116 476,116" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-10)"/>
    <polyline points="78,108 78,176 544,176 544,132" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-10)"/>
    <rect x="28" y="64" width="98" height="44" rx="4" class="fig-box-blue"/>
    <rect x="164" y="48" width="130" height="62" rx="5" class="fig-box-purple"/>
    <rect x="164" y="134" width="142" height="36" rx="4" class="fig-box-orange"/>
    <rect x="350" y="134" width="72" height="36" rx="4" class="fig-box"/>
    <rect x="478" y="80" width="208" height="50" rx="4" class="fig-box-green"/>
    <rect x="28" y="212" width="328" height="68" rx="4" class="fig-box-accent"/>
    <rect x="368" y="212" width="322" height="68" rx="4" class="fig-box"/>
    <text x="360" y="33" text-anchor="middle" font-size="11.5" class="fig-title">带快表 TLB 的分页地址变换硬件通路（TLB 命中跳过所有慢表访存！）</text>
    <text x="77" y="83" text-anchor="middle" font-size="10" class="fig-blue">VA：P ｜ d</text>
    <text x="77" y="99" text-anchor="middle" font-size="9" class="fig-muted">先过越界检查</text>
    <text x="229" y="67" text-anchor="middle" font-size="10.5" class="fig-purple">快表 TLB（相联）</text>
    <text x="229" y="84" text-anchor="middle" font-size="9.5" class="fig-label">全表项并发比较页号 P</text>
    <text x="229" y="100" text-anchor="middle" font-size="9" class="fig-muted">存 P + f + 控制位</text>
    <text x="358" y="61" text-anchor="middle" font-size="9.5" class="fig-green">TLB 命中（仅1次访存）</text>
    <text x="258" y="126" font-size="9" class="fig-orange">未命中</text>
    <text x="235" y="156" text-anchor="middle" font-size="9.5" class="fig-orange">查内存慢表（或 n 级）</text>
    <text x="386" y="156" text-anchor="middle" font-size="9.5" class="fig-label">得页框号 f</text>
    <text x="348" y="114" font-size="9" class="fig-purple">回填TLB</text>
    <text x="582" y="101" text-anchor="middle" font-size="10" class="fig-green">拼合 PA = f &lt;&lt; k | d</text>
    <text x="582" y="119" text-anchor="middle" font-size="9.5" class="fig-label">访存读写目标指令/数据</text>
    <text x="192" y="232" text-anchor="middle" font-size="10.5" class="fig-accent">串行 EAT（默认）vs 并行 EAT（仅未命中差 λ）</text>
    <text x="192" y="251" text-anchor="middle" font-size="9.5" class="fig-label">串行：EAT = a(λ+t) + (1-a)(λ+2t) = 2t + λ - ta</text>
    <text x="192" y="269" text-anchor="middle" font-size="9.5" class="fig-label">并行：EAT = a(λ+t) + (1-a)·2t   （差 (1-a)λ）</text>
    <text x="529" y="232" text-anchor="middle" font-size="10.5" class="fig-title">典型算例（t=100 ns, λ=10 ns, a=95%）</text>
    <text x="529" y="251" text-anchor="middle" font-size="9.5" class="fig-label">无 TLB：200 ns ｜ 串行：115 ns ｜ 并行：114.5 ns</text>
    <text x="529" y="269" text-anchor="middle" font-size="9.5" class="fig-accent">二级页表串行：0.95×110 + 0.05×310 = 120 ns</text>
  </svg>
  <figcaption>图 5-10　TLB 快表并行比较通路与串行/并行 EAT 有效访存时间算例对比</figcaption>
</figure>

---

#### 5.3.4 两级与多级页表（★ 408 综合大题核心）

以 32 位逻辑地址、$4\text{ KB}$ 页面、$4\text{ B}$ 页表项为例：逻辑页号共 $20$ 位，页表项总数达 $2^{20} = 1\text{ M}$ 项，**单张页表占 $2^{20} \times 4\text{ B} = 4\text{ MB}$**，相当于 $1024$ 个页框，而且必须**连续存放**、**每个进程一份**。即便一个仅使用几百 KB 内存的小程序也要为此常驻 $4\text{ MB}$ 连续页表，这在工程上完全不可接受。

**（1）多级页表的设计与两个核心省空间原理**

解决思路是**把庞大的单级页表本身再次分页**，每张分页大小不超过 $1$ 个页框（成为**二级页表**），再增设一张<strong>外层页表（顶级页表 / 页目录）</strong>记录各二级页表离散存放的物理页框号：

1. **离散存放页表分页**：$4\text{ MB}$ 慢表被切为 $1024$ 张 $4\text{ KB}$ 的二级页表，离散放入任意空闲页框，彻底消除大块连续内存需求。
2. **按需调入页表分页**：外层页表项内增设**状态位 $S$**；对进程未用到的虚拟地址区间，对应的二级页表无需创建或可暂驻外存，只有查到 $S = 0$ 时才缺页调入——**真正大幅节省物理内存占用的是状态位 $S$ 的按需驻留，而非仅仅离散存放**！

> **★考点（高频易错陷阱 `14#32`、`26#29`）**：**多级页表省的是连续内存空间，付出的代价是时间（访存变慢）**！单级页表未命中 TLB 时需 $2$ 次访存，**$n$ 级页表未命中 TLB 时需 $n + 1$ 次访存**。多级页表**绝对不能加快地址变换**，也不能减小页表项字节数，更不能减少缺页次数。

**（2）核心铁律与位数划分标准公式**

- **铁律**：**多级页表中，最高一级（顶级页表/页目录）及各级每一张子页表最多只能占 $1$ 个页框（$1$ 个页面大小）**。原因：二级页表原本就是把大页表按 1 页框大小切出来的；若顶级页表超过 $1$ 页，就无法靠单一顶级页目录号字段在 1 页内索引完所有表项，必须再向上套一级页目录。
- **每级页号位数公式**：一个页框能装下的页表项个数为 $\frac{\text{页面大小}}{\text{页表项大小}}$ ，故每级索引（除最顶级外）占用的比特数为：
  $$
  \text{单级索引位数 } m = \log_2 \left( \frac{\text{页面大小}}{\text{页表项大小}} \right)
  $$
- **划分方向（务必从低位向高位切！）**：
  1. 先从最低位切出**页内偏移位数** $k = \log_2(\text{页面大小})$ 。
  2. 剩余高位依次从右向左按 $m$ 位一刀切；切到剩余最高位 $\le m$ 为止，全部划归顶级页表（页目录）。
  - **示例**（$32$ 位逻辑地址，$1\text{ KB}$ 页面，$4\text{ B}$ 页表项）：偏移 $k = 10$ 位，剩余 $22$ 位；单页框装 $1\text{ KB} / 4\text{ B} = 256 = 2^8$ 项 ⇒ $m = 8$ 位。二级试切 $22 - 8 = 14 > 8$（顶级需 $64$ 页，不合格）；三级切得 **`6`（一级）+ `8`（二级）+ `8`（三级）+ `10`（偏移）**。

<figure class="cpd-figure not-content" id="os-c5-fig-11">
  <svg viewBox="0 0 720 330" role="img" aria-label="32位二级页表层次索引离散驻留与页表项物理地址公式图">
    <defs>
      <marker id="os-c5-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="302" rx="6" class="fig-box-subtle"/>
    <polyline points="236,70 236,110 190,110" class="fig-line" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-11)"/>
    <polyline points="386,70 386,100 326,100 326,114" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-11)"/>
    <line x1="188" y1="154" x2="220" y2="154" class="fig-line" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-11)"/>
    <line x1="258" y1="154" x2="288" y2="154" class="fig-line-accent" marker-end="url(#os-c5-arr-11)"/>
    <line x1="364" y1="154" x2="394" y2="154" class="fig-line-accent" marker-end="url(#os-c5-arr-11)"/>
    <polyline points="548,70 548,184 548,198" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-11)"/>
    <rect x="174" y="42" width="124" height="28" rx="3" class="fig-box-purple"/>
    <rect x="300" y="42" width="172" height="28" rx="3" class="fig-box-blue"/>
    <rect x="474" y="42" width="146" height="28" rx="3" class="fig-box-green"/>
    <rect x="28" y="100" width="160" height="86" rx="4" class="fig-box-purple"/>
    <rect x="28" y="138" width="160" height="26" rx="2" class="fig-box-accent"/>
    <rect x="222" y="116" width="36" height="72" rx="4" class="fig-box"/>
    <rect x="290" y="116" width="74" height="72" rx="4" class="fig-box-blue"/>
    <rect x="290" y="142" width="74" height="24" rx="2" class="fig-box-accent"/>
    <rect x="396" y="116" width="108" height="72" rx="4" class="fig-box-orange"/>
    <rect x="520" y="198" width="166" height="44" rx="4" class="fig-box-green"/>
    <rect x="28" y="252" width="658" height="52" rx="4" class="fig-box"/>
    <text x="360" y="32" text-anchor="middle" font-size="11.5" class="fig-title">32 位二级页表地址拆分（10 + 10 + 12，4 KB 页，4 B PTE）与层次索引</text>
    <text x="236" y="60" text-anchor="middle" font-size="10" class="fig-purple">页目录号 P1 (10 位)</text>
    <text x="386" y="60" text-anchor="middle" font-size="10" class="fig-blue">二级页号 P2 (10 位)</text>
    <text x="547" y="60" text-anchor="middle" font-size="10" class="fig-green">页内偏移 W (12 位)</text>
    <text x="108" y="118" text-anchor="middle" font-size="10" class="fig-purple">一级页表/页目录 (占1页)</text>
    <text x="108" y="133" text-anchor="middle" font-size="9" class="fig-muted">PTBR 指向页目录始址</text>
    <text x="108" y="155" text-anchor="middle" font-size="9.5" class="fig-accent">项 P1 → 二级页表框号</text>
    <text x="108" y="177" text-anchor="middle" font-size="9" class="fig-muted">S=1 驻留, S=0 暂不建表</text>
    <text x="240" y="149" text-anchor="middle" font-size="8.6" class="fig-label">第1次</text>
    <text x="240" y="165" text-anchor="middle" font-size="9.5" class="fig-label">访存</text>
    <text x="327" y="133" text-anchor="middle" font-size="8.6" class="fig-blue">二级页表(1页)</text>
    <text x="327" y="158" text-anchor="middle" font-size="9.5" class="fig-accent">项 P2 → PPN</text>
    <text x="327" y="178" text-anchor="middle" font-size="9" class="fig-muted">离散存放主存</text>
    <text x="450" y="138" text-anchor="middle" font-size="9.5" class="fig-orange">物理页框 PPN</text>
    <text x="450" y="156" text-anchor="middle" font-size="9.5" class="fig-label">第2次访存得PPN</text>
    <text x="450" y="174" text-anchor="middle" font-size="9" class="fig-muted">无TLB共3次访存</text>
    <text x="603" y="217" text-anchor="middle" font-size="10" class="fig-green">PA = PPN &lt;&lt; 12 | W</text>
    <text x="603" y="234" text-anchor="middle" font-size="9.5" class="fig-label">第3次访存取最终数据</text>
    <text x="357" y="273" text-anchor="middle" font-size="10" class="fig-title">408 大题通杀模板（13#46、20#46）：</text>
    <text x="357" y="292" text-anchor="middle" font-size="8.6" class="fig-label">页目录项地址 = 页目录始址 + P1×4；二级页表项地址 = (目录项页框号&lt;&lt;12) + P2×4；位运算提取：P1 = LA &gt;&gt; 22，P2 = (LA &gt;&gt; 12) &amp; 0x3FF</text>
  </svg>
  <figcaption>图 5-11　32 位二级页表（10+10+12）层次索引、离散驻留及页表项物理地址通式</figcaption>
</figure>

**（3）408 真题高频考法套路总结**

- **算页目录项 / 二级页表数量（`10#29`、`15年大题`）**：设逻辑地址空间共 $2^{16}$ 页，页表项 $2\text{ B}$ ，页面 $1\text{ KB}$ ⇒ 单张二级页表装 $1024 / 2 = 512 = 2^9$ 项 ⇒ 共需 $2^{16} / 2^9 = 128$ 张二级页表 ⇒ 页目录至少含 **$128$ 项**。
- **位操作提取页目录号与页号（`13#46`、`19#31`、`26#28`）**：对于 `10+10+12` 结构，逻辑地址 `LA` 提取页目录号用 `(LA >> 22) & 0x3FF`（`0x3FF` 为 $10$ 个 `1` 的掩码），提取二级页号用 `(LA >> 12) & 0x3FF`。
- **同页目录号共享二级页表（`15#46`）**：两虚拟地址高 $10$ 位（页目录号）相同 ⇒ 查的是页目录同一项 ⇒ **访问同一个二级页表**。
- **二维数组物理存储 + 二级页表物理地址综合（`20#46`、`24#45`）**：C 语言二维数组 `int A[1024][1024]` 按行优先存放，每行 $1024 \times 4\text{ B} = 4\text{ KB}$ 恰好占 $1$ 个逻辑页；同一行的元素页号相同（相邻行逻辑页号连续加 $1$ ），从而直接将二维定位简化为页内一维数组定位；再通过“表始址 + 下标 $\times$ 项大小”依次算出页目录项和二级页表项的物理地址。
- **反置页表（Inverted Page Table，拓展了解）**：64 位系统页表即使分级仍庞大，反置页表**全系统仅建一张**，按**物理页框号**索引而非虚拟页号，每项记录占用该页框的 `(进程号 PID, 虚拟页号)`，极大节省页表空间，但查找需借助散列或相联硬件。

---

### 5.4 基本分段与段页式存储管理

#### 5.4.1 基本分段存储管理

分页解决了内存空间利用率与外碎片问题，却把程序机械地切成等大物理块——一个函数可能跨越多页，一个页里可能混杂代码与变量，导致**按逻辑单位共享和保护极为困难**。**基本分段存储管理**从**满足用户编程需求**出发：

1. **核心思想与五大便利**：按程序自然的逻辑模块（主程序段、子程序段、数据段、栈段等）划分成长度不一的**段（Segment）**，每个段从 `0` 独立编址。由于**段的物理边界与程序逻辑边界重合**，分段天然带来五项便利：**① 方便编程；② 信息共享方便；③ 信息保护方便；④ 支持段长动态增长；⑤ 方便实现动态链接**。
2. **二维地址空间**：用户编程时必须显式给出**段号 $S$** 和**段内偏移 $W$** 两个独立分量（即二维地址空间）。其中段内偏移位数只决定**每段最大允许长度**，而非实际段长。例如 `09#27`：32 位逻辑地址、段号占 $8$ 位 ⇒ 段内偏移 $24$ 位 ⇒ 最大段长为 $2^{24}\text{ B} = 16\text{ MB}$ 。
3. **段表与两次短路越界检查（★ 高频考点）**：
   - 内存中不对主存预先分块，各段离散装入连续物理分区。段表存放在内存中，每项包含**段基址（内存起始物理地址）、段长 $SL$、存取控制字段**。<strong>段表寄存器（STBR）</strong>存放段表始址与**段表长度 $TL$**（平时存于 PCB）。
   - **地址变换四步（严格不可颠倒且短路）**：
     1. **第一次越界检查**：判断 $S < TL$ （段号以段个数计，从 $0$ 起，$S \ge TL$ 则立即触发越界中断并终止，**不再查表**）。
     2. **查段表**：访存读取第 $S$ 项，得该段段基址 `Base` 与实际段长 $SL$ 。
     3. **第二次越界检查**：判断 $W < SL$ （偏移从 $0$ 起，**$W \ge SL$ 即越界**！注意 $W = SL$ 已经越界，见 `16#28` 2 号段长 `300` 访问偏移 `400` 触发越界异常）。
     4. **算物理地址（加法而非乘法！）**：$PA = \text{Base} + W$ （段基址本身就是物理字节地址，直接累加，无需左移）。
4. **段的共享、可重入纯代码与三层保护（`19#28`）**：
   - 被共享的段必须是**可重入代码（纯代码）**——执行中绝不修改自身；会改变的局部数据需拷贝到各进程私有数据区。
   - **共享段表**：除各进程自有段表外，系统维护全局共享段表，包含**共享进程计数 `count`**（某进程释放共享段时仅 `count--`，**减到 `0` 时才真正回收物理内存**）、各共享进程的存取控制字段（可分别赋予不同权限，如主进程读写、其余进程只读/只执行）及在本进程中的段号。
   - **核心结论（`19#28`）**：**同一共享段在不同进程中可以拥有完全不同的段号**，共享的是同一片物理内存内容，而非逻辑段号！
   - **三层存储保护**：越界检查 → 硬件存取控制检查（读/写/执行权限，**“只执行”不可读也不可写**）→ 环保护机构（$0$ 环内核特权最高，外环应用程序特权低；**数据只能往外环取，服务只能往内环调**）。

<figure class="cpd-figure not-content" id="os-c5-fig-12">
  <svg viewBox="0 0 720 302" role="img" aria-label="基本分段存储管理两次短路越界检查加法变换与共享段表count计数图">
    <defs>
      <marker id="os-c5-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="424" height="274" rx="6" class="fig-box-subtle"/>
    <rect x="452" y="14" width="252" height="274" rx="6" class="fig-box-subtle"/>
    <line x1="126" y1="68" x2="160" y2="68" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-12)"/>
    <line x1="208" y1="92" x2="208" y2="112" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-12)"/>
    <line x1="256" y1="68" x2="296" y2="68" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-12)"/>
    <line x1="362" y1="96" x2="362" y2="122" class="fig-line-accent" marker-end="url(#os-c5-arr-12)"/>
    <line x1="362" y1="162" x2="362" y2="188" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-12)"/>
    <line x1="298" y1="134" x2="274" y2="134" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-12)"/>
    <polyline points="78,90 78,210 296,210" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-12)"/>
    <polyline points="540,84 584,84 584,126" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-12)"/>
    <line x1="540" y1="166" x2="560" y2="166" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-12)"/>
    <rect x="28" y="46" width="96" height="44" rx="4" class="fig-box-blue"/>
    <rect x="162" y="46" width="92" height="44" rx="4" class="fig-box-accent"/>
    <rect x="158" y="114" width="114" height="30" rx="4" class="fig-box-red"/>
    <rect x="298" y="42" width="128" height="54" rx="4" class="fig-box-orange"/>
    <rect x="298" y="124" width="128" height="38" rx="4" class="fig-box-accent"/>
    <rect x="298" y="190" width="128" height="40" rx="4" class="fig-box-green"/>
    <rect x="28" y="242" width="398" height="34" rx="4" class="fig-box"/>
    <rect x="466" y="48" width="74" height="72" rx="4" class="fig-box-blue"/>
    <rect x="466" y="130" width="74" height="72" rx="4" class="fig-box-orange"/>
    <rect x="562" y="128" width="128" height="54" rx="4" class="fig-box-green"/>
    <rect x="466" y="212" width="224" height="64" rx="4" class="fig-box-purple"/>
    <text x="228" y="32" text-anchor="middle" font-size="11.5" class="fig-title">基本分段：两次短路越界检查 + 加法重定位</text>
    <text x="76" y="65" text-anchor="middle" font-size="10" class="fig-blue">二维逻辑地址</text>
    <text x="76" y="81" text-anchor="middle" font-size="9.5" class="fig-label">(段号 S, 偏移 W)</text>
    <text x="208" y="65" text-anchor="middle" font-size="10" class="fig-accent">① 比较</text>
    <text x="208" y="81" text-anchor="middle" font-size="9.5" class="fig-accent">S &lt; TL ?</text>
    <text x="215" y="133" text-anchor="middle" font-size="9.5" class="fig-red">越界中断（短路）</text>
    <text x="362" y="62" text-anchor="middle" font-size="10" class="fig-orange">查内存段表[S]</text>
    <text x="362" y="80" text-anchor="middle" font-size="9.5" class="fig-label">读出 Base 与 段长 SL</text>
    <text x="362" y="141" text-anchor="middle" font-size="9.5" class="fig-accent">② 比较 W &lt; SL ?</text>
    <text x="362" y="156" text-anchor="middle" font-size="9" class="fig-red">W = SL 也越界！</text>
    <text x="362" y="207" text-anchor="middle" font-size="10" class="fig-green">PA = Base + W</text>
    <text x="362" y="223" text-anchor="middle" font-size="9.5" class="fig-label">直接相加，第2次访存</text>
    <text x="227" y="263" text-anchor="middle" font-size="9.5" class="fig-muted">物理内存不预先划分页框 → 各段内部连续，段间离散 → 重新出现外部碎片</text>
    <text x="578" y="32" text-anchor="middle" font-size="11" class="fig-title">段的共享与共享段表（19#28）</text>
    <text x="503" y="68" text-anchor="middle" font-size="9.5" class="fig-blue">P1 段表</text>
    <text x="503" y="86" text-anchor="middle" font-size="9.5" class="fig-label">段 0 →</text>
    <text x="503" y="104" text-anchor="middle" font-size="9" class="fig-muted">Base: 40K</text>
    <text x="503" y="150" text-anchor="middle" font-size="9.5" class="fig-orange">P2 段表</text>
    <text x="503" y="168" text-anchor="middle" font-size="9.5" class="fig-label">段 2 →</text>
    <text x="503" y="186" text-anchor="middle" font-size="9" class="fig-muted">Base: 40K</text>
    <text x="626" y="150" text-anchor="middle" font-size="10" class="fig-green">唯一物理共享段</text>
    <text x="626" y="169" text-anchor="middle" font-size="9" class="fig-label">40K（可重入纯代码）</text>
    <text x="578" y="232" text-anchor="middle" font-size="9.5" class="fig-purple">共享段表：记录 count = 2</text>
    <text x="578" y="249" text-anchor="middle" font-size="9" class="fig-label">• count 减到 0 才真正回收内存</text>
    <text x="578" y="265" text-anchor="middle" font-size="9" class="fig-red">• 各进程可用“不同段号”共享同段</text>
  </svg>
  <figcaption>图 5-12　基本分段两次短路越界检查加法变换与共享段表（count 计数）机制</figcaption>
</figure>

---

#### 5.4.2 段页式存储管理与三种离散方式终极对比

分页无外碎片但共享不便，分段共享方便却重现外碎片。**段页式管理**并非两者的折中妥协，而是**两次划分依次施加**（顺序不可颠倒）：**先按逻辑结构分段**（保留共享、保护与动态链接便利），**再将每个段内部划分为固定大小的页**，物理主存同步划分为等大页框（彻底消灭外碎片）。

1. **段页式的四个易错关键特征**：
   - **地址有 3 个字段，但地址空间仍是二维的**：逻辑地址拆分为 `(段号 S | 段内页号 P | 页内偏移 W)`。从右往左确定位数：$W$ 由页面大小定，$P$ 由“每段最大长度 $\div$ 页面大小”定，$S$ 占其余高位。用户在编程时**只需显式给出段号与段内地址**，把段内地址切为 $(P, W)$ 是系统透明完成的，因此仍属**二维地址空间**。
   - **段表内容彻底改变**：由于段内分页后不再占用连续物理内存，“段基址”失去意义！每个进程一张**段表**（对应段表寄存器 STBR），段表项改存**页表始址 + 页表长度**（以页个数计）；每个段对应一张**页表**，故**一个进程有 1 张段表 + 多张页表**。
   - **两次越界检查与 3 次访存**：先比 $S < TL$ （段表长度）→ **第 1 次访存查段表**得页表始址与页表长度 → 再比 $P < \text{页表长度}$ → **第 2 次访存查该段页表**得页框号 $b$ → 左移拼偏移 $W$ → **第 3 次访存读写数据**。若引入快表 TLB（以 **`(段号 S, 页号 P)`** 为键并行比较），命中时只需 **1 次访存**！
   - **内碎片反而更多**：纯分页只在**每个进程**最后一页产生约半页内碎片；段页式在**每个段**最后一页都会产生内碎片——故“段页式既无内碎片又无外碎片”是高频错误干扰项！

<figure class="cpd-figure not-content" id="os-c5-fig-13">
  <svg viewBox="0 0 720 296" role="img" aria-label="段页式存储管理三级地址字段与三次访存变换过程图">
    <defs>
      <marker id="os-c5-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="268" rx="6" class="fig-box-subtle"/>
    <polyline points="118,68 118,98 86,98 86,112" class="fig-line" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-13)"/>
    <line x1="146" y1="138" x2="184" y2="138" class="fig-line-accent" marker-end="url(#os-c5-arr-13)"/>
    <polyline points="274,68 274,98 250,98 250,112" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-13)"/>
    <line x1="318" y1="138" x2="354" y2="138" class="fig-line-accent" marker-end="url(#os-c5-arr-13)"/>
    <line x1="472" y1="138" x2="508" y2="138" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-13)"/>
    <polyline points="432,68 432,88 594,88 594,112" class="fig-line-dashed" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-13)"/>
    <rect x="46" y="40" width="144" height="28" rx="3" class="fig-box-purple"/>
    <rect x="192" y="40" width="164" height="28" rx="3" class="fig-box-blue"/>
    <rect x="358" y="40" width="148" height="28" rx="3" class="fig-box-green"/>
    <rect x="520" y="40" width="166" height="36" rx="4" class="fig-box"/>
    <rect x="28" y="114" width="116" height="58" rx="4" class="fig-box-purple"/>
    <rect x="186" y="114" width="128" height="58" rx="4" class="fig-box-blue"/>
    <rect x="356" y="114" width="114" height="58" rx="4" class="fig-box-orange"/>
    <rect x="510" y="114" width="176" height="58" rx="4" class="fig-box-green"/>
    <rect x="28" y="192" width="658" height="76" rx="4" class="fig-box-accent"/>
    <text x="360" y="31" text-anchor="middle" font-size="11.5" class="fig-title">段页式地址变换机构：1 张段表 + 多张页表 → 无快表需 3 次访存</text>
    <text x="118" y="58" text-anchor="middle" font-size="10" class="fig-purple">段号 S（如 8 位）</text>
    <text x="274" y="58" text-anchor="middle" font-size="10" class="fig-blue">段内页号 P（如 14 位）</text>
    <text x="432" y="58" text-anchor="middle" font-size="10" class="fig-green">页内偏移 W（如 10 位）</text>
    <text x="603" y="55" text-anchor="middle" font-size="9.5" class="fig-title">段表寄存器 STBR</text>
    <text x="603" y="70" text-anchor="middle" font-size="9" class="fig-muted">存段表始址 + 段表长度 TL</text>
    <text x="86" y="134" text-anchor="middle" font-size="10" class="fig-purple">① 查段表(第1次)</text>
    <text x="86" y="150" text-anchor="middle" font-size="9" class="fig-label">先判 S &lt; TL</text>
    <text x="86" y="164" text-anchor="middle" font-size="9" class="fig-muted">得页表始址与长度</text>
    <text x="250" y="134" text-anchor="middle" font-size="10" class="fig-blue">② 查该段页表(第2次)</text>
    <text x="250" y="150" text-anchor="middle" font-size="9" class="fig-label">先判 P &lt; 页表长度</text>
    <text x="250" y="164" text-anchor="middle" font-size="9" class="fig-muted">得页框号 b</text>
    <text x="413" y="136" text-anchor="middle" font-size="10" class="fig-orange">物理地址合成</text>
    <text x="413" y="155" text-anchor="middle" font-size="9.5" class="fig-label">PA = b &lt;&lt; w | W</text>
    <text x="598" y="136" text-anchor="middle" font-size="10" class="fig-green">③ 取目标数据(第3次)</text>
    <text x="598" y="155" text-anchor="middle" font-size="9.5" class="fig-label">若 TLB(S, P) 命中仅1次</text>
    <text x="357" y="213" text-anchor="middle" font-size="10" class="fig-accent">两大极易误选结论：</text>
    <text x="357" y="233" text-anchor="middle" font-size="9.5" class="fig-label">1. 字段有 3 个（S, P, W），但分段对用户可见、分页透明 → 地址空间仍为“二维”！</text>
    <text x="357" y="251" text-anchor="middle" font-size="9.5" class="fig-label">2. 每个“段”最后一页填不满仍有内碎片（多于纯分页），它消除的是“外碎片”；页内偏移 W 仍无需越界检查。</text>
  </svg>
  <figcaption>图 5-13　段页式存储管理三级字段拆分、两次越界检查及三次访存变换过程</figcaption>
</figure>

**三种离散分配方式终极对比表**

| 比较维度 | 基本分页 | 基本分段 | 段页式管理 |
|---|---|---|---|
| **划分目的与依据** | 系统视角；按固定物理尺寸切分，提利用率 | 用户视角；按程序逻辑模块切分 | 先按逻辑分段，再段内物理分页（兼取两者优点） |
| **地址字段与维数** | `2` 字段（页号，偏移）；**一维**（透明） | `2` 字段（段号，偏移）；**二维**（可见） | **`3` 字段**（段号，页号，偏移）；**二维** |
| **表与寄存器** | 1 进程 1 张页表（存页框号）；PTBR | 1 进程 1 张段表（存段基址 + 段长）；STBR | 1 进程 1 张段表（存页表始址 + 长度）+ 多张页表 |
| **越界检查次数** | `1` 次（$P < \text{页表长度}$ ） | **`2` 次**（$S < TL$ ，$W < SL$ ） | **`2` 次**（$S < TL$ ，$P < \text{页表长度}$ ） |
| **物理地址合成** | $\text{页框号} \times L + W$ （拼接） | $\text{段基址} + W$ （加法） | $\text{页框号} \times L + W$ （拼接） |
| **碎片问题** | 无外碎片，有少量**内碎片**（每进程半页） | 无内碎片，有**外碎片** | 无外碎片，有**内碎片**（每**段**半页，比分页多） |
| **共享与保护** | 不方便（函数常跨多页） | 方便（以逻辑段为单位设权限与共享） | 方便（多个段表项指向同一段页表，粒度为段） |
| **无快表访存次数** | $2$ 次（单级）；$n+1$ 次（$n$ 级） | $2$ 次 | **$3$ 次**（快表按 `(S, P)` 键命中降为 $1$ 次） |


---

### 5.5 虚拟内存概念与请求分页管理 ★

#### 5.5.1 局部性原理、虚存三大特征与软硬件分工

传统存储管理方式（连续分配、基本分页、基本分段、基本段页式）虽然形态各异，但共有两大硬性局限：

- **一次性**：作业必须全部一次性装入内存后才能开始运行，导致**大作业无法运行**且多道程序并发度受限。
- **驻留性**：作业装入后一直常驻内存直到运行结束，大量异常处理分支、闲置数组区白白占据宝贵页框。

**1. 理论基石：程序访问的局部性原理**

虚拟内存之所以可行，并不靠逻辑必然，而依赖于真实程序运行时的经验事实——**局部性原理**：

- **时间局部性**：某条指令或数据一旦被访问，不久之后大概率被再次访问（源于循环语句、热点变量与常用子程序）。
- **空间局部性**：一旦访问了某个存储单元，其物理邻近单元不久之后也很可能被访问（源于指令顺序执行、数组与结构体按连续地址存放）。

> **注意（无局部性反例）**：若程序以完全均匀随机的方式访问散列远大于主存的大表（假设主存仅驻留 $10\%$ 页面，缺页率 $f = 0.9$ ），在 $t_{\text{mem}} = 100\text{ ns}$ 、缺页耗时 $t_{\text{fault}} = 5\text{ ms}$ 下，$EAT = 0.1 \times 100 + 0.9 \times 5\times 10^6 \approx 4.5\text{ ms}$ ，比纯主存慢 $45000$ 倍！只有在有局部性（典型 $f \approx 10^{-5}$ ）时，$EAT = 150\text{ ns}$ 才可接受。

**2. 虚拟内存的定义与三大特征**

**虚拟内存**指具有**请求调入功能**和**置换功能**、能从逻辑上对内存容量加以扩充的一种存储器系统（其速度接近主存，单位成本接近外存）。虚拟内存**必须建立在离散分配管理方式之上**（`12#25`）：连续分配无法支持局部装入。三大特征形成一条推进因果链：

1. **多次性（手段）**：无需一次性全装，一个作业可分多次调入内存（解决“进得来”）。
2. **对换性（手段）**：运行期间允许把暂不使用的页/段换出到外存，需要时再换入（解决“出得去”，使多次调入可以持续循环）。
3. **虚拟性（目的与最本质特征）**：由多次性与对换性共同造就，使用户在逻辑上感受到的内存容量远大于实际物理内存。

> **★考点（容量上限 `12#25`、`23#28`）**：虚拟存储器的最大逻辑容量不是外存大小，也不是内存加外存，而是：
> $$
> \text{虚拟内存最大容量} = \min\left(\text{内存容量} + \text{外存容量},\; 2^{\text{体系结构地址位数}}\right)
> $$
> 例如 32 位 CPU 即使装配 1 TB 硬盘，单进程虚拟地址空间上限仍严格锁定在 $2^{32}\text{ B} = 4\text{ GB}$ 。

**3. 虚拟内存的三方软硬件分工（`26#24` 核心考点）**

| 执行环节 | 负责主体 | 分工依据 |
|---|---|---|
| **生成逻辑（虚拟）地址** | **编译器 / 链接器** | 静态布局工作，与运行时物理位置无关 |
| **分配物理页框、填写页表项** | **操作系统（OS）** | 物理页框属全局动态资源，编译器无从得知 |
| **地址变换（VA → PA）与检测缺页/越界/越权** | **硬件（MMU + TLB）** | 每条访存指令均需执行，软件做不起 |
| **处理缺页中断与其他一切异常** | **操作系统（OS）** | 涉及选受害页、磁盘 I/O、修改页表等低频复杂决策 |

> **注意**：务必分清“**硬件触发/检测**”与“**OS 处理**”——**地址转换不是 OS 做的**（是硬件 MMU），**页表项不是编译器填的**（是 OS），**缺页、越界、越权由硬件检测触发，但处理一律交给 OS**！

<figure class="cpd-figure not-content" id="os-c5-fig-14">
  <svg viewBox="0 0 720 278" role="img" aria-label="虚拟内存特征推进链与三方软硬件分工示意图">
    <defs>
      <marker id="os-c5-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="332" height="250" rx="6" class="fig-box-subtle"/>
    <rect x="364" y="14" width="340" height="250" rx="6" class="fig-box-subtle"/>
    <line x1="182" y1="84" x2="182" y2="100" class="fig-line" marker-end="url(#os-c5-arr-14)"/>
    <line x1="182" y1="146" x2="182" y2="162" class="fig-line-accent" marker-end="url(#os-c5-arr-14)"/>
    <line x1="534" y1="88" x2="534" y2="104" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-14)"/>
    <line x1="534" y1="154" x2="534" y2="170" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-14)"/>
    <rect x="30" y="44" width="304" height="40" rx="4" class="fig-box-blue"/>
    <rect x="30" y="102" width="146" height="44" rx="4" class="fig-box-green"/>
    <rect x="188" y="102" width="146" height="44" rx="4" class="fig-box-green"/>
    <rect x="30" y="164" width="304" height="42" rx="4" class="fig-box-accent"/>
    <rect x="30" y="216" width="304" height="36" rx="4" class="fig-box"/>
    <rect x="378" y="44" width="312" height="44" rx="4" class="fig-box"/>
    <rect x="378" y="106" width="312" height="48" rx="4" class="fig-box-blue"/>
    <rect x="378" y="172" width="312" height="80" rx="4" class="fig-box-orange"/>
    <text x="182" y="32" text-anchor="middle" font-size="11.5" class="fig-title">虚拟内存三大特征推进链</text>
    <text x="182" y="61" text-anchor="middle" font-size="10" class="fig-blue">前提：局部性原理 + 非连续（离散）分配 ★</text>
    <text x="182" y="76" text-anchor="middle" font-size="9" class="fig-muted">打破传统的“一次性”与“驻留性”</text>
    <text x="103" y="121" text-anchor="middle" font-size="10" class="fig-green">多次性（手段）</text>
    <text x="103" y="137" text-anchor="middle" font-size="9" class="fig-label">分批调入，进得来</text>
    <text x="261" y="121" text-anchor="middle" font-size="10" class="fig-green">对换性（手段）</text>
    <text x="261" y="137" text-anchor="middle" font-size="9" class="fig-label">暂换外存，出得去</text>
    <text x="182" y="182" text-anchor="middle" font-size="10.5" class="fig-accent">虚拟性（目的与最本质特征）</text>
    <text x="182" y="198" text-anchor="middle" font-size="9.5" class="fig-label">逻辑内存远大于物理内存</text>
    <text x="182" y="238" text-anchor="middle" font-size="9.5" class="fig-label">逻辑容量 ≤ min(内存+外存, 2^地址位数)</text>
    <text x="534" y="32" text-anchor="middle" font-size="11.5" class="fig-title">虚存三方软硬件协同分工（26#24）</text>
    <text x="534" y="63" text-anchor="middle" font-size="10" class="fig-title">① 编译器 / 链接器（静态）</text>
    <text x="534" y="79" text-anchor="middle" font-size="9.5" class="fig-label">生成从 0 编址的完整虚拟（逻辑）地址</text>
    <text x="534" y="126" text-anchor="middle" font-size="10" class="fig-blue">② 硬件 MMU + TLB（每条访存必做）</text>
    <text x="534" y="144" text-anchor="middle" font-size="9.5" class="fig-label">完成 VA → PA 翻译；检测并触发越界/越权/缺页</text>
    <text x="534" y="192" text-anchor="middle" font-size="10" class="fig-orange">③ 操作系统 OS（低频复杂决策）</text>
    <text x="534" y="211" text-anchor="middle" font-size="9.5" class="fig-label">分配物理页框并填写/修改页表项 PTE</text>
    <text x="534" y="230" text-anchor="middle" font-size="9.5" class="fig-red">全权处理缺页故障、越界、越权等一切异常！</text>
  </svg>
  <figcaption>图 5-14　虚拟内存特征推进链与编译器、硬件 MMU/TLB、操作系统三方职责边界</figcaption>
</figure>

---

#### 5.5.2 请求分页页表与缺页中断（Page Fault）处理全流程 ★

虚拟内存最典型的实现是**请求分页管理方式**（$\text{请求分页} = \text{基本分页} + \text{请求调页} + \text{页面置换}$ ）。（若为**请求分段**，除对应字段外还特有**存取方式**与记录段是否动态扩容的**增补位**；且因段是逻辑单位，**一条指令绝不会跨越两个段**。）

**1. 请求分页页表新增的 4 个字段**

| 页表项字段 | 作用与含义 | 维护者与时机 |
|---|---|---|
| **页框号 $f$** | 记录对应页面当前驻留的物理页框号 | 调入时由 OS 填写 |
| **状态位（存在位）$P$** | `1` 表示该页已调入内存，`0` 表示不在内存 | 调入时 OS 置 `1`，换出时置 `0` |
| **访问字段 $A$** | 记录本页近期是否被访问（`1` 位）或被访问次数 | **硬件 MMU** 访存命中自动置 `1`，置换软件定期/扫描清 `0` |
| **修改位（脏位）$M$** | 标记页面装入内存后是否被写过；`M=0` 换出时直接丢弃省去写盘 | **硬件 MMU** 执行写操作时自动置 `1`，写盘后 OS 清 `0` |
| **外存地址** | 该页在外存（对换区或文件区）上的起始磁盘块号 | 进程装入/映射建立时由 OS 填写 |

**2. 缺页中断（Page Fault）的特性与处理流程（`11#28`、`13#30`、`22#29`）**

- **本质属性**：缺页中断属于**内中断（异常）中的“故障（Fault）”**——它与一般外中断有两大核心区别：
  1. 在**指令执行期间**（取指或取操作数中途）触发，而非指令执行完才检查；缺页处理完成后**必须返回重新执行当前引起缺页的那条指令**，而不是下一条指令！
  2. **一条指令在执行期间可能产生多次缺页中断**（例如指令跨页 + 双操作数各自跨页，最多可达 $6$ 次）。
- **一次完整缺页包含两次中断**：先是 CPU 内部触发的**缺页异常（内中断）**；OS 阻塞该进程让出 CPU 并启动磁盘 **DMA** 读入页面；磁盘搬运完成后发出<strong>磁盘 I/O 完成中断（外中断）</strong>唤醒该进程。
- **必做 vs 可选操作的严格界线（`22#29`、`13#30`）**：
  - **必做操作**：保护现场、分配物理页框、启动磁盘 I/O 读入缺页、修改页表项（填页框号并置 $P = 1$ ）及写入 TLB、恢复现场并重执指令。
  - **可选操作**：**淘汰（置换）内存中的页**仅当内存无空闲页框（或进程驻留集已满）时才执行；**写回外存**仅当发生了置换且被淘汰页的**修改位 $M = 1$** 时才执行。
  - **绝对不包含在缺页处理中**：**处理地址越界错**！因为越界检查先于查存在位 $P$ ，越界时直接进入越界异常处理终止进程，根本走不到缺页分支。

<figure class="cpd-figure not-content" id="os-c5-fig-15">
  <svg viewBox="0 0 720 332" role="img" aria-label="请求分页页表扩展字段与含TLB及缺页中断重执的完整地址变换流程图">
    <defs>
      <marker id="os-c5-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="72" rx="6" class="fig-box-subtle"/>
    <rect x="16" y="96" width="688" height="222" rx="6" class="fig-box-subtle"/>
    <line x1="112" y1="142" x2="142" y2="142" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-15)"/>
    <line x1="230" y1="142" x2="270" y2="142" class="fig-line" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-15)"/>
    <line x1="186" y1="164" x2="186" y2="188" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-15)"/>
    <polyline points="384,142 486,142" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-15)"/>
    <line x1="328" y1="164" x2="328" y2="188" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-15)"/>
    <polyline points="388,205 416,205 416,154 384,154" class="fig-line-dashed" stroke="var(--sl-color-purple)" marker-end="url(#os-c5-arr-15)"/>
    <polyline points="388,218 550,218 550,170" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-15)"/>
    <line x1="328" y1="236" x2="328" y2="254" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-15)"/>
    <polyline points="198,280 68,280 68,166" class="fig-line-dashed" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-15)"/>
    <rect x="30" y="42" width="120" height="32" rx="3" class="fig-box-blue"/>
    <rect x="154" y="42" width="106" height="32" rx="3" class="fig-box-red"/>
    <rect x="264" y="42" width="106" height="32" rx="3" class="fig-box-orange"/>
    <rect x="374" y="42" width="106" height="32" rx="3" class="fig-box-purple"/>
    <rect x="484" y="42" width="84" height="32" rx="3" class="fig-box"/>
    <rect x="572" y="42" width="118" height="32" rx="3" class="fig-box-green"/>
    <rect x="28" y="120" width="82" height="44" rx="4" class="fig-box-blue"/>
    <rect x="144" y="120" width="84" height="44" rx="4" class="fig-box-accent"/>
    <rect x="132" y="190" width="108" height="34" rx="4" class="fig-box-red"/>
    <rect x="272" y="120" width="110" height="44" rx="4" class="fig-box-purple"/>
    <rect x="266" y="190" width="122" height="44" rx="4" class="fig-box-orange"/>
    <rect x="488" y="118" width="200" height="50" rx="4" class="fig-box-green"/>
    <rect x="200" y="256" width="488" height="50" rx="4" class="fig-box-red"/>
    <text x="360" y="32" text-anchor="middle" font-size="11" class="fig-title">请求分页页表项（PTE）完整结构：基本页表 + 4 个新增字段</text>
    <text x="90" y="62" text-anchor="middle" font-size="10" class="fig-blue">物理页框号 f</text>
    <text x="207" y="62" text-anchor="middle" font-size="10" class="fig-red">状态位 P（存在）</text>
    <text x="317" y="62" text-anchor="middle" font-size="9.2" class="fig-orange">访问位 A（硬件置1）</text>
    <text x="427" y="62" text-anchor="middle" font-size="10" class="fig-purple">修改位 M（写置1）</text>
    <text x="526" y="62" text-anchor="middle" font-size="10" class="fig-label">权限 R/W/X</text>
    <text x="631" y="62" text-anchor="middle" font-size="10" class="fig-green">外存磁盘地址</text>
    <text x="360" y="112" text-anchor="middle" font-size="11" class="fig-title">请求分页完整地址变换流水（含 TLB 命中 → 慢表 → 缺页故障 → 指令重执）</text>
    <text x="69" y="139" text-anchor="middle" font-size="9.5" class="fig-blue">CPU 发出</text>
    <text x="69" y="155" text-anchor="middle" font-size="9.5" class="fig-label">VA: P | d</text>
    <text x="186" y="139" text-anchor="middle" font-size="9.5" class="fig-accent">① 越界检查</text>
    <text x="186" y="155" text-anchor="middle" font-size="9.5" class="fig-accent">P &lt; 表长 M ?</text>
    <text x="210" y="180" font-size="9" class="fig-red">越界</text>
    <text x="186" y="211" text-anchor="middle" font-size="9.5" class="fig-red">越界异常(终止)</text>
    <text x="327" y="139" text-anchor="middle" font-size="10" class="fig-purple">② 查 TLB 快表</text>
    <text x="327" y="155" text-anchor="middle" font-size="9" class="fig-muted">页换出须失效TLB</text>
    <text x="435" y="134" text-anchor="middle" font-size="9.5" class="fig-green">TLB命中</text>
    <text x="352" y="180" font-size="9" class="fig-orange">未命中</text>
    <text x="327" y="209" text-anchor="middle" font-size="9.5" class="fig-orange">③ 查内存慢表</text>
    <text x="327" y="225" text-anchor="middle" font-size="9" class="fig-label">P=1 → 写入 TLB</text>
    <text x="470" y="206" text-anchor="middle" font-size="9" class="fig-green">P=1 在内存</text>
    <text x="352" y="248" font-size="9" class="fig-red">P=0 缺页</text>
    <text x="588" y="138" text-anchor="middle" font-size="10" class="fig-green">置 A←1 (写指令还置 M←1)</text>
    <text x="588" y="156" text-anchor="middle" font-size="9.5" class="fig-label">合成 PA = f &lt;&lt; k | d 访存</text>
    <text x="444" y="275" text-anchor="middle" font-size="10" class="fig-red">④ 缺页故障处理（OS 接管，进程阻塞让出 CPU，DMA 读盘）★</text>
    <text x="444" y="294" text-anchor="middle" font-size="9" class="fig-label">空框不足才置换(M=1才写回) → DMA 调入 → I/O完成外中断唤醒 → 改页表写TLB → 重新执行原指令！</text>
  </svg>
  <figcaption>图 5-15　请求分页页表扩展字段与含 TLB/Page Fault/DMA/指令重执的完整硬件-OS 协同流程</figcaption>
</figure>

**3. 含 TLB 与缺页处理的完整 EAT 计算公式与折算陷阱**

- **标准完整公式（`汤小丹 §5.3.5`）**：若先查 TLB（耗时 $\lambda$ ，命中率 $a$ ），TLB 命中则直接读主存（耗时 $t$ ）；TLB 未命中则先访存查页表（耗时 $t$ ），其中有缺页率 $f$ 触发缺页处理（耗时 $\varepsilon$ ）之后更新 TLB 并重新访存读取（如算作 $\lambda + t$ 或按题目约定），否则直接读取（$t$ ）：
  $$
  EAT = \lambda + a \cdot t + (1 - a)\big[t + f(\varepsilon + \lambda + t) + (1 - f)(\lambda + t)\big]
  $$
  若题目忽略 TLB（常见于纯算缺页开销），公式简化为：
  $$
  EAT = (1 - f) \cdot t_{\text{mem}} + f \cdot t_{\text{fault}}
  $$
  其中 $t_{\text{fault}} = \beta \cdot t_{\text{写回加读入}} + (1 - \beta) \cdot t_{\text{仅读入}}$ （$\beta$ 为被换出页是脏页的概率）。
- **缺页率 $f$ 分母折算陷阱**：缺页率定义 $f = \frac{\text{缺页次数 } F}{\text{总页面访问次数 } A}$ ，分母是**访存次数**而非指令条数！若题干给出“每执行 $k$ 条指令缺页一次，且平均每条指令访存 $c$ 次”，必须先折算 $f = \frac{1}{k \times c}$ 。
- **典型真题 `09#46`、`20#28`**：
  - `09#46` 考缺页重执耗时：TLB 初始为空、驻留集为 $2$ 、LRU 局部淘汰。第一次访问某不在内存的页时，完整耗时 = **查 TLB 未命中（$10\text{ ns}$ ）+ 查慢表缺页（$100\text{ ns}$ ）+ 缺页处理含更新页表与 TLB（$10^8\text{ ns}$ ）+ 重执指令查 TLB 命中（$10\text{ ns}$ ）+ 访存读数据（$100\text{ ns}$ ）**，切勿漏掉最后重执的 `10 + 100`！
  - `20#28` 考哪些因素影响请求分页有效访存时间：`EAT` 拆开包含 $f$（缺页率）、$t_{\text{mem}}$（内存访问时间）和 $t_{\text{fault}}$（**磁盘读写时间** + **执行缺页处理程序的 CPU 时间**），四项全部影响。

---

### 5.6 页面置换算法 ★

当发生缺页且没有空闲页框时，操作系统必须通过页面置换算法决定“淘汰哪一页”。**注意区别两个计数概念**：
$$
\text{置换次数} = \begin{cases} \text{缺页次数} - m, & d \ge m \text{（页框最终被装满，$m$ 为分配页框数，$d$ 为不同页面数）} \\ 0, & d < m \text{（有空框永远闲置，套公式会算出负数！）} \end{cases}
$$
此外，如题干写明“某几页初始已调入内存”（如 `25#26`），则初始访问这几页时**不算缺页**！

#### 5.6.1 OPT、FIFO 与 Belady 异常、LRU 与 LFU

**1. 最佳置换算法（OPT，Optimal）**

- **规则**：选择**未来最长时间内不会被访问**（包括此后永远不再出现）的页面予以淘汰。
- **手算三步**：列出当前内存中**全部 $m$ 个页面** → 向后扫描序列记下每页下次出现的下标（未再出现记 $+\infty$ ）→ 淘汰下标最大者（多个 $+\infty$ 任选其一，**缺页次数唯一但淘汰序列不一定唯一**）。
- **核心性质**：OPT 是**唯一逐串成立的最优算法**（对任意引用串、任意页框数，缺页次数均不超过任何其他算法），且**不依赖局部性原理**、**不会发生 Belady 异常**。因无法预知未来，不能在线实现，专作离线 trace 评估标准。

**2. 先进先出置换算法（FIFO）与 Belady 异常**

- **规则**：把调入内存的页按进入先后链成队列，每次缺页淘汰<strong>队头（最先进入内存、驻留最久）</strong>的页面；**页面命中时队列完全不动**！
- **病根与定位**：FIFO 是唯一**访存路径零开销**（无需硬件支持、无需改位或链表）的算法，但“命中不留痕”导致全局变量、循环热页照样被踢出，性能最差。队列由局部置换每进程一份（随 PCB 挂起）、全局置换全系统一份，均**不随进程切换重建**。
- **Belady 异常（`14#30` 核心考点）**：分配的页框数增加，缺页次数反而上升的反常现象。经典反例：序列 `1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5` 在 FIFO 下 **$3$ 页框缺页 $9$ 次，而 $4$ 页框缺页 $10$ 次**！
  - **栈算法判据**：若某算法对任意串在 $m$ 个页框时的驻留集 $B_t(m)$ 恒满足**包含性质** $B_t(m) \subseteq B_t(m+1)$ ，则称其为**栈算法**，**绝对不会出现 Belady 异常**（缺页次数单调不增）。
  - **判断口诀**：**只看淘汰排序依据是否依赖页框数 $m$**！OPT 看未来下标、LRU 看过去最后访问时刻，只与引用串本身有关，与 $m$ 无关 ⇒ **都是栈算法，绝无 Belady 异常**；FIFO 及基于装入环/队列的 **CLOCK（含二次机会、改进 CLOCK）** 排序依赖装入时刻（即依赖哪步缺页、从而依赖 $m$ ）⇒ **是非栈算法，均可能出现 Belady 异常**！但包含性质断裂只是 Belady 异常的**必要非充分条件**，是否真出现异常还需算整串总账。

**3. 最近最久未使用置换算法（LRU）**

- **规则**：淘汰**最近最久未被使用**（最后一次访问时刻最早）的页面，利用“时间局部性”以过去近似未来。
- **反例警示（平均更优 $\neq$ 逐串更优）**：在序列 `1, 2, 1, 3, 2`（$2$ 框）中，FIFO 缺 `3` 次，LRU 因第 3 步命中 `1` 把 `1` 提到栈顶反而淘汰掉第 5 步要用的 `2`，缺 `4` 次！大规模下，**当 $m$ 个页框循环访问 $m+1$ 个页面时，FIFO 与 LRU 命中率都会跌至 $0\%$**。
- **408 考场秒杀技巧（倒推法，`15#27`）**：求给定长串后某页到来时应淘汰谁，**无需从头画表**！直接从序列当前末尾**倒着往前数**，最先凑齐的 $m$ 个不同页号就是当前驻留集，其中<strong>最后一次出现位置最靠左（最早）</strong>的那一页即为淘汰页！
- **LRU 硬件/数据结构实现（沿“精度换开销”梯度演化）**：
  1. **计数器法（精确）**：每页表项记录逻辑时钟戳，每次访存写时间戳，淘汰时 $O(n)$ 扫最小值（有溢出隐患）。
  2. **双向链表栈（精确）**：栈顶最新、栈底最久；每次命中/访存从链表中间摘下节点移至栈顶，淘汰取栈底 $O(1)$ 。
  3. **附加引用位 / 移位寄存器法（近似）**：为每个物理页配一个 $n$ 位移位寄存器 $R = R_{n-1}\dots R_0$ ，访存由硬件置访问位 $A = 1$ ；每隔固定周期（如 $100\text{ ms}$ ）将各 $R$ 右移 $1$ 位，把 $A$ 移入最高位 $R_{n-1}$ 后清 $A = 0$ 。将 $R$ 视作无符号整数，**数值最小者**即为最久未用页（因为高位权重对应更近的时间周期）。
  - **对比 Cache LRU**：Cache 每组仅有 $2\sim 8$ 路，未命中代价几十周期，故纯硬件几个比较位即可实现**精确 LRU**；而主存页框动辄数万、每次访存都写内存或调链表软件开销太高，因此 OS 页面置换退而采用近似方案 **CLOCK**。

**4. 最少使用置换算法（LFU，Least Frequently Used）**

- **规则**：淘汰过去一段时间**被访问次数（频率）最少**的页面（`LRU` 看最后访问时间，`LFU` 看累计频次）。
- **缺陷**：若某页早期被高频访问随后不再使用，高计数会让它长期赖在内存造成新页抖动；若共用移位寄存器硬件实现（统计 $R$ 中 `1` 的个数），同一周期（如 $100\text{ ms}$ ）内访问 $1$ 次与访问 $1000$ 次都会只置位 `1` 次而完全等效，难以反映真实频次。

---

#### 5.6.2 CLOCK（NRU）与改进型 CLOCK 算法 ★

由于精确 LRU 每次命中都要写时间戳或改链表，开销落在了每秒上亿次的访存热路径上，真实操作系统（如 Linux / Unix 变体）转而使用将硬件开销降至 **1 个访问位**、命中时**位置不变**的 **CLOCK 算法**（又称**最近未用算法 NRU**）：

**1. 简单 CLOCK 与二次机会算法**

- **二次机会算法**：在 FIFO 队列基础上为每页增设访问位 $A$ （由硬件 MMU 访存时自动置 $1$ ）；检查队头若 $A = 0$ 直接淘汰，若 $A = 1$ 则清 $A \leftarrow 0$ 后摘下放到队尾“给第二次机会”。
- **简单 CLOCK**：与二次机会**淘汰逻辑完全等价（任何串上缺页次数完全相同）**，只是改为**环形循环队列 + 时钟扫描指针**，淘汰/跳过时页面原地不动，仅移动指针。
- **手算两大铁律（`10#46`）**：
  1. **指针跨次缺页保留位置**：下一次发生缺页时，从**上一次淘汰完成停下的下一格**开始扫描，绝不重置回 0 号框！
  2. **命中不改位置只置 $A=1$**：命中的页仅由硬件置 $A=1$ ，在环上的相对位置不动。最坏情况下全部页 $A=1$ ，指针扫描一整圈全部清 $0$ 回到起点，淘汰起点页本身（最多检查 $m + 1$ 格）。

**2. 改进型 CLOCK 算法（`16#26`、`21#28` 必考重点）**

简单 CLOCK 仅考虑“最近用没用过”（访问位 $A$ ），忽略了“脏页换出需要额外写回磁盘”。改进型 CLOCK 综合考虑 **$(A, M)$** 两个状态位，将内存页分为四类，**淘汰优先级严格如下**：
$$
(0, 0)\; \text{＞}\; (0, 1)\; \text{＞}\; (1, 0)\; \text{＞}\; (1, 1)
$$

> **★考点（为什么 $(0, 1)$ 优先于 $(1, 0)$？`16#26`）**：比较两种“选错”的代价！如果淘汰了 $(1, 0)$（近期刚用过的干净页），因它仍活跃，极可能马上再次缺页——引发一次中断 + 磁盘读，且调它回来时还得踢掉另一页，产生**连锁反应**；而如果淘汰了 $(0, 1)$（很久没用过的脏页），代价只是**多一次写回磁盘**，写完就彻底结束。因此**访问位 $A$ 的权重高于修改位 $M$**：**先看“还用不用”，再看“脏不脏”**。

- **改进型 CLOCK 最多四轮扫描规则**：
  - **第 1 轮**：从指针当前位置扫一圈，寻找 **$(0, 0)$**（最理想牺牲页），**本轮扫描绝对不修改任何 $A$ 位**！（若本轮清零会破坏原先 $(0, 1)$ 与 $(1, 1)$ 的区分）
  - **第 2 轮**：若第 1 轮失败，从原指针位置再扫一圈，寻找 **$(0, 1)$**；**同时将本轮扫描过的每一页的访问位 $A$ 置为 $0$**。
  - **第 3 轮**：若第 2 轮失败，指针回到起点，重复第 1 轮规则寻找 **$(0, 0)$**（此时原来的 $(1, 0)$ 已被第 2 轮清成 $(0, 0)$ ）。
  - **第 4 轮**：若第 3 轮仍失败，重复第 2 轮规则寻找 **$(0, 1)$**（此时环上全为 $(0, 1)$ ，必定在起点命中淘汰）。

---

#### 5.6.3 同一序列算法推演对比与汇总表

下面以经典对比序列**串甲** `3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4`（$m = 3$ 个页框）为例，在图 5-16 中并排演示 OPT、FIFO、LRU、CLOCK 四大算法的每一步驻留状态与关键分歧；图 5-17 演示 FIFO 在 `1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5` 上的 Belady 异常机理；图 5-18 梳理改进型 CLOCK 四象限扫描状态机。

<figure class="cpd-figure not-content" id="os-c5-fig-16">
  <svg viewBox="0 0 720 340" role="img" aria-label="同一访问序列3页框下OPT与FIFO与LRU与CLOCK步进推演对照表">
    <rect x="16" y="14" width="688" height="312" rx="6" class="fig-box-subtle"/>
    <rect x="26" y="42" width="106" height="28" rx="3" class="fig-box"/>
    <rect x="136" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="182" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="228" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="274" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="320" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="366" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="412" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="458" y="42" width="43" height="28" rx="2" class="fig-box-accent"/>
    <rect x="504" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="550" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="596" y="42" width="43" height="28" rx="2" class="fig-box-blue"/>
    <rect x="642" y="42" width="48" height="28" rx="2" class="fig-box-blue"/>
    <rect x="26" y="76" width="106" height="52" rx="3" class="fig-box-green"/>
    <rect x="136" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="182" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="228" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="274" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="320" y="76" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="366" y="76" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="412" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="458" y="76" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="504" y="76" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="550" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="596" y="76" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="642" y="76" width="48" height="52" rx="2" class="fig-box-green"/>
    <rect x="26" y="134" width="106" height="52" rx="3" class="fig-box-orange"/>
    <rect x="136" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="182" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="228" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="274" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="320" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="366" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="412" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="458" y="134" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="504" y="134" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="550" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="596" y="134" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="642" y="134" width="48" height="52" rx="2" class="fig-box-green"/>
    <rect x="26" y="192" width="106" height="52" rx="3" class="fig-box-purple"/>
    <rect x="136" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="182" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="228" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="274" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="320" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="366" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="412" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="458" y="192" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="504" y="192" width="43" height="52" rx="2" class="fig-box-green"/>
    <rect x="550" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="596" y="192" width="43" height="52" rx="2" class="fig-box-red"/>
    <rect x="642" y="192" width="48" height="52" rx="2" class="fig-box-red"/>
    <rect x="26" y="250" width="106" height="44" rx="3" class="fig-box-blue"/>
    <rect x="136" y="250" width="554" height="44" rx="3" class="fig-box"/>
    <rect x="26" y="298" width="664" height="22" rx="3" class="fig-box-accent"/>
    <text x="360" y="32" text-anchor="middle" font-size="11.5" class="fig-title">经典序列“串甲” 3 页框步进推演对照（红格=缺页，绿格=命中；揭示 LRU 并非逐串优于 FIFO）</text>
    <text x="79" y="60" text-anchor="middle" font-size="10" class="fig-title">引用步 (1–12)</text>
    <text x="157" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">3</text>
    <text x="203" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">2</text>
    <text x="249" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">1</text>
    <text x="295" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">0</text>
    <text x="341" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">3</text>
    <text x="387" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">2</text>
    <text x="433" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">4</text>
    <text x="479" y="60" text-anchor="middle" font-size="10" class="fig-accent">3★</text>
    <text x="525" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">2</text>
    <text x="571" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">1</text>
    <text x="617" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">0</text>
    <text x="666" y="60" text-anchor="middle" font-size="10.5" class="fig-blue">4</text>
    <text x="79" y="96" text-anchor="middle" font-size="10" class="fig-green">OPT (最佳)</text>
    <text x="79" y="114" text-anchor="middle" font-size="9.5" class="fig-label">缺7次 / 换4次</text>
    <text x="157" y="96" text-anchor="middle" font-size="9" class="fig-red">3</text>
    <text x="203" y="96" text-anchor="middle" font-size="9" class="fig-red">3,2</text>
    <text x="249" y="96" text-anchor="middle" font-size="9" class="fig-red">3,2,1</text>
    <text x="295" y="96" text-anchor="middle" font-size="9" class="fig-red">3,2,0</text>
    <text x="295" y="114" text-anchor="middle" font-size="8.5" class="fig-muted">汰1</text>
    <text x="341" y="104" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="387" y="104" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="433" y="96" text-anchor="middle" font-size="9" class="fig-red">3,2,4</text>
    <text x="433" y="114" text-anchor="middle" font-size="8.5" class="fig-muted">汰0</text>
    <text x="479" y="104" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="525" y="104" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="571" y="96" text-anchor="middle" font-size="9" class="fig-red">1,2,4</text>
    <text x="571" y="114" text-anchor="middle" font-size="8.5" class="fig-muted">汰3</text>
    <text x="617" y="96" text-anchor="middle" font-size="9" class="fig-red">1,0,4</text>
    <text x="617" y="114" text-anchor="middle" font-size="8.5" class="fig-muted">汰2</text>
    <text x="666" y="104" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="79" y="154" text-anchor="middle" font-size="10" class="fig-orange">FIFO (队列)</text>
    <text x="79" y="172" text-anchor="middle" font-size="9.5" class="fig-label">缺9次 / 换6次</text>
    <text x="157" y="154" text-anchor="middle" font-size="9" class="fig-red">3</text>
    <text x="203" y="154" text-anchor="middle" font-size="9" class="fig-red">3,2</text>
    <text x="249" y="154" text-anchor="middle" font-size="9" class="fig-red">3,2,1</text>
    <text x="295" y="154" text-anchor="middle" font-size="9" class="fig-red">2,1,0</text>
    <text x="295" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰3</text>
    <text x="341" y="154" text-anchor="middle" font-size="9" class="fig-red">1,0,3</text>
    <text x="341" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰2</text>
    <text x="387" y="154" text-anchor="middle" font-size="9" class="fig-red">0,3,2</text>
    <text x="387" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰1</text>
    <text x="433" y="154" text-anchor="middle" font-size="9" class="fig-red">3,2,4</text>
    <text x="433" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰0</text>
    <text x="479" y="162" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="525" y="162" text-anchor="middle" font-size="9" class="fig-green">命中</text>
    <text x="571" y="154" text-anchor="middle" font-size="9" class="fig-red">2,4,1</text>
    <text x="571" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰3</text>
    <text x="617" y="154" text-anchor="middle" font-size="9" class="fig-red">4,1,0</text>
    <text x="617" y="172" text-anchor="middle" font-size="8.5" class="fig-muted">汰2</text>
    <text x="666" y="162" text-anchor="middle" font-size="9" class="fig-green">命中!</text>
    <text x="79" y="212" text-anchor="middle" font-size="10" class="fig-purple">LRU (最新在左)</text>
    <text x="79" y="230" text-anchor="middle" font-size="9.5" class="fig-label">缺10次/换7次</text>
    <text x="157" y="212" text-anchor="middle" font-size="9" class="fig-red">3</text>
    <text x="203" y="212" text-anchor="middle" font-size="9" class="fig-red">2,3</text>
    <text x="249" y="212" text-anchor="middle" font-size="9" class="fig-red">1,2,3</text>
    <text x="295" y="212" text-anchor="middle" font-size="9" class="fig-red">0,1,2</text>
    <text x="295" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰3</text>
    <text x="341" y="212" text-anchor="middle" font-size="9" class="fig-red">3,0,1</text>
    <text x="341" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰2</text>
    <text x="387" y="212" text-anchor="middle" font-size="9" class="fig-red">2,3,0</text>
    <text x="387" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰1</text>
    <text x="433" y="212" text-anchor="middle" font-size="9" class="fig-red">4,2,3</text>
    <text x="433" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰0</text>
    <text x="479" y="212" text-anchor="middle" font-size="9" class="fig-green">3,4,2</text>
    <text x="479" y="230" text-anchor="middle" font-size="8" class="fig-green">命中提栈</text>
    <text x="525" y="212" text-anchor="middle" font-size="9" class="fig-green">2,3,4</text>
    <text x="525" y="230" text-anchor="middle" font-size="8" class="fig-green">命中提栈</text>
    <text x="571" y="212" text-anchor="middle" font-size="9" class="fig-red">1,2,3</text>
    <text x="571" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰4!</text>
    <text x="617" y="212" text-anchor="middle" font-size="9" class="fig-red">0,1,2</text>
    <text x="617" y="230" text-anchor="middle" font-size="8.5" class="fig-muted">汰3</text>
    <text x="666" y="212" text-anchor="middle" font-size="9" class="fig-red">4,0,1</text>
    <text x="666" y="230" text-anchor="middle" font-size="7.4" class="fig-red">汰2(多缺)</text>
    <text x="79" y="268" text-anchor="middle" font-size="9.5" class="fig-blue">简单 CLOCK</text>
    <text x="79" y="284" text-anchor="middle" font-size="9" class="fig-label">缺9次 / 换6次</text>
    <text x="413" y="268" text-anchor="middle" font-size="9.5" class="fig-label">指针自框0循环扫描：[3,2,1]→缺0清圈汰3→缺3汰2→缺2汰1→缺4清圈汰0→3,2命中置1→缺1汰3→缺0汰2→4命中</text>
    <text x="413" y="284" text-anchor="middle" font-size="9" class="fig-muted">另对照教材经典“串乙”(7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1，3框)：OPT=9 / LRU=12 / CLOCK=14 / FIFO=15</text>
    <text x="358" y="313" text-anchor="middle" font-size="9.5" class="fig-accent">分歧解析：串甲第 8–9 步 LRU 命中 3,2 顺带把较早的 4 挤至栈底并在第 10 步淘汰，导致第 12 步访问 4 时反比 FIFO 多缺 1 次</text>
  </svg>
  <figcaption>图 5-16　串甲（3 页框）下 OPT / FIFO / LRU / CLOCK 步进推演及“平均更优 ≠ 逐串更优”分歧点解析</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c5-fig-17">
  <svg viewBox="0 0 720 278" role="img" aria-label="FIFO页面置换3框与4框Belady异常断裂点与栈算法曲线对比图">
    <rect x="16" y="14" width="388" height="250" rx="6" class="fig-box-subtle"/>
    <rect x="416" y="14" width="288" height="250" rx="6" class="fig-box-subtle"/>
    <line x1="454" y1="206" x2="682" y2="206" class="fig-line"/>
    <line x1="454" y1="206" x2="454" y2="56" class="fig-line"/>
    <polyline points="484,116 534,116 584,96 634,136 674,176" class="fig-line" stroke="var(--sl-color-red)"/>
    <polyline points="484,140 534,154 584,166 634,178 674,186" class="fig-line" stroke="var(--sl-color-green)"/>
    <circle cx="534" cy="116" r="4" class="fig-dot"/>
    <circle cx="584" cy="96" r="4" class="fig-box-red"/>
    <circle cx="534" cy="154" r="4" class="fig-green-fill"/>
    <circle cx="584" cy="166" r="4" class="fig-green-fill"/>
    <rect x="28" y="42" width="364" height="32" rx="4" class="fig-box"/>
    <rect x="28" y="80" width="364" height="58" rx="4" class="fig-box-blue"/>
    <rect x="28" y="144" width="364" height="68" rx="4" class="fig-box-red"/>
    <rect x="28" y="218" width="364" height="36" rx="4" class="fig-box-accent"/>
    <rect x="430" y="216" width="260" height="38" rx="4" class="fig-box"/>
    <text x="210" y="32" text-anchor="middle" font-size="11" class="fig-title">Belady 异常追踪（串：1,2,3,4,1,2,5,1,2,3,4,5）</text>
    <text x="210" y="62" text-anchor="middle" font-size="9.5" class="fig-label">FIFO：3 个页框缺页 9 次 → 增加到 4 个页框反升至 10 次！</text>
    <text x="210" y="99" text-anchor="middle" font-size="10" class="fig-blue">3 页框：第 4 步页 1 被淘汰 → 第 5 步重入刷新到队尾</text>
    <text x="210" y="117" text-anchor="middle" font-size="9.5" class="fig-label">第 7 步(访 5)后驻留 {1, 2, 5}，第 8 步(访 1) 命中！</text>
    <text x="210" y="162" text-anchor="middle" font-size="10" class="fig-red">4 页框：第 1–6 步页 1 从未换出，停在最老的队头！</text>
    <text x="210" y="180" text-anchor="middle" font-size="9.5" class="fig-label">第 7 步(访 5) 队头页 1 被踢 → 驻留 {2, 3, 4, 5}（包含断裂）</text>
    <text x="210" y="198" text-anchor="middle" font-size="9.5" class="fig-red">第 8 步(访 1) 反而缺页（多 1 个框少了“刷新资格”）</text>
    <text x="210" y="240" text-anchor="middle" font-size="9.5" class="fig-accent">非栈算法（FIFO / CLOCK）排序依赖页框数 m → 会断裂</text>
    <text x="560" y="32" text-anchor="middle" font-size="11" class="fig-title">缺页次数 vs 分配页框数 m 曲线对比</text>
    <text x="444" y="64" text-anchor="end" font-size="9" class="fig-muted">缺页</text>
    <text x="584" y="84" text-anchor="middle" font-size="9.5" class="fig-red">FIFO: m=4 峰值异常(10)</text>
    <text x="534" y="131" text-anchor="middle" font-size="9" class="fig-muted">m=3(9)</text>
    <text x="518" y="178" text-anchor="middle" font-size="9.5" class="fig-green">栈算法 (OPT/LRU)</text>
    <text x="608" y="196" text-anchor="middle" font-size="9" class="fig-green">严格单调不增</text>
    <text x="678" y="201" text-anchor="end" font-size="9" class="fig-muted">m</text>
    <text x="560" y="232" text-anchor="middle" font-size="9.5" class="fig-label">包含性质 Bt(m) ⊆ Bt(m+1) 仅在 OPT/LRU 恒成立</text>
    <text x="560" y="247" text-anchor="middle" font-size="9" class="fig-muted">14#30：OPT、LRU 绝不会出现 Belady 异常</text>
  </svg>
  <figcaption>图 5-17　FIFO Belady 异常包含性质断裂机理与栈算法（OPT/LRU）单调性曲线对比</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c5-fig-18">
  <svg viewBox="0 0 720 308" role="img" aria-label="改进型CLOCK置换算法四象限优先级与最多四轮扫描状态机图">
    <defs>
      <marker id="os-c5-arr-18" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="290" height="280" rx="6" class="fig-box-subtle"/>
    <rect x="318" y="14" width="386" height="280" rx="6" class="fig-box-subtle"/>
    <line x1="511" y1="90" x2="511" y2="108" class="fig-line" marker-end="url(#os-c5-arr-18)"/>
    <line x1="511" y1="154" x2="511" y2="172" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-18)"/>
    <line x1="511" y1="214" x2="511" y2="232" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-18)"/>
    <rect x="28" y="70" width="128" height="72" rx="4" class="fig-box-green"/>
    <rect x="164" y="70" width="128" height="72" rx="4" class="fig-box-blue"/>
    <rect x="28" y="150" width="128" height="72" rx="4" class="fig-box-orange"/>
    <rect x="164" y="150" width="128" height="72" rx="4" class="fig-box-red"/>
    <rect x="28" y="232" width="264" height="50" rx="4" class="fig-box-accent"/>
    <rect x="332" y="44" width="358" height="44" rx="4" class="fig-box-green"/>
    <rect x="332" y="110" width="358" height="44" rx="4" class="fig-box-blue"/>
    <rect x="332" y="174" width="358" height="40" rx="4" class="fig-box-orange"/>
    <rect x="332" y="234" width="358" height="48" rx="4" class="fig-box-red"/>
    <text x="161" y="32" text-anchor="middle" font-size="11" class="fig-title">改进型 CLOCK 四类页面 (A, M) 优先级 ★</text>
    <text x="161" y="54" text-anchor="middle" font-size="9.5" class="fig-muted">左列 M=0 (干净，免写盘) ｜ 右列 M=1 (脏，须写回)</text>
    <text x="92" y="92" text-anchor="middle" font-size="10.5" class="fig-green">① (0, 0) 最优先</text>
    <text x="92" y="111" text-anchor="middle" font-size="9.5" class="fig-label">未访问 且 未修改</text>
    <text x="92" y="129" text-anchor="middle" font-size="9" class="fig-green">直接淘汰，零代价</text>
    <text x="228" y="92" text-anchor="middle" font-size="10.5" class="fig-blue">② (0, 1) 次优先</text>
    <text x="228" y="111" text-anchor="middle" font-size="9.5" class="fig-label">未访问 但 已修改</text>
    <text x="228" y="129" text-anchor="middle" font-size="9" class="fig-blue">写回1次即止，不连锁</text>
    <text x="92" y="172" text-anchor="middle" font-size="10.5" class="fig-orange">③ (1, 0) 第三类</text>
    <text x="92" y="191" text-anchor="middle" font-size="9.5" class="fig-label">已访问 但 未修改</text>
    <text x="92" y="209" text-anchor="middle" font-size="9" class="fig-orange">淘汰易再缺页并连锁</text>
    <text x="228" y="172" text-anchor="middle" font-size="10.5" class="fig-red">④ (1, 1) 最后考虑</text>
    <text x="228" y="191" text-anchor="middle" font-size="9.5" class="fig-label">已访问 且 已修改</text>
    <text x="228" y="209" text-anchor="middle" font-size="9" class="fig-red">既要写盘又极可能复用</text>
    <text x="160" y="253" text-anchor="middle" font-size="9.5" class="fig-accent">记住优先级：(0,0) &gt; (0,1) &gt; (1,0) &gt; (1,1)</text>
    <text x="160" y="270" text-anchor="middle" font-size="9" class="fig-label">A 权重 &gt; M：先看“还用不用”，再看“脏不脏”</text>
    <text x="511" y="32" text-anchor="middle" font-size="11" class="fig-title">最多四轮扫描淘汰机制（每轮从上轮停下处扫 1 圈）</text>
    <text x="511" y="62" text-anchor="middle" font-size="10" class="fig-green">第 1 轮：找 (0, 0) —— 不改任何位！（防破坏 (0,1)）</text>
    <text x="511" y="79" text-anchor="middle" font-size="9" class="fig-label">找到立即淘汰并前移指针；扫完一圈无 (0,0) → 进入第 2 轮</text>
    <text x="546" y="103" font-size="9" class="fig-muted">失败</text>
    <text x="511" y="128" text-anchor="middle" font-size="10" class="fig-blue">第 2 轮：找 (0, 1) —— 扫过未匹配页的 A 一律清 0！</text>
    <text x="511" y="145" text-anchor="middle" font-size="9" class="fig-label">找到立即写回并淘汰；若无 → 原 (1,0) 已全变 (0,0), (1,1) 变 (0,1)</text>
    <text x="546" y="167" font-size="9" class="fig-orange">失败</text>
    <text x="511" y="190" text-anchor="middle" font-size="10" class="fig-orange">第 3 轮：再找 (0, 0) —— 必抓出原 (1, 0) 干净活跃页</text>
    <text x="511" y="206" text-anchor="middle" font-size="9" class="fig-label">找到即淘汰；若仍无（说明全环原均为 (1,1)）→ 进入第 4 轮</text>
    <text x="546" y="227" font-size="9" class="fig-red">失败</text>
    <text x="511" y="254" text-anchor="middle" font-size="10" class="fig-red">第 4 轮：再找 (0, 1) —— 起点即命中！写回并淘汰起点页</text>
    <text x="511" y="272" text-anchor="middle" font-size="9" class="fig-label">（注：简单 CLOCK 与改进型 CLOCK 均会出现 Belady 异常）</text>
  </svg>
  <figcaption>图 5-18　改进型 CLOCK 算法 (A, M) 四象限优先级与最多四轮扫描状态转换流程</figcaption>
</figure>

**页面置换算法核心属性汇总对比**

| 算法 | 决策依据 | 硬件支持与访存开销 | 栈算法（Belady 异常） | 平均性能与核心优缺点 |
|---|---|---|---|---|
| **OPT** | 未来最久不访问 | 不可在线实现 | **是（绝无异常）** | **逐串最优**；只作理论基准 |
| **LRU** | 过去最久未使用 | 计数器/双向链表栈/移位寄存器；精确实现访存开销高 | **是（绝无异常）** | 近似 OPT，平均很好；反常序列/循环扫描会失灵 |
| **简单 CLOCK（NRU）** | 1 位访问位 $A$ | 1 位 $A$ ；**访存零软件开销** | **否（可能异常）** | 性能接近 LRU，真实 OS 骨架；未区分脏页 |
| **改进 CLOCK** | 访问位 $A$ + 修改位 $M$ | 2 位 $(A, M)$ ；**访存零软件开销** | **否（可能异常）** | 显著减少脏页写盘 I/O；最多扫描 $4$ 轮 |
| **FIFO** | 最早装入内存时间 | **零硬件支持**，仅软件队列 | **否（有异常）** | 最简单，但命中不更新导致热页易被踢，性能最差 |
| **LFU** | 过去累计访问频次 | 移位寄存器/计数器 | 视实现而定 | 易受早期高频冷数据长期占位影响 |


---

### 5.7 页框分配、抖动防治、虚存性能调优与内存映射文件 ★

#### 5.7.1 最少页框数、分配置换策略组合与页面缓冲算法（PBA）

1. **最少页框数（可行性下限，`25#27`）**：
   因为缺页故障处理后必须**重新执行当前指令**，所以系统为一个进程分配的页框数绝不能低于“**执行任意单条指令期间最多同时需要驻留的页面数**”——否则进程会卡在同一条指令上每次重执都缺页、陷入死循环。该下限**仅由指令系统支持的寻址方式（指令架构）决定**，与代码段长、虚拟地址空间大小、物理内存大小毫无关系！

   | 指令类型与寻址方式 | 同时驻留页面构成 | 最少页框数 |
   |---|---|---|
   | 单地址指令 + 直接寻址 | 指令 `1` 页 + 操作数 `1` 页 | **`2`** |
   | 单地址指令 + 间接寻址 | 指令 `1` 页 + 间址单元 `1` 页 + 操作数 `1` 页 | **`3`** |
   | 双地址指令 + 直接寻址 | 指令 `1` 页 + 源操作数 `1` 页 + 目的操作数 `1` 页 | **`3`** |
   | 指令、源操作数、目的操作数各自允许**跨页** | 指令 `2` 页 + 源 `2` 页 + 目的 `2` 页 | **`6`** |

   > **注意**：对比请求分段管理——由于段是信息的逻辑单位，一条指令绝不会被切分到两个段中，因此分段系统不存在“跨块翻倍”这一档。

2. **页框分配策略与置换策略的三种合法组合（`15#30`）**：

   | 分配 \ 置换 | 局部置换（仅在自身页框内淘汰） | 全局置换（可从全系统空闲/他进程页框获取） |
   |---|---|---|
   | **固定分配**（运行期页框总数恒定） | **固定分配 + 局部置换**：实现简单，但难以提前估算合适页框数 | **✗ 矛盾不可组合！**（全局置换必然会改变各进程所占页框数，直接违背“固定”） |
   | **可变分配**（运行期动态增减页框） | **可变分配 + 局部置换**：缺页先换自己；若缺页率过高再追加页框，过低则适当回收（效果最好，对应 PFF 策略） | **可变分配 + 全局置换**：实现最容易，缺页从全局空闲页框链补给；用尽后全局选页换出（缺点是某进程缺页会波及他人） |

3. **物理块（页框）静态分配算法与位示图记账**：
   - **平均分配**：每进程分得 $\lfloor m / n \rfloor$ 个页框（按进程个数分，对大小悬殊的进程实质不公平）。
   - **按比例分配**：设进程 $i$ 总页面数为 $S_i$ ，总页数为 $S = \sum S_i$ ，则 $b_i = \lfloor \frac{S_i}{S} \times m \rfloor$ 。**硬性约束**：若某进程分配值低于“最少页框数”，必须先将其补足至硬下限，再把剩余页框对其他进程重新按比例分配！
   - **考虑优先权的分配**：如将页框按一定比例按大小分，其余按进程重要程度分给实时或高优进程。
   - **空闲页框记账（位示图 `23#25`）**：由于物理页框等大，**回收无需合并**，系统仅需用<strong>位示图（Bitmap）</strong>按 $1\text{ bit}/\text{页框}$ 记录是否占用即可。
     $$
     \text{页框总数} = \frac{\text{物理内存大小}}{\text{页面大小}}, \qquad \text{位示图字节数} = \frac{\text{页框总数}}{8}
     $$
     **算例（`23#25`）**：$16\text{ GB}$ 物理内存、$4\text{ KB}$ 页面 ⇒ 页框数 $= 2^{34} / 2^{12} = 2^{22}$ 个 ⇒ 位图占 $2^{22}\text{ bit} = 2^{19}\text{ B} = 512\text{ KB}$（切勿忘记除以 $8$ 换算为字节）。

4. **页面缓冲算法（PBA）与可回收页框分类**：
   - **PBA 不是置换算法也不是分配策略**，而是架在换出路径上的两级缓冲链表（让低开销置换如 FIFO 也能拥有良好性能）：
     - **空闲页面链表**：未修改（干净）页被换出时不清空数据、不写盘，直接把页框挂到链表尾；需要新页框时从链表头取用（FIFO）。若在被重分配前该页再次被访问，直接从链表中摘回即可，**免除一次磁盘读**！
     - **修改页面链表**：脏页（$M=1$ ）被换出时不立即启动写盘，先挂入该链表，攒够一批（如 $64$ 页）再**一次性批量写回磁盘**，显著摊薄寻道与启动开销。
   - **页框回收范围与时机**：**内核代码/内核数据/内核栈页框不可回收**（若回收，处理内核缺页的代码本身可能不在内存而陷入死锁）。系统必须在空闲页框跌破低水位线时**主动提前批量回收**（如 Linux `kswapd`），绝不能等空闲页框降为 `0` 才动手——因为写回脏页自身还需要临时缓冲页框，归零时系统会彻底卡死。

<figure class="cpd-figure not-content" id="os-c5-fig-19">
  <svg viewBox="0 0 720 296" role="img" aria-label="固定与可变分配及局部与全局置换策略组合矩阵与PBA页面缓冲算法图">
    <defs>
      <marker id="os-c5-arr-19" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="356" height="268" rx="6" class="fig-box-subtle"/>
    <rect x="384" y="14" width="320" height="268" rx="6" class="fig-box-subtle"/>
    <line x1="478" y1="88" x2="508" y2="74" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-19)"/>
    <line x1="478" y1="138" x2="508" y2="152" class="fig-line" stroke="var(--sl-color-orange)" marker-end="url(#os-c5-arr-19)"/>
    <line x1="598" y1="124" x2="598" y2="100" class="fig-line-dashed" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-19)"/>
    <rect x="28" y="42" width="160" height="28" rx="3" class="fig-box"/>
    <rect x="194" y="42" width="166" height="28" rx="3" class="fig-box"/>
    <rect x="28" y="76" width="160" height="90" rx="4" class="fig-box-blue"/>
    <rect x="194" y="76" width="166" height="90" rx="4" class="fig-box-red"/>
    <rect x="28" y="174" width="160" height="96" rx="4" class="fig-box-green"/>
    <rect x="194" y="174" width="166" height="96" rx="4" class="fig-box-orange"/>
    <rect x="396" y="54" width="80" height="104" rx="4" class="fig-box-purple"/>
    <rect x="510" y="46" width="180" height="52" rx="4" class="fig-box-green"/>
    <rect x="510" y="124" width="180" height="54" rx="4" class="fig-box-orange"/>
    <rect x="396" y="190" width="294" height="80" rx="4" class="fig-box-accent"/>
    <text x="194" y="32" text-anchor="middle" font-size="11" class="fig-title">页框分配 × 置换范围 3 种合法组合（15#30）</text>
    <text x="108" y="60" text-anchor="middle" font-size="10" class="fig-title">局部置换（仅限己框）</text>
    <text x="277" y="60" text-anchor="middle" font-size="10" class="fig-title">全局置换（全系统框）</text>
    <text x="108" y="96" text-anchor="middle" font-size="10" class="fig-blue">① 固定 + 局部</text>
    <text x="108" y="116" text-anchor="middle" font-size="9" class="fig-label">分配后页框数恒定</text>
    <text x="108" y="134" text-anchor="middle" font-size="9" class="fig-label">缺页仅换本进程页</text>
    <text x="108" y="152" text-anchor="middle" font-size="9" class="fig-muted">缺点：初值难估准</text>
    <text x="277" y="98" text-anchor="middle" font-size="10.5" class="fig-red">✗ 固定 + 全局</text>
    <text x="277" y="120" text-anchor="middle" font-size="9.5" class="fig-red">自相矛盾 · 不存在！</text>
    <text x="277" y="140" text-anchor="middle" font-size="9" class="fig-label">全局置换抢他进程框</text>
    <text x="277" y="156" text-anchor="middle" font-size="9" class="fig-label">与“固定数量”直接冲突</text>
    <text x="108" y="194" text-anchor="middle" font-size="10" class="fig-green">② 可变 + 局部 ★最优</text>
    <text x="108" y="214" text-anchor="middle" font-size="9" class="fig-label">仅换自身页；缺页太高</text>
    <text x="108" y="232" text-anchor="middle" font-size="9" class="fig-label">再由 OS 追加物理页框</text>
    <text x="108" y="250" text-anchor="middle" font-size="9" class="fig-green">对应缺页频率 PFF 策略</text>
    <text x="277" y="194" text-anchor="middle" font-size="10" class="fig-orange">③ 可变 + 全局 · 最易实现</text>
    <text x="277" y="214" text-anchor="middle" font-size="9" class="fig-label">缺页优先取空闲框链</text>
    <text x="277" y="232" text-anchor="middle" font-size="9" class="fig-label">用尽后从全局选页淘汰</text>
    <text x="277" y="250" text-anchor="middle" font-size="9" class="fig-muted">缺点：缺页波及他进程</text>
    <text x="544" y="32" text-anchor="middle" font-size="11" class="fig-title">页面缓冲算法（PBA）双缓冲链表</text>
    <text x="436" y="88" text-anchor="middle" font-size="9.5" class="fig-purple">被置换</text>
    <text x="436" y="106" text-anchor="middle" font-size="9.5" class="fig-purple">换出页</text>
    <text x="436" y="128" text-anchor="middle" font-size="9" class="fig-muted">M=0 干净</text>
    <text x="436" y="144" text-anchor="middle" font-size="9" class="fig-muted">M=1 脏页</text>
    <text x="600" y="67" text-anchor="middle" font-size="10" class="fig-green">空闲页面链表（数据保留！）</text>
    <text x="600" y="85" text-anchor="middle" font-size="9" class="fig-label">未清空，再次访问可直接摘回</text>
    <text x="606" y="114" font-size="8.2" class="fig-blue">批量写回并入</text>
    <text x="600" y="145" text-anchor="middle" font-size="10" class="fig-orange">修改页面链表（攒批写盘）</text>
    <text x="600" y="163" text-anchor="middle" font-size="9" class="fig-label">攒够如 64 页批量写回后并入空闲链</text>
    <text x="543" y="211" text-anchor="middle" font-size="10" class="fig-accent">22#30 考点解析：</text>
    <text x="543" y="231" text-anchor="middle" font-size="9.5" class="fig-label">页缓冲队列只改善“缺页后的换入/写回代价”，</text>
    <text x="543" y="249" text-anchor="middle" font-size="9.5" class="fig-red">不会降低“缺页率”本身！（26#29：可降平均访存时间）</text>
  </svg>
  <figcaption>图 5-19　分配与置换策略组合矩阵（固定+全局矛盾）及页面缓冲算法（PBA）双链表机制</figcaption>
</figure>

---

#### 5.7.2 页面调入策略与内存映射文件（`mmap`）★

**1. 调入时机与从何处调入**

- **预调页策略**：利用空间局部性预先把预计不久要访问的多个相邻页一并调入；目前成功率仅约 $50\%$ ，因此主要用在**进程首次调入**启动时。
- **请求调页策略**：运行时仅当缺页中断发生才精确调入所需的 $1$ 个页；调入页面 $100\%$ 被用到，但每次都需承担磁盘 I/O 开销（运行期主力）。
- **从何处调入页面的三种情形**（外存分为**连续分配的高速对换区**与**离散分配的慢速文件区**）：
  1. **系统拥有足够对换区**：进程运行前把所有相关文件拷贝到对换区，以后全部从对换区高速换入换出。
  2. **系统缺少足够对换区**：不会被修改的数据/只读代码直接从**文件区**调入，换出时无需写回；可能被修改的部分（数据/堆/栈）换出时写到对换区，以后从对换区调入。
  3. **UNIX 方式**：未运行过的页面全部从**文件区**调入；运行过且被换出的页面写入对换区，之后从对换区调入；支持多进程共享，若目标页已被其他进程调入内存则直接复用，免去重复调页。

**2. 内存映射文件（Memory-Mapped Files，`25#30`、`26#30` 新大纲必考热点）**

**内存映射文件**通过系统调用 `mmap(addr, length, prot, flags, fd, offset)` 将磁盘上的文件内容**直接登记为进程虚拟地址空间某一段的后备存储**，之后进程用指针读写内存就等价于读写文件，不再反复执行 `read()` / `write()` 系统调用。

- **`mmap` 与常规 `read()/write()` 的核心性能差异（共用页高速缓存）**：
  - **常规 `read()`**：`磁盘` $\xrightarrow{\text{DMA}}$ `内核页高速缓存` $\xrightarrow{\text{CPU 拷贝 + 内核/用户态切换}}$ `用户缓冲区`。读取 $4\text{ MB}$ 文件（$4\text{ KB}$ 页）需 $1024$ 次系统调用，占用 $4\text{ MB}$ 页缓存 + $4\text{ MB}$ 用户缓冲区 = $8\text{ MB}$ 物理内存（$n$ 个进程共占 $4(n+1)\text{ MB}$ ）。
  - **`mmap()`**：`磁盘` $\xrightarrow{\text{按需缺页 DMA}}$ `内核页高速缓存` $\leftarrow$ **直接将这批内核物理页框号填入用户进程页表**！从而**彻底消除“页缓存 → 用户缓冲区”的 CPU 内存拷贝与用户缓冲区占用**。
- **五个 408 极易误选的 `mmap` 细节边界（`25#30`、`26#30`）**：
  1. **映射到哪里？** 映射到**各进程的虚拟地址空间**（而非物理地址空间），且不等于文件系统内部“逻辑页到磁盘块”的映射！
  2. **`mmap()` 返回时一个字节都没读**：只划分虚拟地址区间并将对应 PTE 置为 `P=0`（无效/不在内存），真正读盘发生在首次指针访问触发**缺页中断**时（延迟加载）。因此 **`mmap` 耗时与文件大小无关**，`mmap` 是将高频率系统调用替换为高单价缺页中断。
  3. **省掉了哪一次拷贝？** 省掉的是**页高速缓存 → 用户缓冲区的 CPU 拷贝**，**“磁盘 → 页高速缓存”的 DMA 传输绝对省不掉**！
  4. **多进程通信（IPC）地址对比（`26#30`）**：多个进程以**共享映射**（`MAP_SHARED`）映射同一个文件时，它们页表项中指向的是**同一批物理页框**（物理地址完全相同），故一方写入另一方立即可见；但**各自进程的虚拟地址由各自地址空间独立分配，通常完全不同**（仅页框号与共享物理地址相同，各进程保护位也可不同）！
  5. **映射语义与写回时机**：
     - **`MAP_SHARED`（共享映射）**：修改对其他映射进程可见，且写回原文件；写回时机有四种——页被置换出时（不确定）、OS 周期性后台回写（不确定）、解除映射 `munmap` / 进程退出时、以及**唯一能确保立即落盘的显式系统调用 `msync()`**。
     - **`MAP_PRIVATE`（私有映射，写时复制）**：进程写入时内核复制私有副本，修改对其他进程不可见且**永远不写回原文件**（私有页后备存储变为对换区）。
     - **`MAP_ANONYMOUS`（匿名映射）**：不关联文件（如 `malloc` 申请大块内存），初始清零，后备存储为对换区。
     - **页对齐约束**：`offset` 必须按页对齐；若映射长度非整页，尾页余量读写不越界但超出文件真实长度的部分**不会写回增加文件大小**。

<figure class="cpd-figure not-content" id="os-c5-fig-20">
  <svg viewBox="0 0 720 298" role="img" aria-label="常规read两次拷贝与mmap内存映射文件共享页高速缓存及多进程通信对比图">
    <defs>
      <marker id="os-c5-arr-20" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="688" height="100" rx="6" class="fig-box-subtle"/>
    <rect x="16" y="124" width="688" height="160" rx="6" class="fig-box-subtle"/>
    <line x1="158" y1="68" x2="218" y2="68" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-20)"/>
    <line x1="400" y1="68" x2="468" y2="68" class="fig-line" stroke="var(--sl-color-red)" marker-end="url(#os-c5-arr-20)"/>
    <line x1="158" y1="184" x2="218" y2="184" class="fig-line" stroke="var(--sl-color-blue)" marker-end="url(#os-c5-arr-20)"/>
    <polyline points="468,162 426,162 426,176 402,176" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-20)"/>
    <polyline points="468,216 426,216 426,192 402,192" class="fig-line" stroke="var(--sl-color-green)" marker-end="url(#os-c5-arr-20)"/>
    <rect x="28" y="46" width="128" height="44" rx="4" class="fig-box-orange"/>
    <rect x="220" y="44" width="178" height="48" rx="4" class="fig-box-blue"/>
    <rect x="470" y="44" width="220" height="48" rx="4" class="fig-box-red"/>
    <rect x="28" y="156" width="128" height="56" rx="4" class="fig-box-orange"/>
    <rect x="220" y="154" width="180" height="60" rx="4" class="fig-box-green"/>
    <rect x="470" y="144" width="220" height="36" rx="4" class="fig-box-blue"/>
    <rect x="470" y="196" width="220" height="36" rx="4" class="fig-box-blue"/>
    <rect x="28" y="242" width="662" height="32" rx="4" class="fig-box-accent"/>
    <text x="360" y="32" text-anchor="middle" font-size="11" class="fig-title">（a）常规 read() / write() 路径：两次数据拷贝 + 双倍物理内存（内核缓存 + 用户缓冲）</text>
    <text x="92" y="66" text-anchor="middle" font-size="10" class="fig-orange">磁盘文件</text>
    <text x="92" y="81" text-anchor="middle" font-size="9" class="fig-muted">inode 索引块</text>
    <text x="188" y="61" text-anchor="middle" font-size="9" class="fig-blue">① DMA</text>
    <text x="309" y="64" text-anchor="middle" font-size="10" class="fig-blue">内核页高速缓存</text>
    <text x="309" y="81" text-anchor="middle" font-size="9" class="fig-label">Page Cache (4 MB)</text>
    <text x="434" y="61" text-anchor="middle" font-size="9" class="fig-red">② CPU拷贝</text>
    <text x="580" y="64" text-anchor="middle" font-size="10" class="fig-red">各进程私有用户缓冲区</text>
    <text x="580" y="81" text-anchor="middle" font-size="9" class="fig-label">每次 read 陷入内核，n 进程占 4n MB</text>
    <text x="360" y="141" text-anchor="middle" font-size="11" class="fig-title">（b）内存映射文件 mmap()：映射到虚拟地址空间 + 共用页高速缓存零 CPU 拷贝（25#30、26#30）</text>
    <text x="92" y="180" text-anchor="middle" font-size="10" class="fig-orange">磁盘文件（后备）</text>
    <text x="92" y="197" text-anchor="middle" font-size="9" class="fig-muted">mmap() 返回时0字节读</text>
    <text x="188" y="177" text-anchor="middle" font-size="9" class="fig-blue">缺页DMA</text>
    <text x="310" y="174" text-anchor="middle" font-size="10" class="fig-green">共享物理页框 (Page Cache)</text>
    <text x="310" y="191" text-anchor="middle" font-size="9" class="fig-label">全系统唯一一份 (共 4 MB)</text>
    <text x="310" y="206" text-anchor="middle" font-size="9" class="fig-green">零 CPU 拷贝！写盘由 msync/OS</text>
    <text x="580" y="160" text-anchor="middle" font-size="9.5" class="fig-blue">进程 P1 虚拟地址空间 W1</text>
    <text x="580" y="174" text-anchor="middle" font-size="9" class="fig-label">如 0x10000000 → 同一物理页框</text>
    <text x="580" y="212" text-anchor="middle" font-size="9.5" class="fig-blue">进程 P2 虚拟地址空间 W2</text>
    <text x="580" y="226" text-anchor="middle" font-size="9" class="fig-label">如 0x7F000000 → 同一物理页框</text>
    <text x="359" y="262" text-anchor="middle" font-size="9.5" class="fig-accent">结论（26#30）：共享映射实现 IPC，P1 与 P2 映射的物理地址相同，但虚拟地址通常不同；私有映射写时复制永不写回文件</text>
  </svg>
  <figcaption>图 5-20　常规 read() 两次拷贝 vs mmap() 共用页高速缓存零 CPU 拷贝与多进程虚拟-物理地址映射对比</figcaption>
</figure>

---

#### 5.7.3 工作集、抖动（Thrashing）成因防治与性能调优总账 ★

**1. 驻留集与工作集（`16#29`、`26#29`）**

- **驻留集（供给侧）**：当前实际分配并驻留在物理内存中的页面集合（OS 决定）。
- **工作集 $W(t, \Delta)$（需求侧）**：进程在当前时刻 $t$ **之前**的最近 $\Delta$ 次页面访问（时间窗口 $(t - \Delta, t)$ ）中**实际访问过的所有不重复页面组成的集合**（由程序访问模式决定，是 $\Delta$ 的单调非降函数）。
  - **考场计算规则（`16#29`）**：从给定时刻 $t$ **往前数** $\Delta$ 次访问并**去重**！例如序列截至 $t$ 最近 $6$ 次为 `6, 0, 3, 2, 3, 2`（$\Delta = 6$ ），去重得工作集 $W = \{6, 0, 3, 2\}$ 。
  - **窗口尺寸 $\Delta$ 选取原则**：看 $|W|$ 随 $\Delta$ 增大的**平台期**——过小则漏掉活跃页引发频繁缺页，过大则跨过局部性转移点把已淘汰旧阶段的页算进来，浪费页框。**分配原则：$\text{驻留集} \supseteq W(t, \Delta)$**。

**2. 抖动（Thrashing / 颠簸）的成因与正反馈机制（`11#29`）**

- **定义与根本原因**：刚换出的页面马上又要换入，系统几乎全部时间耗费在磁盘换入/换出 I/O 上而 CPU 利用率急剧跌落至趋近于 `0`。根本原因在于并发运行进程过多、每个进程分得的物理页框太少，导致总需求超过物理供给：
  $$
  \sum_i |W_i| > \text{可用物理页框总数}
  $$
- **为什么会自我强化（倒 U 曲线陷阱）**：当多道程序度越过最优峰值 $N_{\max}$ 进入抖动区间时，各进程阻塞在换页队列上 ⇒ **CPU 利用率急剧下降** ⇒ 若系统仅靠“CPU 利用率低”误判为多道程度不足，继续调入新进程 ⇒ 每进程页框更少、缺页更剧烈 ⇒ 形成正反馈雪崩！因此，**仅看 CPU 利用率低无法区分“没进程可跑（该加）”与“全堵在换页（该减）”**。

**3. 抖动预防四大措施与两大定量准则**

1. **采取局部置换策略**：禁止抖动进程抢夺其他进程的页框，把危害局部化（但抖动进程仍会拉长磁盘 I/O 等待队列，治标不治本）。
2. **把工作集算法融入处理机调度**：只有当所有活跃进程都吃饱且仍有足够空闲页框覆盖新进程工作集时，才接纳新进程。
3. **利用 $L = S$ 准则（Denning, 1980）**：比较**平均缺页到达间隔 $L$**（若题给每秒缺页 $k$ 次频率，务必**取倒数** $L = 1 / k$ ）与**平均缺页服务时间 $S$**：
   - $L \gg S$ ：磁盘空闲，可提高多道程度；
   - $L \approx S$ ：磁盘与处理机同时满负荷，是理想稳定点；
   - $L < S$ ：缺页请求到达快于磁盘服务速度，I/O 队列发散滑向抖动，必须降低多道程度！
4. **选择暂停（挂起）部分进程（`11#29` 唯一直接有效措施）**：**增加磁盘对换区容量对解决抖动无效**（瓶颈在物理内存页框不够，不在外存），提高优先级只会加重争抢；必须**挂起/撤销部分进程**释放物理页框（优先挑体积大释放块多、或剩余执行时间多/优先级低的进程）。此外，**缺页频率（PFF）策略**通过监控单进程缺页率是否越过由 $EAT$ 目标反解出的上下限 $f = \frac{EAT - t_{\text{mem}}}{t_{\text{fault}} - t_{\text{mem}}}$ ，动态增减该进程页框或将其挂起。

<figure class="cpd-figure not-content" id="os-c5-fig-21">
  <svg viewBox="0 0 720 292" role="img" aria-label="多道程序度与CPU利用率倒U曲线抖动正反馈及工作集窗口平台期图">
    <defs>
      <marker id="os-c5-arr-21" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect x="16" y="14" width="336" height="264" rx="6" class="fig-box-subtle"/>
    <rect x="364" y="14" width="340" height="264" rx="6" class="fig-box-subtle"/>
    <line x1="48" y1="168" x2="332" y2="168" class="fig-line" marker-end="url(#os-c5-arr-21)"/>
    <line x1="48" y1="168" x2="48" y2="44" class="fig-line" marker-end="url(#os-c5-arr-21)"/>
    <line x1="202" y1="68" x2="202" y2="168" class="fig-line-dashed"/>
    <line x1="234" y1="84" x2="234" y2="168" class="fig-line-dashed" stroke="var(--sl-color-red)"/>
    <path d="M 48 166 Q 118 76 202 68 Q 222 68 234 84 Q 252 130 296 160 L 322 164" class="fig-line" stroke="var(--sl-color-blue)"/>
    <circle cx="202" cy="68" r="3.5" class="fig-green-fill"/>
    <circle cx="234" cy="84" r="3.5" class="fig-dot"/>
    <line x1="538" y1="84" x2="538" y2="154" class="fig-line-dashed" stroke="var(--sl-color-red)"/>
    <rect x="24" y="190" width="320" height="76" rx="4" class="fig-box-red"/>
    <rect x="378" y="46" width="312" height="36" rx="4" class="fig-box"/>
    <rect x="378" y="88" width="154" height="38" rx="4" class="fig-box-blue"/>
    <rect x="542" y="88" width="148" height="38" rx="4" class="fig-box-green"/>
    <rect x="378" y="134" width="312" height="44" rx="4" class="fig-box-accent"/>
    <rect x="378" y="186" width="312" height="80" rx="4" class="fig-box"/>
    <text x="184" y="32" text-anchor="middle" font-size="11" class="fig-title">多道程序度 vs CPU 利用率与抖动区间</text>
    <text x="43" y="54" text-anchor="end" font-size="9" class="fig-muted">CPU%</text>
    <text x="202" y="57" text-anchor="middle" font-size="9.5" class="fig-green">最优度 Nmax</text>
    <text x="242" y="76" font-size="9.5" class="fig-red">抖动起点 N2</text>
    <text x="306" y="112" text-anchor="middle" font-size="9.5" class="fig-red">抖动区</text>
    <text x="306" y="128" text-anchor="middle" font-size="9" class="fig-muted">狂换页 I/O</text>
    <text x="328" y="181" text-anchor="end" font-size="9" class="fig-muted">多道程序度 N</text>
    <text x="184" y="209" text-anchor="middle" font-size="10" class="fig-red">抖动正反馈（11#29 必考防治）：</text>
    <text x="184" y="226" text-anchor="middle" font-size="8.5" class="fig-label">∑|WSi| &gt; 总页框 → 缺页暴增 → CPU 闲 → 误加新进程 → 更缺页!</text>
    <text x="184" y="244" text-anchor="middle" font-size="8.6" class="fig-label">对策：挂起/撤销部分进程 ✓；扩大磁盘交换区 ✗（错，非外存瓶颈）</text>
    <text x="184" y="260" text-anchor="middle" font-size="9" class="fig-accent">L = S 准则：L(到达间隔=1/频) &lt; S(缺页服务时间) 即抖动</text>
    <text x="534" y="32" text-anchor="middle" font-size="11" class="fig-title">工作集窗口 Δ 选取与 16#29 考法</text>
    <text x="534" y="68" text-anchor="middle" font-size="9.5" class="fig-label">访问串：1, 2, 1, 3, 2, 1  |  4, 5, 4, 6, 5, 4  (← t 时刻)</text>
    <text x="455" y="104" text-anchor="middle" font-size="9.5" class="fig-blue">局部阶段 I：{1, 2, 3}</text>
    <text x="455" y="119" text-anchor="middle" font-size="8.5" class="fig-muted">转移点（第6→7步）</text>
    <text x="616" y="104" text-anchor="middle" font-size="9.5" class="fig-green">局部阶段 II：{4, 5, 6}</text>
    <text x="616" y="119" text-anchor="middle" font-size="8.5" class="fig-muted">往前数 Δ 次再去重</text>
    <text x="534" y="152" text-anchor="middle" font-size="9.5" class="fig-accent">平台期最佳区 Δ ∈ [3, 6] → 均得 |W| = 3（{4,5,6}）</text>
    <text x="534" y="169" text-anchor="middle" font-size="9" class="fig-label">Δ=2 漏掉页6(过小易抖)；Δ=9 跨过转移点变6(过大浪费)</text>
    <text x="534" y="206" text-anchor="middle" font-size="10" class="fig-title">影响缺页率 4 大因素与程序编写考点（20#46、22#30）</text>
    <text x="534" y="225" text-anchor="middle" font-size="9" class="fig-label">① 页面大小(大→降缺页但增内碎片)  ② 物理块数(边际递减)</text>
    <text x="534" y="242" text-anchor="middle" font-size="9" class="fig-label">③ 置换算法(缺页率 FIFO&gt;CLOCK&gt;LRU&gt;OPT) ④ 程序局部性</text>
    <text x="534" y="259" text-anchor="middle" font-size="9" class="fig-blue">C二维数组行优先存：按行访问 1024 次缺页 vs 按列 1024² 次！</text>
  </svg>
  <figcaption>图 5-21　多道程序度与 CPU 利用率倒 U 曲线、抖动正反馈环及工作集窗口平台期规律</figcaption>
</figure>

**4. 影响缺页率的四大因素与系统性能调优总账（`20#46`、`22#30`、`26#29`）**

一切虚存性能调优举措，最终都落在 $EAT = (1 - f) t_{\text{mem}} + f t_{\text{fault}}$ 的三个参数上：

| 改进措施 | 作用环节与直接优化的参数 | 关键辨析与 408 陷阱 |
|---|---|---|
| **增大 TLB 容量 / 页表常驻内存** | 压低等效 $t_{\text{mem}}$（`14#28`、`26#29`） | TLB 命中免查慢表；页表常驻免掉查表自身引发的磁盘 I/O |
| **使用更优置换算法**（LRU/CLOCK 替代 FIFO） | 降低缺页率 $f$ | 缺页率排序 **FIFO ＞ CLOCK ＞ LRU ＞ OPT**（与性能序相反） |
| **按工作集合理分配物理块 / 预调页** | 降低缺页率 $f$（`26#29`） | 物理块数增加降缺页，但超过工作集后**边际收益急剧递减** |
| **改进程序编制方式（如按行优先遍历数组）** | 降低缺页率 $f$ | 唯一由应用程序自身控制的因素（`20#46` C 语言按行存储） |
| **页面缓冲算法（PBA） / 改进型 CLOCK** | 降低缺页代价 $t_{\text{fault}}$ | **改变缺页后换入/写回耗时**，**不改变缺页率 $f$**（`22#30`、`26#29`） |
| **多级页表** | **节省页表连续内存空间**（`14#32`、`26#29`） | **不能降低**平均访存时间，未命中 TLB 时反而**变慢**！ |
| **增大磁盘对换区容量** | 扩大外存可换出空间上限 | **既不能加快地址变换（`14#28`），也不能消除抖动（`11#29`）** |

---

### 本章 408 高频易错与真题速查汇总

| 核心考点 | 极易踩坑误区（错项特征） | 精准判定依据（真题考号） |
|---|---|---|
| **逻辑地址形成与程序态** | 误选“编译阶段形成逻辑地址”或“链接程序在内核态” | 完整逻辑地址在**链接阶段**形成（`11#30`）；仅**装入程序**运行在内核态（`26#23`） |
| **内存映像对象定位** | 误把指针自身和指向内容混放；误认为 PCB 在用户区 | `ptr` 本身在**数据段**、`malloc` 块在**堆**、局部变量在**栈**、PCB 在**内核区**（`25#46`） |
| **连续分配与碎片判别** | 用总空闲量判断能否装入；漏判伙伴算法重新产生内碎片 | 碎片看**最大连续空闲块**（`19#32`）；**仅伙伴算法回收只合并等大块**（`24#27`） |
| **多级页表核心作用** | 误以为“加快地址变换”或“缩小页表项位数” | 优点是**减少页表占用的连续内存空间**，未命中 TLB 时访存反而变慢（`14#32`、`26#29`） |
| **分页 vs 分段变换** | 段式跳过越界直接加；认为段页式既无内碎片也无外碎片 | 分段先比 $S < TL$ 再比 $W < SL$ （`16#28`）；共享段**段号可不同**（`19#28`）；段页式**每段都有内碎片** |
| **虚存概念与三方分工** | 误认为地址转换由 OS 做、页表项由编译器填、容量等于外存 | MMU 做转换，OS 填页表并处理一切异常（`26#24`）；容量 $\le \min(\text{内+外}, 2^{\text{位数}})$（`12#25`、`23#28`） |
| **缺页中断与置换** | 误认为缺页必淘汰页面、包含越界错；分不清置换与缺页数 | 淘汰仅在无空框时发生（`22#29`）；越界不在缺页内（`13#30`）；置换次数 $=$ 缺页 $- m$ （`19#29`） |
| **Belady 与 CLOCK** | 误以为 CLOCK 不会 Belady；记反 `(0,1)` 与 `(1,0)` 优先级 | **仅 OPT、LRU 是栈算法无 Belady**（`14#30`）；改进 CLOCK **$(0,0)>(0,1)>(1,0)>(1,1)$**（`16#26`） |
| **内存映射文件 `mmap`** | 误以为映射到物理空间、多进程虚拟地址相同、省掉 DMA | 映射到**虚拟地址空间**（`25#30`）；省掉**页缓存→用户态 CPU 拷贝**；共享者**物理地址相同但虚拟地址可不同**（`26#30`） |

## 第6章 文件管理

### 6.1 文件的基本概念与元数据结构 ★

#### 6.1.1 为什么需要“文件”抽象与文件系统层次结构

主存虽然访问速度快，但存在两个无法绕开的物理约束：**容量有限**与**断电易失**。计算机系统必须配置大容量的非易失性外存（机械硬盘 HDD、固态硬盘 SSD、光盘、U 盘等）来持久保存程序与数据。

然而，裸磁盘向上层软件暴露的接口极为原始——仅仅是一个**按编号排列的一维扇区数组**（例如只能请求“读取第 8213 号扇区”）。如果应用程序直接在裸扇区上编程，将会立刻遭遇三大工程痛点，而**文件**（File）这一抽象的每一条核心性质都是被这些痛点倒逼出来的：

| 裸磁盘的原始痛点 | 逼出的文件抽象性质 | 文件系统的具体实现形态 |
| --- | --- | --- |
| 用户无法记住成千上万个扇区号，换机器后扇区号失效 | **按名存取** | 文件必须有名字，由**目录与 inode** 完成“文件名 $\mapsto$ 物理位置”的映射 |
| 一份数据往往占用多个不连续扇区，零散难以管理 | **成组管理** | 文件是一组有意义信息的集合；系统以**磁盘块**（或簇）为单位分配物理空间 |
| 多用户共用同一块磁盘，极易互相覆盖或越权偷窥 | **属性与保护** | 文件除了正文数据外，还携带所有者、权限、时间戳等**元数据** |

> **注意**：“文件是最小逻辑操作单位”与“磁盘块是最小物理分配单位”并不矛盾，只是主语不同。用户能够命名、整体复制或授权的最小对象是**文件**；操作系统向磁盘申请和划拨空间的最小物理单位是**磁盘块（或簇，通常为 $2^k$ 个扇区）**。即便一个文件只有 1 字节，在外存上依然要占满一整个磁盘块，余下空间形成**内部碎片**。

为实现上述抽象，操作系统在内核中构筑了自顶向下的**文件系统（File System）六层结构**：用户接口层负责接收系统调用；文件目录系统将路径与文件名翻译成元数据位置；存取控制模块校验操作权限；逻辑文件系统把用户的记录或字节流请求转换为文件内逻辑块号；物理文件系统将逻辑块号映射为外存物理块号并执行空闲块分配/回收；最底层的设备驱动程序直接驱动磁盘控制器完成扇区 I/O。

<figure class="cpd-figure not-content" id="os-c6-fig-1">
  <svg viewBox="0 0 720 340" role="img" aria-label="文件系统的六层抽象架构与裸磁盘痛点逼出的文件三大性质">
    <defs>
      <marker id="os-c6-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="380" height="308" rx="8"/>
    <rect class="fig-box-subtle" x="412" y="16" width="292" height="308" rx="8"/>
    <line class="fig-line" x1="206" y1="82" x2="206" y2="90" marker-end="url(#os-c6-arr-1)"/>
    <line class="fig-line" x1="206" y1="125" x2="206" y2="133" marker-end="url(#os-c6-arr-1)"/>
    <line class="fig-line" x1="206" y1="168" x2="206" y2="176" marker-end="url(#os-c6-arr-1)"/>
    <line class="fig-line" x1="206" y1="211" x2="206" y2="219" marker-end="url(#os-c6-arr-1)"/>
    <line class="fig-line" x1="206" y1="254" x2="206" y2="262" marker-end="url(#os-c6-arr-1)"/>
    <rect class="fig-box-purple" x="30" y="48" width="352" height="34" rx="5"/>
    <rect class="fig-box-blue" x="30" y="91" width="352" height="34" rx="5"/>
    <rect class="fig-box-accent" x="30" y="134" width="352" height="34" rx="5"/>
    <rect class="fig-box-green" x="30" y="177" width="352" height="34" rx="5"/>
    <rect class="fig-box-orange" x="30" y="220" width="352" height="34" rx="5"/>
    <rect class="fig-box" x="30" y="263" width="352" height="44" rx="5"/>
    <rect class="fig-box-blue" x="426" y="50" width="264" height="58" rx="6"/>
    <rect class="fig-box-green" x="426" y="120" width="264" height="58" rx="6"/>
    <rect class="fig-box-orange" x="426" y="190" width="264" height="58" rx="6"/>
    <rect class="fig-box-accent" x="426" y="260" width="264" height="48" rx="6"/>
    <text class="fig-title" x="206" y="36" font-size="12" text-anchor="middle">文件系统的六层抽象架构（自顶向下）</text>
    <text class="fig-purple" x="40" y="69" font-size="10">① 用户接口层：open / read / write / close 系统调用</text>
    <text class="fig-blue" x="40" y="112" font-size="10.2">② 文件目录系统：按名查找（路径名 → inode 号）</text>
    <text class="fig-accent" x="40" y="155" font-size="10.2">③ 存取控制模块：校验用户身份与 rwx 访问权限</text>
    <text class="fig-green" x="40" y="198" font-size="10.2">④ 逻辑文件系统：记录/字节流 → 文件内逻辑块号 + 偏移</text>
    <text class="fig-orange" x="40" y="241" font-size="10.2">⑤ 物理文件系统：逻辑块号 → 物理盘块 + 空闲块管理</text>
    <text class="fig-label" x="42" y="281" font-size="11">⑥ 设备驱动与 I/O 控制层：物理盘块号 → 柱面/磁道/扇区</text>
    <text class="fig-muted" x="42" y="298" font-size="10">磁盘本身只提供按编号排列的一维扇区数组</text>
    <text class="fig-title" x="558" y="36" font-size="12" text-anchor="middle">裸盘三大痛点逼出的文件抽象</text>
    <text class="fig-blue" x="438" y="68" font-size="11">痛点 1：扇区号难记且换盘失效</text>
    <text class="fig-label" x="438" y="85" font-size="10.5">→ 按名存取（目录项：文件名 ↦ inode 号）</text>
    <text class="fig-muted" x="438" y="100" font-size="9.5">用户只见逻辑路径名，不感知物理扇区</text>
    <text class="fig-green" x="438" y="138" font-size="11">痛点 2：数据跨越多个离散扇区</text>
    <text class="fig-label" x="438" y="155" font-size="10.5">→ 成组管理（文件为单位、块为分配粒度）</text>
    <text class="fig-muted" x="438" y="170" font-size="9.5">1 B 文件亦占满 1 块，产生内部碎片</text>
    <text class="fig-orange" x="438" y="208" font-size="11">痛点 3：多用户共用磁盘互相踩踏</text>
    <text class="fig-label" x="438" y="225" font-size="10.5">→ 属性与保护（元数据按归属分两处存放）</text>
    <text class="fig-muted" x="438" y="240" font-size="9.5">跟名字走入目录项，跟本体走入 inode</text>
    <text class="fig-accent" x="558" y="279" font-size="11" text-anchor="middle">★ 两层公共接口：文件内字节偏移量</text>
    <text class="fig-muted" x="558" y="296" font-size="10" text-anchor="middle">逻辑结构与物理结构由此完全解耦、正交组合</text>
  </svg>
  <figcaption>图 6-1　文件系统的六层抽象架构与“裸扇区 → 按名文件”的核心职责分层</figcaption>
</figure>

文件的元数据（属性）并不是一股脑塞在同一个地方的，而是严格按照“**属性归属原则**”划分存放位置：

> **★考点**：判断某项文件属性存放在**目录项**还是 **FCB / inode**，唯一标准是看该属性“**跟着名字走**”还是“**跟着文件本体走**”。
> - **跟着名字走（存目录项）**：**文件名**（在同一目录下唯一；广义文件名包含主名与用于关联打开程序的扩展名）与**标识符 / inode 号**（文件系统内唯一编号）。
> - **跟着本体走（存 FCB / inode）**：**文件类型**（普通/目录/设备/链接）、**外存物理位置指针**、**文件大小**、**保护信息**（所有者 UID/GID 与访问权限，绝不会放进目录项，否则换个名字就能绕过权限！）、**时间戳**、**链接计数**。
> - **两条直接推论**：① **inode 中不保存文件名**（故同一 inode 可通过硬链接挂多个名字）；② **重命名或同分区移动文件只改目录项，inode 原封不动**。

文件可从四个**互相正交**的维度进行分类，同一个文件（如 `/usr/lib/libc.so`）在四个维度上各取一个值：

1. **按用途**：系统文件（内核、驱动程序）、用户文件（源码、文档）、库文件（标准函数库）。
2. **按逻辑结构**：无结构文件（流式文件，无明显内部边界的字节流，如 `.txt`、ELF 可执行文件）与有结构文件（记录式文件，由若干包含数据项的记录构成）。
3. **按存取方式**：顺序存取（如磁带）、随机/直接存取（如磁盘）、索引存取。**注意**：用户逻辑上想用随机存取，最终仍受限于物理结构——采用**隐式链接分配**的文件只能顺序存取。
4. **按组织形式与信息交换单位（UNIX 视角）**：**普通文件**、**目录文件**（即文件夹，内容是一系列目录项）、**特殊文件**（映射 I/O 设备如 `/dev/printer` 及进程间通信管道 `pipe`，分为字符设备文件与块设备文件）。

#### 6.1.2 文件控制块（FCB）与索引节点（inode）★

在操作系统内部，文件存在的唯一标志是**文件控制块（FCB，File Control Block）**，它如同进程控制块 PCB 之于进程、线程控制块 TCB 之于线程，集中存放管理该文件所需的全部元数据，主要分三类：

- **基本信息**：文件名、文件物理位置（起始盘块号/地址项）、文件逻辑结构、文件物理结构等。
- **存取控制信息**：文件主标识符、各类用户对文件的访问权限（读/写/执行等）。**★ 真题结论（09#30）**：文件的**访问控制信息**合理存放在 **FCB（拆分后即 inode）** 中，而非 FAT 表（只管盘块链接）、用户口令表（只管身份鉴别）或系统注册表。
- **使用信息**：文件创建时间、最后修改时间、最后访问时间、当前已打开进程数、是否加锁等。

早期简单文件系统把**一个 FCB 直接当作一个目录项**，全部 FCB 顺序排成**文件目录**。这在目录文件变大时会引发严重的 I/O 性能灾变——在按路径名查找文件的过程中，系统自始至终只用到“**文件名**”这一个字段，然而庞大 FCB 中装满的权限、大小、时间戳、十几个盘块地址全被顺带着搬进内存，白白挤占了每个盘块能容纳的目录项数量！

**索引节点（inode，Index Node）的瘦身思想**：把 FCB 劈成两半——**目录项**仅保留检索必需的 `(文件名, inode 号)`；其余全部文件描述信息剥离出来，集中存放在独立定长的 **inode** 结构中（在磁盘上连续排列成 **inode 区**）。

> **★考点**：**目录项瘦身后的磁盘 I/O 次数经典对比**（以 4 KB 盘块、目录下有 1024 个文件、目录顺序查找且命中位置均匀分布为例）：
> 1. **未拆分前**（设完整 FCB 占 128 B）：每块容纳 $4096 / 128 = 32$ 个 FCB，目录共占 $1024 / 32 = 32$ 个盘块，平均检索目录需读盘 $\frac{32 + 1}{2} = 16.5$ 次。
> 2. **拆分后**（设瘦身目录项仅占 32 B）：每块可装 $4096 / 32 = 128$ 个目录项，目录缩减为 $1024 / 128 = 8$ 个盘块，平均检索目录仅需 $\frac{8 + 1}{2} = 4.5$ 次读盘！
> 3. **别忘了最后多出的 1 次**：找到目标目录项只拿到 inode 号，还须**多读 1 次该 inode 所在的盘块**以获取大小、权限和块指针，故总计 $4.5 + 1 = 5.5$ 次（降至原来的 $1/3$）。同理若按早期 UNIX 目录项 16 B（14 B 文件名 + 2 B 指针）、1 KB 块（容 64 项 vs 16 个完整 FCB）、640 个文件计算，目录从 40 块降为 10 块，平均检索从约 20 次降为 5 次。**目录内文件越多，$+1$ 次开销的占比越微不足道，I/O 加速比越趋近于表项大小的压缩倍数。**

> **注意（25#29 真题坑点）**：新建文件 `F` 时，文件系统初始化 `F` 的 inode 并将 `(文件名, inode 号)` 写入目录项，但**绝不会在目录文件中写入 `F` 的访问权限信息**——因为瘦身后的目录项根本没有字段存放权限，权限只在 inode 里！

<figure class="cpd-figure not-content" id="os-c6-fig-2">
  <svg viewBox="0 0 720 330" role="img" aria-label="传统 FCB 目录项与 UNIX 瘦身目录项加独立 inode 的磁盘 IO 对比及 inode 定位">
    <defs>
      <marker id="os-c6-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="196" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="196" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="224" width="688" height="90" rx="8"/>
    <line class="fig-line-accent" x1="554" y1="85" x2="574" y2="85" marker-end="url(#os-c6-arr-2)"/>
    <rect class="fig-box-red" x="30" y="48" width="308" height="74" rx="6"/>
    <line class="fig-divider" x1="107" y1="48" x2="107" y2="122"/>
    <line class="fig-divider" x1="184" y1="48" x2="184" y2="122"/>
    <line class="fig-divider" x1="261" y1="48" x2="261" y2="122"/>
    <rect class="fig-box" x="30" y="132" width="308" height="66" rx="5"/>
    <rect class="fig-box-green" x="382" y="48" width="172" height="74" rx="6"/>
    <line class="fig-divider" x1="382" y1="85" x2="554" y2="85"/>
    <rect class="fig-box-accent" x="576" y="48" width="114" height="74" rx="6"/>
    <rect class="fig-box" x="382" y="132" width="308" height="66" rx="5"/>
    <rect class="fig-box-blue" x="30" y="248" width="424" height="52" rx="5"/>
    <rect class="fig-box-orange" x="466" y="248" width="224" height="52" rx="5"/>
    <text class="fig-title" x="184" y="36" font-size="11.5" text-anchor="middle">方案 A：传统完整 FCB 作目录项（检索慢）</text>
    <text class="fig-red" x="68" y="70" font-size="10.5" text-anchor="middle">FCB 1</text>
    <text class="fig-muted" x="68" y="88" font-size="9.5" text-anchor="middle">文件名 +</text>
    <text class="fig-muted" x="68" y="102" font-size="9.5" text-anchor="middle">全套元数据</text>
    <text class="fig-red" x="145" y="70" font-size="10.5" text-anchor="middle">FCB 2</text>
    <text class="fig-muted" x="145" y="95" font-size="9.5" text-anchor="middle">128 B/项</text>
    <text class="fig-red" x="222" y="70" font-size="10.5" text-anchor="middle">FCB 3</text>
    <text class="fig-muted" x="222" y="95" font-size="9.5" text-anchor="middle">每块 32 项</text>
    <text class="fig-red" x="299" y="70" font-size="10.5" text-anchor="middle">… FCB 32</text>
    <text class="fig-muted" x="299" y="95" font-size="9.5" text-anchor="middle">占 32 块</text>
    <text class="fig-label" x="42" y="150" font-size="10.5">设目录 1024 文件、4 KB 块、128 B/FCB：</text>
    <text class="fig-red" x="42" y="168" font-size="10.5">• 平均读盘 = (32 + 1) / 2 = 16.5 次</text>
    <text class="fig-muted" x="42" y="186" font-size="10">检索仅比文件名，却把大量无用属性搬入内存</text>
    <text class="fig-title" x="536" y="36" font-size="11.5" text-anchor="middle">方案 B：拆分瘦身（目录项 + 独立 inode）★</text>
    <text class="fig-green" x="468" y="69" font-size="10" text-anchor="middle">(文件名, inode #2)</text>
    <text class="fig-green" x="468" y="106" font-size="9.4" text-anchor="middle">(文件名, ino #42) · 32 B/项</text>
    <text class="fig-accent" x="633" y="68" font-size="11" text-anchor="middle">inode 区 (#42)</text>
    <text class="fig-muted" x="633" y="86" font-size="9.5" text-anchor="middle">权限 / 大小 / 时间</text>
    <text class="fig-muted" x="633" y="102" font-size="9.5" text-anchor="middle">i_links / 块指针</text>
    <text class="fig-label" x="394" y="150" font-size="10.5">瘦身至 32 B/项 → 每块 128 项 → 仅占 8 块：</text>
    <text class="fig-green" x="394" y="168" font-size="10.5">• 平均读目录 (8 + 1) / 2 = 4.5 次</text>
    <text class="fig-accent" x="394" y="186" font-size="10.5">• + 命中后读目标 inode 1 次 = 5.5 次（降至 1/3）</text>
    <text class="fig-title" x="360" y="241" font-size="11.5" text-anchor="middle">★ inode 不存“文件名”亦不存“自身 inode 号”：由定长数组位置隐式定位</text>
    <text class="fig-blue" x="40" y="268" font-size="10">inode 区 = 格式化时固定的定长数组（下标即全分区唯一 inode 号）</text>
    <text class="fig-label" x="40" y="287" font-size="9.2">块号 = 始块 + ⌊ino/每块数⌋；偏移 = (ino mod 每块数) × 项大小</text>
    <text class="fig-orange" x="476" y="268" font-size="10">两类极易混的“计数”边界：</text>
    <text class="fig-label" x="476" y="287" font-size="9.2">磁盘 i_links(硬链数) vs 内存引用(进程)</text>
  </svg>
  <figcaption>图 6-2　传统 FCB 目录 vs 瘦身目录项 + 独立 inode 磁盘读取 I/O 次数对比及 inode 数组定位机制</figcaption>
</figure>

**磁盘 inode 与内存 inode 的关键字段拆解**：

1. **磁盘 inode（持久化形式）**：
   - `i_mode`（文件类型与 9-bit `rwx` 权限）、`i_uid` / `i_gid`（所有者与组 ID）、`i_size`（字节长度）、`i_blocks`（占用块数）。
   - **三个时间戳（极易考混淆点）**：`i_atime`（最后访问时间——**读**内容即更新）、`i_mtime`（最后修改时间——**改文件正文内容**才更新）、`i_ctime`（inode 变更时间——**改元数据即更新**）。因此修改文件内容必同时更新 `mtime` 与 `ctime`，而只修改文件权限（`chmod`）只会更新 `ctime`、`mtime` 不变！
   - `i_links`（硬链接计数）：记录磁盘上有多少个目录项指向该 inode。
   - **块指针数组**（多教材分歧点）：UNIX System V 共 **13 个地址项**（10 个直接 + 1 一次间接 + 1 二次间接 + 1 三次间接）；Linux ext2/ext3 共 **15 个地址项**（12 个直接 + 3 个间接）。**★ 做题必须以题目给出的直接地址项个数为准，切忌套背 10 或 12！**
   - **为什么磁盘 inode 里既不放文件名，也不放“我是几号 inode”**？不放文件名是因为一个文件可挂多个名字（硬链接）；不放自身号是因为格式化时 inode 区已被划成一段连续的定长数组，inode 号直接作为**数组下标**由存放位置隐含确定：

$$
\text{块号} = \text{inode 区起始块} + \left\lfloor \frac{\text{inode 号}}{\lfloor B / S_{\text{inode}} \rfloor} \right\rfloor, \qquad \text{块内偏移} = \left(\text{inode 号} \bmod \left\lfloor \frac{B}{S_{\text{inode}}} \right\rfloor\right) \times S_{\text{inode}}
$$

   由该公式立即推出三大系统推论：① inode 号仅在本分区（本文件系统）内唯一；② inode 总数在**高级格式化时就已固定**，事后无法动态扩张；③ 因此现实中可能出现“**磁盘还有大量空闲数据块，却创建不了任何新文件**”的现象（只要大量小文件把固定配额的 inode 耗尽）。

2. **内存 inode（活动 inode）**：
   文件打开时，系统把磁盘 inode 读入内存“活动 inode 表”，并额外追加 4 项磁盘上不需要的动态管理字段：
   - **inode 编号**：脱离了原磁盘数组位置，在内存中必须显式登记编号；
   - **引用计数（打开进程/文件表项计数）**：关机后没有“正在打开”这回事，只在内存存在；
   - **状态标志（脏位 / 锁位）**：指示内存副本是否被修改（脏位相对于磁盘基准而言）或正被互斥锁定；
   - **逻辑设备号与链表指针**：记录所属分区设备及空闲/哈希链表挂接指针。

> **★考点**：**链接计数 `i_links`（磁盘 inode） $\neq$ 引用计数 `i_count`（内存 inode）**！只有当**磁盘链接计数减为 0**（再无目录项指向它）**且内存引用计数减为 0**（再无进程还打开着它）时，系统才真正回收该 inode 与占用的数据块。若文件在被进程打开期间遭删除，目录项会先消失（他人无法按路径再打开），但原进程通过已持有的 `fd` 照样能正常读写，直至最后一个 `close` 时空间才真正释放。

---

### 6.2 文件的操作、打开文件表与管道 ★

#### 6.2.1 六大基本操作 + `lseek` 与 `truncate` 的底层动作

操作系统向上提供一组标准文件操作原语，复杂功能（如文件复制 $=$ `create` 目标 + 循环 `read` 源/`write` 目标 + 双 `close`）均由它们组合而成。按“碰不碰磁盘”分层，各操作核心步骤及易错暗坑如下：

| 系统调用 | 是否碰磁盘 | 核心执行步骤与关键机制 | 常见易错误解 |
| --- | --- | --- | --- |
| `create`（建立） | 元数据 + 目录 | ① 检查同目录是否重名；② 分配并初始化 FCB/inode（填入类型/权限/时间，**块指针通常置空**）；③ 向父目录添加 `(文件名, inode 号)`；④ **数据块通常延迟到首次 `write` 时再分配** | 误以为建空文件也要分配数据块、或权限写进目录项（**25#29 考点**） |
| `delete`（删除） | 元数据 + 目录 + 空闲表 | ① 查目录项取 inode 号；② **先回收外存数据块**；③ **再删除目录项**；④ 磁盘 `i_links` 减 1，仅当 `i_links == 0` 且内存引用计数 $= 0$ 时释放 inode | 误以为先删目录项再回收空间（两步间掉电会产生无法找回的**孤儿块**）；或误以为会连带删掉父目录（**13#23 考点**） |
| `open`（打开） | 仅目录与元数据 | ① 按路径查目录得 inode 号；② 校验访问权限；③ **将 FCB/inode 读入内存**（首次打开时）；④ 登记两级打开文件表；⑤ 返回整型句柄 `fd` | 误以为 `open` 会读取文件内容、修改权限或返回缓冲区指针（**14#29、24#29 考点**） |
| `close`（关闭） | 归零时回写脏元数据 | ① 清除进程表 `fd` 项；② 打开计数减 1；③ 归零则回收系统表项、**释放内存 inode 空间**（脏则写回磁盘） | 误以为 `close` 会删目录项、释放外存 inode 或减磁盘链接计数（**23#31 考点**） |
| `read`（读） | 查页缓存，未命中读盘 | ① 由 `fd` 找表项与内存 inode；② 用读指针算逻辑块与偏移；③ 查**内核页缓存**（未命中则读盘并触发**提前读/预读**）；④ 拷至用户缓冲区，读指针前移实际读出字节数 | 误以为读到字节数少于请求数即出错（短读常见于近 EOF、管道或信号中断；**返回 0 才表 EOF**） |
| `write`（写） | 写缓冲，常延迟落盘 | ① 由写指针算逻辑块，若无物理块则向空闲管理申领并填块指针（可能连带分配各级索引块）；② 拷至内核缓冲区置脏（**延迟写**）；③ 写指针与长度更新 | 误以为 `write` 返回即落盘（断电会丢，需 `fsync` 强制刷盘；延迟写反而因合并写提高性能，**18#31 考点**） |
| `lseek`（重定位） | **0 次磁盘 I/O** | 直接修改打开文件表中的当前读写偏移量整数，支持随机位置读写或追加 | 误以为 `lseek` 会预读目标盘块或触发分配新块 |
| `truncate`（截断） | 元数据 + 空闲表 | 遍历地址项**回收全部数据块及索引块**，inode 长度置 0 并更新时间，**保留目录项、inode 号、权限及已打开的 `fd`** | 与 `delete` 混淆：需“清空重来但不断现有 `fd` 与权限”时用 `truncate` |

> **★考点（三大常考真题套路秒杀口诀）**：
> - **“首次打开 `open` 干什么？”（14#29、24#29）**：**唯一做按名查找的操作**，只把 **FCB/inode 读到内存**并返回一个整数 **`fd`**（不读正文、不改权限、不给用户暴露内核缓冲区指针）。此后 `read`/`write`/`lseek`/`close` 一律只认 `fd`。
> - **“关闭 `close` 干什么？”（23#31）**：**关闭只动内存、删除才动磁盘**。文件仅被进程 $P$ 打开，当 $P$ 关闭它时，系统释放的是该文件**内存 inode 所占空间**（绝不删目录项、不释放外存 inode、不减磁盘 `i_links`）。
> - **“哪种行为会留下孤儿块？”**：删除时如果先抹去目录项、还没来得及回收盘块就断电，磁盘上没有任何路径能再找到该 inode，它占用的块永久失联，只能靠 `fsck` 全盘扫描抢救；先回收空间再删目录项则始终可追踪。

#### 6.2.2 两级（三层）打开文件表与 `dup`/`fork` 共享模型 ★

若没有 `open` 缓存机制，进程每次调用 `read("/usr/local/bin/foo")` 都必须从根目录逐级读目录块、比对名字再读目标 inode（深度 $n$ 路径每次读写耗费 $2n$ 次磁盘 I/O）。`open` 的实质就是**把一次昂贵的目录检索结果缓存成进程内一个极便宜的整型数组下标 `fd`**。

但是如果只建一张全局打开表，不同进程就会互相干扰读写位置；如果只建每进程一张私表，同一个文件在内存中会出现多份不同步的 inode 副本，且谁也不知道到底有几个进程在同时使用它、何时能够安全淘汰缓存。因此内核通过**分表解耦**解决这一矛盾（按“能否让不同进程看到不同值”划分）：

1. **进程打开文件表（文件描述符表，File Descriptor Table）**：每个进程私有一张。数组下标即为**文件描述符 `fd`**（通常 `0` 为标准输入 `stdin`、`1` 为标准输出 `stdout`、`2` 为标准错误 `stderr`，新 `open` 返回最小可用非负整数）。同一个文件在不同进程中对应的 `fd` 完全可以不同。
2. **系统打开文件表（System-wide Open File Table）**：全系统共享一张。
3. **内存 inode 表（活跃 inode 表）**：全系统唯一，每个正在被打开的文件仅存一份。

> **注意（两本核心教材的表结构口径统一）**：
> - **通行教学口径**（侧重两级划分）：把**读写指针、访问模式**放在**进程打开文件表**中，系统打开文件表仅按文件登记一份 FCB/inode 信息、**打开计数**与文件锁（如 **20#23 真题**结论：“多个进程共享同一文件时，在系统打开文件表中**仅有一个表项**包含该文件的属性”，进程各自表格内容因读写指针不同而**不相同**，且进程关闭时不直接删系统表项，必须等**打开计数减为 0** 才删）。
> - **Linux VFS 与《操作系统教程》实际结构**（三层模型：`fd` 表 $\to$ 系统打开文件表 `struct file` $\to$ 内存 `inode` 表）：**读写偏移量与打开模式存放在系统打开文件表 `file` 对象中**，进程 `fd` 表仅映射 `fd -> file*`。两个进程各自独立 `open()` 同一个文件时，会生成**两个独立的 `file` 表项**（指向同一个内存 `inode`），因此各自维护独立的读写偏移量；而同一进程 `dup(fd)` 或 `fork()` 产生的父子进程会**共享同一个 `file` 表项**，从而**共享同一个读写偏移量**。
> - **不变的核心结论**：无论采用哪本教材的命名方式，**① 读写位置属于“一次打开事件”，不属于“文件本体”（绝不在 inode 里）；② 两个各自独立 `open` 同一文件的进程读写位置互相独立；③ `fork`/`dup` 复制得到的描述符共享同一偏移量。**

<figure class="cpd-figure not-content" id="os-c6-fig-3">
  <svg viewBox="0 0 720 356" role="img" aria-label="进程文件描述符表、系统打开文件表与内存 inode 表三层联动及系统调用流程">
    <defs>
      <marker id="os-c6-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="192" height="248" rx="8"/>
    <rect class="fig-box-subtle" x="234" y="16" width="234" height="248" rx="8"/>
    <rect class="fig-box-subtle" x="494" y="16" width="210" height="248" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="274" width="688" height="66" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 196 112 L 222 112 L 222 90 L 246 90" marker-end="url(#os-c6-arr-3)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 196 130 L 222 130 L 222 104 L 246 104" marker-end="url(#os-c6-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="196" y1="210" x2="246" y2="210" marker-end="url(#os-c6-arr-3)"/>
    <path class="fig-line-accent" d="M 454 96 L 480 96 L 480 96 L 506 96" marker-end="url(#os-c6-arr-3)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 454 198 L 480 198 L 480 124 L 506 124" marker-end="url(#os-c6-arr-3)"/>
    <line class="fig-line-dashed" x1="599" y1="158" x2="599" y2="174" marker-start="url(#os-c6-arr-3)" marker-end="url(#os-c6-arr-3)"/>
    <rect class="fig-box-blue" x="28" y="44" width="168" height="106" rx="6"/>
    <rect class="fig-box-green" x="28" y="162" width="168" height="88" rx="6"/>
    <rect class="fig-box-accent" x="248" y="54" width="206" height="84" rx="6"/>
    <rect class="fig-box-orange" x="248" y="156" width="206" height="84" rx="6"/>
    <rect class="fig-box-purple" x="508" y="54" width="182" height="104" rx="6"/>
    <rect class="fig-box" x="508" y="176" width="182" height="72" rx="6"/>
    <text class="fig-title" x="112" y="34" font-size="11.5" text-anchor="middle">进程描述符表（进程私有）</text>
    <text class="fig-blue" x="40" y="62" font-size="11">进程 A（open + dup）</text>
    <text class="fig-muted" x="40" y="80" font-size="9.8">fd 0/1/2: stdin/out/err</text>
    <text class="fig-label" x="40" y="114" font-size="10.2">fd 3 → 系统表项 #0</text>
    <text class="fig-label" x="40" y="133" font-size="10.2">fd 4 (dup) → 系统表项 #0</text>
    <text class="fig-green" x="40" y="180" font-size="10.2">进程 B（独立 open 同文件）</text>
    <text class="fig-label" x="40" y="213" font-size="10.2">fd 3 → 系统表项 #1</text>
    <text class="fig-muted" x="40" y="233" font-size="9.5">相同 fd 整数在不同进程互不干涉</text>
    <text class="fig-title" x="351" y="34" font-size="11.5" text-anchor="middle">系统打开文件表（全局共享）</text>
    <text class="fig-accent" x="260" y="73" font-size="10.8">表项 #0（A 的 fd 3/4 共用）</text>
    <text class="fig-label" x="260" y="92" font-size="10">offset = 120 | mode = O_RDWR</text>
    <text class="fig-muted" x="260" y="110" font-size="9.8">打开计数 ref = 2（dup/fork 同步）</text>
    <text class="fig-muted" x="260" y="126" font-size="9.8">inode 指针 → 内存 inode #42</text>
    <text class="fig-orange" x="260" y="175" font-size="10.8">表项 #1（B 独立打开）</text>
    <text class="fig-label" x="260" y="194" font-size="10">offset = 0 | mode = O_RDONLY</text>
    <text class="fig-muted" x="260" y="212" font-size="9.8">打开计数 ref = 1（偏移相互独立）</text>
    <text class="fig-muted" x="260" y="228" font-size="9.8">inode 指针 → 内存 inode #42</text>
    <text class="fig-title" x="599" y="34" font-size="11.5" text-anchor="middle">内存 inode 表 &amp; 磁盘</text>
    <text class="fig-purple" x="599" y="74" font-size="11" text-anchor="middle">内存 inode #42（全局唯一）</text>
    <text class="fig-label" x="518" y="95" font-size="10">• 文件元数据 + 数据块指针</text>
    <text class="fig-label" x="518" y="113" font-size="10">• 内存引用计数 = 2（表项数）</text>
    <text class="fig-label" x="518" y="131" font-size="10">• 状态标志：脏位 / 锁 / 设备号</text>
    <text class="fig-muted" x="518" y="148" font-size="9.5">教学两级口径将偏移量归入进程表</text>
    <text class="fig-label" x="599" y="196" font-size="10.5" text-anchor="middle">页缓存（延迟写 / 预读）</text>
    <text class="fig-muted" x="599" y="215" font-size="9.5" text-anchor="middle">↕ fsync 刷盘 / 缺页读盘</text>
    <text class="fig-muted" x="599" y="234" font-size="8.6" text-anchor="middle">磁盘 inode #42 (i_links) + 数据块</text>
    <text class="fig-accent" x="28" y="294" font-size="11">★ 真题高频动作分界：open 只查目录加载 inode（不读正文）并返回整数 fd；lseek 只改 offset（0 次 I/O）；</text>
    <text class="fig-label" x="28" y="314" font-size="10.5">read/write/close 均凭 fd 不再按名搜索；close 仅使计数减 1，归零才释放内存 inode（不动目录项与磁盘 i_links）。</text>
  </svg>
  <figcaption>图 6-3　文件描述符表、系统打开文件表与内存 inode 表的三层联动机制（含独立 open 与 dup/fork 的偏移差异）</figcaption>
</figure>

#### 6.2.3 作为特殊文件的管道（`pipe` 与 `FIFO`）

在 UNIX/Linux “一切皆文件”的设计哲学下，用于进程间通信的**管道**（Pipe）在内核中同样被抽象为一个特殊文件，通过标准文件描述符与 `read()`/`write()` 系统调用进行交互。

- **管道的底层载体是内存缓冲区，而非外存磁盘**：虽然管道披着“文件”的外衣，但由于进程间通信追求高吞吐与低延迟，内核直接在主存中开辟**固定大小的字节流缓冲队列**（如 4 KB / 64 KB）来模拟文件，而不落盘。因此**管道容量受内存与内核缓冲区上限限制，绝不受磁盘容量限制**。
- **管道协调的三大核心机制**：
  1. **互斥**：一个进程正在读或写管道缓冲区时，另一端必须互斥等待。
  2. **同步**：典型的“生产者–消费者”缓冲关系。缓冲区写满时**写进程阻塞**（直到读进程取走数据唤醒）；缓冲区为空时**读进程阻塞**（直到写进程写入新数据唤醒）。因此**读操作与写操作均可能被阻塞**。
  3. **存在性确认**：只有通信对端仍处于打开存在状态时才允许通信（写关闭则读尽返 0 EOF；读端全关闭则写进程收到 `SIGPIPE` 异常信号）。

| 比较维度 | 普通管道 / 匿名管道（`pipe(int fd[2])`） | 命名管道（`FIFO`） |
| --- | --- | --- |
| 在目录树中存在 | 否（无文件名，仅内存临时 inode） | **是**（有路径名与目录项，可用 `open` 打开） |
| 通信进程关系限制 | **仅限具有亲缘关系的进程**（父子/兄弟，靠 `fork` 继承 `fd[0]`/`fd[1]`） | **任意无亲缘关系的进程**均可通过路径名打开通信 |
| 通信方向与双工性 | **单向（仅单工）**；双向通信必须建立**两条管道** | 允许双向，但 **UNIX FIFO 同一时刻仍只支持半双工**；**Windows 命名管道支持全双工** |
| 允许并发写者数 | 通常一写一读 | 允许多个写者或读者并发访问 |
| 生命周期 | 仅随进程通信存在，所有 `fd` 关闭后立即消亡 | 通信完成后管道节点仍保留在文件系统中，直到被显式删除 |

<figure class="cpd-figure not-content" id="os-c6-fig-4">
  <svg viewBox="0 0 720 272" role="img" aria-label="管道作为特殊文件的内存环形缓冲区原理与匿名管道和命名管道对比">
    <defs>
      <marker id="os-c6-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="388" height="162" rx="8"/>
    <rect class="fig-box-subtle" x="420" y="16" width="284" height="162" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="190" width="688" height="66" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="124" y1="75" x2="150" y2="75" marker-end="url(#os-c6-arr-4)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="268" y1="75" x2="294" y2="75" marker-end="url(#os-c6-arr-4)"/>
    <rect class="fig-box-blue" x="28" y="48" width="96" height="54" rx="6"/>
    <rect class="fig-box-accent" x="152" y="44" width="116" height="62" rx="6"/>
    <rect class="fig-box-green" x="296" y="48" width="96" height="54" rx="6"/>
    <rect class="fig-box" x="28" y="118" width="364" height="48" rx="5"/>
    <rect class="fig-box-purple" x="434" y="48" width="256" height="44" rx="6"/>
    <rect class="fig-box-orange" x="434" y="102" width="256" height="64" rx="6"/>
    <rect class="fig-box-red" x="28" y="214" width="212" height="30" rx="5"/>
    <rect class="fig-box-red" x="254" y="214" width="212" height="30" rx="5"/>
    <rect class="fig-box-green" x="480" y="214" width="212" height="30" rx="5"/>
    <text class="fig-title" x="210" y="35" font-size="11.5" text-anchor="middle">匿名管道 pipe(fd[2])：单向、仅亲缘进程</text>
    <text class="fig-blue" x="76" y="70" font-size="10.5" text-anchor="middle">写端进程</text>
    <text class="fig-muted" x="76" y="88" font-size="9.5" text-anchor="middle">write(fd[1])</text>
    <text class="fig-accent" x="210" y="64" font-size="10.5" text-anchor="middle">内存环形缓冲区</text>
    <text class="fig-label" x="210" y="80" font-size="9.5" text-anchor="middle">FIFO 字节流队列</text>
    <text class="fig-muted" x="210" y="96" font-size="9.5" text-anchor="middle">满写阻塞 / 空读阻塞</text>
    <text class="fig-green" x="344" y="70" font-size="10.5" text-anchor="middle">读端进程</text>
    <text class="fig-muted" x="344" y="88" font-size="9.5" text-anchor="middle">read(fd[0])</text>
    <text class="fig-label" x="40" y="137" font-size="10">• 双向通信必须建两条管道；通信结束后管道自动销毁</text>
    <text class="fig-muted" x="40" y="155" font-size="10">• 三大协调：互斥访问 + 空/满同步阻塞 + 判断对端仍存在</text>
    <text class="fig-title" x="562" y="35" font-size="11.5" text-anchor="middle">命名管道 FIFO：任意进程可用</text>
    <text class="fig-purple" x="562" y="67" font-size="10.5" text-anchor="middle">路径入口（如 /tmp/myfifo）</text>
    <text class="fig-muted" x="562" y="83" font-size="9.5" text-anchor="middle">具名目录项，不同进程可分别 open()</text>
    <text class="fig-orange" x="444" y="121" font-size="10">• 允许多写者/多读者，关闭后文件仍存</text>
    <text class="fig-label" x="444" y="138" font-size="10">• UNIX FIFO：双向但同刻仅半双工</text>
    <text class="fig-label" x="444" y="155" font-size="10">• Windows 命名管道：支持全双工</text>
    <text class="fig-title" x="360" y="206" font-size="11" text-anchor="middle">★ 管道真题辨析要点（常考概念正误判断）</text>
    <text class="fig-red" x="134" y="233" font-size="10" text-anchor="middle">✗ 错：容量受磁盘容量限制（实为内存）</text>
    <text class="fig-red" x="360" y="233" font-size="10" text-anchor="middle">✗ 错：一条普通管道即可双向同步传</text>
    <text class="fig-green" x="586" y="233" font-size="10" text-anchor="middle">✓ 对：读/写操作皆可能发生阻塞</text>
  </svg>
  <figcaption>图 6-4　管道作为特殊文件的内存缓冲模型（匿名管道与命名管道的通信方向及同步机制对比）</figcaption>
</figure>

---

### 6.3 文件的逻辑结构

#### 6.3.1 逻辑结构与物理结构的公共分界线

谈论“文件内部怎么组织”时，存在两个截然不同的视角：**逻辑结构**面对用户与程序员（“如何把第 $k$ 条记录定位到文件内第 $X$ 个字节”）；**物理结构**面对操作系统与磁盘（“如何把文件内第 $X$ 个字节映射到第 $Y$ 个物理盘块的第 $Z$ 个字节”）。

这两层通过**文件内字节偏移量**作为公共接口实现**彻底解耦**：任意一种逻辑结构理论上可以搭配任意一种物理结构，互不干涉。

> **注意（两大高频概念混淆点）**：
> 1. **索引文件 $\neq$ 索引分配**：**索引文件**属于逻辑结构，是为文件内部的**记录**建立索引表；**索引分配**属于物理结构，是为文件占用的**磁盘块**建立索引块。两者名称相似但处在完全不同的抽象层！
> 2. **随机存取能力最终由物理结构锁死**：逻辑上就算声明为“支持随机存取的记录文件”，若底层物理结构采用**隐式链接分配**，仍无法跳过前序盘块直接读取第 $k$ 条记录。

#### 6.3.2 无结构文件与有结构文件

1. **无结构文件（流式文件）**：文件内部无任何记录边界，仅是一串无结构的二进制流或字符流（如 `.txt`、图像、ELF 可执行文件），只能按字节长度与偏移量访问。**UNIX/Linux 把一切普通文件都视为字节流式文件**，记录格式由应用程序自己解释。
2. **有结构文件（记录式文件）**：由一组相似的**记录**（Record）组成，每条记录由若干**数据项**（字段）构成（如数据库表的一行），通常以某个数据项作为**关键字（Key）**。按记录占用字节长度是否一致，分为：
   - **定长记录**：所有记录长度均为固定值 $L$，第 $k$ 条记录起始偏移 $= k \times L$（从 0 编号）。
   - **可变长记录**：各条记录长度不等（如“特长描述”字段长短悬殊），必须在每条记录前附带长度字段（或用分隔符隔开），否则无法划分记录边界。

#### 6.3.3 四类有结构文件的组织形式与检索代价推导

为什么需要演化出四种有结构文件？这完全是一条被“**如何快速找到第 $k$ 条或关键字为 $K$ 的记录**”推着走的工程演进链：

1. **顺序文件（Sequential File）**：
   物理上可顺序存储也可链式存储（**考研默认物理上顺序存储**）。按记录是否按关键字有序分为两类：
   - **串结构**：按记录存入的时间先后顺序排列，与关键字无关。按关键字查找须从头逐条比较，平均 $O(N)$；但插入新记录极快，直接追加到文件末尾即可（$O(1)$）。
   - **顺序结构**：记录按关键字递增或递减排序。插入/删除需要移动大量后继记录以维持有序性（实际系统常借日志文件批量延迟合并）。
   - **★ 随机存取与折半查找的前提定理**：**只有物理上顺序存储且为定长记录的顺序文件，才能实现随机存取；在此基础上若还是顺序结构（按关键字有序），才能使用折半查找（$O(\log_2 N)$）！** 原因在于折半查找要求 $O(1)$ 跳转到第 $k$ 条记录，定长记录偏移 $= k \times L$ 一步算出；而**变长记录即使物理连续且按关键字有序，因为不知道前 $k$ 条记录的总长度，依然无法随机存取、无法折半查找！**

2. **索引文件（Indexed File — 稠密索引）**：
   专为解决**变长记录无法随机访问**的痛点而生。为文件中的**每一条记录**在索引表中建立一个定长索引项 `(关键字, 指向记录的指针)`，索引表按关键字排序且表项本身定长连续存放（本质上**索引表自身就是一个定长记录的顺序结构顺序文件**）。
   - 由此，变长记录的主文件不必连续存放，系统通过**折半查找定长索引表**即可定位目标记录（$O(\log_2 N)$）。
   - **插入代价比拼**：向 $N$ 条记录的文件插入 1 条新记录时，顺序结构的顺序文件平均要搬移 $\frac{N}{2}$ 条**完整的记录**；索引文件只需把新记录直接追加到主文件末尾，然后平均移动 $\frac{N}{2}$ 个**极小巧的索引项**即可（数据搬运量缩减 1～2 个数量级）。
   - **仅对变长记录划算**：定长记录本就可以直接算出偏移，加索引反而多占空间并多一层间接查找；索引文件还可针对非关键字数据项（如姓名）建立多个辅助索引表以加速多维查询。

3. **索引顺序文件（Indexed Sequential File — 稀疏索引）**：
   索引文件每条记录建一项，若每条记录很小而索引项很大，索引表甚至比主文件还要大（空间浪费严重）。**索引顺序文件**将记录分块成组，只为**每组建立一个索引项**（记录该组最大/最小关键字与组起始位置），类似字典“部首检字法”，属于**稀疏索引**（代表实现：ISAM、VSAM，另配**溢出区**暂存增删改记录以免频繁挪动主文件）。

> **★考点（索引顺序文件平均检索长度 $\sqrt{N}$ 完整推导与 $L$ 级推广）**：
> 设文件共 $N$ 条记录，平均分为 $g = N/s$ 组，每组 $s$ 条记录，索引表与组内均采用顺序查找。由于两段先后串行执行，平均查找次数为两段代价之和：
> $$
> f(s) = \frac{g}{2} + \frac{s}{2} = \frac{N}{2s} + \frac{s}{2}
> $$
> 对 $s$ 求导并令 $f'(s) = 0$（或用均值不等式 $\frac{N}{2s} + \frac{s}{2} \ge 2\sqrt{\frac{N}{4}} = \sqrt{N}$），当且仅当两段代价相等即 **$s = g = \sqrt{N}$** 时取极小值：
> $$
> f_{\min} = \frac{\sqrt{N}}{2} + \frac{\sqrt{N}}{2} = \sqrt{N}
> $$
> - **一维算例**：$N = 10000$ 条记录时，纯顺序文件平均查 $5000$ 次；分 $100$ 组每组 $100$ 条，平均查 $50 + 50 = 100$ 次，加速比达 $\frac{\sqrt{N}}{2} = 50$ 倍。
> - **多级推广（$L$ 段检索）**：若把大索引表继续分组再建高一级索引（共分 $L-1$ 级索引表 + $1$ 级记录组，合计 $L$ 段），每段等长取 $t = N^{1/L}$，则平均查找次数通式为 $\frac{L}{2} N^{1/L}$。例如 $N = 10^6$ 时，一级索引顺序文件（$L=2$）平均查 $500+500=1000$ 次；改用两级索引（$L=3$，顶级 $100$ 项 $\to$ 次级 $100$ 项 $\to$ 组内 $100$ 条）则仅需平均 $50 + 50 + 50 = 150$ 次。

4. **散列文件（Hash 文件 / 直接文件）**：
   直接利用散列函数计算物理记录位置：$\text{记录地址} = H(\text{关键字})$，无冲突时 $O(1)$ 一次定位。必然发生的散列冲突有三种解法：① **链地址法**（同义词挂链，装填因子高时仍稳健）；② **开放定址法**（探测下一空位，会产生**堆积/聚集**现象导致本不冲突的关键字也开始冲突）；③ **溢出区法**（溢出记录统一归入溢出区顺序找）。致命缺点：**散列打乱了关键字的大小次序，彻底不支持按顺序存取或范围查询**。

| 逻辑结构 | 记录/关键字查找策略 | 顺序存取 | 随机存取 | 平均检索长度 | 核心代价与典型场景 |
| --- | --- | --- | --- | --- | --- |
| **顺序文件（串结构）** | 从头逐条顺序比较 | **最优** | 不支持 | $N / 2$ | 插入可直接追加至尾 $O(1)$；适合批处理、磁带 |
| **顺序文件（顺序结构）** | 有序定长时可折半查找 | **最优** | **仅定长支持** | $\log_2 N$（定长） | 插入须搬动后继记录；适合批处理兼偶发查询 |
| **索引文件（稠密）** | 折半查有序定长索引表 | 支持 | **支持（含变长）** | $\log_2 N$ | 索引表空间大；专为**变长记录**实现快速随机检索 |
| **索引顺序文件（稀疏）** | 查索引表定组 + 组内查 | 支持 | 支持 | $\sqrt{N}$（一级） | 折中空间与时间；适合海量记录（ISAM / VSAM） |
| **散列文件（Hash）** | 函数计算直达，不比较 | **不支持** | **支持** | $\approx 1$ | 需处理冲突（拉链/开放/溢出）；适合单条点查 |

<figure class="cpd-figure not-content" id="os-c6-fig-5">
  <svg viewBox="0 0 720 340" role="img" aria-label="有结构文件四种逻辑结构顺序文件、索引文件、索引顺序文件与散列文件查找对照">
    <defs>
      <marker id="os-c6-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="176" width="336" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="176" width="336" height="148" rx="8"/>
    <line class="fig-line-accent" x1="508" y1="58" x2="536" y2="58" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="508" y1="79" x2="536" y2="96" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="508" y1="100" x2="536" y2="79" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="146" y1="222" x2="172" y2="222" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="146" y1="252" x2="172" y2="252" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="464" y1="232" x2="482" y2="232" marker-end="url(#os-c6-arr-5)"/>
    <line class="fig-line-accent" x1="572" y1="232" x2="590" y2="232" marker-end="url(#os-c6-arr-5)"/>
    <rect class="fig-box-blue" x="28" y="44" width="312" height="36" rx="5"/>
    <line class="fig-divider" x1="106" y1="44" x2="106" y2="80"/>
    <line class="fig-divider" x1="184" y1="44" x2="184" y2="80"/>
    <line class="fig-divider" x1="262" y1="44" x2="262" y2="80"/>
    <rect class="fig-box-accent" x="380" y="44" width="128" height="68" rx="5"/>
    <rect class="fig-box-green" x="538" y="44" width="154" height="68" rx="5"/>
    <rect class="fig-box-orange" x="28" y="204" width="118" height="68" rx="5"/>
    <rect class="fig-box-green" x="174" y="204" width="166" height="68" rx="5"/>
    <rect class="fig-box-purple" x="380" y="210" width="84" height="44" rx="5"/>
    <rect class="fig-box-accent" x="484" y="210" width="88" height="44" rx="5"/>
    <rect class="fig-box" x="592" y="204" width="100" height="56" rx="5"/>
    <text class="fig-title" x="184" y="34" font-size="11.5" text-anchor="middle">① 顺序文件（串结构 vs 顺序结构）</text>
    <text class="fig-blue" x="67" y="66" font-size="10.5" text-anchor="middle">K1 | 记录0</text>
    <text class="fig-blue" x="145" y="66" font-size="10.5" text-anchor="middle">K2 | 记录1</text>
    <text class="fig-blue" x="223" y="66" font-size="10.5" text-anchor="middle">K3 | 记录2</text>
    <text class="fig-blue" x="301" y="66" font-size="10.5" text-anchor="middle">K4 | 记录3</text>
    <text class="fig-label" x="28" y="102" font-size="10">• 串结构：按存入先后排，查找 O(N)，追加至尾 O(1)</text>
    <text class="fig-label" x="28" y="122" font-size="10">• 顺序结构：按关键字有序；★ 定长 + 顺序存才可折半</text>
    <text class="fig-red" x="28" y="142" font-size="10">• 变长顺序文件即使有序，因算不出 k×L 仍无法折半！</text>
    <text class="fig-title" x="536" y="34" font-size="11.5" text-anchor="middle">② 索引文件（稠密索引 · 专治变长记录）</text>
    <text class="fig-accent" x="444" y="61" font-size="10" text-anchor="middle">K1 | ptr0（定长）</text>
    <text class="fig-accent" x="444" y="81" font-size="10" text-anchor="middle">K2 | ptr1（有序）</text>
    <text class="fig-accent" x="444" y="101" font-size="10" text-anchor="middle">K3 | ptr2（折半）</text>
    <text class="fig-green" x="615" y="62" font-size="10" text-anchor="middle">变长记录 0（L0）</text>
    <text class="fig-green" x="615" y="82" font-size="10" text-anchor="middle">变长记录 2（L2）</text>
    <text class="fig-green" x="615" y="102" font-size="10" text-anchor="middle">变长记录 1（L1）</text>
    <text class="fig-label" x="380" y="132" font-size="10">• 把原本不可随机存取的变长文件变成支持 O(log2 N)</text>
    <text class="fig-muted" x="380" y="150" font-size="10">• 注意区分：索引文件(记录级) ≠ 索引分配(磁盘块级)</text>
    <text class="fig-title" x="184" y="194" font-size="11.5" text-anchor="middle">③ 索引顺序文件（稀疏索引 · ★ √N 平衡）</text>
    <text class="fig-orange" x="87" y="225" font-size="10" text-anchor="middle">组1最大K | 组首</text>
    <text class="fig-orange" x="87" y="255" font-size="10" text-anchor="middle">组2最大K | 组首</text>
    <text class="fig-green" x="257" y="225" font-size="10" text-anchor="middle">组1（含 s 条顺序记录）</text>
    <text class="fig-green" x="257" y="255" font-size="10" text-anchor="middle">组2（含 s 条顺序记录）</text>
    <text class="fig-label" x="28" y="293" font-size="10">★ 极值：f(s) = N/(2s) + s/2 → s = √N 时平均查 √N 次</text>
    <text class="fig-muted" x="28" y="311" font-size="10">推广 L 段：f = (L/2)·N^(1/L)（配溢出区防频繁重排）</text>
    <text class="fig-title" x="536" y="194" font-size="11.5" text-anchor="middle">④ 散列文件（Hash 函数直接计算地址）</text>
    <text class="fig-purple" x="422" y="236" font-size="10.5" text-anchor="middle">关键字 K</text>
    <text class="fig-accent" x="528" y="236" font-size="10.5" text-anchor="middle">Addr = H(K)</text>
    <text class="fig-label" x="642" y="226" font-size="10" text-anchor="middle">记录桶地址</text>
    <text class="fig-muted" x="642" y="246" font-size="9.5" text-anchor="middle">（冲突处理）</text>
    <text class="fig-label" x="380" y="293" font-size="10">• 理想 O(1) 直达；冲突用拉链法/开放定址(堆积)/溢出区</text>
    <text class="fig-red" x="380" y="311" font-size="10">• 散列打散了关键字大小序，彻底不支持顺序存取！</text>
  </svg>
  <figcaption>图 6-5　有结构文件四大逻辑结构查找路径对照与“文件内偏移量”抽象机制</figcaption>
</figure>

---

### 6.4 目录管理与文件共享 ★

#### 6.4.1 目录的本质与四代目录结构演进

文件系统不仅要组织单个文件内部的记录，还要把成千上万个文件有序组织起来。**目录（Directory，即文件夹）本质上也是一种特殊的文件**，它同样拥有自己的 inode 并占用数据块，只不过它的正文内容是一张**目录项表**，在采用 inode 的系统中每条目录项极简地存成 `(文件名, inode 号)`。

为了解决“重名冲突、用户隔离、分层分类、共享协作”四大需求，目录结构经历了四代演进：

1. **单级目录**：全系统只有一张目录表，所有文件混在一起。绝对**不允许重名**，多用户、多项目下极易名字碰撞，查找也慢。
2. **两级目录**：分为第一级**主文件目录（MFD）**（登记用户名与对应 UFD 入口）和第二级**用户文件目录（UFD）**。解决了**不同用户之间的文件重名**问题，并实现了**命名空间隔离**（A 用户只能检索自己的 UFD）。**注意**：两级目录提供的隔离靠的是“根本看不到他人表项”，它**不是细粒度的 `rwx` 访问权限控制**，且仍然不支持用户内部再分子目录。
3. **树形目录（多级目录）**：现代系统的标准结构。以根目录 `/` 为唯一树根，目录下可混合存放普通文件与任意深度的子目录文件，严格树中每个文件**有且仅有一个父目录**。从根出发经 `/`（UNIX）或 `\`（Windows）拼接到目标的路径称**绝对路径**（如 `/home/alice/docs/report.txt`）；从当前位置出发的路径称**相对路径**。
   - **★ `.` 与 `..` 的本质**：系统在创建任何新目录时都会自动写入两条普通目录项（它们就是系统内置、结构严格受控的两个**硬链接**）：`.` 指向**该目录自身**的 inode，`..` 指向**父目录**的 inode。由这一事实直接推出三条硬结论：① **空目录的链接计数 `i_links` $= 2$**（父目录里一条名字 + 自己目录里的 `.`）；② **任意目录的链接计数 $= 2 + \text{直属子目录数}$**（每个直属子目录里各有一条 `..` 指回它）；③ **根目录的 `.` 与 `..` 指向同一个 inode**（系统遍历时据此判断“已到达根”）。
4. **无环图目录（DAG，Directed Acyclic Graph）**：在树形目录基础上打破“每个文件只能有一个父目录”的限制，允许**多个目录项指向同一个共享文件或子目录**（例如项目组共享公共库文件），使目录结构从“树”变为“有向无环图”。系统必须为每个共享对象维护共享计数器（仅当计数归零才回收空间），且**严禁父子互指成环**（否则遍历工具会陷入无限死循环）。

<figure class="cpd-figure not-content" id="os-c6-fig-6">
  <svg viewBox="0 0 720 334" role="img" aria-label="单级目录、两级目录、树形多级目录与无环图 DAG 目录演进对比">
    <defs>
      <marker id="os-c6-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="146" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="146" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="174" width="336" height="146" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="174" width="336" height="146" rx="8"/>
    <line class="fig-line" x1="184" y1="68" x2="72" y2="92" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="184" y1="68" x2="146" y2="92" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="184" y1="68" x2="222" y2="92" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="184" y1="68" x2="296" y2="92" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="536" y1="68" x2="454" y2="86" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="536" y1="68" x2="618" y2="86" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="184" y1="218" x2="112" y2="236" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="184" y1="218" x2="258" y2="236" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="112" y1="262" x2="74" y2="278" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line" x1="112" y1="262" x2="152" y2="278" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line-accent" x1="464" y1="224" x2="520" y2="256" marker-end="url(#os-c6-arr-6)"/>
    <line class="fig-line-accent" x1="608" y1="224" x2="552" y2="256" marker-end="url(#os-c6-arr-6)"/>
    <rect class="fig-box" x="128" y="44" width="112" height="24" rx="4"/>
    <rect class="fig-box-red" x="44" y="94" width="56" height="24" rx="4"/>
    <rect class="fig-box-red" x="118" y="94" width="56" height="24" rx="4"/>
    <rect class="fig-box-red" x="194" y="94" width="56" height="24" rx="4"/>
    <rect class="fig-box-red" x="268" y="94" width="56" height="24" rx="4"/>
    <rect class="fig-box-blue" x="476" y="44" width="120" height="24" rx="4"/>
    <rect class="fig-box-green" x="386" y="88" width="136" height="36" rx="5"/>
    <rect class="fig-box-green" x="550" y="88" width="136" height="36" rx="5"/>
    <rect class="fig-box-accent" x="148" y="196" width="72" height="22" rx="4"/>
    <rect class="fig-box-blue" x="76" y="238" width="72" height="24" rx="4"/>
    <rect class="fig-box" x="218" y="238" width="80" height="24" rx="4"/>
    <rect class="fig-box-green" x="36" y="280" width="76" height="22" rx="4"/>
    <rect class="fig-box" x="118" y="280" width="92" height="22" rx="4"/>
    <rect class="fig-box-blue" x="404" y="200" width="120" height="24" rx="4"/>
    <rect class="fig-box-blue" x="548" y="200" width="120" height="24" rx="4"/>
    <rect class="fig-box-purple" x="456" y="258" width="160" height="30" rx="5"/>
    <text class="fig-title" x="184" y="34" font-size="11.5" text-anchor="middle">① 单级目录</text>
    <text class="fig-label" x="184" y="60" font-size="10.5" text-anchor="middle">全局唯一根目录</text>
    <text class="fig-red" x="72" y="110" font-size="10" text-anchor="middle">a.txt</text>
    <text class="fig-red" x="146" y="110" font-size="10" text-anchor="middle">b.c</text>
    <text class="fig-red" x="222" y="110" font-size="10" text-anchor="middle">c.doc</text>
    <text class="fig-red" x="296" y="110" font-size="10" text-anchor="middle">d.bin</text>
    <text class="fig-muted" x="184" y="142" font-size="10" text-anchor="middle">全系统禁止重名，检索慢，不支持多用户隔离</text>
    <text class="fig-title" x="536" y="34" font-size="11.5" text-anchor="middle">② 两级目录（MFD + UFD）</text>
    <text class="fig-blue" x="536" y="60" font-size="10.5" text-anchor="middle">主文件目录 MFD</text>
    <text class="fig-green" x="454" y="103" font-size="10" text-anchor="middle">UFD_A（用户 A）</text>
    <text class="fig-muted" x="454" y="118" font-size="9.2" text-anchor="middle">a.txt, main.c</text>
    <text class="fig-green" x="618" y="103" font-size="10" text-anchor="middle">UFD_B（用户 B）</text>
    <text class="fig-muted" x="618" y="118" font-size="8.6" text-anchor="middle">a.txt(允许重名!), data</text>
    <text class="fig-muted" x="536" y="144" font-size="10" text-anchor="middle">解决不同用户重名与命名空间隔离（非权限控制）</text>
    <text class="fig-title" x="184" y="191" font-size="11.5" text-anchor="middle">③ 树形目录（严格单父节点）</text>
    <text class="fig-accent" x="184" y="211" font-size="10.5" text-anchor="middle">/（根）</text>
    <text class="fig-blue" x="112" y="254" font-size="10" text-anchor="middle">home/</text>
    <text class="fig-label" x="258" y="254" font-size="10" text-anchor="middle">etc/config</text>
    <text class="fig-green" x="74" y="295" font-size="10" text-anchor="middle">alice/</text>
    <text class="fig-muted" x="164" y="295" font-size="8.2" text-anchor="middle">. (自) / .. (父)</text>
    <text class="fig-muted" x="275" y="282" font-size="9.5" text-anchor="middle">空目录 i_links = 2</text>
    <text class="fig-muted" x="275" y="298" font-size="9.5" text-anchor="middle">根 . 与 .. 同指根</text>
    <text class="fig-title" x="536" y="191" font-size="11.5" text-anchor="middle">④ 无环图目录（DAG · 文件共享）</text>
    <text class="fig-blue" x="464" y="216" font-size="10" text-anchor="middle">/home/alice</text>
    <text class="fig-blue" x="608" y="216" font-size="10" text-anchor="middle">/shared/team</text>
    <text class="fig-purple" x="536" y="277" font-size="9.8" text-anchor="middle">report.txt（共享计数 = 2）</text>
    <text class="fig-muted" x="536" y="308" font-size="10" text-anchor="middle">允许多父目录共享同一文件；禁止成环防死循环</text>
  </svg>
  <figcaption>图 6-6　目录结构的四代演进规律与树形目录“.”“..”硬链接计数特性</figcaption>
</figure>

#### 6.4.2 树形目录路径解析 I/O 次数经典计算与当前工作目录加速 ★

在无目录项缓存的情况下，按路径解析打开文件时，**每向下一级目录都要执行 2 次磁盘 I/O**：第 1 次读出该级目录的 **inode**（才知道它的目录项放在哪些盘块上），第 2 次读出该级目录的**数据块**（从中按名匹配出下一级目录或文件的 inode 号）。

> **★考点（路径解析 I/O 次数与当前工作目录加速原理）**：
> - 设根目录 `/` 的 inode 已在系统启动时常驻内存，其余 inode 均在磁盘上，每个目录仅占 1 个数据块。解析深度为 $n$ 的路径（从根往下经过 $n-1$ 个目录及最终目标文件，共含 $n$ 个名称分量）并**打开**目标文件，需要 **$2n$ 次磁盘 I/O**（最后 1 次是读取目标文件自己的 inode）。若根目录 inode 也不在内存，则需 **$2n + 1$ 次**。
> - **“打开（`open`）”只算到读取目标文件的 inode 为止**，不含读取该文件的正文数据块；若一个目录文件本身很大占用多个盘块，还要加上在该目录内线性查找多出的盘块读取次数。
> - **设置当前工作目录（`cwd`）的主要目的（10#31 真题）**：由于进程访问的文件具有空间局部性，引入当前工作目录后可通过**相对路径**（如 `docs/report.txt` 或 `./hello`）直接从内存中已知的当前目录 inode 起步，跳过公共前缀级数及其 $2k$ 次盘 I/O，从而**加快文件的检索速度**（既不节省外存，也不节省内存，亦不改变读写正文的速度！）。

**目录项格式与最大文件数上限计算（20#31 真题）**：当目录项为定长格式 `(文件名, inode 号)` 时，整个分区最多能创建的不同文件本体数量，取决于“**编号天花板与名字天花板二者取小**”：

$$
\text{文件数上限} = \min\left(2^{8 \times \text{inode 号字节数}}, \;\; |\Sigma|^{\text{文件名最大字节数}}\right)
$$

例如某目录项占 64 字节，其中 **4 字节**存 inode 号、**60 字节**存由小写英文字母组成的文件名，则编号上限为 $2^{4 \times 8} = 2^{32}$，名字上限为 $26^{60}$（远大于 $2^{240}$），故最多可创建 **$2^{32}$ 个**文件。切勿直接拿文件名字节数 60 当作 $2^{60}$！

<figure class="cpd-figure not-content" id="os-c6-fig-7">
  <svg viewBox="0 0 720 340" role="img" aria-label="树形目录路径解析 2n 次磁盘 IO 步进追踪与当前工作目录相对路径加速图">
    <defs>
      <marker id="os-c6-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-accent" x="16" y="16" width="688" height="38" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="216" width="688" height="108" rx="8"/>
    <line class="fig-line-accent" x1="139" y1="132" x2="155" y2="132" marker-end="url(#os-c6-arr-7)"/>
    <line class="fig-line-accent" x1="277" y1="132" x2="293" y2="132" marker-end="url(#os-c6-arr-7)"/>
    <line class="fig-line-accent" x1="415" y1="132" x2="431" y2="132" marker-end="url(#os-c6-arr-7)"/>
    <line class="fig-line-accent" x1="553" y1="132" x2="569" y2="132" marker-end="url(#os-c6-arr-7)"/>
    <rect class="fig-box-green" x="19" y="66" width="120" height="136" rx="6"/>
    <rect class="fig-box-blue" x="157" y="66" width="120" height="136" rx="6"/>
    <rect class="fig-box-blue" x="295" y="66" width="120" height="136" rx="6"/>
    <rect class="fig-box-orange" x="433" y="66" width="120" height="136" rx="6"/>
    <rect class="fig-box-purple" x="571" y="66" width="130" height="136" rx="6"/>
    <rect class="fig-box-green" x="28" y="242" width="368" height="70" rx="5"/>
    <rect class="fig-box-red" x="408" y="242" width="284" height="70" rx="5"/>
    <text class="fig-accent" x="360" y="39" font-size="11.5" text-anchor="middle">路径解析算例：open("/home/alice/docs/report.txt")（深度 n = 4，根 inode 已驻内存）</text>
    <text class="fig-green" x="79" y="88" font-size="11" text-anchor="middle">① 根目录 /</text>
    <text class="fig-label" x="79" y="112" font-size="10" text-anchor="middle">inode #2 在内存</text>
    <text class="fig-muted" x="79" y="128" font-size="9.5" text-anchor="middle">(I/O = 0 次)</text>
    <text class="fig-label" x="79" y="150" font-size="10" text-anchor="middle">读 / 数据块 (+1)</text>
    <text class="fig-accent" x="79" y="172" font-size="9.8" text-anchor="middle">找 home → #18</text>
    <text class="fig-muted" x="79" y="192" font-size="9.5" text-anchor="middle">累计 1 次盘 I/O</text>
    <text class="fig-blue" x="217" y="88" font-size="11" text-anchor="middle">② home/</text>
    <text class="fig-label" x="217" y="112" font-size="10" text-anchor="middle">读 inode #18 (+1)</text>
    <text class="fig-label" x="217" y="134" font-size="10" text-anchor="middle">读 home 块 (+1)</text>
    <text class="fig-accent" x="217" y="172" font-size="9.8" text-anchor="middle">找 alice → #77</text>
    <text class="fig-muted" x="217" y="192" font-size="9.5" text-anchor="middle">累计 3 次盘 I/O</text>
    <text class="fig-blue" x="355" y="88" font-size="11" text-anchor="middle">③ alice/</text>
    <text class="fig-label" x="355" y="112" font-size="10" text-anchor="middle">读 inode #77 (+1)</text>
    <text class="fig-label" x="355" y="134" font-size="10" text-anchor="middle">读 alice 块 (+1)</text>
    <text class="fig-accent" x="355" y="172" font-size="9.8" text-anchor="middle">找 docs → #200</text>
    <text class="fig-muted" x="355" y="192" font-size="9.5" text-anchor="middle">累计 5 次盘 I/O</text>
    <text class="fig-orange" x="493" y="88" font-size="11" text-anchor="middle">④ docs/</text>
    <text class="fig-label" x="493" y="112" font-size="10" text-anchor="middle">读 inode #200 (+1)</text>
    <text class="fig-label" x="493" y="134" font-size="10" text-anchor="middle">读 docs 块 (+1)</text>
    <text class="fig-accent" x="493" y="172" font-size="9.8" text-anchor="middle">找 report → #305</text>
    <text class="fig-muted" x="493" y="192" font-size="9.5" text-anchor="middle">累计 7 次盘 I/O</text>
    <text class="fig-purple" x="636" y="88" font-size="11" text-anchor="middle">⑤ report.txt</text>
    <text class="fig-label" x="636" y="114" font-size="10" text-anchor="middle">读 inode #305 (+1)</text>
    <text class="fig-muted" x="636" y="136" font-size="9.5" text-anchor="middle">存入打开文件表</text>
    <text class="fig-muted" x="636" y="152" font-size="9.5" text-anchor="middle">返回句柄 fd</text>
    <text class="fig-purple" x="636" y="182" font-size="10.5" text-anchor="middle">★ 共 8 次 = 2n</text>
    <text class="fig-title" x="360" y="233" font-size="11.5" text-anchor="middle">设置当前工作目录（10#31 考点）与数 I/O 边界准则</text>
    <text class="fig-green" x="40" y="260" font-size="10.5">★ 设 cwd = /home/alice 后改用相对路径 docs/report.txt：</text>
    <text class="fig-label" x="40" y="279" font-size="10">直接从内存已知的 inode #77 起步，跳过前 2 级（省 4 次盘 I/O）</text>
    <text class="fig-muted" x="40" y="297" font-size="9.8">结论：设置当前目录的主要目的是【加快文件检索速度】</text>
    <text class="fig-red" x="420" y="260" font-size="10.5">两大计次陷阱：</text>
    <text class="fig-label" x="420" y="279" font-size="10">1) 根 inode 也要读盘时：总数 = 2n + 1 次</text>
    <text class="fig-label" x="420" y="297" font-size="10">2) open 止步于目标 inode，不含读正文块！</text>
  </svg>
  <figcaption>图 6-7　深度 n 树形路径解析 2n 次磁盘 I/O 步进过程与当前工作目录（相对路径）跳级加速原理</figcaption>
</figure>

#### 6.4.3 目录操作、空位复用与目录内部实现

1. **删除非空目录的两条策略**：① **禁止直接删除非空目录**（安全但须由上层递归删光所有子项与子目录，如标准 `rmdir`）；② **允许级联删除非空目录**（方便但极危险，一条误操作如 `rm -r` 即清空整棵子树）。
2. **删除一个目录项后留下的空位怎么处理**：
   - **标记删除（真实系统普遍采用）**：在目录项内写入“已删除”特殊标记（如首字节置特殊值），**不移动任何其他目录项**，删除耗时 $O(1)$ 且不破坏其他按位置引用的逻辑，后续新建文件优先复用该空位；缺点是目录文件大小只增不减，可能出现碎片化空洞。
   - **移动填补**：把最后一个目录项移过来或后续整体前移填坑，检索紧凑但每次删除搬动成本高且可能破坏位置索引。
3. **目录文件的内部组织方式**：
   - **线性表**：目录内文件数十至数百个时实现最简单、常数极小且天然保持条目顺序。
   - **哈希表**：单目录达上千文件时改为散列结构使查找均摊 $O(1)$。若采用开放定址解决冲突，**探测增量常数必须与目录表长度互质**（才能不重不漏走遍全表）；当装填因子过高扩容时必须全表 rehash；缺点是彻底打散了条目的原有次序。现代系统常采用**混合方案**（磁盘目录块仍线性存储 + 内存中构建哈希索引 / `dentry cache`）。

#### 6.4.4 文件共享：硬链接 vs 软链接（符号链接）★

**文件共享**是指多个用户或目录路径共同使用**同一份文件实体**（全盘只有一份数据，任一共享者修改后其他共享者实时可见），它与**文件复制**（各自拥有独立数据副本，修改互不影响）截然不同。

实现文件共享主要有两种基于无环图（DAG）的机制，它们的全部分歧都源自一个根本问题——“**链接里存的是什么？**”：

1. **基于索引节点的共享方式 —— 硬链接（Hard Link，`ln A D`）**：
   - **本质**：让不同目录里的多条目录项直接填入**同一个 inode 号**（由于 inode 中不存放文件名，因此各目录项可以使用完全不同的文件名）。硬链接创建后，“原文件名”与“新建硬链接”**完全平等**，谁也不是原件、谁也不是副本！
   - **创建与删除机制**：每新增一个硬链接，该 inode 的磁盘链接计数 `i_links` 加 1；当某用户删除自己的链接文件名时，系统**仅删除该目录项并使 `i_links` 减 1**。**只有当 `i_links == 0` 且内存引用计数也为 0 时，系统才真正回收该 inode 与占用的数据块**，避免对仍在使用文件的其他用户造成指针悬空。
   - **两条硬限制及其原因**：① **不能跨越文件系统（跨分区）**（因为 inode 号只是本分区 inode 数组的下标，跨分区同号指向完全无关的另一文件）；② **普通用户不能对目录建立硬链接**（防止目录之间连成任意闭环而使遍历死循环；系统自建的 `.` 与 `..` 属于受控例外）。

2. **基于符号链的共享方式 —— 软链接 / 符号链接（Symbolic Link，`ln -s A L`）**：
   - **本质**：新建一个独立的 `link` 类型小文件（**拥有自己独立的 inode 号与引用计数**），其数据内容就是目标文件的**路径名字符串**（类似 Windows 快捷方式）。若路径足够短，现代文件系统可直接把路径塞进该软链接 inode 本该放块指针的那片区域中，省去分配一个数据块，称为**快速符号链接（Fast Symlink）**。
   - **计数与删除行为**：创建软链接**绝不修改目标文件的 `i_links`**。若目标文件被删除（其 `i_links` 归零并被回收），内核**并不会主动追查并删除指向它的软链接**（内核压根不知道有哪些独立小文件里写着它的路径名），软链接因而变为失效的**悬空链接（断链，Dangling Link）**，再次通过它访问时报错（提示目标已删除后用户可清理该软链接）。
   - **相对路径 vs 绝对路径软链接的搬家差异**：`ln -s file.txt L` 写入的是相对路径 `"file.txt"`，系统在解析该软链接时以**软链接文件 `L` 自己所在的目录**为起点（而非当前工作目录）。因此把整个父目录打包搬走时，相对软链接依然有效；单独移动 `L` 时，只有**绝对路径**软链接依然有效。

> **★考点（软链接额外的磁盘 I/O 量化与真题三剑客）**：
> - **访问开销对比**：访问硬链接与访问原文件代价**完全一致**（$2n$ 次，0 额外开销）。访问软链接需先花 $2n$ 次解析到软链接自己的 inode $\to$ **多读 1 次软链接数据块取出路径字符串** $\to$ 按该路径**重新从头解析一遍目标路径（$2m$ 次，其中 $m$ 为目标路径深度）**，总计额外耗费 **$1 + 2m$ 次磁盘 I/O**（快速符号链接省去那 1 次数据块读盘）。
> - **真题 09#31**：`F1` 初始计数 $1$ $\to$ 建软链接 `F2`（**`F2` 独立，自己计数 $= 1$，不碰 `F1`**）$\to$ 建硬链接 `F3`（共享 `F1` 的 inode，计数升为 $2$）$\to$ 删 `F1`（原 inode 计数降为 $1$），故最终 **`F2 = 1`、`F3 = 1`**。
> - **真题 17#31**：两进程分别打开互为硬链接的文件 `f1` 和 `f2`，它们**共享同一个内存 inode**，且各自 `fd` 指向各自打开文件表项；但“**读写指针位置保持相同**”**错误**（各自独立 `open` 具有独立的读写偏移量！）。
> - **真题 21#30**：删除存在快捷方式（软链接）的文件 `file1` 时，内核**不必**完成“删除 `file1` 的快捷方式”这一操作，因为软链接是独立文件。

| 比较维度 | 硬链接（Hard Link） | 软链接 / 符号链接（Symbolic Link） |
| --- | --- | --- |
| **存放内容与本质** | 目录项中直接存**目标的 inode 号** | 独立的 `link` 小文件，内容存**目标路径字符串** |
| **是否分配新 inode** | **否**（多条目录项共享同一个 inode） | **是**（拥有自己独立的 inode 与文件属性） |
| **对目标 `i_links` 的影响** | 创建 $+1$、删除 $-1$（**归零且无打开才回收**） | **完全不影响**目标文件的链接计数 |
| **跨文件系统 / 跨分区** | **不可以**（inode 号仅本分区有效） | **可以**（路径解析可穿过挂载点） |
| **链接目录** | **不可以**（防任意成环致死循环） | **可以** |
| **删目标文件后** | 其他硬链接**照常访问**，数据安然无恙 | 软链接沦为**悬空链接（断链）**，访问报错 |
| **额外 I/O 访问开销** | **0 次额外 I/O**（与直接打开完全等速） | 多 **$1 + 2m$ 次**磁盘 I/O（快速符号链接少 1 次） |

<figure class="cpd-figure not-content" id="os-c6-fig-8">
  <svg viewBox="0 0 720 332" role="img" aria-label="硬链接共享同一 inode 与软链接独立 inode 存路径及断链行为对比">
    <defs>
      <marker id="os-c6-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="336" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="16" width="336" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="264" width="688" height="54" rx="8"/>
    <line class="fig-line-accent" x1="98" y1="92" x2="146" y2="118" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line-accent" x1="262" y1="92" x2="218" y2="118" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="184" y1="178" x2="184" y2="194" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line-accent" x1="450" y1="92" x2="450" y2="118" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="614" y1="92" x2="614" y2="118" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="450" y1="178" x2="450" y2="194" marker-end="url(#os-c6-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="614" y1="178" x2="614" y2="194" marker-end="url(#os-c6-arr-8)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-red)" d="M 538 216 L 526 216 L 526 70 L 518 70" marker-end="url(#os-c6-arr-8)"/>
    <rect class="fig-box-blue" x="30" y="48" width="136" height="44" rx="5"/>
    <rect class="fig-box-blue" x="186" y="48" width="152" height="44" rx="5"/>
    <rect class="fig-box-accent" x="88" y="120" width="192" height="58" rx="6"/>
    <rect class="fig-box-green" x="88" y="196" width="192" height="40" rx="5"/>
    <rect class="fig-box-blue" x="382" y="48" width="136" height="44" rx="5"/>
    <rect class="fig-box-purple" x="538" y="48" width="152" height="44" rx="5"/>
    <rect class="fig-box-accent" x="382" y="120" width="136" height="58" rx="6"/>
    <rect class="fig-box-orange" x="538" y="120" width="152" height="58" rx="6"/>
    <rect class="fig-box-green" x="382" y="196" width="136" height="40" rx="5"/>
    <rect class="fig-box-red" x="538" y="196" width="152" height="40" rx="5"/>
    <text class="fig-title" x="184" y="34" font-size="11.5" text-anchor="middle">硬链接（ln A D）：共享同一个 inode</text>
    <text class="fig-blue" x="98" y="67" font-size="10.5" text-anchor="middle">目录项 “A”</text>
    <text class="fig-muted" x="98" y="83" font-size="9.5" text-anchor="middle">→ inode #42</text>
    <text class="fig-blue" x="262" y="67" font-size="10.5" text-anchor="middle">目录项 “D”</text>
    <text class="fig-muted" x="262" y="83" font-size="9.5" text-anchor="middle">→ inode #42</text>
    <text class="fig-accent" x="184" y="143" font-size="11" text-anchor="middle">inode #42（i_links = 2）</text>
    <text class="fig-muted" x="184" y="162" font-size="9.5" text-anchor="middle">A 与 D 完全平等，删一仅计数 -1</text>
    <text class="fig-green" x="184" y="214" font-size="10.5" text-anchor="middle">唯一的数据块集合</text>
    <text class="fig-muted" x="184" y="229" font-size="9" text-anchor="middle">计数归 0 且无打开时才回收</text>
    <text class="fig-title" x="536" y="34" font-size="11.5" text-anchor="middle">软链接（ln -s A L）：独立文件存路径</text>
    <text class="fig-blue" x="450" y="67" font-size="10.5" text-anchor="middle">目录项 “A”</text>
    <text class="fig-muted" x="450" y="83" font-size="9.5" text-anchor="middle">→ inode #42</text>
    <text class="fig-purple" x="614" y="67" font-size="10.5" text-anchor="middle">目录项 “L”</text>
    <text class="fig-muted" x="614" y="83" font-size="9.5" text-anchor="middle">→ inode #99（新）</text>
    <text class="fig-accent" x="450" y="143" font-size="10.5" text-anchor="middle">inode #42</text>
    <text class="fig-muted" x="450" y="162" font-size="9.5" text-anchor="middle">i_links = 1（不变！）</text>
    <text class="fig-orange" x="614" y="143" font-size="10.5" text-anchor="middle">inode #99 (link)</text>
    <text class="fig-muted" x="614" y="162" font-size="9.5" text-anchor="middle">自身独立计数 = 1</text>
    <text class="fig-green" x="450" y="220" font-size="10" text-anchor="middle">A 的实际数据块</text>
    <text class="fig-red" x="614" y="213" font-size="10" text-anchor="middle">存路径 “/dir/A”</text>
    <text class="fig-muted" x="614" y="229" font-size="9" text-anchor="middle">删 A 后成悬空断链</text>
    <text class="fig-accent" x="28" y="286" font-size="10.5">★ 09#31 / 17#31 / 21#30 真题必会：硬链接禁止跨区与链目录，0 额外 I/O；两进程开硬链接仍各有独立读写指针！</text>
    <text class="fig-label" x="28" y="305" font-size="10">软链接允许跨文件系统与链目录，删原文件内核不管快捷方式（留断链），访问多花 1+2m 次 I/O（快速符号链省 1 次）。</text>
  </svg>
  <figcaption>图 6-8　硬链接与软链接的底层存储结构、引用计数演化及跨文件系统/断链行为对照</figcaption>
</figure>

---

### 6.5 文件的物理结构（外存分配方式）★★

#### 6.5.1 三大分配路线的分歧与两条统一评判准则

文件的物理结构（外存分配方式）解决的核心问题是：**如何把逻辑结构输出的“第 $i$ 个逻辑块”映射成磁盘上的“物理盘块号”**（块内偏移只需通过 `字节偏移 mod 块大小` 即可算出，真正困难的是块号映射）。

> **★考点（统领物理结构全部优缺点的核心逻辑）**：
> 三种外存分配方式的全部分歧，仅仅在于“**把逻辑块号 $\mapsto$ 物理块号这张映射表存在哪里？**”：
> 1. 存在**目录项**里（只放得下起点与长度，于是强制文件物理上必须连着放） $\implies$ **连续分配**；
> 2. 存在**数据块自己内部**（每块尾留一个下一块指针） $\implies$ **隐式链接分配**；
> 3. **抽出来集中存储**：全盘合建一张常驻内存总表 $\implies$ **显式链接分配（FAT）**；每个文件自建一张小表 $\implies$ **索引分配**。
>
> 由此立刻推导出两项统一判别标准：
> - **支不支持随机存取**：看“**能不能不先读前序数据块就算出第 $i$ 块的物理块号**”。连续分配（加法直算）、FAT（查常驻内存表）、索引分配（读索引块得全部块号）均支持；**只有隐式链接不支持**！
> - **有没有外部碎片**：看“**分配时是否要求物理盘块连成一片**”。**只有连续分配有外部碎片**（与之同源的缺点是必须预知长度、增长要整体搬家）；链接与索引按单块离散分配，均无外部碎片。**注意：内部碎片四种分配方式全都有！**

#### 6.5.2 连续分配

连续分配为每个文件分配一组**物理上相邻的连续磁盘块**，目录项只需保存 `(起始块号, 文件块数)`。访问第 $i$ 个逻辑块时直接由公式 $\text{物理块号} = \text{起始块号} + i$ 算出，只需 1 次访盘即可取回数据。

- **优点**：① 支持顺序存取与**随机存取**；② **顺序访问速度在所有物理结构中最快**（连续盘块通常位于同一磁道或相邻磁道上，磁头寻道移动距离最小）。
- **缺点**：① **产生外部碎片**（空闲总块数足够，但被反复建立与删除打断成多个不连续小洞，无法满足大文件的连续请求；根治唯有代价极其高昂的磁盘紧凑整理）；② 建立文件前必须预知文件长度；③ 极不利于动态增长（一旦后续相邻块已被占用，文件追加或中间插入就必须整体搬家至更大连续区）。
- **★ 真题经典场景（13#24、11#46）**：对于 **CD-ROM 只读光盘**或**一次写入不可修改的介质**，文件大小天生确定且不存在动态扩展与删除碎片化，因此**连续分配反而是最优选择**（扬其磁头零跳转的极速优势、避其不可扩展的唯一短板）！

#### 6.5.3 链接分配：隐式链接 vs 显式链接（FAT）

1. **隐式链接分配**：
   每个文件是一个离散盘块构成的链表，目录项记录 `(起始块号, 结束块号)`，并在**每个数据块的末尾保留若干字节存放下一物理块号指针**（末块指针置 `-1` 或 `null`）。
   - **优点**：彻底消除外部碎片，文件可随时动态扩展，创建时无需预知文件长度。
   - **缺点**：① **只能顺序存取，绝不支持随机存取**（要读第 $i$ 逻辑块，必须从首块开始依次读盘 $i + 1$ 次才能顺藤摸瓜拿到地址）；② 块内指针占用数据空间，且**破坏了每块可用数据容量为 $2^k$ 字节的幂对齐**（使得字节偏移除以可用字节数无法用移位实现）；③ 可靠性差，链路中任一指针损坏会导致后续全部块失联。

2. **显式链接分配（FAT，File Allocation Table）**：
   把全盘所有盘块的 `next` 指针从数据块内部全部抽取出来，集中做成全盘唯一的**文件分配表（FAT）**，**系统开机后将 FAT 常驻内存**；目录项仅需记录文件**起始块号**，数据块恢复纯净的 $2^k$ 字节可用空间。
   - **随机存取恢复（16#47 真题给分点）**：按文件名查目录拿到起始块号后，沿**常驻内存的 FAT 表**顺链跳转查出第 $i$ 逻辑块对应的物理块号，**找块号过程完全不产生磁盘 I/O**，拿到物理块号后只需 1 次读盘！
   - **双功能**：FAT 既描述已用文件块的链式归属，也可以通过特殊标记值（如 `0` 或 `-2`）标识未分配盘块，因此 **FAT 同时具备管理外存空闲空间的能力**（19#26、25#31 真题考点）。
   - **★ 容量瓶颈量化算例**：FAT 是“**全盘每个盘块对应 1 项**”的全局数组，大小仅由磁盘总块数决定（与文件数无关）。设磁盘容量为 $1\text{ TB}$、盘块 $4\text{ KB}$、每个 FAT 表项占 $4\text{ B}$：总块数 $= 2^{40} / 2^{12} = 2^{28}$ 块（$256\text{ M}$ 块），则 **FAT 表占内存 $2^{28} \times 4\text{ B} = 1\text{ GB}$**！正因为 FAT 随容量线性暴涨而难以常驻内存，大容量 FAT32 分区被迫将簇（块）调大（如 $32\text{ KB}$，表缩至 $128\text{ MB}$），代价是小文件的**内部碎片**急剧恶化。

<figure class="cpd-figure not-content" id="os-c6-fig-9">
  <svg viewBox="0 0 720 344" role="img" aria-label="连续分配、隐式链接与显式链接 FAT 表物理结构及寻址路径对比">
    <defs>
      <marker id="os-c6-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="688" height="96" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="122" width="688" height="96" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="228" width="688" height="100" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="178" y1="176" x2="206" y2="176" marker-end="url(#os-c6-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="342" y1="176" x2="374" y2="176" marker-end="url(#os-c6-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="510" y1="176" x2="542" y2="176" marker-end="url(#os-c6-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="178" y1="284" x2="206" y2="284" marker-end="url(#os-c6-arr-9)"/>
    <rect class="fig-box-blue" x="28" y="42" width="150" height="58" rx="5"/>
    <rect class="fig-box" x="208" y="44" width="484" height="54" rx="5"/>
    <rect class="fig-box-blue" x="276" y="44" width="224" height="54" rx="2"/>
    <line class="fig-divider" x1="332" y1="44" x2="332" y2="98"/>
    <line class="fig-divider" x1="388" y1="44" x2="388" y2="98"/>
    <line class="fig-divider" x1="444" y1="44" x2="444" y2="98"/>
    <rect class="fig-box-orange" x="28" y="148" width="150" height="58" rx="5"/>
    <rect class="fig-box-orange" x="208" y="148" width="134" height="56" rx="5"/>
    <line class="fig-divider" x1="298" y1="148" x2="298" y2="204"/>
    <rect class="fig-box-orange" x="376" y="148" width="134" height="56" rx="5"/>
    <line class="fig-divider" x1="466" y1="148" x2="466" y2="204"/>
    <rect class="fig-box-orange" x="544" y="148" width="146" height="56" rx="5"/>
    <line class="fig-divider" x1="636" y1="148" x2="636" y2="204"/>
    <rect class="fig-box-green" x="28" y="254" width="150" height="60" rx="5"/>
    <rect class="fig-box-accent" x="208" y="252" width="268" height="66" rx="5"/>
    <rect class="fig-box" x="492" y="252" width="198" height="66" rx="5"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 178 55 L 274 55" marker-end="url(#os-c6-arr-9)"/>
    <text class="fig-title" x="28" y="34" font-size="11">① 连续分配（Sequential）：第 i 块 = 起始块 + i，支持随机，顺序读最快，但有外部碎片</text>
    <text class="fig-blue" x="103" y="64" font-size="10.5" text-anchor="middle">目录项 data.txt</text>
    <text class="fig-muted" x="103" y="84" font-size="9.5" text-anchor="middle">首块: 5 | 长度: 4</text>
    <text class="fig-muted" x="242" y="75" font-size="10" text-anchor="middle">空洞 1..4</text>
    <text class="fig-blue" x="304" y="67" font-size="10" text-anchor="middle">块 5</text>
    <text class="fig-muted" x="304" y="84" font-size="9" text-anchor="middle">(逻辑 0)</text>
    <text class="fig-blue" x="360" y="67" font-size="10" text-anchor="middle">块 6</text>
    <text class="fig-muted" x="360" y="84" font-size="9" text-anchor="middle">(逻辑 1)</text>
    <text class="fig-blue" x="416" y="67" font-size="10" text-anchor="middle">块 7</text>
    <text class="fig-muted" x="416" y="84" font-size="9" text-anchor="middle">(逻辑 2)</text>
    <text class="fig-blue" x="472" y="67" font-size="10" text-anchor="middle">块 8</text>
    <text class="fig-muted" x="472" y="84" font-size="9" text-anchor="middle">(逻辑 3)</text>
    <text class="fig-muted" x="596" y="67" font-size="10" text-anchor="middle">块 9..12（空洞/外部碎片）</text>
    <text class="fig-muted" x="596" y="84" font-size="9.2" text-anchor="middle">只读介质(CD-ROM)最适用</text>
    <text class="fig-title" x="28" y="140" font-size="11">② 隐式链接（Implicit）：指针嵌入块尾，无外部碎片，只能顺序存取（读第 i 块需读盘 i+1 次）</text>
    <text class="fig-orange" x="103" y="170" font-size="10.5" text-anchor="middle">目录项 log.txt</text>
    <text class="fig-muted" x="103" y="190" font-size="9.5" text-anchor="middle">首块: 2 | 尾块: 10</text>
    <text class="fig-label" x="253" y="172" font-size="10" text-anchor="middle">块 2 数据</text>
    <text class="fig-muted" x="253" y="190" font-size="9" text-anchor="middle">(非 2^k 字节)</text>
    <text class="fig-orange" x="320" y="180" font-size="10.5" text-anchor="middle">→ 5</text>
    <text class="fig-label" x="421" y="172" font-size="10" text-anchor="middle">块 5 数据</text>
    <text class="fig-muted" x="421" y="190" font-size="9" text-anchor="middle">(逻辑块 1)</text>
    <text class="fig-orange" x="488" y="180" font-size="10.5" text-anchor="middle">→ 10</text>
    <text class="fig-label" x="590" y="172" font-size="10" text-anchor="middle">块 10 数据</text>
    <text class="fig-muted" x="590" y="190" font-size="9" text-anchor="middle">(逻辑块 2)</text>
    <text class="fig-red" x="663" y="180" font-size="10" text-anchor="middle">-1 结束</text>
    <text class="fig-title" x="28" y="245" font-size="11">③ 显式链接（FAT 文件分配表）：指针抽离并常驻内存，0 盘 I/O 跳链实现随机存取 ★</text>
    <text class="fig-green" x="103" y="276" font-size="10.5" text-anchor="middle">目录项 f1</text>
    <text class="fig-muted" x="103" y="296" font-size="9.5" text-anchor="middle">首块号: 2</text>
    <text class="fig-accent" x="342" y="268" font-size="10.5" text-anchor="middle">常驻内存 FAT 表（每盘块 1 项）</text>
    <text class="fig-label" x="342" y="287" font-size="10" text-anchor="middle">0:[空闲]  1:[空闲]  2:[→5]  5:[→10]</text>
    <text class="fig-muted" x="342" y="306" font-size="9.5" text-anchor="middle">10:[-1 结束]  （顺链查找不访盘！）</text>
    <text class="fig-label" x="500" y="271" font-size="9.2">• 恢复 2^k 数据块且无外部碎片</text>
    <text class="fig-label" x="500" y="289" font-size="9.2">• 兼作空闲块管理（空闲写标记）</text>
    <text class="fig-red" x="500" y="307" font-size="9.2">• 瓶颈：1 TB/4 KB 盘 FAT 占 1 GB</text>
  </svg>
  <figcaption>图 6-9　连续分配、隐式链接与显式链接（FAT）物理结构及寻址 I/O 代价对比</figcaption>
</figure>

#### 6.5.4 索引分配与 UNIX 混合索引经典计算 ★★

FAT 最大的缺陷是它为**全盘每一块**建表（不论是否空闲或归属哪个文件），容量一大便再也塞不进内存。**索引分配**（Indexed Allocation）借鉴内存页表的思路：**只为当前正在打开的文件建立索引**——每个文件配备专门的**索引块（Index Block）**，按逻辑块号 $0, 1, 2, \dots$ 顺序记录所分配的全部物理盘块号，支持随机存取、无外部碎片、易于动态扩展。

然而，若一个只有 1 KB 的极小文件也分配一个 4 KB 的独立索引块（共占 2 块即 8 KB，空间利用率跌至 $12.5\%$），固定一块的元数据开销太大；而超大文件一个索引块又装不下，于是衍生出三种大文件索引扩展方案：

1. **链接索引**：多个索引块串成链表（尾项指下一索引块）。空间最省，但访问第 $i$ 块最坏需沿链读入 $\lceil i / k \rceil$ 个索引块，**随机访问性能随文件增大而线性退化**。
2. **多级索引（如二级、三级索引）**：类似多级页表，顶级索引块指向次级索引块。设每块大小为 $B$、块号宽 $S_{\text{ptr}}$，则单个索引块的扇出度为 $k = \lfloor B / S_{\text{ptr}} \rfloor$，$L$ 级索引最大可寻址 $k^L \times B$ 字节（例：$B = 4\text{ KB}, S_{\text{ptr}} = 4\text{ B} \implies k = 1024$，一级 $4\text{ MB}$、二级 $4\text{ GB}$、三级 $4\text{ TB}$）。缺陷是**小文件也必须走满 $L$ 级索引（惩罚小文件读写速度）**。
3. **混合索引（增量式索引 — UNIX / Linux 方案）★★**：结合直接地址与多级间接地址，在 inode 中同时布置 **直接地址项 + 一次间接 + 二次间接 + 三次间接**。“**为最常见的小文件省去全部索引块（0 索引块、仅 1 次读盘），为罕见的特大文件兜底**。”

<figure class="cpd-figure not-content" id="os-c6-fig-10">
  <svg viewBox="0 0 720 356" role="img" aria-label="大文件三种索引方案对比及 UNIX 混合索引 10 直接加 123 级间接架构图">
    <defs>
      <marker id="os-c6-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="236" height="164" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="190" width="236" height="150" rx="8"/>
    <rect class="fig-box-subtle" x="268" y="16" width="436" height="324" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="412" y1="78" x2="554" y2="78" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="412" y1="138" x2="438" y2="138" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="534" y1="138" x2="554" y2="138" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="412" y1="198" x2="438" y2="198" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="534" y1="186" x2="554" y2="186" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="620" y1="200" x2="620" y2="210" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="412" y1="276" x2="436" y2="276" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="490" y1="276" x2="508" y2="276" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="562" y1="264" x2="582" y2="264" marker-end="url(#os-c6-arr-10)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" x1="636" y1="280" x2="636" y2="294" marker-end="url(#os-c6-arr-10)"/>
    <rect class="fig-box-blue" x="28" y="42" width="212" height="40" rx="5"/>
    <rect class="fig-box-orange" x="28" y="88" width="212" height="40" rx="5"/>
    <rect class="fig-box-green" x="28" y="134" width="212" height="38" rx="5"/>
    <rect class="fig-box" x="28" y="216" width="212" height="114" rx="5"/>
    <rect class="fig-box-green" x="284" y="52" width="128" height="52" rx="5"/>
    <rect class="fig-box-blue" x="284" y="114" width="128" height="48" rx="5"/>
    <rect class="fig-box-orange" x="284" y="172" width="128" height="56" rx="5"/>
    <rect class="fig-box-purple" x="284" y="238" width="128" height="86" rx="5"/>
    <rect class="fig-box-green" x="556" y="54" width="134" height="48" rx="5"/>
    <rect class="fig-box-blue" x="440" y="116" width="94" height="44" rx="5"/>
    <rect class="fig-box-blue" x="556" y="116" width="134" height="44" rx="5"/>
    <rect class="fig-box-orange" x="440" y="176" width="94" height="48" rx="5"/>
    <rect class="fig-box-orange" x="556" y="172" width="134" height="28" rx="4"/>
    <rect class="fig-box" x="556" y="212" width="134" height="24" rx="4"/>
    <rect class="fig-box-purple" x="438" y="252" width="52" height="48" rx="5"/>
    <rect class="fig-box-purple" x="510" y="252" width="52" height="48" rx="5"/>
    <rect class="fig-box-purple" x="584" y="248" width="106" height="32" rx="4"/>
    <rect class="fig-box" x="584" y="296" width="106" height="28" rx="4"/>
    <text class="fig-title" x="134" y="34" font-size="11.5" text-anchor="middle">大文件三种索引方式对比</text>
    <text class="fig-blue" x="38" y="59" font-size="10">① 链接索引（索引块串联）</text>
    <text class="fig-muted" x="38" y="75" font-size="9.5">最省，但最坏读 ceil(i/k) 块（慢）</text>
    <text class="fig-orange" x="38" y="105" font-size="10">② 多级索引（固定 L 级）</text>
    <text class="fig-muted" x="38" y="121" font-size="9.5">最大 k^L 块，但惩罚小文件（走满L级）</text>
    <text class="fig-green" x="38" y="150" font-size="10">③ 混合索引（UNIX/Linux）★</text>
    <text class="fig-muted" x="38" y="165" font-size="9.5">小文件免索引块，大文件逐级扩展</text>
    <text class="fig-title" x="134" y="208" font-size="11" text-anchor="middle">★ 访问某块磁盘 I/O 次数通则</text>
    <text class="fig-accent" x="38" y="236" font-size="10">假设：目标 inode 已在内存</text>
    <text class="fig-green" x="38" y="256" font-size="10">• 直接地址块：1 次（仅数据块）</text>
    <text class="fig-blue" x="38" y="274" font-size="10">• 一次间接块：2 次（1 索引+1 数）</text>
    <text class="fig-orange" x="38" y="292" font-size="10">• 二次间接块：3 次（2 索引+1 数）</text>
    <text class="fig-purple" x="38" y="310" font-size="10">• 三次间接块：4 次（3 索引+1 数）</text>
    <text class="fig-red" x="38" y="325" font-size="9.5">★ 若 inode 尚在磁盘：全部 +1 次！</text>
    <text class="fig-title" x="486" y="36" font-size="10.4" text-anchor="middle">UNIX System V 混合索引结构（13 个地址项，设 B=4KB, ptr=4B → k=1024）</text>
    <text class="fig-green" x="348" y="74" font-size="10.5" text-anchor="middle">addr[0..9]</text>
    <text class="fig-muted" x="348" y="92" font-size="9.5" text-anchor="middle">10 个直接地址项</text>
    <text class="fig-green" x="623" y="75" font-size="10.5" text-anchor="middle">直达 10 个数据块</text>
    <text class="fig-muted" x="623" y="92" font-size="9.5" text-anchor="middle">10 × 4 KB = 40 KB</text>
    <text class="fig-blue" x="348" y="135" font-size="10.5" text-anchor="middle">addr[10]</text>
    <text class="fig-muted" x="348" y="152" font-size="9.5" text-anchor="middle">一次间接地址项</text>
    <text class="fig-blue" x="487" y="135" font-size="10" text-anchor="middle">一级索引块</text>
    <text class="fig-muted" x="487" y="151" font-size="9.2" text-anchor="middle">存 1024 个块号</text>
    <text class="fig-blue" x="623" y="135" font-size="10" text-anchor="middle">1024 个数据块</text>
    <text class="fig-muted" x="623" y="151" font-size="9.2" text-anchor="middle">1024 × 4 KB = 4 MB</text>
    <text class="fig-orange" x="348" y="196" font-size="10.5" text-anchor="middle">addr[11]</text>
    <text class="fig-muted" x="348" y="214" font-size="9.5" text-anchor="middle">二次间接地址项</text>
    <text class="fig-orange" x="487" y="196" font-size="10" text-anchor="middle">一级索引块</text>
    <text class="fig-muted" x="487" y="213" font-size="9.2" text-anchor="middle">指 1024 二级块</text>
    <text class="fig-orange" x="623" y="190" font-size="9.8" text-anchor="middle">二级索引块 × 1024</text>
    <text class="fig-label" x="623" y="228" font-size="9.8" text-anchor="middle">1024² 块 = 4 GB</text>
    <text class="fig-purple" x="348" y="276" font-size="10.5" text-anchor="middle">addr[12]</text>
    <text class="fig-muted" x="348" y="294" font-size="9.5" text-anchor="middle">三次间接地址项</text>
    <text class="fig-purple" x="464" y="274" font-size="10" text-anchor="middle">一级</text>
    <text class="fig-muted" x="464" y="290" font-size="9" text-anchor="middle">索引</text>
    <text class="fig-purple" x="536" y="274" font-size="10" text-anchor="middle">二级</text>
    <text class="fig-muted" x="536" y="290" font-size="9" text-anchor="middle">×1024</text>
    <text class="fig-purple" x="637" y="268" font-size="9.8" text-anchor="middle">三级索引 ×1024²</text>
    <text class="fig-label" x="637" y="314" font-size="9.8" text-anchor="middle">1024³ 块 = 4 TB</text>
  </svg>
  <figcaption>图 6-10　大文件索引扩展对比、UNIX 混合索引四级扇出架构及无缓存读盘 I/O 次数通则</figcaption>
</figure>

> **★考点（混合索引五大经典步骤——10#30、15#29、18#46、22#45、26#46 年年必会！）**：
> 设盘块大小 $B$、块号宽度 $S_{\text{ptr}}$、直接地址项 $d$ 个、一次/二次/三次间接各 $1$ 个，按以下五步稳拿满分：
> 1. **算扇出度 $k$**：$k = \lfloor B / S_{\text{ptr}} \rfloor$（千万不要死背 $1024$ 或 $256$，$B$ 与 $S_{\text{ptr}}$ 一改全变！）。
> 2. **逐段算容量**：直接段 $= d \cdot B$；一次间接 $= k \cdot B$；二次间接 $= k^2 \cdot B$；三次间接 $= k^3 \cdot B$。
> 3. **★ 求最大文件大小 = 四部分相加之和**：$\text{MaxSize} = (d + k + k^2 + k^3) \cdot B$（**四部分寻址的是互不重叠的区间，漏加前三项必扣分！**）。此外注意题目给定的直接项数是 $d$（可能是 $8$、$10$ 或 $12$）。
> 4. **排累计阈值，定位字节偏移归属**：一次间接的起点是直接段的终点 $d \cdot B$（而非 $0$！），二次间接的起点是 $(d + k) \cdot B$。先算累计阈值再比对目标字节偏移，才能准确判定落在第几级。
> 5. **数 I/O 次数**：inode 已在内存时，直接/一次/二次/三次分别需要 **$1, 2, 3, 4$ 次**磁盘 I/O；若 inode 未在内存需全部 **$+1$**；若题目问连续读取跨多个块，中间已读入的索引块可复用不必重复读盘。
>
> **综合大题衍生提问（12#46、14#46、16#47、26#46）**：
> - “目录项最少占多少字节？” $\implies \text{文件名最大字节数} + \lceil \frac{\lceil \log_2(\text{总盘块数}) \rceil}{8} \rceil$（磁盘块号至少需要 $\lceil \log_2(\text{总块数}) \rceil$ 位，并向上取整至整字节！）。
> - “把混合索引改回隐式/连续，插入记录需多少次 I/O？” $\implies$ 按前后盘块搬迁或改指针数逐步累加（注意读取和写回各算一次盘 I/O）。

<figure class="cpd-figure not-content" id="os-c6-fig-11">
  <svg viewBox="0 0 720 318" role="img" aria-label="混合索引五步计算算例：累计阈值定位 3 MB 偏移与 3 次读盘 I/O 拆解">
    <defs>
      <marker id="os-c6-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-accent" x="16" y="16" width="688" height="42" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="166" width="688" height="136" rx="8"/>
    <line class="fig-line-accent" x1="154" y1="224" x2="192" y2="224" marker-end="url(#os-c6-arr-11)"/>
    <line class="fig-line-accent" x1="330" y1="224" x2="368" y2="224" marker-end="url(#os-c6-arr-11)"/>
    <line class="fig-line-accent" x1="506" y1="224" x2="544" y2="224" marker-end="url(#os-c6-arr-11)"/>
    <rect class="fig-box-green" x="16" y="72" width="144" height="78" rx="6"/>
    <rect class="fig-box-blue" x="170" y="72" width="166" height="78" rx="6"/>
    <rect class="fig-box-orange" x="346" y="72" width="186" height="78" rx="6"/>
    <rect class="fig-box-purple" x="542" y="72" width="162" height="78" rx="6"/>
    <rect class="fig-box" x="30" y="198" width="124" height="52" rx="5"/>
    <rect class="fig-box-orange" x="194" y="198" width="136" height="52" rx="5"/>
    <rect class="fig-box-orange" x="370" y="198" width="136" height="52" rx="5"/>
    <rect class="fig-box-green" x="546" y="198" width="142" height="52" rx="5"/>
    <text class="fig-accent" x="360" y="41" font-size="11" text-anchor="middle">算例：块 B = 2 KB | 块号 4 B → 扇出 k = 512 | 地址项：8 直接 + 1 一级 + 1 二级 + 1 三级</text>
    <text class="fig-green" x="88" y="92" font-size="10.5" text-anchor="middle">① 直接段 (8 块)</text>
    <text class="fig-label" x="88" y="112" font-size="10" text-anchor="middle">容量 = 16 KB</text>
    <text class="fig-muted" x="88" y="132" font-size="9.5" text-anchor="middle">累计 [0, 16 KB)</text>
    <text class="fig-blue" x="253" y="92" font-size="10.5" text-anchor="middle">② 一次间接 (512 块)</text>
    <text class="fig-label" x="253" y="112" font-size="10" text-anchor="middle">容量 = 1 MB</text>
    <text class="fig-muted" x="253" y="132" font-size="9.5" text-anchor="middle">累计 [16 KB, 1.016 MB)</text>
    <text class="fig-orange" x="439" y="92" font-size="10.5" text-anchor="middle">③ 二次间接 (512² 块) ★</text>
    <text class="fig-label" x="439" y="112" font-size="10" text-anchor="middle">容量 = 512 MB</text>
    <text class="fig-orange" x="439" y="132" font-size="9.5" text-anchor="middle">累计 [1.016, 513.02 MB)</text>
    <text class="fig-purple" x="623" y="92" font-size="10.5" text-anchor="middle">④ 三次间接 (512³ 块)</text>
    <text class="fig-label" x="623" y="112" font-size="10" text-anchor="middle">容量 = 256 GB</text>
    <text class="fig-purple" x="623" y="132" font-size="8.6" text-anchor="middle">总和 = 256GB+513MB+16KB</text>
    <text class="fig-title" x="360" y="185" font-size="11.5" text-anchor="middle">访问偏移 3 MB（= 3,145,728 B &gt; 1.016 MB → 命中二次间接）磁盘 I/O 追踪</text>
    <text class="fig-label" x="92" y="220" font-size="10.5" text-anchor="middle">内存 inode</text>
    <text class="fig-muted" x="92" y="238" font-size="9.5" text-anchor="middle">取 addr[9] (0 次)</text>
    <text class="fig-orange" x="262" y="220" font-size="10.5" text-anchor="middle">读一级索引块</text>
    <text class="fig-label" x="262" y="238" font-size="9.5" text-anchor="middle">第 1 次盘 I/O</text>
    <text class="fig-orange" x="438" y="220" font-size="10.5" text-anchor="middle">读二级索引块</text>
    <text class="fig-label" x="438" y="238" font-size="9.5" text-anchor="middle">第 2 次盘 I/O</text>
    <text class="fig-green" x="617" y="220" font-size="10.5" text-anchor="middle">读目标数据块</text>
    <text class="fig-accent" x="617" y="238" font-size="9.5" text-anchor="middle">第 3 次盘 I/O (共 3 次)</text>
    <text class="fig-red" x="360" y="271" font-size="10" text-anchor="middle">★ 两大致命失分坑：1) 最大文件长度是【四部分相加】，漏加前 3 段必扣分；</text>
    <text class="fig-label" x="360" y="290" font-size="10" text-anchor="middle">2) 必须先算“累计区间起点”再比较偏移（一次间接始于直接段末尾，而非 0！）。</text>
  </svg>
  <figcaption>图 6-11　混合索引“算扇出 → 算各段 → 四部分求和 → 排累计区间 → 数 I/O 次数”标准五步计算流程</figcaption>
</figure>

---

### 6.6 外存空闲空间管理 ★

#### 6.6.1 按粒度分层的五大管理方法与合法结构判定

每当需要为文件新分配物理块或删除文件释放空间时，系统必须知道“磁盘上哪些盘块目前空闲”。该管理结构在**高级格式化**（逻辑格式化）时建立，按描述粒度可分为四类主流方法（外加 FAT 兼管）：

| 管理方法 | 描述粒度与存储形式 | 空间开销特性 | 均摊分配盘 I/O | 查找连续空闲块 | 典型适用场景 |
| --- | --- | --- | --- | --- | --- |
| **空闲表法** | 按**段**：`(起始块号, 空闲块数)` 线性表 | 随碎片增多而浮动 | 常驻内存则 0 次 | **容易** | **连续分配**、对换区（Swap） |
| **空闲盘块链** | 按**块**：指针寄存在空闲块内部串成链 | 0 额外存储区开销 | **1 次/块（最慢）** | 极难 | 小型离散分配（现已少用） |
| **空闲盘区链** | 按**段**：首块含 `(区长度, 下一区指针)` | 0 额外存储区开销 | 1 次拿到一整段 | 较容易 | 离散分配与段合并 |
| **位示图法** | 按**块**：每块占 **1 bit**，二维位矩阵 | **$N / 8$ B（与剩余量无关！）** | 常驻内存则 0 次 | **最容易**（位扫描） | 通用微机/现代系统（按块组切分） |
| **成组链接法** | **分组栈**：组内数组寄存在上组首块 + 内存栈 | 0 额外存储区开销 | 约 $1/\text{组大小}$ 次 | 难 | **UNIX / 大型文件系统** |

> **★考点（19#26、25#31 真题结论）**：**哪些数据结构可用于管理空闲磁盘块？**
> - **可以**：**位图（位示图）**、**空闲磁盘块链**、**FAT 表**（为全盘每一块建项，空闲项写入特定标记即可）、空闲表、成组链接法。
> - **不可以**：**索引节点（inode）**——inode 描述的是“**某个具体文件占用了哪些物理块**”，无法回答“磁盘上哪些块处于空闲状态”。

#### 6.6.2 空闲表法、空闲链表法与位示图双向换算 ★

1. **空闲表法**：适合连续分配。分配时采用类似内存动态分区分配的**首次适应**或**循环首次适应**算法；回收时若回收区与空闲表相邻前驱或后继空闲区接壤，**必须合并**成一条表项。
2. **空闲链表法**：分为**空闲盘块链**（节点粒度为 1 个盘块，指针直接写在空闲块内部，分配 $k$ 块要从链头逐个读盘 $k$ 次，I/O 极慢）与**空闲盘区链**（节点粒度为连续空闲段，首块写本段盘块数及下一盘区指针，分配与回收也做合并）。
3. **位示图法（Bitmap）★**：
   用二进制的一位对应一个盘块（如 `0` 表示空闲、`1` 表示已用；**也有教材规定恰好相反！**）。
   - **唯一性质（24#26 真题）**：若全盘总块数为 $N$，则位示图固定占 $N$ bit $= N / 8$ 字节，**它是唯一“占用空间大小仅由磁盘容量决定、与当前已用或剩余空闲块数量完全无关”的方法**（无论盘是全空还是全满，位示图尺寸丝毫不变）。
   - **经典真题套路**：
     - **算位图占几个簇/盘块（14#27）**：`总簇数 = 分区容量 ÷ 簇大小` $\to$ `位图字节数 = 总簇数 ÷ 8` $\to$ **别忘了最后再除以簇大小得出“占几个簇”**！（如 10 GB / 4 KB 或 $2^{33}\text{ B}/4\text{ KB}$ 等均按此三步换算）。
     - **非 0 号块起始定位（15#31）**：若题干给定“位示图存放在 32～127 号盘块（盘块与块内字节均从 0 起编）”，释放块号 $b$ 时先算全局字节号 $\lfloor b/8 \rfloor$ $\to$ 除以每块字节数得相对块号和块内字节偏移 $\to$ **切记加上起始块号 32**！

> **★考点（位示图二维坐标双向换算与“前三确认”）**：
> 做位示图坐标计算题前，**务必逐一核对题干三项约定**：① **块号从 0 还是从 1 起？** ② **行号与列号从 0 还是从 1 起？** ③ **0 和 1 谁代表空闲？**
> 设位示图每行有 $n$ 位（字长 $n$ 位），行号 $i$、列号 $j$、盘块号 $b$：
> - **全部从 0 起编号**：
> $$
> i = \left\lfloor \frac{b}{n} \right\rfloor, \quad j = b \bmod n \quad \Longleftrightarrow \quad b = i \times n + j
> $$
> - **全部从 1 起编号（如汤小丹教材约定）**：先减 1 映射回 0 起坐标系，算完各自加 1：
> $$
> i = \left\lfloor \frac{b - 1}{n} \right\rfloor + 1, \quad j = (b - 1) \bmod n + 1 \quad \Longleftrightarrow \quad b = n \times (i - 1) + j
> $$
> （验算：8 字 $\times$ 32 位，全从 1 起，归还块号 $b=100$ $\implies$ $i = \lfloor 99/32 \rfloor + 1 = 4$，$j = (99 \bmod 32) + 1 = 4$，即第 4 行第 4 列。）

<figure class="cpd-figure not-content" id="os-c6-fig-12">
  <svg viewBox="0 0 720 340" role="img" aria-label="空闲表法、空闲盘块/盘区链、FAT 兼管及位示图法与坐标换算对比">
    <defs>
      <marker id="os-c6-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="218" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="246" y="16" width="228" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="486" y="16" width="218" height="148" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="176" width="688" height="148" rx="8"/>
    <line class="fig-line-accent" x1="290" y1="68" x2="318" y2="68" marker-end="url(#os-c6-arr-12)"/>
    <line class="fig-line-accent" x1="366" y1="68" x2="394" y2="68" marker-end="url(#os-c6-arr-12)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="296" y1="118" x2="324" y2="118" marker-end="url(#os-c6-arr-12)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="408" y1="118" x2="432" y2="118" marker-end="url(#os-c6-arr-12)"/>
    <rect class="fig-box-blue" x="28" y="42" width="194" height="84" rx="5"/>
    <rect class="fig-box-orange" x="256" y="54" width="34" height="28" rx="4"/>
    <rect class="fig-box-orange" x="320" y="54" width="46" height="28" rx="4"/>
    <rect class="fig-box-orange" x="396" y="54" width="46" height="28" rx="4"/>
    <rect class="fig-box-green" x="256" y="102" width="40" height="30" rx="4"/>
    <rect class="fig-box-green" x="326" y="102" width="82" height="30" rx="4"/>
    <rect class="fig-box" x="434" y="102" width="30" height="30" rx="4"/>
    <rect class="fig-box-accent" x="498" y="42" width="194" height="84" rx="5"/>
    <rect class="fig-box-blue" x="30" y="204" width="256" height="106" rx="5"/>
    <rect class="fig-box" x="302" y="204" width="388" height="106" rx="5"/>
    <text class="fig-title" x="125" y="34" font-size="11.5" text-anchor="middle">① 空闲表法（配连续分配）</text>
    <text class="fig-blue" x="125" y="60" font-size="10" text-anchor="middle">序号  | 起始块号 | 块数</text>
    <text class="fig-label" x="125" y="79" font-size="10" text-anchor="middle">1     |    2     |   5</text>
    <text class="fig-label" x="125" y="97" font-size="10" text-anchor="middle">2     |   15     |   3</text>
    <text class="fig-label" x="125" y="115" font-size="10" text-anchor="middle">3     |   25     |   8</text>
    <text class="fig-muted" x="125" y="146" font-size="9.5" text-anchor="middle">首次适应分配，回收须合并相邻区</text>
    <text class="fig-title" x="360" y="34" font-size="11.5" text-anchor="middle">② 空闲盘块链 vs 空闲盘区链</text>
    <text class="fig-orange" x="273" y="72" font-size="9.5" text-anchor="middle">链头</text>
    <text class="fig-orange" x="343" y="72" font-size="9.5" text-anchor="middle">块 3</text>
    <text class="fig-orange" x="419" y="72" font-size="9.5" text-anchor="middle">块 7</text>
    <text class="fig-muted" x="458" y="72" font-size="9" text-anchor="middle">…</text>
    <text class="fig-muted" x="360" y="95" font-size="9" text-anchor="middle">盘块链：走一步读 1 次盘（最慢）</text>
    <text class="fig-green" x="276" y="121" font-size="9.5" text-anchor="middle">区头</text>
    <text class="fig-green" x="367" y="121" font-size="9.5" text-anchor="middle">[块2, 5块]</text>
    <text class="fig-muted" x="449" y="121" font-size="8.2" text-anchor="middle">null</text>
    <text class="fig-muted" x="360" y="150" font-size="9.2" text-anchor="middle">盘区链：以连续段作节点，少读盘</text>
    <text class="fig-title" x="595" y="34" font-size="11.5" text-anchor="middle">③ 空闲管理合法结构判定</text>
    <text class="fig-accent" x="595" y="62" font-size="10.2" text-anchor="middle">可管理空闲块（19#26 / 25#31）：</text>
    <text class="fig-green" x="595" y="82" font-size="10" text-anchor="middle">✓ 位示图  ✓ 空闲链表  ✓ FAT</text>
    <text class="fig-red" x="595" y="102" font-size="10" text-anchor="middle">✗ 索引节点 inode 不能！</text>
    <text class="fig-muted" x="595" y="118" font-size="9" text-anchor="middle">（inode 只记某文件占了哪些块）</text>
    <text class="fig-muted" x="595" y="148" font-size="9.5" text-anchor="middle">FAT 用特定表项值标识盘块空闲</text>
    <text class="fig-title" x="360" y="194" font-size="11.5" text-anchor="middle">④ 位示图法（Bitmap）：★ 唯一空间占用仅与磁盘容量有关、与空闲块数无关的方法（24#26）</text>
    <text class="fig-blue" x="158" y="224" font-size="10" text-anchor="middle">字/列 →   0   1   2   3   4   5   6   7</text>
    <text class="fig-label" x="158" y="244" font-size="10" text-anchor="middle">行 0 :   1   1   0   0   1   1   1   1</text>
    <text class="fig-label" x="158" y="264" font-size="10" text-anchor="middle">行 1 :   0   0   1   1   0   1   0   0</text>
    <text class="fig-muted" x="158" y="285" font-size="9.5" text-anchor="middle">（0=空闲, 1=已用；部分题规定相反）</text>
    <text class="fig-accent" x="158" y="302" font-size="9.5" text-anchor="middle">固定大小 = N bit = N/8 字节</text>
    <text class="fig-red" x="312" y="224" font-size="9.2">★ 算前必确认：块号起点(0/1)？行列起点(0/1)？0/1 谁空闲？</text>
    <text class="fig-label" x="312" y="246" font-size="9.2">• 全 0 起：i = ⌊b/n⌋,  j = b mod n     ⟺  b = i·n + j</text>
    <text class="fig-label" x="312" y="268" font-size="9.2">• 全 1 起：i = ⌊(b-1)/n⌋+1, j = (b-1)%n+1 ⟺ b = n(i-1)+j</text>
    <text class="fig-muted" x="312" y="290" font-size="9.2">• 真题提醒：位图占几簇勿忘 ÷ 簇大小；非 0 起步须 + 起始块号！</text>
  </svg>
  <figcaption>图 6-12　空闲表法、空闲链表法、FAT 兼管及位示图法坐标双向换算对比</figcaption>
</figure>

#### 6.6.3 UNIX 成组链接法（Grouping-Linking）分配与回收全步骤 ★

在大型文件系统中，空闲表和空闲盘块链都会变得极其冗长，而全盘位示图在 TB 级磁盘上也达到数十 MB 难以全量常驻。**UNIX 成组链接法**巧妙结合了“表”的成批性与“链”的轻量性——仅让**当前第一组**（称为**空闲盘块号栈**）常驻**内存超级块**，其余各组空闲块号均寄存在前一组某块空闲盘块内，实现**平时 0 次盘 I/O、零额外空间占用**！

以汤小丹教材经典参数（每组最多 **100 个**空闲块号）为例，其静态拓扑如下：
- 内存超级块中维护空闲盘块号栈 `S.free[0..99]` 以及空闲盘块数计数器 **`N`**（`N` 兼作栈顶指针：栈顶元素永远是 `S.free[N - 1]`，栈底元素固定为 `S.free[0]`）。
- **每组首块的双重身份**：当前组（即内存栈）的栈底 `S.free[0]` 指向的那块空闲块（如 201 号块）里，提前写好了**下一组**全部 100 个空闲块号（301～400）和计数 `100`；同理下一组首块（301 号块）写着再下一组，直到**倒数第二组首块中把最末一组（仅 99 块）登记完毕，并将其 `S.free[0]` 置为 `0` 作为全链结束哨兵**。

> **★考点（成组链接法两大临界操作的严格时序——切勿颠倒！）**：
> - **常态分配（$N > 1$）**：直接从内存超级块栈弹出 `S.free[N - 1]` 分配给用户，并令 `N--`（**0 次磁盘 I/O**）。
> - **★ 临界分配（栈空临界，即 $N == 1$ 只剩栈底）**：此时 `S.free[0]` 对应的盘块存有下一组全部空闲块清单，**绝不能直接将其分配出去**！
>   1. **第一步（1 次读盘）**：检查非结束标志 `0` 后，读取栈底 `S.free[0]` 盘块的内容，将下一组的计数与所有空闲块号复制进内存空闲盘块号栈；
>   2. **第二步**：再把原栈底对应的那个盘块本身分配给请求者。
>   （**逆序灾难**：若先分配再读盘，用户写数据会立刻覆盖原栈底盘块里的清单，导致后面成千上万个空闲块全部丢失！）
> - **常态回收（$N < 100$）**：将被回收的盘块号直接压入内存栈顶 `S.free[N] = 块号`，令 `N++`（**0 次磁盘 I/O**）。
> - **★ 临界回收（栈满临界，即 $N == 100$ 满栈时再回收块 $X$）**：
>   1. **第一步（1 次写盘）**：将当前内存栈里已满的 `N = 100` 及 100 个盘块号全部写入**刚被回收、内容已无用的空闲块 $X$** 中；
>   2. **第二步**：清空内存栈，令 **`S.free[0] = X`**、**`N = 1`**（使块 $X$ 成为新的栈底兼下一组清单索引块）。

<figure class="cpd-figure not-content" id="os-c6-fig-13">
  <svg viewBox="0 0 720 356" role="img" aria-label="UNIX 成组链接法分组栈拓扑结构与栈空分配和栈满回收临界状态转移">
    <defs>
      <marker id="os-c6-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="688" height="168" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="196" width="336" height="144" rx="8"/>
    <rect class="fig-box-subtle" x="368" y="196" width="336" height="144" rx="8"/>
    <line class="fig-line-accent" x1="180" y1="146" x2="218" y2="146" marker-end="url(#os-c6-arr-13)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="364" y1="146" x2="402" y2="146" marker-end="url(#os-c6-arr-13)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="540" y1="146" x2="574" y2="146" marker-end="url(#os-c6-arr-13)"/>
    <rect class="fig-box-accent" x="30" y="46" width="150" height="124" rx="6"/>
    <rect class="fig-box-green" x="220" y="46" width="144" height="124" rx="6"/>
    <rect class="fig-box-blue" x="404" y="46" width="136" height="124" rx="6"/>
    <rect class="fig-box" x="576" y="46" width="114" height="124" rx="6"/>
    <rect class="fig-box-orange" x="30" y="224" width="308" height="48" rx="5"/>
    <rect class="fig-box-green" x="30" y="280" width="308" height="48" rx="5"/>
    <rect class="fig-box-purple" x="382" y="224" width="308" height="48" rx="5"/>
    <rect class="fig-box-blue" x="382" y="280" width="308" height="48" rx="5"/>
    <text class="fig-title" x="360" y="34" font-size="11.5" text-anchor="middle">UNIX 成组链接法结构（设每组 100 块；超级块栈驻内存，其余组寄存在前一组首块中）</text>
    <text class="fig-accent" x="105" y="65" font-size="10.5" text-anchor="middle">内存超级块空闲栈</text>
    <text class="fig-label" x="105" y="84" font-size="9.8" text-anchor="middle">N = 100（兼栈顶指针）</text>
    <text class="fig-muted" x="105" y="102" font-size="9.5" text-anchor="middle">S.free[99] = 300 (栈顶)</text>
    <text class="fig-muted" x="105" y="120" font-size="9.5" text-anchor="middle">S.free[98] = 299 …</text>
    <text class="fig-red" x="105" y="152" font-size="10" text-anchor="middle">S.free[0] = 201 (栈底)</text>
    <text class="fig-green" x="292" y="65" font-size="10.5" text-anchor="middle">第 1 组：201～300</text>
    <text class="fig-muted" x="292" y="86" font-size="9.5" text-anchor="middle">202～300：可用空闲块</text>
    <text class="fig-muted" x="292" y="106" font-size="9.5" text-anchor="middle">（出栈直接分配 0 I/O）</text>
    <text class="fig-accent" x="292" y="138" font-size="9.8" text-anchor="middle">块 201（存下一组清单）</text>
    <text class="fig-label" x="292" y="155" font-size="9.5" text-anchor="middle">N=100 | 301～400</text>
    <text class="fig-blue" x="472" y="65" font-size="10.5" text-anchor="middle">第 2 组：301～400</text>
    <text class="fig-muted" x="472" y="92" font-size="9.5" text-anchor="middle">302～400：可用空闲块</text>
    <text class="fig-accent" x="472" y="138" font-size="9.8" text-anchor="middle">块 301（存下下组）</text>
    <text class="fig-label" x="472" y="155" font-size="9.5" text-anchor="middle">N=100 | 401～500</text>
    <text class="fig-label" x="633" y="65" font-size="10.5" text-anchor="middle">最末一组</text>
    <text class="fig-muted" x="633" y="88" font-size="9.5" text-anchor="middle">倒数第 2 组首块</text>
    <text class="fig-muted" x="633" y="106" font-size="9.5" text-anchor="middle">仅含 99 个可用块</text>
    <text class="fig-red" x="633" y="138" font-size="10" text-anchor="middle">S.free[0] = 0</text>
    <text class="fig-muted" x="633" y="155" font-size="9.2" text-anchor="middle">（0 作结束哨兵）</text>
    <text class="fig-title" x="184" y="214" font-size="11" text-anchor="middle">★ 临界 1：栈空分配（只剩 N=1 栈底 201）</text>
    <text class="fig-orange" x="42" y="244" font-size="10">① 先读盘块 201 进内存栈（1 次读盘）</text>
    <text class="fig-muted" x="42" y="261" font-size="9.5">将 301～400 与 N=100 装填到超级块空闲栈</text>
    <text class="fig-green" x="42" y="300" font-size="10">② 再把原栈底块 201 本身分配给用户</text>
    <text class="fig-red" x="42" y="317" font-size="9.5">顺序绝不可反！否则覆写 201 丢失全链</text>
    <text class="fig-title" x="536" y="214" font-size="11" text-anchor="middle">★ 临界 2：栈满回收（N=100 时回收块 X）</text>
    <text class="fig-purple" x="394" y="244" font-size="10">① 先把当前满栈 100 块号写入块 X（1 次写盘）</text>
    <text class="fig-muted" x="394" y="261" font-size="9.5">利用刚变空闲的无用盘块 X 保存原整组清单</text>
    <text class="fig-blue" x="394" y="300" font-size="10">② 清空超级块栈，置 N = 1, S.free[0] = X</text>
    <text class="fig-muted" x="394" y="317" font-size="9.5">X 成为新栈底；平时非临界操作 0 次盘 I/O！</text>
  </svg>
  <figcaption>图 6-13　UNIX 成组链接法结构与“栈空分配先读后分 / 栈满回收先写后置底”临界转移过程</figcaption>
</figure>

---

### 6.7 文件保护

#### 6.7.1 访问类型与访问控制矩阵的两类切分：ACL vs 能力表

多用户共用同一个文件系统时，必须阻止未授权的偷窥、篡改或误删。文件系统通常支持的访问操作包括：**读**（Read）、**写**（Write）、**执行**（Execute）、**追加**（Append）、**删除**（Delete）与**列目录/读属性**（List）。

概念上，“哪个用户对哪个文件允许做哪种操作”天然构成一张二维**访问控制矩阵（Access Control Matrix）**：**行表示用户（或域），列表示文件对象**。但在实际工程中，该矩阵规模是用户数与文件数的乘积（例如 $1000 \times 10^6 = 10^9$ 格）且**极度稀疏**，无法整张保存，只能压缩存储非空项。切分非空项的唯一两种方向决定了两大访问控制模型：

| 比较维度 | 访问控制列表（ACL，按**列**切） | 能力表（Capability List，按**行**切） |
| --- | --- | --- |
| **一张表挂在谁身上** | 挂在**每个文件**的 FCB / inode 中 | 挂在**每个用户 / 进程**身上 |
| **实际存储位置** | 该文件 FCB 或 inode 内的扩展区域 | **内核系统专区**（严禁用户进程直接修改，防自我越权） |
| **回答“谁能访问文件 X”** | **一步直达**（读文件 $X$ 的 inode 即得） | 极慢（必须扫描全系统所有用户的能力表） |
| **回答“用户 A 能访问哪些文件”** | 极慢（必须扫描全盘所有文件的 ACL） | **一步直达** |
| **撤销某文件的全部授权** | **极方便**（改该文件一处 ACL 即可） | 极难（须逐一清除所有相关用户的能力项） |
| **撤销某用户的全部权限** | 极难（须扫描全盘清除该用户） | **极方便**（直接清空该用户能力表） |

> **注意**：现代主流操作系统往往将两者**串联并用**——进程首次访问某文件时，内核检查该文件的 **ACL** 完成完整授权验证，通过后为该进程生成一个轻量级的**能力凭证**（如打开文件描述符 `fd` 中记录本次 `open` 模式）挂到进程表上；后续 `read`/`write` 只需核对进程持有的能力凭证即可快速放行，兼顾**集中撤销的便利性**与**高频访问的高效性**。

#### 6.7.2 UNIX 9-bit 权限模型、目录 `rwx` 语义反转与位串位数计算 ★

完整 ACL 长度不定且检查开销偏大，UNIX/Linux 对访问控制矩阵做出了极端精简的工程妥协：不再逐一枚举具体用户，而是将用户压缩归纳为三大类别——**文件主（`owner`/`u`）**、**同组用户（`group`/`g`）**、**其他用户（`others`/`o`）**，每类仅赋予 **读（`r`）、写（`w`）、执行（`x`）** 3 个比特位，合计正好 **$3 \times 3 = 9\text{ bit}$**（例如 `rwxr-xr--` 对应八进制 `754`）。这 9 个比特以**定长字段直接嵌入 inode 的 `i_mode`** 中，读取 inode 时顺带进内存，权限校验零额外磁盘 I/O；其代价则是**无法只对某一个特定外组用户单独授权**（若需精细到单人授权，仍须另挂扩展 ACL）。

**★ 极易反直觉的目录 `rwx` 语义反转**：由于目录的内容是一张 `(文件名, inode 号)` 的表，“执行一个目录”没有意义，因此 `rwx` 作用于目录文件时含义发生彻底变化：

| 权限位 | 作用于**普通文件** | 作用于**目录文件** | 反直觉推论 |
| --- | --- | --- | --- |
| **`r`（读）** | 读取文件正文内容 | **列出目录内有哪些文件名**（如 `ls`） | 只有 `r` 没有 `x` 时，能看见名字却打不开任何内部文件 |
| **`w`（写）** | 修改或截断文件正文内容 | **增删或重命名该目录内的目录项** | **★ 删除文件的决定权在“所在目录的 `w` 权限”，不在文件自身权限！** |
| **`x`（执行）** | 将程序装入内存执行 | **穿越权 / 搜索权**（允许路径解析经过该目录） | 只有 `x` 没有 `r` 时，知道确切名字即可读写内部文件但列不出清单；**中间任一级目录缺 `x`，其下所有子目录和文件全部不可达！** |

> **★考点（17#30 真题必会：权限位串计算通式）**：
> 当使用定长二进制位串存储“若干类用户 $\times$ 若干种操作”的权限组合时，由于每一类用户针对每一种操作都需要独立回答“允许/禁止（1 bit）”，所需的最少二进制位数为纯粹的**乘法组合**：
> $$
> \text{所需最少位数} = \text{用户类别数} \times \text{访问权限种类数}
> $$
> 真题例（17#30）：4 类用户（安全管理员、文件主、文件主的伙伴、其他用户）$\times$ 5 种权限（完全控制、执行、修改、读取、写入）$= 4 \times 5 = 20$ 位（切勿算成加法 $4+5=9$ 或漏算用户类别！）。

<figure class="cpd-figure not-content" id="os-c6-fig-14">
  <svg viewBox="0 0 720 340" role="img" aria-label="访问控制矩阵按列切 ACL 与按行切能力表、UNIX 9-bit 权限及目录 rwx 语义反转">
    <rect class="fig-box-subtle" x="16" y="16" width="212" height="168" rx="8"/>
    <rect class="fig-box-subtle" x="244" y="16" width="222" height="168" rx="8"/>
    <rect class="fig-box-subtle" x="482" y="16" width="222" height="168" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="196" width="326" height="130" rx="8"/>
    <rect class="fig-box-subtle" x="356" y="196" width="348" height="130" rx="8"/>
    <rect class="fig-box" x="28" y="42" width="188" height="92" rx="5"/>
    <rect class="fig-box-blue" x="256" y="42" width="198" height="72" rx="5"/>
    <rect class="fig-box" x="256" y="122" width="198" height="50" rx="5"/>
    <rect class="fig-box-purple" x="494" y="42" width="198" height="72" rx="5"/>
    <rect class="fig-box" x="494" y="122" width="198" height="50" rx="5"/>
    <rect class="fig-box-accent" x="28" y="220" width="96" height="42" rx="5"/>
    <rect class="fig-box-green" x="131" y="220" width="96" height="42" rx="5"/>
    <rect class="fig-box-orange" x="234" y="220" width="96" height="42" rx="5"/>
    <rect class="fig-box" x="368" y="220" width="324" height="94" rx="5"/>
    <line class="fig-divider" x1="36" y1="67" x2="208" y2="67"/>
    <line class="fig-divider" x1="80" y1="48" x2="80" y2="126"/>
    <text class="fig-title" x="122" y="34" font-size="11" text-anchor="middle">访问控制矩阵 M[用户][文件]</text>
    <g text-anchor="middle" font-size="9.8">
      <text class="fig-accent" x="104" y="61">F1</text>
      <text class="fig-accent" x="144" y="61">F2</text>
      <text class="fig-accent" x="184" y="61">F3</text>
      <text class="fig-accent" x="54" y="81">U_A</text>
      <text class="fig-label" x="104" y="81">RW</text>
      <text class="fig-label" x="144" y="81">R</text>
      <text class="fig-muted" x="184" y="81">-</text>
      <text class="fig-accent" x="54" y="100">U_B</text>
      <text class="fig-label" x="104" y="100">R</text>
      <text class="fig-label" x="144" y="100">RWX</text>
      <text class="fig-label" x="184" y="100">RW</text>
      <text class="fig-accent" x="54" y="119">U_C</text>
      <text class="fig-muted" x="104" y="119">-</text>
      <text class="fig-label" x="144" y="119">R</text>
      <text class="fig-label" x="184" y="119">R</text>
    </g>
    <text class="fig-muted" x="122" y="152" font-size="9.5" text-anchor="middle">乘积规模 u×f 巨大且极度稀疏</text>
    <text class="fig-muted" x="122" y="170" font-size="9.5" text-anchor="middle">实际无法整张存，只存非空部分</text>
    <text class="fig-title" x="355" y="34" font-size="11" text-anchor="middle">按列切 → ACL（挂在文件上）</text>
    <text class="fig-blue" x="262" y="60" font-size="9.8">存 FCB / inode 中：</text>
    <text class="fig-label" x="262" y="79" font-size="9">F1: [(U_A,RW), (U_B,R)]</text>
    <text class="fig-label" x="262" y="98" font-size="9">F2: [(U_A,R), (U_B,RWX), (U_C,R)]</text>
    <text class="fig-label" x="262" y="140" font-size="9.5">✓ 按文件查与撤销授权：一步</text>
    <text class="fig-muted" x="262" y="159" font-size="9.5">✗ 按用户查全部文件：扫全盘</text>
    <text class="fig-title" x="593" y="34" font-size="11" text-anchor="middle">按行切 → 能力表（挂在用户上）</text>
    <text class="fig-purple" x="500" y="60" font-size="9.8">存内核专区（防用户自改）：</text>
    <text class="fig-label" x="500" y="79" font-size="9">U_A: [(F1,RW), (F2,R)]</text>
    <text class="fig-label" x="500" y="98" font-size="9">U_B: [(F1,R), (F2,RWX), (F3,RW)]</text>
    <text class="fig-label" x="504" y="140" font-size="9.8">✓ 按用户查与撤销权限：一步</text>
    <text class="fig-muted" x="504" y="159" font-size="9.8">✗ 按文件撤销全部授权：扫全用户</text>
    <text class="fig-title" x="179" y="213" font-size="11" text-anchor="middle">UNIX 9-bit 权限与位串计算通式</text>
    <text class="fig-accent" x="76" y="238" font-size="10.2" text-anchor="middle">owner (u)</text>
    <text class="fig-muted" x="76" y="254" font-size="9.5" text-anchor="middle">rwx (7)</text>
    <text class="fig-green" x="179" y="238" font-size="10.2" text-anchor="middle">group (g)</text>
    <text class="fig-muted" x="179" y="254" font-size="9.5" text-anchor="middle">r-x (5)</text>
    <text class="fig-orange" x="282" y="238" font-size="10.2" text-anchor="middle">others (o)</text>
    <text class="fig-muted" x="282" y="254" font-size="9.5" text-anchor="middle">r-- (4)</text>
    <text class="fig-accent" x="28" y="286" font-size="10">★ 位数 = 用户类别数 × 权限种类数 (17#30)</text>
    <text class="fig-muted" x="28" y="308" font-size="9.8">口令(存 FCB)易截获；唯有【加密】拆盘绕过 OS 仍有效</text>
    <text class="fig-title" x="530" y="213" font-size="11" text-anchor="middle">★ 目录文件的 rwx 语义完全不同于普通文件</text>
    <text class="fig-label" x="380" y="241" font-size="10">• r：读目录名字清单 (ls)；w：增删改目录项</text>
    <text class="fig-label" x="380" y="261" font-size="10">• x：穿越/搜索权（缺任一级目录 x，其下全不可达）</text>
    <text class="fig-red" x="380" y="282" font-size="10">• 反直觉推论：删文件看【所在目录的 w】，非文件自身！</text>
    <text class="fig-muted" x="380" y="302" font-size="9.8">• 有 r 无 x：能列名字却进不去；有 x 无 r：盲猜名可访问</text>
  </svg>
  <figcaption>图 6-14　访问控制矩阵按列/按行切分模型、UNIX 9-bit 定长权限及目录 rwx 语义反转</figcaption>
</figure>

#### 6.7.3 口令保护与加密保护

**口令保护**在文件或目录 FCB 中存放口令，在访问入口验证；优点是实现简单、时空开销极低，缺点是口令泄露即全盘失守。**加密保护**则直接用密钥对文件正文进行加解密变换。必须明白：**访问控制列表、UNIX 权限位和口令保护全部建立在“操作系统本身可信且请求必经内核”的前提之上**；一旦攻击者拆下硬盘挂接到其他机器上或取得超级管理员权限，唯有**文件加密**依然能够死守数据的机密性（代价是每次 I/O 的加解密算力开销及密钥管理风险）。

---

### 6.8 文件系统的全局布局、虚拟文件系统（VFS）与挂载 ★

#### 6.8.1 磁盘物理分区布局与文件系统的外存/内存结构

将一块全新的物理裸磁盘投入使用，必须严格经历以下四个步骤（**17#29 真题核心顺序**）：
1. **低级格式化（物理格式化）**：在硬件层面划分磁道与扇区（写入扇区头、数据区与 **ECC 校验码**，确定校验码位数）。
2. **磁盘分区**：将整块盘划分为若干逻辑分区（如 C 盘、D 盘、Swap 交换区），并在盘首写入 **MBR（主引导记录，含 446 B 引导代码 + 64 B 分区表）** 或 GPT 分区表。**注意：MBR 在整块硬盘只有一份，它不认识任何文件系统，只负责选出活动分区并移交控制权。**
3. **高级格式化（逻辑格式化）**：在**各个独立分区内部**构建文件系统。**★ 17#29 真题考点**：磁盘逻辑格式化程序负责① 生成分区引导记录 **PBR（引导块）**；② 初始化**超级块（Superblock）**；③ **初始化保存空闲磁盘块信息的数据结构**（如块位图、inode 位图）；④ 初始化 inode 区并**建立文件系统的根目录**（含 `.` 与 `..`）。
4. **挂载使用**：将分区内的文件系统接入操作系统的全局目录树。

**外存分区内部结构的排序铁律**：“越是启动和解析时必须最先读到的元信息，就越靠前、且处于固定的偏移位置”——引导块（Boot Block / PBR） $\to$ **超级块（Superblock，存储文件系统魔数、块大小、总块数、空闲块/inode 计数、inode 区起点及根目录 inode 号；它一旦损坏整个分区即瘫痪，故实际系统通常在各块组留存多份备份）** $\to$ 空闲空间管理区（位图等） $\to$ **inode 表区（格式化时固定总数量）** $\to$ 根目录与数据块区域。

与外存结构对应，系统在**内存中**维护五大核心运行时结构以加速日常访问：
- **内存超级块**：文件系统被**挂载**时读入，运行时直接改写，**卸载**（`umount`）时写回磁盘；每个已挂载分区一份。
- **内存 inode 表**：文件第一次 `open` 时由磁盘调入，记忆 `i_count`、脏位、锁；引用计数归 0 且无脏数据后释放。
- **系统打开文件表**与**进程打开文件表**（见 6.2.2 节）。
- **目录项缓存（dentry cache）**：在路径解析经过某一目录分量时顺手将该 `(父目录, 名字) -> inode` 映射缓存在内存，**它是五大结构中唯一纯粹源自磁盘已有信息的只读副本，因此在内存紧张时可随时安全丢弃**（按 LRU 等策略淘汰）。

> **★考点（25#32 真题万能判别法：功能到底归谁？）**：
> 判断某项功能“是否由文件系统为机械硬盘（HDD）和固态硬盘（SSD）共同提供”，只需问一句：“**这件事是否跟具体的底层物理存储介质有关？**”
> - **与硬件强相关的，一概不归文件系统**：划分扇区（归低级格式化/控制器）、降低磁头寻道时间（归 I/O 层的磁盘调度算法，且 SSD 根本无寻道）、实现均衡磨损（归 SSD 内部控制器的 FTL 闪存翻译层，机械盘不需要）。
> - **与硬件完全无关的，才归文件系统**：**确定盘块 / 簇（Cluster）大小**——盘块是文件系统定义的逻辑分配单位，同一块 HDD 或 SSD 在格式化时均可由文件系统自由设定为 1 KB / 4 KB / 8 KB。
> - **提升文件访问速度的四大合法优化（18#31 真题）**：**提前读（预读）**、**为文件分配连续的簇（减少寻道）**、**延迟写（合并写入并延迟落盘）**、**采用磁盘高速缓存（页缓存）**——全部有效！

<figure class="cpd-figure not-content" id="os-c6-fig-15">
  <svg viewBox="0 0 720 356" role="img" aria-label="磁盘整盘 MBR 分区布局、单分区文件系统外存布局与内存五大结构及功能归属">
    <defs>
      <marker id="os-c6-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="688" height="86" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="114" width="688" height="104" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="230" width="400" height="110" rx="8"/>
    <rect class="fig-box-subtle" x="430" y="230" width="274" height="110" rx="8"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-accent)" x1="176" y1="88" x2="28" y2="114"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-accent)" x1="354" y1="88" x2="690" y2="114"/>
    <rect class="fig-box-orange" x="28" y="44" width="136" height="44" rx="5"/>
    <rect class="fig-box-accent" x="176" y="44" width="178" height="44" rx="5"/>
    <rect class="fig-box-blue" x="366" y="44" width="178" height="44" rx="5"/>
    <rect class="fig-box" x="556" y="44" width="134" height="44" rx="5"/>
    <rect class="fig-box-orange" x="28" y="144" width="110" height="60" rx="5"/>
    <rect class="fig-box-red" x="148" y="144" width="136" height="60" rx="5"/>
    <rect class="fig-box-green" x="294" y="144" width="122" height="60" rx="5"/>
    <rect class="fig-box-blue" x="426" y="144" width="122" height="60" rx="5"/>
    <rect class="fig-box-purple" x="558" y="144" width="134" height="60" rx="5"/>
    <rect class="fig-box" x="28" y="254" width="376" height="74" rx="5"/>
    <rect class="fig-box-green" x="442" y="254" width="250" height="74" rx="5"/>
    <text class="fig-title" x="360" y="34" font-size="11.5" text-anchor="middle">整块磁盘布局（制盘顺序：低格划扇区 → 分区 → 高格建根目录与空闲表 → 挂载）</text>
    <text class="fig-orange" x="96" y="63" font-size="10.5" text-anchor="middle">MBR 主引导记录</text>
    <text class="fig-muted" x="96" y="79" font-size="9" text-anchor="middle">全盘唯一(446+64+2B)</text>
    <text class="fig-accent" x="265" y="63" font-size="10.5" text-anchor="middle">分区 1（文件系统 1）</text>
    <text class="fig-muted" x="265" y="79" font-size="9" text-anchor="middle">逻辑格式化独立建立</text>
    <text class="fig-blue" x="455" y="63" font-size="10.5" text-anchor="middle">分区 2（文件系统 2）</text>
    <text class="fig-muted" x="455" y="79" font-size="9" text-anchor="middle">各分区 inode 互不干涉</text>
    <text class="fig-label" x="623" y="63" font-size="10.5" text-anchor="middle">对换区 Swap</text>
    <text class="fig-muted" x="623" y="79" font-size="9" text-anchor="middle">常采用连续分配</text>
    <text class="fig-title" x="360" y="134" font-size="11" text-anchor="middle">单个文件系统分区外存结构（“越须最先读取的越靠前且位置约定固定”）</text>
    <text class="fig-orange" x="83" y="166" font-size="10.5" text-anchor="middle">引导块 PBR</text>
    <text class="fig-muted" x="83" y="183" font-size="9.2" text-anchor="middle">每分区 1 个</text>
    <text class="fig-muted" x="83" y="197" font-size="9.2" text-anchor="middle">引导本分区 OS</text>
    <text class="fig-red" x="216" y="166" font-size="10.5" text-anchor="middle">超级块 Superblock</text>
    <text class="fig-muted" x="216" y="183" font-size="9.2" text-anchor="middle">块大小/总数/根入口</text>
    <text class="fig-muted" x="216" y="197" font-size="9.2" text-anchor="middle">坏则全废(多副本)</text>
    <text class="fig-green" x="355" y="166" font-size="10.5" text-anchor="middle">空闲管理区</text>
    <text class="fig-muted" x="355" y="183" font-size="9.2" text-anchor="middle">数据块位图 /</text>
    <text class="fig-muted" x="355" y="197" font-size="9.2" text-anchor="middle">inode 位图</text>
    <text class="fig-blue" x="487" y="166" font-size="10.5" text-anchor="middle">inode 表区</text>
    <text class="fig-muted" x="487" y="183" font-size="9.2" text-anchor="middle">定长数组</text>
    <text class="fig-muted" x="487" y="197" font-size="9.2" text-anchor="middle">总量高格时固定</text>
    <text class="fig-purple" x="625" y="166" font-size="10.5" text-anchor="middle">根目录与数据区</text>
    <text class="fig-muted" x="625" y="183" font-size="9.2" text-anchor="middle">存放目录与正文块</text>
    <text class="fig-muted" x="625" y="197" font-size="9.2" text-anchor="middle">占分区绝大部分</text>
    <text class="fig-title" x="216" y="247" font-size="11" text-anchor="middle">内存五大运行时数据结构（开机/打开重建）</text>
    <text class="fig-label" x="38" y="272" font-size="9.8">① 内存超级块(挂载建)  ② 内存 inode 表(open 建)</text>
    <text class="fig-label" x="38" y="292" font-size="9.8">③ 系统打开文件表       ④ 进程描述符表</text>
    <text class="fig-accent" x="38" y="312" font-size="9.8">⑤ dentry 缓存（纯内存只读缓存，随时可丢弃！）</text>
    <text class="fig-title" x="567" y="247" font-size="11" text-anchor="middle">★ 硬件无关性判断 (25#32)</text>
    <text class="fig-green" x="452" y="272" font-size="10">✓ 确定盘块大小：归文件系统</text>
    <text class="fig-red" x="452" y="292" font-size="9.8">✗ 划扇区：硬件；降寻道：调度</text>
    <text class="fig-red" x="452" y="312" font-size="9.8">✗ 均衡磨损：SSD 控制器 FTL</text>
  </svg>
  <figcaption>图 6-15　整盘分区与单文件系统外存物理布局、内存五大缓存结构及文件系统硬件无关性边界</figcaption>
</figure>

#### 6.8.2 虚拟文件系统（VFS）与 `vnode` 接口抽象 ★

现代操作系统需要同时挂载截然不同的存储设备：系统盘可能是 `ext4`（混合索引 + 磁盘 inode）、U 盘可能是 `FAT32`（显式 FAT 表，压根没有磁盘 inode 号与硬链接）、光盘是只读的 `ISO 9660`、远程网络目录则是 `NFS`（数据根本不在本机）。但用户进程调用的是**同一套 POSIX 标准系统调用**（`open()`、`read()`、`write()`）。

为此，内核引入了**虚拟文件系统（VFS，Virtual File System）**。VFS 本身**不对应任何具体物理存储设备或特定磁盘格式**，而是用 C 语言结构体中的**函数指针表**（即面向对象设计中的抽象基类与虚函数表 `vtable`）向上提供统一接口、向下制定统一驱动契约（例如规定新接入的文件系统必须实现 `struct file_operations { read, write, open, release }` 并注册进内核，VFS 自身代码一行不改即可调用 `file->f_op->read(...)`）。

VFS 在内存中维护四大核心对象，形成“整棵文件系统 $\to$ 单个文件 $\to$ 路径名称 $\to$ 一次打开”的递减从属链：
1. **超级块对象（`super_block`）**：代表一个已挂载的具体文件系统；`super_block` 与 `inode` 为 **1:n**（解释了硬链接不能跨文件系统）。
2. **索引节点对象（`inode` / `vnode`）**：代表一个文件本体；**仅存在于内存中**，包含所有文件系统共有的通用属性、一组操作函数指针，以及一个指向底层具体文件系统私有结构（如本地 `ext4_inode_info` 或远程 `rnode`）的指针。
3. **目录项对象（`dentry`）**：VFS 独创的纯内存对象（磁盘上无直接对应物），代表路径中的单个分量（抹平目录与普通文件的遍历差异，将 `(父目录, 名字) -> inode` 缓存起来实现 `dentry cache`）；`inode` 与 `dentry` 为 **1:n**（一个本体可对应多个硬链接名称）。
4. **文件对象（`file`）**：代表一次 `open()` 会话，记录当前读写偏移量 `f_pos`、访问模式与 `f_op` 虚函数表指针；`dentry` 与 `file` 为 **1:n**。

> **★考点（25#28 真题全部四个选项辨析）**：关于**虚拟文件系统（VFS）**，以下认识必须毫不含糊：
> - **✓ 正确定义**：**VFS 定义了可访问不同文件系统的统一标准接口**（屏蔽底层实现差异，支持无缝扩展新文件系统）。
> - **✗ 误解 1**：认为 VFS 是“运行在虚拟内存中的文件系统”。**错！** 这里的“虚拟”指的是**面向接口抽象、不绑定任何具体存储介质**，与虚拟内存毫无关系。
> - **✗ 误解 2**：认为 VFS 能加快文件系统的访问速度。**错！** VFS 反而多了一层函数指针间接分发调用开销，它用极小代价换取的是**兼容性与可扩展性**（而非加速）。
> - **✗ 误解 3**：认为 VFS 只能访问本地文件系统，不能访问网络文件系统。**刚好说反！** 支持跨主机访问 **NFS、SMB 等远程网络文件系统**正是 VFS 存在的核心价值之一。

<figure class="cpd-figure not-content" id="os-c6-fig-16">
  <svg viewBox="0 0 720 338" role="img" aria-label="虚拟文件系统 VFS 四大核心对象、vnode 结构与函数指针多态分发架构">
    <defs>
      <marker id="os-c6-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-accent" x="16" y="16" width="688" height="40" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="68" width="688" height="142" rx="8"/>
    <rect class="fig-box" x="16" y="294" width="688" height="30" rx="5"/>
    <line class="fig-line-accent" x1="627" y1="56" x2="627" y2="96" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" x1="170" y1="138" x2="194" y2="138" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" x1="370" y1="138" x2="394" y2="138" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" x1="538" y1="138" x2="560" y2="138" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" x1="283" y1="198" x2="283" y2="211"/>
    <line class="fig-line" x1="125" y1="211" x2="595" y2="211"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="125" y1="211" x2="125" y2="224" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="360" y1="211" x2="360" y2="224" marker-end="url(#os-c6-arr-16)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="595" y1="211" x2="595" y2="224" marker-end="url(#os-c6-arr-16)"/>
    <rect class="fig-box-blue" x="28" y="98" width="142" height="80" rx="5"/>
    <rect class="fig-box-purple" x="196" y="94" width="174" height="104" rx="5"/>
    <rect class="fig-box-green" x="396" y="98" width="142" height="80" rx="5"/>
    <rect class="fig-box-orange" x="562" y="98" width="130" height="80" rx="5"/>
    <rect class="fig-box-blue" x="16" y="226" width="218" height="58" rx="6"/>
    <rect class="fig-box-orange" x="251" y="226" width="218" height="58" rx="6"/>
    <rect class="fig-box-green" x="486" y="226" width="218" height="58" rx="6"/>
    <text class="fig-accent" x="360" y="40" font-size="11.5" text-anchor="middle">用户态进程统一标准接口（POSIX）：open() / read(fd, buf, n) / write() / close()</text>
    <text class="fig-title" x="360" y="86" font-size="11" text-anchor="middle">VFS 核心层：四大内存对象与 C 语言函数指针多态（vtable 虚表分发）</text>
    <text class="fig-blue" x="99" y="118" font-size="10.5" text-anchor="middle">super_block</text>
    <text class="fig-label" x="99" y="138" font-size="9.8" text-anchor="middle">已挂载文件系统</text>
    <text class="fig-muted" x="99" y="156" font-size="9.2" text-anchor="middle">(1:n → vnode)</text>
    <text class="fig-muted" x="99" y="170" font-size="9.2" text-anchor="middle">跨挂载不可硬链</text>
    <text class="fig-purple" x="283" y="113" font-size="10.5" text-anchor="middle">★ vnode（仅存内存）</text>
    <text class="fig-label" x="283" y="132" font-size="9.8" text-anchor="middle">通用属性 + 操作函数表</text>
    <text class="fig-accent" x="283" y="151" font-size="9.5" text-anchor="middle">f_op → 具体 read/write</text>
    <text class="fig-label" x="283" y="170" font-size="9.5" text-anchor="middle">私有指针 → 底层 inode</text>
    <text class="fig-muted" x="283" y="187" font-size="9" text-anchor="middle">(1:n → dentry)</text>
    <text class="fig-green" x="467" y="118" font-size="10.5" text-anchor="middle">dentry（纯内存）</text>
    <text class="fig-label" x="467" y="138" font-size="9.8" text-anchor="middle">路径名分量缓存</text>
    <text class="fig-muted" x="467" y="156" font-size="9.2" text-anchor="middle">抹平文件/目录</text>
    <text class="fig-muted" x="467" y="170" font-size="9.2" text-anchor="middle">(1:n → file)</text>
    <text class="fig-orange" x="627" y="118" font-size="10.5" text-anchor="middle">file（打开会话）</text>
    <text class="fig-label" x="627" y="138" font-size="9.8" text-anchor="middle">偏移 f_pos / mode</text>
    <text class="fig-muted" x="627" y="156" font-size="9.2" text-anchor="middle">调用 f_op-&gt;read</text>
    <text class="fig-muted" x="627" y="170" font-size="9.2" text-anchor="middle">open 建 / close 消</text>
    <text class="fig-blue" x="125" y="246" font-size="10.5" text-anchor="middle">ext4 本地文件系统驱动</text>
    <text class="fig-muted" x="125" y="264" font-size="9.5" text-anchor="middle">ext4_fops.read → 混合索引读盘</text>
    <text class="fig-muted" x="125" y="278" font-size="9" text-anchor="middle">（绑定本地磁盘 ext4_inode_info）</text>
    <text class="fig-orange" x="360" y="246" font-size="10.5" text-anchor="middle">FAT32 可移动盘驱动</text>
    <text class="fig-muted" x="360" y="264" font-size="9.5" text-anchor="middle">fat_fops.read → 查 FAT 簇链</text>
    <text class="fig-muted" x="360" y="278" font-size="9" text-anchor="middle">（由 VFS 动态虚构出 vnode）</text>
    <text class="fig-green" x="595" y="246" font-size="10.5" text-anchor="middle">NFS 网络文件系统驱动</text>
    <text class="fig-muted" x="595" y="264" font-size="9.5" text-anchor="middle">nfs_fops.read → 远程 RPC 报文</text>
    <text class="fig-muted" x="595" y="278" font-size="9" text-anchor="middle">（指针指向远程节点 rnode）</text>
    <text class="fig-red" x="360" y="313" font-size="10" text-anchor="middle">★ 25#28 考点：VFS 是接口层（非运行在虚存中），因间接跳转不加速，且完全支持远程 NFS 网络文件系统！</text>
  </svg>
  <figcaption>图 6-16　虚拟文件系统（VFS）四大核心对象、vnode 与底层多文件系统指针多态分发</figcaption>
</figure>

#### 6.8.3 文件系统挂载（Mount）与挂载点穿越机制

即使插上了一个包含完整超级块、目录与文件的 U 盘分区，用户依然无法从系统根目录 `/` 遍历访问它——因为**目录项里只存 inode 号，而 inode 号只是各自分区 inode 数组的下标**，系统盘目录里没有任何条目能够跨越分区直接指向 U 盘的 inode。

**文件系统挂载**（Mounting / 安装）的作用就是在统一的全局目录树上安装一个**跳板**：在内存中建立一张**挂载表（Mount Table）**，记录 `(设备标识, 挂载点目录, 文件系统类型, 超级块指针, 挂载选项)`（在 Windows 下则映射为平级的盘符 `D:`、`E:`，在 macOS 下挂载至 `/Volumes`，在 Linux 下通常挂载至 `/mnt` 或 `/media`）。

- **挂载与卸载对称动作**：
  - **挂载（`mount`）**：① 读被挂设备的超级块并按指定文件系统类型验证魔数（因此 `mount` 常须知晓文件系统类型以便选取驱动填充 VFS 超级块）；② 检查挂载点真实存在且为**目录**；③ 在内存挂载表中登记关联关系（每次系统重启须重新挂载，如读取 `/etc/fstab`）；④ 此后路径解析走到挂载点目录时，不再读它自己的数据块，而是查挂载表“**换根**”跳转到被挂文件系统的根目录继续解析。
  - **卸载（`umount`）**：① 检查是否有进程正在打开使用该文件系统（**繁忙使用中禁止卸载**）；② 将内存页缓存中尚未落盘的**延迟写脏数据全部强行写回外存**（防跨机数据不一致）；③ 移除挂载表项，挂载点恢复原状。

> **注意（挂载遮蔽效应与根自举特例）**：
> 1. **原内容被“遮蔽”而非删除**：“挂载点应为空目录”只是防止踩坑的实践建议而非语法硬限制。若非空目录上执行了挂载，原目录内的文件**既没有被删也没有释放空间**，只是暂无路径能到达而被遮蔽（`umount` 后立刻原样出现）；而且**挂载前已经打开这些被遮蔽文件的进程因持有 `fd -> 内存 inode`，在挂载期间照常读写**！
> 2. **根文件系统 `/` 如何先于路径完成首次挂载（自举循环打破）**：跟操作系统引导同理，第一次挂载根本不用路径！内核启动时直接从引导参数获知**根设备号**，调用对应驱动读超级块并将其根目录的 `dentry` 直接指派为全局目录树起点 `/`，此后所有其它分区才有挂载点路径可用。
> 3. **VFS vs 挂载表的分工**：**VFS 管“进入某个文件系统之后按哪套驱动去读写”**，**挂载表管“路径走到哪一步该切换到另一个文件系统”**。

<figure class="cpd-figure not-content" id="os-c6-fig-17">
  <svg viewBox="0 0 720 342" role="img" aria-label="多文件系统挂载表、目录树拼接换根穿越与遮蔽效应机理图">
    <defs>
      <marker id="os-c6-arr-17" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="16" width="224" height="206" rx="8"/>
    <rect class="fig-box-subtle" x="256" y="16" width="214" height="206" rx="8"/>
    <rect class="fig-box-subtle" x="486" y="16" width="218" height="206" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="234" width="688" height="92" rx="8"/>
    <line class="fig-line" x1="128" y1="68" x2="72" y2="90" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line" x1="128" y1="68" x2="180" y2="90" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-red)" x1="180" y1="122" x2="180" y2="152" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line-accent" stroke-width="1.8" x1="226" y1="106" x2="266" y2="106" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line-accent" stroke-width="1.8" x1="458" y1="106" x2="546" y2="62" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="595" y1="74" x2="595" y2="92" marker-end="url(#os-c6-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="595" y1="122" x2="595" y2="138" marker-end="url(#os-c6-arr-17)"/>
    <rect class="fig-box-blue" x="88" y="42" width="80" height="26" rx="4"/>
    <rect class="fig-box" x="30" y="92" width="84" height="30" rx="4"/>
    <rect class="fig-box-accent" x="134" y="92" width="92" height="30" rx="4"/>
    <rect class="fig-box-red" x="108" y="154" width="122" height="54" rx="5"/>
    <rect class="fig-box-accent" x="268" y="44" width="190" height="106" rx="5"/>
    <rect class="fig-box-green" x="548" y="44" width="94" height="30" rx="4"/>
    <rect class="fig-box-green" x="548" y="94" width="94" height="28" rx="4"/>
    <rect class="fig-box-green" x="548" y="140" width="94" height="28" rx="4"/>
    <rect class="fig-box-blue" x="28" y="256" width="328" height="58" rx="5"/>
    <rect class="fig-box-orange" x="368" y="256" width="324" height="58" rx="5"/>
    <text class="fig-title" x="128" y="34" font-size="11" text-anchor="middle">系统盘根文件系统（ext4）</text>
    <text class="fig-blue" x="128" y="59" font-size="10.5" text-anchor="middle">/（#2）</text>
    <text class="fig-label" x="72" y="111" font-size="10" text-anchor="middle">home/</text>
    <text class="fig-accent" x="180" y="111" font-size="10" text-anchor="middle">mnt/ (#48)</text>
    <text class="fig-red" x="169" y="172" font-size="9.8" text-anchor="middle">old.txt（被遮蔽!）</text>
    <text class="fig-muted" x="169" y="188" font-size="8.8" text-anchor="middle">未删且空间仍占，</text>
    <text class="fig-muted" x="169" y="201" font-size="8.8" text-anchor="middle">umount 后恢复可达</text>
    <text class="fig-title" x="363" y="34" font-size="11" text-anchor="middle">内存挂载表（重启须重建）</text>
    <text class="fig-accent" x="363" y="64" font-size="10" text-anchor="middle">设备：/dev/sdb1</text>
    <text class="fig-label" x="363" y="84" font-size="10" text-anchor="middle">挂载点：/mnt (#48)</text>
    <text class="fig-label" x="363" y="104" font-size="10" text-anchor="middle">类型：FAT32 | 选项：rw</text>
    <text class="fig-green" x="363" y="124" font-size="10" text-anchor="middle">超块指针：→ U 盘超级块</text>
    <text class="fig-muted" x="363" y="142" font-size="9" text-anchor="middle">（路径到 /mnt 时换根！）</text>
    <text class="fig-label" x="363" y="172" font-size="9.8" text-anchor="middle">★ 分工界线：</text>
    <text class="fig-muted" x="363" y="190" font-size="9.5" text-anchor="middle">挂载表管“何时换树”，</text>
    <text class="fig-muted" x="363" y="206" font-size="9.5" text-anchor="middle">VFS 管“进去后如何读”</text>
    <text class="fig-title" x="595" y="34" font-size="11" text-anchor="middle">被挂设备：U 盘（FAT32）</text>
    <text class="fig-green" x="595" y="63" font-size="10.2" text-anchor="middle">U 盘根 /</text>
    <text class="fig-green" x="595" y="112" font-size="10" text-anchor="middle">photos/</text>
    <text class="fig-green" x="595" y="158" font-size="10" text-anchor="middle">a.jpg</text>
    <text class="fig-muted" x="595" y="186" font-size="9.2" text-anchor="middle">未挂载前虽结构完整，</text>
    <text class="fig-muted" x="595" y="202" font-size="9.2" text-anchor="middle">但无入口可从 / 到达</text>
    <text class="fig-title" x="360" y="249" font-size="11" text-anchor="middle">★ 挂载与卸载的核心机理与边界特例</text>
    <text class="fig-blue" x="40" y="274" font-size="9.8">1. 挂载点原内容只被遮蔽：不释放空间，umount 后恢复；</text>
    <text class="fig-label" x="40" y="294" font-size="9.8">2. 挂前已打开 old.txt 的进程因持有内存 inode 照常读写！</text>
    <text class="fig-orange" x="380" y="274" font-size="9.8">3. 根文件系统 / 自举：内核按引导设备号直接挂，不靠路径；</text>
    <text class="fig-label" x="380" y="294" font-size="9.8">4. 卸载前必先检查无繁忙占用，并写回全部延迟写脏数据！</text>
  </svg>
  <figcaption>图 6-17　多文件系统挂载表结构、目录树拼接“换根”解析及挂载点遮蔽效应原理</figcaption>
</figure>

---

### 本章 408 历年高频真题索引与核心速查

| 年份题号 | 核心考查知识点 | 秒杀关键依据 |
| --- | --- | --- |
| **09#30 / 25#29** | 文件访问控制信息存放位置 / 新建文件操作 | 权限跟着本体走 $\implies$ 存在 **FCB/inode**；目录项仅存 `(文件名, inode 号)`，**绝不写权限** |
| **09#31 / 17#31 / 21#30** | 硬链接 vs 软链接计数、打开指针与删除行为 | 软链接是**独立文件**（不改目标 `i_links`，删原文件不删快捷方式）；硬链接共享同一 `inode` 但各次 `open` 读写指针仍独立 |
| **10#31 / 20#31** | 当前工作目录目的 / 目录文件数上限计算 | 工作目录省前缀解析 I/O $\implies$ **加快检索速度**；上限 $= \min(2^{8 \times \text{inode 字节}}, \; \lvert \Sigma \rvert^{\text{文件名字节}})$ |
| **14#29 / 20#23 / 23#31 / 24#29** | `open`/`close`/两级打开文件表分工 | **只有 `open` 按名查目录**且只把 **FCB/inode 读进内存**返回整数 `fd`；系统打开表仅 1 项存文件属性；`close` 归零只释放**内存 inode** |
| **13#23** | 删除文件不可能执行的操作 | 只删关联目录项（及计数归零后的 FCB/空间），**不会删除文件所在的目录本身** |
| **09#28 / 13#24 / 11#46** | 物理分配方式选型（随机扩展 / 只读介质） | 兼顾随机访问与动态扩展选**索引分配**；CD-ROM/一次写入介质（无扩张无删除碎片）选**连续分配** |
| **10#30 / 15#29 / 18#46 / 22#45 / 26#46** | UNIX 混合索引容量、偏移归属及 I/O 次数计算 | **四部分相加**算最大容量；先算**累计阈值**再比偏移；无缓存时直接/1/2/3 级分别耗时 $1/2/3/4$ 次盘 I/O（inode 未在内存 $+1$） |
| **14#46 / 16#47** | 隐式链接修改开销 / FAT 表下按名存取流程 | FAT 常驻内存故顺链跳转 **0 次磁盘 I/O**，仅目录查找与最终读数据块访盘 |
| **14#27 / 15#31 / 19#26 / 24#26 / 25#31** | 位示图空间与坐标换算 / 合法空闲管理结构 | 位示图是**唯一大小与剩余空间无关**的结构；**位图、空闲链、FAT** 可管空闲块（**inode 不行**） |
| **17#30** | 二进制权限位串最少位数计算 | $\text{所需位数} = \text{用户类别数} \times \text{访问权限种类数}$ |
| **17#29 / 18#31 / 25#28 / 25#32** | 逻辑格式化任务 / 访问加速 / VFS 概念 / HDD 与 SSD 共有功能 | 逻辑格式化建**根目录与空闲管理结构**；**延迟写/预读/高速缓存/连续簇**全加速；VFS 是**统一接口**（支持 NFS、不加速、非虚存）；**盘块大小**与硬件无关由文件系统统一提供 |

## 第7章 输入输出（I/O）与磁盘管理

> **★考点**：本章在 408 统考中与《计算机组成原理》I/O 系统高度联动，总体特点是<strong>“概念重分层边界、计算重缓冲与磁盘、大题重磁盘/驱动综合”</strong>。复习时需抓住一条底层主线：**硬件垫一层设备控制器抹平电气差异 → 软件分四层将控制姿势封装为统一调用 → 缓冲/假脱机/LUT 抹平速度与独占矛盾 → 机械盘（HDD）与固态盘（SSD）的物理特性反向决定调度与 FTL 策略**。

现代计算机中，CPU 每秒可执行数十亿条指令，内存读写在数十纳秒级，而外设不仅比 CPU 慢 **5～8 个数量级**（如键盘每秒仅几十字节、机械磁盘转一圈约数毫秒），而且**形态与语义各异**（按字符流/按数据块/按网络报文收发、顺序/随机访问）。外设本身（机械部分）与主机总线之间必须经过一层电子逻辑与多层系统软件协作，才能既保证上层编程简洁，又不浪费 CPU 算力。

### 7.1 I/O 设备、控制器与端口编址

#### 7.1.1 三级粒度与设备分类

理解 I/O 硬件体系，首先必须分清同一链路上的**三级粒度**，以及“硬件接口”与“软件接口”的边界：

1. **I/O 设备（机械部件）**：真正执行输入输出物理动作的机械/光电实体（如磁盘驱动器中的主轴、盘片、磁头臂）。广义上可统称“机械+电子”，狭义与真题语境中通常专指机械部分。
2. **设备控制器 / 适配器（电子部件）**：即硬件意义上的 **I/O 接口**（如磁盘控制器、USB 控制器、网卡），它把杂乱的外设电气信号与时序统一为若干**可寻址的寄存器**。这是软件实现“设备独立性”的**硬件前提**。
3. **I/O 端口（Port）**：设备控制器内部**可被 CPU 直接寻址和读写的寄存器**。“寄存器”与“端口”本质上是同一批硬件的两种视角——从控制器内部看是有位宽与功能的**寄存器**，从 CPU 地址空间看是有地址编号的**端口**。

> **注意**：<strong>硬件“I/O 接口”（控制器）</strong>与<strong>软件“应用程序 I/O 接口”（API）</strong>切勿混淆——前者插在主板上，后者写在头文件里；前者向 CPU 暴露寄存器端口，后者向进程暴露 `open`/`read`/`write` 系统调用。

OS 从四个正交维度对 I/O 设备分类，**四套标准各自服务于一个不同的内核决策**，同一台设备可在四个维度各取一值（例如打印机既是“人机交互设备”，又是“字符设备”，还是“独占设备”与“中低速设备”）：

| 分类维度 | 类别 | 核心特征与典型代表 | 决定的 OS 策略 |
| --- | --- | --- | --- |
| **使用特性** | 人机交互 / 存储 / 机机通信 | 键盘鼠标显示器 / 磁盘光盘 / 网卡调制解调器 | 归属哪个内核子系统管理 |
| **传输速率** | 低速 / 中速 / 高速 | 几～几百 B/s（键鼠）/ 几千～几十万 B/s（打印机）/ MB/s～GB/s（磁盘、SSD、网卡） | 选取轮询、中断还是 DMA 方式与缓冲规模 |
| **信息交换单位** | **块设备** vs **字符设备** | 块：固定大小数据块（512 B～4 KB），**可寻址、随机访问**（HDD/SSD）<br>字符：连续字符流，**不可寻址、只能顺序收发**（键盘/打印机） | 决定采用何种驱动模型、缓冲机制及**是否需要磁盘调度** |
| **共享属性** | 独占 / 共享 / 虚拟设备 | 独占：一期内仅归单进程（打印机）<br>共享：**同一时间段内**多进程交替使用，必须可寻址（磁盘）<br>虚拟：经 SPOOLing 改造后的独占设备（虚拟打印机） | 决定设备分配策略与**是否会因设备互斥引起死锁** |

> **★考点**：**块设备与字符设备的根本分界是“能不能寻址（随机访问）”，而不是传输快慢**（2026#31）。你无法对打印机发出“重打第 37 块”的指令，故打印机虽慢但属于不可寻址的字符设备；只有可寻址的块设备才谈得上磁盘调度，也因此字符设备与块设备**绝对不是同一种 I/O 方式**。另外，共享设备指“**同一时间段内**”多进程交替访问（而非同一时刻），且因不具备互斥独占要求，不会因资源互斥导致死锁。

#### 7.1.2 设备控制器（I/O 接口）的组成与端口编址

设备控制器内部划分为**三大部分**：**与 CPU（处理机）的接口**（挂载数据线、地址线、控制线）、**I/O 逻辑**（包含地址译码器与命令译码，接收 CPU 地址并选中对应设备与寄存器）、**与设备的接口**（收发数据、状态、控制三类信号）。围绕“将 CPU 从设备事务中解脱”的目标，控制器内部通常配置至少三类端口寄存器，承担六项核心功能：

1. **接收和识别命令**：通过<strong>控制/命令寄存器（CR）</strong>与命令译码器解析 CPU 下达的读、写、状态测试等指令。
2. **数据交换**：通过<strong>数据缓冲寄存器（DBR）</strong>在 CPU/主存与设备之间中转数据。
3. **标识和报告设备状态**：通过<strong>状态寄存器（DSR）</strong>的就绪位（Ready）、忙位（Busy）、错误位（Error）向 CPU 汇报当前能否接收或发送数据。
4. **地址识别**：由地址译码器识别系统总线上的端口地址，生成片选有效信号（`SEL`），确保一次仅选中目标控制器的目标端口。
5. **数据缓冲**：利用控制器内置数据缓存匹配主存总线与外设之间的瞬时速率差。
6. **差错控制**：对传入数据计算校验码（如奇偶校验、CRC），一旦出错即置位状态寄存器报错。

CPU 访问控制器内的端口（寄存器）有两种硬件编址方式：

| 对比维度 | 独立编址（专用 I/O 端口映射） | 统一编址（内存映射 I/O，MMIO） |
| --- | --- | --- |
| **地址空间归属** | I/O 端口独立成套，与主存物理地址互不重叠 | 端口占用主存物理地址空间的高端区域 |
| **访问指令** | 必须使用专用 I/O 指令（如 x86 的 `IN`/`OUT`） | 直接复用普通访存指令（`LOAD`/`STORE`） |
| **硬件与地址代价** | 需增设 `M/IO#` 等控制引脚区分访存还是访端口，**不占主存地址空间** | 无需额外控制引脚，但**切走部分物理内存地址空间**（如早期 32 位机可用内存常卡在 3.2～3.5 GB） |
| **编程与保护** | 专用 I/O 指令属**特权指令**，天然只能内核态执行；高级语言指针难直接访问 | 访存指令统一且支持丰富寻址方式，C 指针可直接映射设备寄存器；需靠**页表权限位**禁止用户态越权访问 |
| **典型架构** | Intel x86（早/传统 PC 外设端口） | MIPS、ARM、RISC-V（现代嵌入式与片上外设） |

> **★考点**：端口编址的权衡可高度浓缩为一句话：**独立编址“省地址费指令”**，**统一编址“省指令费地址”**。

<figure class="cpd-figure not-content" id="os-c7-fig-1">
  <svg viewBox="0 0 720 330" role="img" aria-label="设备控制器三部分组成与IO端口独立编址和统一编址对比">
    <defs>
      <marker id="os-c7-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="414" height="304" rx="7"/>
    <rect class="fig-box-subtle" x="440" y="12" width="266" height="304" rx="7"/>
    <rect class="fig-box-blue" x="28" y="46" width="128" height="36" rx="4"/>
    <rect class="fig-box-accent" x="28" y="96" width="386" height="22" rx="3"/>
    <rect class="fig-box" x="28" y="132" width="386" height="114" rx="5"/>
    <rect class="fig-box-blue" x="38" y="142" width="112" height="94" rx="4"/>
    <rect class="fig-box-purple" x="162" y="142" width="122" height="94" rx="4"/>
    <rect class="fig-box-orange" x="296" y="142" width="108" height="94" rx="4"/>
    <rect class="fig-box-green" x="48" y="264" width="338" height="38" rx="4"/>
    <line class="fig-line-accent" x1="92" y1="82" x2="92" y2="95" marker-start="url(#os-c7-arr-1)" marker-end="url(#os-c7-arr-1)"/>
    <line class="fig-line-accent" x1="94" y1="118" x2="94" y2="140" marker-start="url(#os-c7-arr-1)" marker-end="url(#os-c7-arr-1)"/>
    <line class="fig-line" x1="150" y1="189" x2="160" y2="189" marker-end="url(#os-c7-arr-1)"/>
    <line class="fig-line" x1="284" y1="189" x2="294" y2="189" marker-end="url(#os-c7-arr-1)"/>
    <line class="fig-line-accent" x1="350" y1="238" x2="350" y2="262" marker-start="url(#os-c7-arr-1)" marker-end="url(#os-c7-arr-1)"/>
    <rect class="fig-box-blue" x="454" y="48" width="112" height="92" rx="4"/>
    <rect class="fig-box-orange" x="578" y="48" width="114" height="92" rx="4"/>
    <rect class="fig-box-blue" x="454" y="168" width="238" height="62" rx="4"/>
    <rect class="fig-box-orange" x="454" y="232" width="238" height="44" rx="4"/>
    <rect class="fig-box" x="454" y="282" width="238" height="24" rx="3"/>
    <text class="fig-title" x="28" y="33" font-size="12">① 设备控制器（硬件 I/O 接口）三部分结构</text>
    <text class="fig-blue" x="92" y="68" font-size="11" text-anchor="middle">CPU / 内存</text>
    <text class="fig-muted" x="292" y="68" font-size="10" text-anchor="middle">硬件接口插在主板上，非软件 API</text>
    <text class="fig-accent" x="221" y="111" font-size="10.2" text-anchor="middle">系统总线（数据线 + 地址线 + 控制线）</text>
    <text class="fig-blue" x="94" y="160" font-size="10.2" text-anchor="middle">与 CPU 接口</text>
    <text class="fig-label" x="94" y="179" font-size="9.5" text-anchor="middle">DBR（数据端口）</text>
    <text class="fig-label" x="94" y="196" font-size="9.5" text-anchor="middle">DSR（状态端口）</text>
    <text class="fig-label" x="94" y="213" font-size="9.5" text-anchor="middle">CR（控制端口）</text>
    <text class="fig-muted" x="94" y="229" font-size="9" text-anchor="middle">内为寄存器/外为端口</text>
    <text class="fig-purple" x="223" y="160" font-size="10.2" text-anchor="middle">I/O 逻辑</text>
    <text class="fig-muted" x="223" y="179" font-size="9.5" text-anchor="middle">地址译码器（SEL）</text>
    <text class="fig-muted" x="223" y="196" font-size="9.5" text-anchor="middle">命令译码控制</text>
    <text class="fig-muted" x="223" y="213" font-size="9.5" text-anchor="middle">差错校验 / 中断逻辑</text>
    <text class="fig-orange" x="350" y="160" font-size="10.2" text-anchor="middle">与设备接口</text>
    <text class="fig-muted" x="350" y="182" font-size="9.5" text-anchor="middle">设备控制信号</text>
    <text class="fig-muted" x="350" y="200" font-size="9.5" text-anchor="middle">设备状态信号</text>
    <text class="fig-muted" x="350" y="218" font-size="9.5" text-anchor="middle">数据串/并转换</text>
    <text class="fig-green" x="217" y="287" font-size="10.5" text-anchor="middle">I/O 设备（机械部件：盘片 / 磁头 / 打印头）</text>
    <text class="fig-title" x="454" y="33" font-size="12">② I/O 端口两种编址对照</text>
    <text class="fig-blue" x="510" y="66" font-size="10.2" text-anchor="middle">独立编址（x86）</text>
    <text class="fig-muted" x="510" y="84" font-size="9.2" text-anchor="middle">主存：0～FFFFH</text>
    <text class="fig-muted" x="510" y="100" font-size="9.2" text-anchor="middle">端口：00H～FFH</text>
    <text class="fig-label" x="510" y="117" font-size="9.2" text-anchor="middle">IN / OUT 专用指令</text>
    <text class="fig-muted" x="510" y="132" font-size="8.8" text-anchor="middle">省地址·费指令·M/IO#</text>
    <text class="fig-orange" x="635" y="66" font-size="10.2" text-anchor="middle">统一编址（MMIO）</text>
    <text class="fig-muted" x="635" y="84" font-size="9.2" text-anchor="middle">共享统一物理空间</text>
    <text class="fig-muted" x="635" y="100" font-size="9.2" text-anchor="middle">高端地址映射端口</text>
    <text class="fig-label" x="635" y="117" font-size="9.2" text-anchor="middle">LOAD / STORE 复用</text>
    <text class="fig-muted" x="635" y="132" font-size="8.4" text-anchor="middle">省指令·费地址·页表保护</text>
    <text class="fig-title" x="454" y="160" font-size="10.8">统一编址地址空间切分示意（如 RISC-V / ARM）</text>
    <text class="fig-blue" x="573" y="190" font-size="10.2" text-anchor="middle">物理主存地址空间（0000H ～ EFFFH）</text>
    <text class="fig-muted" x="573" y="206" font-size="9.2" text-anchor="middle">普通内存单元：存指令与数据</text>
    <text class="fig-muted" x="573" y="220" font-size="9" text-anchor="middle">（部分物理地址被高端 I/O 端口切走）</text>
    <text class="fig-orange" x="573" y="250" font-size="10" text-anchor="middle">I/O 端口映射区（F000H ～ FFFFH）</text>
    <text class="fig-muted" x="573" y="266" font-size="9.2" text-anchor="middle">映射 DBR / DSR / CR 等设备寄存器</text>
    <text class="fig-label" x="573" y="298" font-size="9.5" text-anchor="middle">★ 核心判据：寄存器对内是寄存器，对 CPU 是端口</text>
  </svg>
  <figcaption>图 7-1　设备控制器三部分结构、I/O 端口寄存器及独立编址与统一编址（MMIO）对比</figcaption>
</figure>

---

### 7.2 四种 I/O 控制方式与中断分工 ★

四种 I/O 控制方式位于同一条演进主线上：**逐步把 CPU 从低速设备的等待与逐字搬运中解放出来**。判断两种方式的本质差异，抓住两条硬分界：**① 数据流是否经过 CPU 通用寄存器；② CPU 的介入粒度（全程忙等 → 每字中断 → 每块中断 → 每组块中断）**。

> **注意**：<strong>“CPU 利用率最高的控制方式，单次请求的响应延迟反而最长”</strong>并不是笔误！因为方式越高级，CPU 在启动准备（预处理、填表、编通道程序）时花的启动配置越复杂，但它换取了传输期间更少的 CPU 介入次数。

#### 7.2.1 程序直接控制方式（轮询 / 查询）

CPU 内无中断机构（或关中断）时，只能通过软件循环读取控制器的状态寄存器（DSR）测试就绪位，确认就绪后再从数据寄存器（DBR）取走一个字。

- **独占查询**：CPU 发出启动命令后，死循环持续测试状态位，**100% CPU 时间用于忙等**，CPU 与外设完全**串行**工作（如从终端读入 1 字符耗时 100 ms，真正取走仅 0.1 ms，99.9 ms 白白空转）。
- **定时查询**：CPU 启动外设后设置一个定时器并切往其他程序运行，每隔固定周期响应定时中断去查询状态端口并搬运数据。CPU 可在间隔期间并行跑其他任务，但定时中断本身仍占开销，且**两次查询间隔不得超过外设填满数据端口的时间**，否则新数据会覆盖旧数据导致丢失。

> **★考点算例（定时查询不丢数据的最大间隔与 CPU 占比）**：设主频 $500\text{ MHz}$，$\text{CPI} = 4$，外设传输率 $2\text{ MB/s}$，I/O 接口 DBR 宽 $32\text{ bit}$（$4\text{ B}$），每次查询与搬运需执行 $10$ 条指令。
> 1. 外设填满 $4\text{ B}$ 的时间：$\frac{4\text{ B}}{2 \times 10^6\text{ B/s}} = 2\ \mu\text{s}$，故**最多每隔 $2\ \mu\text{s}$ 必须查询一次**，否则数据被覆写。
> 2. 每秒最多查询次数：$\frac{1\text{ s}}{2\ \mu\text{s}} = 5 \times 10^5$ 次；每次耗时 $10 \times 4 = 40$ 个时钟周期；每秒消耗 $5 \times 10^5 \times 40 = 2 \times 10^7$ 个时钟周期。
> 3. CPU 时间占比：$\frac{2 \times 10^7}{500 \times 10^6} = 4\%$。

#### 7.2.2 中断驱动方式

CPU 启动外设后立即返回执行其他任务；外设每准备好一个字放入 DBR，控制器即通过中断请求线向 CPU 发中断信号。CPU 仅在每条指令执行末尾的**中断周期**检测中断请求，满足条件（开中断且未被屏蔽）则转入中断服务程序（ISR）将数据经 CPU 寄存器搬入内存缓冲区。

- **病根所在**：CPU 已经不再“死等”，但**传输基本单位仍是“字”**，每传一个字就要中断一次（读 $1\text{ KB}$ 块需中断 $1024$ 次），每次中断都要压栈/切态/保存现场/恢复现场，开销极其可观。
- **高速外设为何不能用中断方式（量化判据）**：设上例改为 $40\text{ MB/s}$ 高速外设，DBR 仍为 $4\text{ B}$，每次中断响应与处理总共需要 $400$ 个时钟周期。则外设每 $\frac{4\text{ B}}{40\text{ MB/s}} = 0.1\ \mu\text{s}$ 就填满一次端口，而 CPU 每次中断处理耗时 $\frac{400}{500\text{ MHz}} = 0.8\ \mu\text{s} > 0.1\ \mu\text{s}$——CPU 处理速度是数据到达间隔的 $1/8$，**必然来不及取走数据而丢包**！对高速块设备，DMA 不是优化而是**唯一可行方案**。

##### 中断链路的软硬件分工与数据流停靠点（408 高频 ★）

判断中断步骤归硬件还是操作系统，只需一条铁律：**凡要动 `PC`、`PSW`（程序状态字）或 CPU 运行模式位的动作，因用户态无权限且需原子化切换，必由硬件（中断隐指令）完成；其余普通指令可执行的动作归操作系统完成。**

| 动作 | 执行者 | 核心理由与真题依据（2012#24、2015#23、2020#25、2023#24） |
| --- | --- | --- |
| **保存断点（`PC`、`PSW`）** | **硬件** | 由中断隐指令自动压栈；注意**子程序调用不保存 `PSW`**（不跨模式也不改中断允许位） |
| **切换 CPU 为内核态 / 关中断** | **硬件** | 用户态无法自行提权，必须由硬件置模式位与关中断标志 |
| **取中断向量并跳入 ISR 入口** | **硬件** | 硬件根据中断号索引中断向量表跳转（**向量表本身适合用数组**，定长支持 $O(1)$ 随机访问） |
| **初始化中断向量表** | **操作系统** | 开机初始化时由 OS 写入各中断服务程序首址 |
| **保存现场（通用寄存器）、保存中断屏蔽字** | **操作系统** | 在 ISR 开头由普通压栈指令完成（TLB、Cache 由硬件自管，不归 OS 保存） |
| **提供与执行中断服务（数据搬运/状态更新）** | **操作系统** | 时钟中断服务程序负责更新内核时钟、当前进程占用 CPU 时间与剩余时间片（2018#29） |

> **★考点（输入数据流停靠点，2010#32、2024#31、2026#32）**：一条完整输入链为四段：
> $\text{输入设备} \xrightarrow{\text{设备控制器}} \text{控制器数据寄存器} \xrightarrow{\text{中断处理程序/驱动}} \text{内核缓冲区} \xrightarrow{\text{系统调用返回}} \text{用户缓冲区}$。
> 按下键盘按键后：**① 首先获得键盘输入信息的是中断处理程序**（不是系统调用处理程序，也不是命令解释程序）；**② 中断服务例程执行结束时，数据停留在内核缓冲区**（不在控制器、不在 CPU 寄存器，也尚未进用户缓冲区，需待用户进程被唤醒且系统调用返回时才拷贝到用户缓冲区）。

#### 7.2.3 DMA 方式（直接存储器访问）★

**DMA（Direct Memory Access）** 在外设与主存之间开辟了一条**由 DMA 控制器（DMAC）硬件控制的直接数据通路**，实现“**数据块**”级的批量传输。

- **三大核心特征**：① 传输基本单位为**数据块**；② 数据直接在设备与主存间流动，**不经过 CPU 通用寄存器**（注意：依然占用系统总线）；③ CPU 仅在传送的<strong>开始（预处理）</strong>和<strong>结束（后处理）</strong>时介入一次。
- **DMAC 内部四大核心寄存器**：**命令/状态寄存器（CR）**（存 I/O 命令方向与状态）、**主存地址寄存器/计数器（MAR/AR）**（存当前访存单元地址，每传一字递增）、**数据计数器/字计数器（DC/WC）**（存本次传送字数，常以补码存 $-N$ 递增至 $0$ 溢出判结束，或存 $N$ 递减至 $0$）、**数据缓冲寄存器（DR/BR）**（暂存一个字/字节）；另配设备地址寄存器（DAR，存磁盘 CHS 等设备侧地址）以及请求与中断机构。

**DMA 传送三阶段（2017#32 顺序考点）**：

1. **预处理（CPU 执行 I/O 指令完成）**：CPU 向 DMAC 的 CR、MAR、DC、DAR 写入传送方向、主存首址、传送字数和设备地址，启动设备并转去执行其他程序。
2. **数据传送（DMAC 硬件自治完成）**：外设准备好一个字放入 DR 后，向 DMAC 发出 **`DREQ`（DMA 请求）** → DMAC 向 CPU 发出 **`HRQ`（保持/总线请求）** → CPU 在合适时机回送 **`HLDA`（总线响应）** 交出总线控制权 → DMAC 接管总线并直接向主存发读写控制信号，将数据经系统总线在 DR 与 MAR 所指主存单元间传送，随后修改 `MAR` 与 `DC` → 循环直到 `DC` 计满（溢出/`DC=0`）。
3. **后处理（CPU 进 ISR 完成）**：DMAC 发出 **`INTR`（DMA 结束中断请求）** → CPU 响应中断执行后处理程序，校验数据完整性、决定是否启动下一块、唤醒等待 I/O 的阻塞进程。

**DMA 与 CPU 争用主存的三种方式**：

| 方式 | 做法与时机 | 优缺点与适用条件 |
| --- | --- | --- |
| **停止 CPU 访存** | 整块数据传送期间 CPU 交出总线控制权并停止访存 | 控制简单，但外设两个字之间的准备间隙主存被闲置，CPU 停摆效率低 |
| **周期挪用（周期窃取）★** | 每当外设准备好一个字，DMAC 申请**窃取 1 个或数个主存存取周期**传完立即归还；发生于**任一机器/存取周期结束时** | **现代最常用**。三种情况：① CPU 不访存 → DMA 直接用；② CPU 正在存取周期中间 → DMA 等该周期结束；③ **CPU 与 DMA 同时请求 → DMA 优先**（防高速外设数据被覆盖丢失） |
| **DMA 与 CPU 交替访存** | 将每个 CPU 工作周期划为 $C_1$（专供 DMA）与 $C_2$（专供 CPU） | 无需总线申请与归还仲裁，总吞吐最高；但要求**主存存取周期小于半个 CPU 工作周期**，硬件逻辑最复杂 |

> **注意**：**DMA 并不“打断 CPU 程序的断点执行”**！周期挪用仅在总线与存取周期层面窃取访存权（不会压栈保存 PC/PSW，也不切入中断处理程序）。若 CPU 指令缓冲中已预取到不需访存的指令（如寄存器加法），CPU 仍可继续执行。

> **★考点算例（周期挪用占比 & DMA CPU 开销对比）**：
> - **算例 A（周期挪用总线占比）**：某磁盘传输率 $20\text{ MB/s}$，DMAC 的数据缓冲寄存器宽 $4\text{ B}$，主存存取周期 $50\text{ ns}$，采用周期挪用传输 $4\text{ KB}$ 数据块。
>   - 挪用按 **DR 位宽** 发生：共需挪用 $\frac{4096\text{ B}}{4\text{ B}} = 1024$ 次（千万不能错当成只挪 1 次！）。
>   - 挪用总线总时长：$1024 \times 50\text{ ns} = 51.2\ \mu\text{s}$。
>   - 数据流过所需时长（分母）：$\frac{4096\text{ B}}{20 \times 10^6\text{ B/s}} = 204.8\ \mu\text{s}$。
>   - **总线挪用时间占比**：$\frac{51.2}{204.8} = 25\%$。（若改用每 4 B 中断耗时 $5\ \mu\text{s}$ 的中断方式，需 $5120\ \mu\text{s} = 25 \times 204.8\ \mu\text{s}$，必丢数据！）
> - **算例 B（DMA 下 CPU 时间占比）**：接前文 $500\text{ MHz}$ 主频、$40\text{ MB/s}$ 外设，改用 DMA 方式每块传 $1000\text{ B}$，预处理+后处理共需 $500$ 个时钟周期。
>   - 每秒 DMA 次数：$\frac{40\text{ MB/s}}{1000\text{ B}} = 4 \times 10^4$ 次；CPU 消耗 $4 \times 10^4 \times 500 = 2 \times 10^7$ 周期，占比仅为 $\frac{2 \times 10^7}{500 \times 10^6} = 4\%$（对比中断方式每 4 B 就耗 400 周期完全跑不动，DMA 轻松胜任 $40\text{ MB/s}$ 高速设备）。

**DMA 方式的硬件瓶颈**：因为 DMAC 内部只有**单一的 `MAR` 与 `DC`**，且不具备取指译码能力，所以一次 DMA 启动**只能把一段连续的设备数据传送到一段连续的内存空间**，且无法主动组织多次跨区传送。

#### 7.2.4 I/O 通道控制方式与四种方式横向对比

> **注意**：2026 年 408 大纲“五（一）2 I/O 控制方式”仅点名轮询、中断、DMA 三项，通道方式本身不考繁琐硬件细节，但理解通道与 DMA 的层级差异（可不连续传输、组织“一组块”），有助于精准界定 DMA 的能力边界，且下一节设备分配四表中的 `CHCT` 仍依赖通道概念。

**I/O 通道（Channel）** 是专门负责 I/O 操作的处理机，与通用 CPU 的两点本质区别：**指令类型单一**（只有通道指令）、**没有独立内存**（通道程序 `CCW` 存放在主机内存中）。操作系统响应应用程序发出的广义 I/O 指令后，在主存中组织好**通道程序**（每条通道指令含操作码、内存地址、计数、通道程序结束位 $P$、记录结束标志 $R$），CPU 仅发一条启动命令即可撤离；正因**每条通道指令都自带内存地址与计数**，通道能将一组分散块搬往**非连续的多片内存区域**，全部完成后才发一次中断。按传输方式分为：**字节多路通道**（多子通道按字节交叉轮转，接大量慢速字符设备）、**选择通道**（单子通道被高速设备独占至整批传完，利用率低）、**数组多路通道**（多子通道按数据块轮流交替服务多台高速磁盘，寻道可并行、总线传输分时）。

| 对比维度 | 程序查询（轮询） | 中断驱动 | DMA 方式 | 通道方式（拓展） |
| --- | --- | --- | --- | --- |
| **CPU 干预粒度** | 全程盲等轮询 | **每个字**中断一次 | **每个数据块**中断一次 | **每组数据块**中断一次 |
| **传输基本单位** | 字 | 字 | 数据块 | 一组块 |
| **数据通路** | 设备 ↔ 控制器 ↔ **CPU 寄存器** ↔ 内存 | 设备 ↔ 控制器 ↔ **CPU 寄存器** ↔ 内存 | 设备 ↔ **DMAC** ↔ 内存（直通） | 设备 ↔ 控制器 ↔ **通道** ↔ 内存 |
| **CPU 与外设并行** | 独占查询完全串行；定时查询部分并行 | 设备准备与 CPU 并行，搬运串行 | 几乎完全并行（仅首尾介入） | 高度并行（通道自治执行程序） |
| **内存连续性要求** | 无（逐字程序放置） | 无（逐字程序放置） | **必须连续**（单一 MAR+DC） | **可不连续**（每条 CCW 自带地址） |
| **CPU 利用率 / 单次响应延迟** | 利用率最低 / **延迟最短** | 利用率较低 / 延迟较短 | 利用率较高 / 延迟较长 | 利用率最高 / **延迟最长** |

> **★考点（单处理机下的并行性，2009#23）**：在单 CPU 系统中，借助中断、DMA 与通道，**处理机与设备、处理机与通道、设备与设备之间均可实现真正并行**；但**进程与进程之间在单处理机上只能并发（交替占用 CPU），不能并行**！

<figure class="cpd-figure not-content" id="os-c7-fig-2">
  <svg viewBox="0 0 720 336" role="img" aria-label="四种IO控制方式数据通路演进与CPU介入粒度对比">
    <defs>
      <marker id="os-c7-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="72" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="92" width="692" height="72" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="172" width="692" height="74" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="254" width="692" height="70" rx="6"/>
    <line class="fig-line" x1="218" y1="54" x2="244" y2="54" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line" x1="318" y1="54" x2="350" y2="54" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line" x1="450" y1="54" x2="484" y2="54" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line" x1="218" y1="134" x2="244" y2="134" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line" x1="318" y1="134" x2="350" y2="134" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line" x1="450" y1="134" x2="484" y2="134" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line-accent" x1="218" y1="204" x2="260" y2="204" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line-accent" x1="360" y1="204" x2="484" y2="204" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line-dashed" x1="422" y1="216" x2="422" y2="204"/>
    <line class="fig-line-accent" x1="218" y1="292" x2="244" y2="292" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line-accent" x1="318" y1="292" x2="350" y2="292" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <line class="fig-line-accent" x1="450" y1="292" x2="484" y2="292" marker-start="url(#os-c7-arr-2)" marker-end="url(#os-c7-arr-2)"/>
    <rect class="fig-box" x="150" y="38" width="66" height="32" rx="4"/>
    <rect class="fig-box" x="246" y="38" width="70" height="32" rx="4"/>
    <rect class="fig-box-red" x="352" y="38" width="96" height="32" rx="4"/>
    <rect class="fig-box" x="486" y="38" width="58" height="32" rx="4"/>
    <rect class="fig-box" x="150" y="118" width="66" height="32" rx="4"/>
    <rect class="fig-box" x="246" y="118" width="70" height="32" rx="4"/>
    <rect class="fig-box-orange" x="352" y="118" width="96" height="32" rx="4"/>
    <rect class="fig-box" x="486" y="118" width="58" height="32" rx="4"/>
    <rect class="fig-box" x="150" y="188" width="66" height="32" rx="4"/>
    <rect class="fig-box-blue" x="262" y="188" width="96" height="32" rx="4"/>
    <rect class="fig-box-subtle" x="378" y="216" width="88" height="24" rx="4"/>
    <rect class="fig-box" x="486" y="188" width="58" height="32" rx="4"/>
    <rect class="fig-box" x="150" y="276" width="66" height="32" rx="4"/>
    <rect class="fig-box" x="246" y="276" width="70" height="32" rx="4"/>
    <rect class="fig-box-green" x="352" y="276" width="96" height="32" rx="4"/>
    <rect class="fig-box" x="486" y="276" width="58" height="32" rx="4"/>
    <text class="fig-red" x="26" y="42" font-size="11">① 程序查询（轮询）</text>
    <text class="fig-muted" x="26" y="60" font-size="9.5">全程忙等·每字干预</text>
    <text class="fig-label" x="183" y="58" font-size="10.5" text-anchor="middle">外设</text>
    <text class="fig-label" x="281" y="58" font-size="10.5" text-anchor="middle">控制器</text>
    <text class="fig-red" x="400" y="58" font-size="10" text-anchor="middle">CPU 寄存器</text>
    <text class="fig-label" x="515" y="58" font-size="10.5" text-anchor="middle">主存</text>
    <text class="fig-muted" x="556" y="46" font-size="9.5">通路：经 CPU 寄存器</text>
    <text class="fig-red" x="556" y="64" font-size="9.5">缺点：CPU 100% 空转</text>
    <text class="fig-orange" x="26" y="122" font-size="11">② 程序中断驱动</text>
    <text class="fig-muted" x="26" y="140" font-size="9.5">异步通知·每字中断</text>
    <text class="fig-label" x="183" y="138" font-size="10.5" text-anchor="middle">外设</text>
    <text class="fig-label" x="281" y="138" font-size="10.5" text-anchor="middle">控制器</text>
    <text class="fig-orange" x="400" y="138" font-size="10" text-anchor="middle">CPU 寄存器</text>
    <text class="fig-label" x="515" y="138" font-size="10.5" text-anchor="middle">主存</text>
    <text class="fig-muted" x="556" y="126" font-size="9.5">通路：仍经 CPU 寄存器</text>
    <text class="fig-orange" x="556" y="144" font-size="9.5">病根：按字中断太勤</text>
    <text class="fig-blue" x="26" y="202" font-size="11">③ DMA 直接访问 ★</text>
    <text class="fig-muted" x="26" y="220" font-size="9.5">整块直通·每块中断</text>
    <text class="fig-label" x="183" y="208" font-size="10.5" text-anchor="middle">外设</text>
    <text class="fig-blue" x="310" y="208" font-size="10.2" text-anchor="middle">DMAC（直连）</text>
    <text class="fig-muted" x="422" y="232" font-size="9" text-anchor="middle">CPU 仅首尾介入</text>
    <text class="fig-label" x="515" y="208" font-size="10.5" text-anchor="middle">主存</text>
    <text class="fig-blue" x="556" y="200" font-size="9.5">不经 CPU 寄存器（窃总线）</text>
    <text class="fig-muted" x="556" y="218" font-size="9.5">限制：仅传连续区</text>
    <text class="fig-green" x="26" y="284" font-size="11">④ I/O 通道控制</text>
    <text class="fig-muted" x="26" y="302" font-size="9.5">读主存 CCW·每组块</text>
    <text class="fig-label" x="183" y="296" font-size="10.5" text-anchor="middle">外设</text>
    <text class="fig-label" x="281" y="296" font-size="10.5" text-anchor="middle">控制器</text>
    <text class="fig-green" x="400" y="296" font-size="9.8" text-anchor="middle">通道（可分散）</text>
    <text class="fig-label" x="515" y="296" font-size="10.5" text-anchor="middle">主存</text>
    <text class="fig-green" x="556" y="284" font-size="9.5">通道程序 CCW 放主存</text>
    <text class="fig-muted" x="556" y="302" font-size="9.5">可分散多块·延迟最长</text>
  </svg>
  <figcaption>图 7-2　四种 I/O 控制方式数据通路、CPU 介入粒度与能力边界演进对比</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c7-fig-3">
  <svg viewBox="0 0 720 318" role="img" aria-label="DMA控制器内部寄存器结构与周期挪用三阶段工作时序">
    <defs>
      <marker id="os-c7-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="162" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="184" width="692" height="122" rx="7"/>
    <rect class="fig-box" x="22" y="48" width="90" height="106" rx="5"/>
    <rect class="fig-box-blue" x="168" y="42" width="376" height="118" rx="6"/>
    <rect class="fig-box" x="588" y="48" width="102" height="106" rx="5"/>
    <rect class="fig-box" x="180" y="70" width="84" height="34" rx="3"/>
    <rect class="fig-box" x="274" y="70" width="92" height="34" rx="3"/>
    <rect class="fig-box" x="376" y="70" width="84" height="34" rx="3"/>
    <rect class="fig-box" x="470" y="70" width="64" height="34" rx="3"/>
    <rect class="fig-box-accent" x="180" y="114" width="166" height="34" rx="3"/>
    <rect class="fig-box-orange" x="358" y="114" width="176" height="34" rx="3"/>
    <line class="fig-line" x1="112" y1="74" x2="166" y2="74" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line" x1="166" y1="100" x2="112" y2="100" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line-accent" x1="112" y1="132" x2="166" y2="132" marker-start="url(#os-c7-arr-3)" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line" x1="588" y1="76" x2="546" y2="76" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line" x1="546" y1="104" x2="588" y2="104" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line-accent" x1="588" y1="134" x2="546" y2="134" marker-start="url(#os-c7-arr-3)" marker-end="url(#os-c7-arr-3)"/>
    <rect class="fig-box" x="28" y="218" width="150" height="44" rx="4"/>
    <rect class="fig-box-blue" x="200" y="218" width="320" height="44" rx="4"/>
    <rect class="fig-box-green" x="542" y="218" width="148" height="44" rx="4"/>
    <line class="fig-line-accent" x1="178" y1="240" x2="198" y2="240" marker-end="url(#os-c7-arr-3)"/>
    <line class="fig-line-accent" x1="520" y1="240" x2="540" y2="240" marker-end="url(#os-c7-arr-3)"/>
    <text class="fig-title" x="28" y="32" font-size="11.5">① DMA 控制器（DMAC）内部寄存器与总线握手信号</text>
    <text class="fig-label" x="67" y="76" font-size="10.5" text-anchor="middle">CPU</text>
    <text class="fig-muted" x="67" y="94" font-size="9" text-anchor="middle">执行其他任务</text>
    <text class="fig-muted" x="67" y="122" font-size="9" text-anchor="middle">与主存共享</text>
    <text class="fig-muted" x="67" y="138" font-size="9" text-anchor="middle">系统总线</text>
    <text class="fig-muted" x="140" y="68" font-size="8.6" text-anchor="middle">HLDA</text>
    <text class="fig-muted" x="140" y="95" font-size="8.2" text-anchor="middle">HRQ/INTR</text>
    <text class="fig-accent" x="140" y="126" font-size="8.6" text-anchor="middle">总线</text>
    <text class="fig-blue" x="356" y="60" font-size="10.8" text-anchor="middle">DMAC（直接存储器访问控制器）</text>
    <text class="fig-label" x="222" y="85" font-size="9.8" text-anchor="middle">MAR / AR</text>
    <text class="fig-muted" x="222" y="98" font-size="8.5" text-anchor="middle">主存地址+1</text>
    <text class="fig-label" x="320" y="85" font-size="9.8" text-anchor="middle">DC / WC</text>
    <text class="fig-muted" x="320" y="98" font-size="8.5" text-anchor="middle">计数（-N→0）</text>
    <text class="fig-label" x="418" y="85" font-size="9.8" text-anchor="middle">DR / BR</text>
    <text class="fig-muted" x="418" y="98" font-size="8.5" text-anchor="middle">数据缓冲</text>
    <text class="fig-label" x="502" y="85" font-size="9.8" text-anchor="middle">CR</text>
    <text class="fig-muted" x="502" y="98" font-size="8.5" text-anchor="middle">命令状态</text>
    <text class="fig-accent" x="263" y="130" font-size="9.5" text-anchor="middle">控制与总线仲裁逻辑</text>
    <text class="fig-muted" x="263" y="143" font-size="8.5" text-anchor="middle">发读写线·响应 DREQ</text>
    <text class="fig-orange" x="446" y="130" font-size="9.5" text-anchor="middle">DAR &amp; 中断机构</text>
    <text class="fig-muted" x="446" y="143" font-size="8.5" text-anchor="middle">设备址·溢出发 INTR</text>
    <text class="fig-muted" x="567" y="70" font-size="8.8" text-anchor="middle">DREQ</text>
    <text class="fig-muted" x="567" y="98" font-size="8.8" text-anchor="middle">DACK</text>
    <text class="fig-accent" x="567" y="128" font-size="8.8" text-anchor="middle">数据</text>
    <text class="fig-label" x="639" y="84" font-size="10.5" text-anchor="middle">高速外设</text>
    <text class="fig-muted" x="639" y="104" font-size="9.2" text-anchor="middle">（磁盘/网卡）</text>
    <text class="fig-muted" x="639" y="124" font-size="9" text-anchor="middle">按字装入 DR</text>
    <text class="fig-title" x="28" y="204" font-size="11.5">② DMA 传送三阶段与周期挪用（2017#32 流程顺序）</text>
    <text class="fig-label" x="103" y="236" font-size="10.2" text-anchor="middle">阶段 1：预处理（CPU）</text>
    <text class="fig-muted" x="103" y="253" font-size="9" text-anchor="middle">置 CR/MAR/DC/DAR·启动</text>
    <text class="fig-blue" x="360" y="236" font-size="10.2" text-anchor="middle">阶段 2：成块传送（DMAC 硬件控制）</text>
    <text class="fig-muted" x="360" y="253" font-size="9" text-anchor="middle">DREQ → 挪用 1 存取周期（DMA 优先）→ 改 MAR/DC</text>
    <text class="fig-green" x="616" y="236" font-size="10.2" text-anchor="middle">阶段 3：后处理（CPU）</text>
    <text class="fig-muted" x="616" y="253" font-size="9" text-anchor="middle">DC=0 发中断·校验并唤醒</text>
    <text class="fig-red" x="360" y="290" font-size="10" text-anchor="middle">★ 周期挪用要点：在任一机器/存取周期末检查；CPU 与 DMA 同时请求访存时 DMA 优先（防数据覆写丢失）</text>
  </svg>
  <figcaption>图 7-3　DMA 控制器内部核心寄存器（MAR/DC/DR/CR/DAR）及周期挪用三阶段工作流程</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c7-fig-4">
  <svg viewBox="0 0 720 304" role="img" aria-label="中断处理软硬件职责划分与键盘鼠标输入四段数据流停靠点">
    <defs>
      <marker id="os-c7-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="338" height="148" rx="7"/>
    <rect class="fig-box-subtle" x="364" y="12" width="342" height="148" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="170" width="692" height="122" rx="7"/>
    <rect class="fig-box-orange" x="28" y="48" width="310" height="44" rx="4"/>
    <rect class="fig-box-blue" x="28" y="102" width="310" height="44" rx="4"/>
    <rect class="fig-box-blue" x="378" y="48" width="314" height="44" rx="4"/>
    <rect class="fig-box-green" x="378" y="102" width="314" height="44" rx="4"/>
    <rect class="fig-box" x="26" y="218" width="112" height="42" rx="4"/>
    <rect class="fig-box-orange" x="178" y="218" width="128" height="42" rx="4"/>
    <rect class="fig-box-blue" x="356" y="218" width="144" height="42" rx="4"/>
    <rect class="fig-box-green" x="550" y="218" width="142" height="42" rx="4"/>
    <line class="fig-line-accent" x1="138" y1="239" x2="176" y2="239" marker-end="url(#os-c7-arr-4)"/>
    <line class="fig-line-accent" x1="306" y1="239" x2="354" y2="239" marker-end="url(#os-c7-arr-4)"/>
    <line class="fig-line-accent" x1="500" y1="239" x2="548" y2="239" marker-end="url(#os-c7-arr-4)"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 硬件中断隐指令职责（动 PC/PSW/模式）</text>
    <text class="fig-orange" x="183" y="66" font-size="10.2" text-anchor="middle">1. 保存断点（PC、PSW 压栈）＋ 关中断</text>
    <text class="fig-muted" x="183" y="83" font-size="9.2" text-anchor="middle">注意：子程序调用不保护 PSW（未跨态）</text>
    <text class="fig-blue" x="183" y="120" font-size="10.2" text-anchor="middle">2. 切 CPU 至内核态 ＋ 按中断号取向量</text>
    <text class="fig-muted" x="183" y="137" font-size="9.2" text-anchor="middle">向量表由 OS 开机初始化，硬件仅负责寻址取用</text>
    <text class="fig-title" x="378" y="33" font-size="11.5">② 操作系统软件职责（2015#23 / 2020#25 / 2023#24）</text>
    <text class="fig-blue" x="535" y="66" font-size="10.2" text-anchor="middle">1. 初始化中断向量表（采用数组 O(1) 定位）</text>
    <text class="fig-muted" x="535" y="83" font-size="9.2" text-anchor="middle">保存现场（通用寄存器）＋ 保存中断屏蔽字</text>
    <text class="fig-green" x="535" y="120" font-size="10.2" text-anchor="middle">2. 执行中断服务（ISR）：搬数据 / 更新时钟</text>
    <text class="fig-muted" x="535" y="137" font-size="9.2" text-anchor="middle">TLB、Cache 由硬件透明管理，无需 OS 保存</text>
    <text class="fig-title" x="28" y="191" font-size="11.5">③ 外设输入四段数据流与 ISR 结束停靠点（2010#32 / 2024#31 / 2026#32 ★）</text>
    <text class="fig-label" x="82" y="236" font-size="10" text-anchor="middle">输入设备</text>
    <text class="fig-muted" x="82" y="252" font-size="9" text-anchor="middle">键盘 / 鼠标</text>
    <text class="fig-muted" x="157" y="211" font-size="8.5" text-anchor="middle">控制器</text>
    <text class="fig-orange" x="242" y="236" font-size="10" text-anchor="middle">控制器数据寄存器</text>
    <text class="fig-muted" x="242" y="252" font-size="9" text-anchor="middle">DBR（硬件发中断）</text>
    <text class="fig-muted" x="330" y="211" font-size="8.5" text-anchor="middle">ISR/驱动</text>
    <text class="fig-blue" x="428" y="236" font-size="10" text-anchor="middle">内核缓冲区 ★</text>
    <text class="fig-muted" x="428" y="252" font-size="9" text-anchor="middle">ISR 结束时停靠在此</text>
    <text class="fig-muted" x="524" y="211" font-size="8.5" text-anchor="middle">系统调用</text>
    <text class="fig-green" x="621" y="236" font-size="10" text-anchor="middle">用户缓冲区</text>
    <text class="fig-muted" x="621" y="252" font-size="9" text-anchor="middle">唤醒返用户态拷入</text>
    <text class="fig-accent" x="360" y="280" font-size="9.8" text-anchor="middle">按键最先响应的是中断处理程序；ISR 结束时数据在内核缓冲区，不在用户缓冲区或 DBR 中</text>
  </svg>
  <figcaption>图 7-4　中断软硬件分工（断点归硬件 vs 现场归 OS）及键盘/鼠标输入四段数据流停靠点</figcaption>
</figure>

---

### 7.3 I/O 软件层次结构与接口 ★

#### 7.3.1 四层层次结构与归层铁律

I/O 软件的分层由**四条设计目标**推演而来：**设备无关性**（换物理设备不改上层代码）、**屏蔽硬件细节**（隔离五花八门的寄存器布局）、**就地出错处理**（暂态错底端重试消化，仅永久错上报）、**同步/异步控制**（发请求可阻塞，完成可唤醒）。

> **★考点（归层黄金判据）**：判断某功能属于哪一层，只需问：**“换一种设备时，这一步的代码要不要重写？”**
> - **需要按硬件重写** → **设备驱动程序**（**唯一**真正了解具体控制器寄存器布局的一层）。
> - **不用重写但跑在内核态** → **设备独立性软件**（设备无关软件）。
> - **跑在用户态** → **用户层 I/O 软件**。
> - **由中断信号触发、直接处理硬件中断机制** → **中断处理程序**。

自顶向下四层结构中，**仅有第 1 层处于用户态，下面三层均处于内核态**（合称 **I/O 核心子系统**），因此跨越软件四层仅在第 1 层与第 2 层之间发生**一次**用户态到内核态切换：

| 层次 | 运行态 | 核心职责与考纲边界 |
| --- | --- | --- |
| **1. 用户层 I/O 软件** | **用户态** | • 系统调用封装与库函数（如 C 标准库 `printf`/`scanf` 与系统调用大体一一对应，而 Win32 API 不一一对应）<br>• SPOOLing 假脱机守护进程（运行在用户态，在逻辑功能上 408 大纲归入 I/O 核心子系统专题考查） |
| **2. 设备独立性软件**<br>（设备无关软件） | **内核态** | • 向上提供统一接口与设备无关的**逻辑块大小**（屏蔽不同磁盘物理扇区差异）<br>• **设备命名映射（逻辑设备表 LUT）**、**设备保护**（将设备视作特殊文件，检查 FCB 权限）<br>• **缓冲管理**、**设备分配与回收**、**I/O 调度**（如磁盘调度）<br>• 仅处理**驱动程序无法解决的持久性差错**（如决定终止进程还是报告错误） |
| **3. 设备驱动程序** | **内核态** | • **唯一与具体硬件相关**，将抽象逻辑块号等请求翻译为物理坐标（柱面/磁头/扇区）与控制器寄存器操作序列<br>• 服务请求合法性校验、检查设备状态、传递参数、启动设备并阻塞自身等待中断<br>• **就地处理暂时性错误**（如电源抖动或校验失败时重传，多次失败再上报） |
| **4. 中断处理程序** | **内核态** | • 直接面对**硬件中断机制**（而非某款外设的寄存器布局），以极高优先级精简执行<br>• 检查中断原因，将控制器 DBR 中的数据搬至内核缓冲区，**唤醒阻塞进程入就绪队列**，并推进下一排队请求 |

> **注意**：**切勿被层次图误导！** 虽然“中断处理程序”画在最贴近硬件的最底层，但它面对的是**通用硬件中断机制**（保存现场、识别中断源、唤醒等待进程），**并不比驱动程序更了解具体某台设备的寄存器协议**。层次图的上下反映的是“向下发出请求 / 向上响应通知”的调用关系。此外，设备独立性软件与设备驱动程序的界限在不同操作系统中会因性能考量略有浮动（例如部分本属无关层的功能下放驱动）。

#### 7.3.2 一次读磁盘 / 按键输入的跨层完整链路

以进程调用 `read()` 读磁盘文件或键盘为例，自顶向下发起请求再自底向上中断返回的 9 步链路（**2011#26、2012#26、2013#25 连续三年考同一条先后次序；2023#46 综合大题**）：

1. **用户层 I/O 软件**：用户进程调用库函数或 `read()` 系统调用（产生陷入/Trap 切换至内核态）。
2. **设备独立性软件**：检查参数与访问权限；查**高速缓存/缓冲区**，若命中则直接拷贝至用户缓冲区并返回；未命中则将逻辑设备名经 **LUT** 映射为物理设备与驱动入口。
3. **设备独立性软件**：将请求插入对应设备队列，把**请求进程改为阻塞态**（此时 CPU 切换去调度其他就绪进程）。
4. **设备驱动程序**：计算物理地址（柱面/盘面/扇区），向控制器命令/控制/地址寄存器写入参数并**启动硬件设备**（随后驱动控制权交回并阻塞等待）。
5. **硬件层**：磁盘寻道旋转或由 DMAC/控制器完成物理读写，将数据写入控制器数据寄存器（或经 DMA 写入内核缓冲区）。
6. **中断处理程序**：设备完成后发中断，硬件保存断点切内核态，中断处理程序判别中断原因、检测是否出错。
7. **中断处理程序 + 驱动程序**：驱动/ISR 从控制器数据寄存器取数入内核缓冲区（若为 DMA 则校验块完成），并**唤醒等待该设备的进程（由阻塞态转为就绪态）**。
8. **设备独立性软件**：待调度器重新选中该进程后，系统调用在内核末尾将数据从**内核缓冲区拷入用户缓冲区**。
9. **用户层 I/O 软件**：恢复用户态并自系统调用返回，进程获得数据继续执行。

> **★考点（2011–2013 选择题 & 2023#46 大题秒杀法）**：
> - 选择题常把“**设备驱动程序**”与“**中断处理程序**”顺序对调！只要抓因果方向：**必须先由驱动程序启动设备，设备做完才触发中断处理程序**，故顺序必为：**用户层 I/O 软件 → 设备独立性软件（系统调用处理）→ 设备驱动程序 → 中断处理程序**。
> - **2023#46 键盘输入**：`read` 无数据立即将进程 $P$ 插入**阻塞队列**（此后 CPU 立刻切走调度他程）→ 用户按键 → 启动**键盘中断处理程序**（此时 $P$ 仍处于**阻塞态**，CPU 处于**内核态**）→ **键盘驱动程序**把字符从控制器数据端口读入内核缓冲区 → 将 $P$ 移入**就绪队列**（此后调度程序才可能选中 $P$）→ $P$ 从系统调用返回。

<figure class="cpd-figure not-content" id="os-c7-fig-5">
  <svg viewBox="0 0 720 384" role="img" aria-label="IO软件四层层次结构与一次读磁盘双向控制数据流">
    <defs>
      <marker id="os-c7-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="74" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="104" width="692" height="268" rx="7"/>
    <line class="fig-line-dashed" x1="20" y1="95" x2="700" y2="95" stroke="var(--sl-color-red)"/>
    <rect class="fig-box-blue" x="210" y="24" width="300" height="52" rx="5"/>
    <rect class="fig-box-purple" x="210" y="120" width="300" height="62" rx="5"/>
    <rect class="fig-box-orange" x="210" y="196" width="300" height="60" rx="5"/>
    <rect class="fig-box-green" x="210" y="270" width="300" height="50" rx="5"/>
    <rect class="fig-box" x="210" y="330" width="300" height="32" rx="5"/>
    <rect class="fig-box" x="28" y="26" width="160" height="46" rx="4"/>
    <rect class="fig-box" x="28" y="126" width="160" height="50" rx="4"/>
    <rect class="fig-box" x="28" y="202" width="160" height="48" rx="4"/>
    <rect class="fig-box" x="532" y="26" width="160" height="46" rx="4"/>
    <rect class="fig-box" x="532" y="126" width="160" height="50" rx="4"/>
    <rect class="fig-box" x="532" y="202" width="160" height="48" rx="4"/>
    <rect class="fig-box" x="532" y="272" width="160" height="46" rx="4"/>
    <line class="fig-line-accent" x1="108" y1="72" x2="108" y2="124" marker-end="url(#os-c7-arr-5)"/>
    <line class="fig-line-accent" x1="108" y1="176" x2="108" y2="200" marker-end="url(#os-c7-arr-5)"/>
    <path class="fig-line-accent" d="M 108 250 L 108 346 L 208 346" marker-end="url(#os-c7-arr-5)"/>
    <path class="fig-line-green" d="M 510 346 L 612 346 L 612 320" marker-end="url(#os-c7-arr-5)"/>
    <line class="fig-line-green" x1="612" y1="272" x2="612" y2="252" marker-end="url(#os-c7-arr-5)"/>
    <line class="fig-line-green" x1="612" y1="202" x2="612" y2="178" marker-end="url(#os-c7-arr-5)"/>
    <line class="fig-line-green" x1="612" y1="126" x2="612" y2="74" marker-end="url(#os-c7-arr-5)"/>
    <rect class="fig-box" x="266" y="85" width="188" height="19" rx="4"/>
    <text class="fig-red" x="360" y="98" font-size="9.2" text-anchor="middle">唯一态切换边界 (User ↔ Kernel)</text>
    <text class="fig-muted" x="116" y="117" font-size="9.2">向下：发起请求</text>
    <text class="fig-muted" x="604" y="117" font-size="9.2" text-anchor="end">向上：中断完成</text>
    <text class="fig-blue" x="360" y="44" font-size="11.2" text-anchor="middle">第 1 层：用户层 I/O 软件（用户态）</text>
    <text class="fig-muted" x="360" y="62" font-size="9.5" text-anchor="middle">库函数封装（printf/scanf）· 系统调用 API · SPOOLing 进程</text>
    <text class="fig-purple" x="360" y="140" font-size="11.2" text-anchor="middle">第 2 层：设备独立性软件（内核态）</text>
    <text class="fig-muted" x="360" y="157" font-size="9.3" text-anchor="middle">统一驱动接口 · LUT 逻辑物理映射 · 设备保护 · 逻辑块视图</text>
    <text class="fig-muted" x="360" y="172" font-size="9.3" text-anchor="middle">缓冲管理 · 设备分配回收 · I/O 调度 · 永久性差错报告</text>
    <text class="fig-orange" x="360" y="216" font-size="11.2" text-anchor="middle">第 3 层：设备驱动程序（内核态 ★）</text>
    <text class="fig-muted" x="360" y="233" font-size="9.3" text-anchor="middle">唯一碰硬件寄存器布局！抽象块号→CHS·写端口·就地重传</text>
    <text class="fig-muted" x="360" y="248" font-size="9.3" text-anchor="middle">必须可重入 · 与控制方式（轮询/中断/DMA）紧密相关</text>
    <text class="fig-green" x="360" y="290" font-size="11.2" text-anchor="middle">第 4 层：中断处理程序（内核态）</text>
    <text class="fig-muted" x="360" y="308" font-size="9.3" text-anchor="middle">面向硬件中断机制 · 判原因 · 搬数据入内核缓冲 · 唤醒进程</text>
    <text class="fig-label" x="360" y="350" font-size="10.5" text-anchor="middle">硬件层（设备控制器寄存器 / DMA / 物理磁盘或外设）</text>
    <text class="fig-label" x="108" y="45" font-size="9.8" text-anchor="middle">① read() 陷入内核</text>
    <text class="fig-muted" x="108" y="61" font-size="8.8" text-anchor="middle">发抽象块读请求</text>
    <text class="fig-label" x="108" y="145" font-size="9.8" text-anchor="middle">② 查缓存/LUT/权限</text>
    <text class="fig-muted" x="108" y="162" font-size="8.8" text-anchor="middle">未命中则进程阻塞</text>
    <text class="fig-label" x="108" y="221" font-size="9.8" text-anchor="middle">③ 译成 CHS 写端口</text>
    <text class="fig-muted" x="108" y="238" font-size="8.8" text-anchor="middle">启动硬件并阻塞</text>
    <text class="fig-label" x="612" y="45" font-size="9.8" text-anchor="middle">⑦ 返回用户态</text>
    <text class="fig-muted" x="612" y="61" font-size="8.8" text-anchor="middle">用户获得读入数据</text>
    <text class="fig-label" x="612" y="145" font-size="9.8" text-anchor="middle">⑥ 拷入用户缓冲区</text>
    <text class="fig-muted" x="612" y="162" font-size="8.8" text-anchor="middle">调度选中再执行</text>
    <text class="fig-label" x="612" y="221" font-size="9.8" text-anchor="middle">⑤ 搬入内核缓冲</text>
    <text class="fig-muted" x="612" y="238" font-size="8.8" text-anchor="middle">校验并唤醒进程</text>
    <text class="fig-label" x="612" y="291" font-size="9.8" text-anchor="middle">④ 设备完成发中断</text>
    <text class="fig-muted" x="612" y="308" font-size="8.8" text-anchor="middle">ISR 响应并判原因</text>
  </svg>
  <figcaption>图 7-5　I/O 软件四层层次结构、内核核心子系统边界与一次读盘双向执行链路</figcaption>
</figure>

#### 7.3.3 应用层 I/O 接口、驱动程序接口与阻塞/非阻塞/异步 I/O

1. **输入/输出应用程序接口（系统调用接口）**

为了实现“一切皆文件”的统一调用形式，同时尊重底层设备不可抹除的**语义单位差异**，内核向应用层开放三类设备接口：

- **字符设备接口**：面向键盘、鼠标、打印机等不可寻址流设备，基本操作为单字符 `get`/`put`。为避免每个字符陷入内核一次的巨大切换开销，终端驱动通常采用**行缓冲**——输入侧凑够一行（按回车）才交予应用，期间用户进程挂起；输出侧进程送入一行即可继续，仅当第二行到来而第一行尚未被设备取空时才阻塞。
- **块设备接口**：面向磁盘、SSD 等可寻址块设备，按数据块（$512\text{ B}\sim 4\text{ KB}$）`read`/`write` 并支持 `lseek` 随机定位，同时提供<strong>内存映射文件接口（<code>mmap</code>）</strong>跳过传统缓冲区拷贝。
- **网络设备接口**：由于网络存在**连接语义**、多条并发连接以及报文丢包不可靠特性，无法直接套用磁盘寻址语义，故单独抽象出 **Socket（套接字）**（`socket`/`bind`/`listen`/`connect`/`send`/`recv`），建立连接后再退化为按文件描述符（`fd`）读写。

> **注意（同名两条边界辨析）**：应用程序接口的 `open`/`close`/`read`/`write`/`ioctl` 是**内核向应用开放的系统调用**；而驱动程序接口的 `open`/`close`/`read`/`write`/`ioctl`（外加中断处理入口）是**驱动向内核设备独立性软件注册的函数指针表**（类似 VFS 的虚函数表手法），签名为统一约定、硬件差异封在函数体中。**`ioctl`** 则是统一接口外合法的“逃生通道”，专用于传达弹出光盘、设置波特率等设备专属指令。

2. **设备驱动程序的核心特征与五步处理过程（2022#32、2026#31）**

驱动程序的五步标准启动流程遵循<strong>“从最便宜的检查到最不可逆的硬件动作”</strong>：**① 抽象要求转具体参数**（逻辑块号 $\to$ CHS） → **② 合法性校验**（如对只读打开设备发写、向打印机发读均报错） → **③ 读状态寄存器查设备就绪** → **④ 写入数据/控制/方式参数**（速率、校验位等） → **⑤ 写命令寄存器启动设备**并阻塞等待中断。

- **四大核心考点特征**：
  1. **与 I/O 控制方式紧密相关**（2022#32）：同一款设备若分别采用轮询、中断、DMA 编写，驱动源码结构迥异（轮询需自己死等 DSR，中断要注册 ISR 并阻塞，DMA 需多配 MAR/DC 寄存器）。**“驱动与 I/O 控制方式无关”是经典错项！**
  2. **驱动阻塞自身**（2022#32）：驱动向控制器发出启动命令后将控制权交回内核并**把自己阻塞**，从而使处理机与设备真正并行；故**进程在执行驱动程序时可能进入阻塞态**。
  3. **必须运行在内核态且可重入**：因为要直接读写端口与特权 I/O 指令，错误可拖垮整个内核；可能同时被多进程并发重入调用，故不能依赖非保护的全局状态变量。
  4. **按设备类型配置而非按台数配置**：多台同型号终端可共用同一份驱动。

3. **阻塞、非阻塞与异步 I/O 对比**

| 特性维度 | 阻塞 I/O（Blocking） | 非阻塞 I/O（Non-blocking） | 异步 I/O（Asynchronous） |
| --- | --- | --- | --- |
| **调用后是否立即返回** | **否**，进程阻塞并让出 CPU | **是**，立即返回（可能 0 字节或部分数据） | **是**，立即返回（内核承诺替你做完） |
| **数据谁来搬进用户缓冲区** | 内核唤醒时同步搬完 | **进程自己**轮询检测到就绪后再同步调 `read` 搬 | **内核全程自动**等待外设并搬入用户缓冲区 |
| **一次逻辑读系统调用次数** | 1 次 | 多次（反复轮询检测状态） | **1 次**（完成后通过信号/回调通知） |
| **适用与吞吐直觉** | 进程无别事可做时，阻塞让出 CPU **反而提高系统整体吞吐** | 进程需同时轮询多路且不愿切走 | 高并发异步架构，彻底解放应用等待与拷贝轮询 |

<figure class="cpd-figure not-content" id="os-c7-fig-6">
  <svg viewBox="0 0 720 276" role="img" aria-label="阻塞IO、非阻塞IO与异步IO时空行为及数据拷贝责任对比">
    <defs>
      <marker id="os-c7-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="80" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="100" width="692" height="80" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="188" width="692" height="78" rx="6"/>
    <rect class="fig-box" x="128" y="34" width="76" height="36" rx="4"/>
    <rect class="fig-box-red" x="220" y="34" width="234" height="36" rx="4"/>
    <rect class="fig-box-orange" x="470" y="34" width="120" height="36" rx="4"/>
    <rect class="fig-box-green" x="606" y="34" width="84" height="36" rx="4"/>
    <line class="fig-line-accent" x1="204" y1="52" x2="218" y2="52" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="454" y1="52" x2="468" y2="52" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="590" y1="52" x2="604" y2="52" marker-end="url(#os-c7-arr-6)"/>
    <rect class="fig-box-blue" x="128" y="122" width="110" height="36" rx="4"/>
    <rect class="fig-box-blue" x="252" y="122" width="110" height="36" rx="4"/>
    <rect class="fig-box-blue" x="376" y="122" width="90" height="36" rx="4"/>
    <rect class="fig-box-orange" x="480" y="122" width="112" height="36" rx="4"/>
    <rect class="fig-box-green" x="606" y="122" width="84" height="36" rx="4"/>
    <line class="fig-line-accent" x1="238" y1="140" x2="250" y2="140" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="362" y1="140" x2="374" y2="140" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="466" y1="140" x2="478" y2="140" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="592" y1="140" x2="604" y2="140" marker-end="url(#os-c7-arr-6)"/>
    <rect class="fig-box-green" x="128" y="210" width="96" height="36" rx="4"/>
    <rect class="fig-box-purple" x="240" y="210" width="214" height="36" rx="4"/>
    <rect class="fig-box-orange" x="470" y="210" width="120" height="36" rx="4"/>
    <rect class="fig-box-green" x="606" y="210" width="84" height="36" rx="4"/>
    <line class="fig-line-accent" x1="224" y1="228" x2="238" y2="228" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="454" y1="228" x2="468" y2="228" marker-end="url(#os-c7-arr-6)"/>
    <line class="fig-line-accent" x1="590" y1="228" x2="604" y2="228" marker-end="url(#os-c7-arr-6)"/>
    <text class="fig-red" x="26" y="46" font-size="11">① 阻塞 I/O</text>
    <text class="fig-muted" x="26" y="64" font-size="9.2">让出 CPU·等待</text>
    <text class="fig-label" x="166" y="56" font-size="10" text-anchor="middle">read() 调用</text>
    <text class="fig-red" x="337" y="50" font-size="10" text-anchor="middle">进程阻塞切走（内核等数据就绪）</text>
    <text class="fig-muted" x="337" y="64" font-size="8.8" text-anchor="middle">CPU 转去执行其他就绪进程</text>
    <text class="fig-orange" x="530" y="50" font-size="9.8" text-anchor="middle">内核拷入用户区</text>
    <text class="fig-muted" x="530" y="64" font-size="8.8" text-anchor="middle">同步阻塞完成</text>
    <text class="fig-green" x="648" y="56" font-size="10" text-anchor="middle">唤醒并继续</text>
    <text class="fig-blue" x="26" y="134" font-size="11">② 非阻塞 I/O</text>
    <text class="fig-muted" x="26" y="152" font-size="9.2">轮询·立即返回</text>
    <text class="fig-blue" x="183" y="137" font-size="9.5" text-anchor="middle">read()→未就绪</text>
    <text class="fig-muted" x="183" y="151" font-size="8.5" text-anchor="middle">立刻返回继续跑</text>
    <text class="fig-blue" x="307" y="137" font-size="9.5" text-anchor="middle">read()→未就绪</text>
    <text class="fig-muted" x="307" y="151" font-size="8.5" text-anchor="middle">轮询查状态</text>
    <text class="fig-blue" x="421" y="137" font-size="9.5" text-anchor="middle">就绪触发</text>
    <text class="fig-muted" x="421" y="151" font-size="8.5" text-anchor="middle">发起读入</text>
    <text class="fig-orange" x="536" y="137" font-size="9.5" text-anchor="middle">进程调 read 拷贝</text>
    <text class="fig-muted" x="536" y="151" font-size="8.5" text-anchor="middle">此段仍同步等</text>
    <text class="fig-green" x="648" y="144" font-size="10" text-anchor="middle">处理数据</text>
    <text class="fig-green" x="26" y="222" font-size="11">③ 异步 I/O</text>
    <text class="fig-muted" x="26" y="240" font-size="9.2">全程托管给内核</text>
    <text class="fig-green" x="176" y="225" font-size="9.5" text-anchor="middle">aio_read()</text>
    <text class="fig-muted" x="176" y="239" font-size="8.5" text-anchor="middle">1 次即返回</text>
    <text class="fig-purple" x="347" y="225" font-size="10" text-anchor="middle">进程无阻跑主线；内核后台等设备</text>
    <text class="fig-muted" x="347" y="239" font-size="8.8" text-anchor="middle">彻底免除轮询</text>
    <text class="fig-orange" x="530" y="225" font-size="9.8" text-anchor="middle">内核拷入用户区</text>
    <text class="fig-muted" x="530" y="239" font-size="8.8" text-anchor="middle">内核主动搬完</text>
    <text class="fig-green" x="648" y="225" font-size="9.8" text-anchor="middle">信号/回调</text>
    <text class="fig-muted" x="648" y="239" font-size="8.5" text-anchor="middle">通知可用</text>
  </svg>
  <figcaption>图 7-6　阻塞、非阻塞与异步 I/O 两道分界线：进程是否阻塞让出 CPU vs 数据拷贝由谁同步完成</figcaption>
</figure>

---

### 7.4 设备分配与回收、逻辑设备表与 SPOOLing ★

#### 7.4.1 设备分配的数据结构与四要素

在带通道的大型系统中，一次物理 I/O 需要打通**内存 $\leftrightarrow$ 通道 $\leftrightarrow$ 控制器 $\leftrightarrow$ 设备**整条链路，因此内核按物理链路从顶至下建立四级控制表，**三级中任一级忙碌都会导致分配阻塞**：

1. **系统设备表（SDT）**：全系统仅 **1 张**，登记系统中全部物理设备表目（设备类型、标识符、**指向 DCT 的指针**、**驱动程序入口**）。
2. **设备控制表（DCT）**：**每台物理设备 1 张**，含设备类型、设备标识、**忙/闲标志**、**等待队列队首指针**（挂阻塞进程的 PCB）、**指向 COCT 的指针**、以及**重复执行次数**（差错控制的重试上限）。
3. **控制器控制表（COCT）**：**每个设备控制器 1 张**，含控制器标识、忙/闲标志、等待队列指针、**指向 CHCT 的指针**。
4. **通道控制表（CHCT）**：**每个通道 1 张**，含通道标识、忙/闲标志、等待队列指针。

> **★考点（设备分配考虑的四项因素，2023#32）**：系统进行设备分配时必须同时考量以下四项，缺一不可——**① 设备的类型**（固有属性：独占/共享/虚拟）、**② 设备的访问权限**、**③ 设备的占用状态**（忙/闲）、**④ 逻辑设备与物理设备的映射关系**。

#### 7.4.2 设备分配策略、安全分配与回收流程

- **静态分配 vs 动态分配**：静态分配在作业/进程启动前一次分给全部独占设备直至结束才归还（易浪费，但防止运行中动态抢锁）；动态分配按需申请、用完即还，资源利用率高。
- **安全分配 vs 不安全分配**（与死锁章节共用判定逻辑）：
  - **安全分配**：进程发出 I/O 请求后**立即进入阻塞态**直到 I/O 完成才被唤醒。因进程在占用一台设备期间**无法运行也无法继续申请另一台设备**，直接**摒弃了死锁的“请求和保持”必要条件**，绝对不会死锁；代价是 CPU 与 I/O 串行。
  - **不安全分配**：发出请求后可继续运行，仅当所求设备被占用时才阻塞。允许一进程同时并发操控多台设备、推进快，但每次分配必须执行安全性检查以防陷入不安全状态引发死锁。
- **分配与回收完整步骤**：
  - **分配**：按请求查 SDT → 找 DCT 检查忙闲（忙则入 DCT 等待队列；闲则按安全性分配）→ 顺 DCT 查 COCT 检查忙闲 → 顺 COCT 查 CHCT 检查忙闲。**只有设备、控制器、通道三者全闲，链路才建立并启动设备**；任一级忙均把 PCB 挂入该级等待队列。
  - **回收**：按镜像逆序逐级释放——置 DCT 为闲并唤醒 DCT 等待队首进程 → 置 COCT 为闲并唤醒 COCT 队首 → 置 CHCT 为闲并唤醒 CHCT 队首 → 若经 LUT 分配则注销 LUT 表项。

#### 7.4.3 设备独立性与逻辑设备表（LUT）

若进程直接用“物理设备名”申请独占设备，不仅换设备需改程序，而且即使同类另一台打印机正空闲也只能死等。**设备独立性**的解法是：**程序员通过系统调用打开设备时，仅使用逻辑设备名（如 `/dev/printer` 或文件名 `/dev/sda`），系统通过逻辑设备表（LUT，Logical Unit Table）动态映射到空闲的同类物理设备**。

- **LUT 表项结构**：`[ 逻辑设备名 | 物理设备名 | 驱动程序入口地址 ]`（冗余存储驱动入口是为了直接跳转而省去二次查 SDT）。
- **LUT 的两种设置范围**：
  - **整个系统设一张 LUT**：所有用户共享，逻辑设备名**不允许重名**，适用于单用户系统。
  - **为每个用户（或进程 PCB）设一张 LUT**：不同用户可使用相同逻辑设备名（如都叫 `printer`），彼此隔离映射，适用于**多用户系统**。

> **★考点（2009#32、2020#30）**：① 程序员在程序中打开设备使用的是**逻辑设备名**（不能是物理设备名、主设备号或从设备号）；② 具备设备独立性的系统可用**文件名**访问物理设备，换用物理设备时**无需修改应用程序**（仅修改 LUT 映射），并支持 **I/O 重定向**（把标准输出重映射到文件或另一设备）。

<figure class="cpd-figure not-content" id="os-c7-fig-7">
  <svg viewBox="0 0 720 314" role="img" aria-label="设备分配四级控制表SDT到DCT到COCT到CHCT与逻辑设备表LUT映射">
    <defs>
      <marker id="os-c7-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="444" height="290" rx="7"/>
    <rect class="fig-box-subtle" x="470" y="12" width="236" height="290" rx="7"/>
    <rect class="fig-box-blue" x="28" y="46" width="132" height="104" rx="5"/>
    <rect class="fig-box-orange" x="184" y="46" width="130" height="122" rx="5"/>
    <rect class="fig-box-purple" x="336" y="46" width="110" height="104" rx="5"/>
    <rect class="fig-box-green" x="336" y="176" width="110" height="72" rx="5"/>
    <rect class="fig-box" x="28" y="190" width="286" height="98" rx="5"/>
    <line class="fig-line-accent" x1="160" y1="88" x2="182" y2="88" marker-end="url(#os-c7-arr-7)"/>
    <line class="fig-line-accent" x1="314" y1="98" x2="334" y2="98" marker-end="url(#os-c7-arr-7)"/>
    <line class="fig-line-accent" x1="391" y1="150" x2="391" y2="174" marker-end="url(#os-c7-arr-7)"/>
    <rect class="fig-box-accent" x="484" y="46" width="208" height="44" rx="4"/>
    <rect class="fig-box" x="484" y="106" width="208" height="106" rx="4"/>
    <rect class="fig-box-green" x="484" y="228" width="208" height="60" rx="4"/>
    <line class="fig-line-accent" x1="588" y1="90" x2="588" y2="104" marker-end="url(#os-c7-arr-7)"/>
    <text class="fig-title" x="28" y="32" font-size="11.5">① 四级分配表（沿物理链路：仅全闲才分配）</text>
    <text class="fig-blue" x="94" y="64" font-size="10.2" text-anchor="middle">SDT 系统设备表</text>
    <text class="fig-muted" x="94" y="80" font-size="9" text-anchor="middle">（全系统唯一 1 张）</text>
    <text class="fig-label" x="94" y="98" font-size="9" text-anchor="middle">• 设备类型 / 标识符</text>
    <text class="fig-label" x="94" y="114" font-size="9" text-anchor="middle">• DCT 指针 →</text>
    <text class="fig-label" x="94" y="130" font-size="9" text-anchor="middle">• 驱动程序入口</text>
    <text class="fig-orange" x="249" y="64" font-size="10.2" text-anchor="middle">DCT 设备控制表</text>
    <text class="fig-muted" x="249" y="80" font-size="9" text-anchor="middle">（每台设备 1 张）</text>
    <text class="fig-label" x="249" y="98" font-size="9" text-anchor="middle">• 类型 / 忙闲标志</text>
    <text class="fig-label" x="249" y="114" font-size="9" text-anchor="middle">• 等待队首 PCB</text>
    <text class="fig-label" x="249" y="130" font-size="9" text-anchor="middle">• COCT 指针 →</text>
    <text class="fig-label" x="249" y="146" font-size="9" text-anchor="middle">• 重复执行次数</text>
    <text class="fig-purple" x="391" y="64" font-size="10" text-anchor="middle">COCT 控制器表</text>
    <text class="fig-muted" x="391" y="80" font-size="8.8" text-anchor="middle">（每控制器 1 张）</text>
    <text class="fig-label" x="391" y="98" font-size="8.8" text-anchor="middle">• 忙闲 / 队列指针</text>
    <text class="fig-label" x="391" y="116" font-size="8.8" text-anchor="middle">• CHCT 指针 ↓</text>
    <text class="fig-green" x="391" y="194" font-size="10" text-anchor="middle">CHCT 通道表</text>
    <text class="fig-muted" x="391" y="210" font-size="8.8" text-anchor="middle">（每通道 1 张）</text>
    <text class="fig-label" x="391" y="228" font-size="8.8" text-anchor="middle">• 忙闲 / 队列指针</text>
    <text class="fig-label" x="38" y="210" font-size="9.8">★ 设备分配考量四因素（2023#32）：</text>
    <text class="fig-muted" x="38" y="228" font-size="9">1. 设备类型（独占/共享/虚拟）</text>
    <text class="fig-muted" x="38" y="244" font-size="9">2. 设备访问权限  3. 当前忙闲状态</text>
    <text class="fig-muted" x="38" y="260" font-size="9">4. 逻辑设备与物理设备映射关系</text>
    <text class="fig-red" x="38" y="278" font-size="9">★ 安全分配：请求后立即阻塞（防死锁）</text>
    <text class="fig-title" x="484" y="32" font-size="11.5">② 逻辑设备表 LUT（设备独立性）</text>
    <text class="fig-accent" x="588" y="65" font-size="10" text-anchor="middle">用户应用 open(&quot;/dev/printer&quot;)</text>
    <text class="fig-muted" x="588" y="81" font-size="8.8" text-anchor="middle">只能用逻辑名（2009#32 / 2020#30）</text>
    <text class="fig-label" x="588" y="124" font-size="9.8" text-anchor="middle">LUT 表项（三元组）</text>
    <text class="fig-muted" x="494" y="146" font-size="8.8">逻辑设备名</text>
    <text class="fig-muted" x="562" y="146" font-size="8.8">物理设备名</text>
    <text class="fig-muted" x="634" y="146" font-size="8.8">驱动入口</text>
    <text class="fig-label" x="494" y="166" font-size="8.8">printer</text>
    <text class="fig-label" x="562" y="166" font-size="8.8">dev_prn_2</text>
    <text class="fig-label" x="634" y="166" font-size="8.8">0xC080</text>
    <text class="fig-label" x="494" y="186" font-size="8.8">/dev/sda</text>
    <text class="fig-label" x="562" y="186" font-size="8.8">disk_0_0</text>
    <text class="fig-label" x="634" y="186" font-size="8.8">0xD120</text>
    <text class="fig-muted" x="588" y="203" font-size="8.5" text-anchor="middle">多用户系统应每用户（PCB）配 1 张</text>
    <text class="fig-green" x="588" y="246" font-size="9.5" text-anchor="middle">设备独立性三大收益：</text>
    <text class="fig-muted" x="588" y="263" font-size="8.8" text-anchor="middle">• 换物理设备不改应用（改 LUT）</text>
    <text class="fig-muted" x="588" y="278" font-size="8.8" text-anchor="middle">• 同类空闲即用 · 支持 I/O 重定向</text>
  </svg>
  <figcaption>图 7-7　设备分配四级数据结构（SDT → DCT → COCT → CHCT）与逻辑设备表（LUT）映射机制</figcaption>
</figure>

#### 7.4.4 假脱机技术（SPOOLing）★

**SPOOLing**（Simultaneous Peripheral Operations On-Line，联机同时外围操作），又称**假脱机技术**，是在**多道程序设计技术**、**通道技术**与<strong>高速随机外存（磁盘）</strong>三个前提支持下，用主机软件进程模拟早期脱机输入/输出中的“外围控制机（卫星机）”，**把低速独占设备虚拟改造成多进程可共享的虚拟设备**。

- **SPOOLing 系统的四大硬件/软件部件**：
  1. **输入井与输出井**：开辟在**磁盘**上的两个存储区域（井内以**井文件**形式组织各作业的数据并链接成输入/输出队列）。
  2. **输入缓冲区与输出缓冲区**：开辟在**内存**中的中转区域，缓和磁盘与低速外设之间的速度差（注：两外设之间不能跳过内存/主存直传，必须借内存缓冲区中转）。
  3. **输入进程（预输入进程 $SP_i$）与输出进程（缓输出进程 $SP_o$）**：模拟脱机外围控制机，专门负责**低速外设 $\leftrightarrow$ 内存缓冲区 $\leftrightarrow$ 磁盘井**之间的**实际 I/O 传送**。
  4. **井管理程序**：负责**运行中的用户作业 $\leftrightarrow$ 磁盘输入/输出井**之间的**虚拟 I/O**（作业要读数据时由井管理程序从输入井取出，作业要打印/输出时交由井管理程序存入输出井）。

- **共享打印机（SPOOLing 经典落法）与守护进程（Daemon）**：
  当多进程同时请求一台独占打印机时，系统**根本不把物理打印机分配给进程**，而是由假脱机管理进程做两件事：① 在磁盘输出井中申请空闲盘块存入待打印数据；② 填写一张**用户请求打印表**（含井中位置、份数、格式）并**挂到请求打印队列**，随后**立即返回**（进程视打印已完成）。真正的物理打印由后台**假脱机打印进程**（或作为唯一允许操作打印机的**守护进程**）逐张摘取队首请求打印，队列空时打印进程阻塞自身。

> **★考点（2016#31 必防坑点）**：
> - **SPOOLing 的三大特点**：① **提高了 I/O 速度**（高速虚拟 I/O 代替低速实际 I/O）；② **将独占设备改造为共享设备**（物理上打印机仍串行独占，逻辑上多进程同时提交请求）；③ **实现了虚拟设备功能**。
> - **死锁免疫本质**：系统分配给进程的是“磁盘输出井空间 + 打印请求表”（而非独占物理打印机），从而**破坏了死锁的“互斥”必要条件**，不会因争抢打印机死锁。
> - **最易出错选项（2016#31 错项）**：**“由用户作业控制设备与输入/输出井之间的数据传送”是错误的！** 这段实际外设与磁盘井之间的数据传送完全由 **SPOOLing 的输入/输出进程（系统后台进程）** 控制，用户作业只负责把数据写入输出井并挂请求就立刻返回继续计算。

<figure class="cpd-figure not-content" id="os-c7-fig-8">
  <svg viewBox="0 0 720 324" role="img" aria-label="SPOOLing假脱机打印系统架构图与虚拟IO和实际IO分离机制">
    <defs>
      <marker id="os-c7-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="300" rx="7"/>
    <rect class="fig-box-subtle" x="28" y="48" width="96" height="196" rx="5"/>
    <rect class="fig-box-subtle" x="150" y="48" width="112" height="196" rx="5"/>
    <rect class="fig-box-subtle" x="290" y="48" width="176" height="196" rx="5"/>
    <rect class="fig-box-subtle" x="492" y="48" width="196" height="196" rx="5"/>
    <rect class="fig-box" x="36" y="74" width="80" height="44" rx="4"/>
    <rect class="fig-box-blue" x="36" y="168" width="80" height="58" rx="4"/>
    <rect class="fig-box-purple" x="160" y="74" width="92" height="44" rx="4"/>
    <rect class="fig-box-purple" x="160" y="176" width="92" height="44" rx="4"/>
    <rect class="fig-box-green" x="302" y="74" width="152" height="60" rx="4"/>
    <rect class="fig-box-orange" x="302" y="162" width="152" height="66" rx="4"/>
    <rect class="fig-box-blue" x="504" y="74" width="172" height="62" rx="4"/>
    <rect class="fig-box-blue" x="504" y="162" width="172" height="66" rx="4"/>
    <rect class="fig-box-accent" x="28" y="256" width="660" height="44" rx="4"/>
    <line class="fig-line-accent" x1="116" y1="96" x2="158" y2="96" marker-end="url(#os-c7-arr-8)"/>
    <line class="fig-line-accent" x1="252" y1="96" x2="300" y2="96" marker-end="url(#os-c7-arr-8)"/>
    <line class="fig-line-accent" x1="454" y1="104" x2="502" y2="104" marker-end="url(#os-c7-arr-8)"/>
    <line class="fig-line-green" x1="502" y1="196" x2="456" y2="196" marker-end="url(#os-c7-arr-8)"/>
    <line class="fig-line-green" x1="300" y1="196" x2="254" y2="196" marker-end="url(#os-c7-arr-8)"/>
    <line class="fig-line-green" x1="158" y1="196" x2="118" y2="196" marker-end="url(#os-c7-arr-8)"/>
    <text class="fig-title" x="360" y="32" font-size="12" text-anchor="middle">SPOOLing 假脱机系统架构（软件进程 + 磁盘井 + 内存缓冲模拟外围控制机）</text>
    <text class="fig-muted" x="76" y="64" font-size="9.5" text-anchor="middle">低速独占外设</text>
    <text class="fig-label" x="76" y="93" font-size="10" text-anchor="middle">输入设备</text>
    <text class="fig-muted" x="76" y="109" font-size="8.8" text-anchor="middle">读卡/扫描仪</text>
    <text class="fig-blue" x="76" y="187" font-size="10" text-anchor="middle">共享打印机</text>
    <text class="fig-muted" x="76" y="203" font-size="8.8" text-anchor="middle">物理仍串行</text>
    <text class="fig-muted" x="76" y="218" font-size="8.8" text-anchor="middle">唯一被守护</text>
    <text class="fig-muted" x="206" y="64" font-size="9.5" text-anchor="middle">内存缓冲区</text>
    <text class="fig-purple" x="206" y="93" font-size="9.8" text-anchor="middle">输入缓冲区</text>
    <text class="fig-muted" x="206" y="109" font-size="8.5" text-anchor="middle">输入进程 SPi 控</text>
    <text class="fig-purple" x="206" y="194" font-size="9.8" text-anchor="middle">输出缓冲区</text>
    <text class="fig-muted" x="206" y="210" font-size="8.5" text-anchor="middle">输出进程 SPo 控</text>
    <text class="fig-muted" x="378" y="64" font-size="9.5" text-anchor="middle">磁盘（高速随机外存）</text>
    <text class="fig-green" x="378" y="94" font-size="10.2" text-anchor="middle">输入井（井文件队列）</text>
    <text class="fig-muted" x="378" y="110" font-size="8.8" text-anchor="middle">预读收容输入数据</text>
    <text class="fig-muted" x="378" y="125" font-size="8.8" text-anchor="middle">井管理程序取用</text>
    <text class="fig-orange" x="378" y="180" font-size="10.2" text-anchor="middle">输出井（打印请求队列）</text>
    <text class="fig-muted" x="378" y="197" font-size="8.2" text-anchor="middle">Job1 表 → Job2 表 → Job3 表</text>
    <text class="fig-muted" x="378" y="213" font-size="8.8" text-anchor="middle">进程写完井+挂表即返回</text>
    <text class="fig-muted" x="590" y="64" font-size="9.5" text-anchor="middle">主机内存运行的用户进程</text>
    <text class="fig-blue" x="590" y="96" font-size="10" text-anchor="middle">需输入数据的用户作业</text>
    <text class="fig-muted" x="590" y="114" font-size="8.8" text-anchor="middle">经井管理程序高速虚拟读入</text>
    <text class="fig-blue" x="590" y="182" font-size="10" text-anchor="middle">进程 P1 / P2 / P3 打印请求</text>
    <text class="fig-muted" x="590" y="200" font-size="8.8" text-anchor="middle">仅申请空闲盘块+打印表</text>
    <text class="fig-muted" x="590" y="216" font-size="8.8" text-anchor="middle">高速虚拟 I/O（互不阻塞）</text>
    <text class="fig-accent" x="358" y="274" font-size="10" text-anchor="middle">★ 必背考点：外设 ↔ 井的数据传送由输入/输出进程（SPi/SPo）完成，绝不是由用户作业控制（2016#31）</text>
    <text class="fig-muted" x="358" y="290" font-size="9.2" text-anchor="middle">三前提：多道程序 + 通道 + 高速外存 | 破坏死锁“互斥”条件（争磁盘空间而非物理打印机）</text>
  </svg>
  <figcaption>图 7-8　SPOOLing 假脱机系统双井双缓冲双进程数据流及共享打印机实现机理</figcaption>
</figure>

---

### 7.5 缓冲区管理与时空性能计算 ★

#### 7.5.1 引入缓冲的目的与磁盘高速缓存辨析

缓冲区（Buffer）是一块预留存储区（可用昂贵高速硬件寄存器如 TLB 快表实现，但**设备独立性软件层主要管理内存中的缓冲区**），用于化解生产者和消费者在**速度、粒度、时机**上的三重矛盾：

1. **缓和 CPU 与 I/O 设备速度不匹配**：生产者放下数据即走，消费者按自身节奏取走。
2. **减少对 CPU 的中断频率，放宽中断响应时间限制**：凑满一缓冲区才发一次中断，避免每字节打断 CPU。
3. **解决数据粒度不匹配**：**这是独立于速度匹配的矛盾**（即使两边速率相等，磁盘按 4 KB 块读写而程序仅需几个字节时仍须缓冲）。
4. **提高 CPU 与 I/O 设备的并行性**：以异步交接代替面对面串行等待。

**两级内存缓冲与磁盘高速缓存辨析（2015#28、2012#32）**：

| 存储区域 | 所在位置 | 核心机制 | 主要目的（408 高频） |
| --- | --- | --- | --- |
| **内核缓冲区** | 内核内存 | 预读（提前读）＋ 滞后写（延迟写） | **减少实际磁盘 I/O 次数**（**不是**减少寻道时间，也不是实现设备无关性） |
| **用户缓冲区** | 进程用户空间 | 一次 `read` 从内核多拷一批数据 | **减少系统调用与 CPU 态切换次数** |
| **磁盘高速缓存**<br>（Disk Cache） | 物理驻内存、逻辑属磁盘 | 固定专用缓存区 或 动态缓冲池（与请求分页共享空闲页框） | **“取走后是否保留”是它与一般缓冲区的根本分界**：普通缓冲区取走即空；磁盘高速缓存取走后仍留存副本以期再次命中 |

> **★考点（2012#32）**：能改善磁盘 I/O 性能的措施包括**重排 I/O 请求次序**（磁盘调度）、**预读与滞后写**（缓冲管理）、**优化文件物理块分布**（减少寻道）；而**在同一磁盘上划分多个分区不能改善性能**（分区仅是逻辑划分，甚至可能使访问跨区导致寻道变远）。

#### 7.5.2 单缓冲与双缓冲时空公式及流水线计算 ★

**硬性使用约束**：当缓冲区非空时，只能从中传出数据而不能往里充入数据；当缓冲区为空时，可以往里充入数据，但必须充满一整块后才能往外传出。

记三大阶段耗时：$T$ 为设备输入一块数据到缓冲区的时间，$M$ 为内核缓冲区拷贝到用户工作区的时间，$C$ 为 CPU 计算处理一块数据的时间。理解单、双缓冲公式无需死背，只需盯住唯一分水岭：**“在 $M$ 拷贝期间，外设能不能继续往缓冲区写下一块？”**

1. **单缓冲（Single Buffer）**：内存中仅设 $1$ 个缓冲区。
   - **冲突根源**：在 $M$ 期间，唯一缓冲区内的数据正在往外搬（尚未清空），设备被挡在门外无法开始下一块的 $T$ ；一旦 $M$ 结束、CPU 在工作区执行 $C$ 时，缓冲区已清空，设备可立即并行充入下一块（$T$ 与 $C$ 并行）。
   - **每块稳态平均耗时**：
     $$
     T_{\text{单稳态}} = \max(T, C) + M
     $$
   - **连续输入并处理完 $n$ 块的总时间（408 计算题防坑必背！）**：切忌直接用 $\max(T, C) + M$ 乘以 $n$！首块必须先经历 $T + M$ 才进入工作区，中间流转 $n - 1$ 个稳态周期，最后一块尚须在工作区完成计算 $C$：
     $$
     T_{\text{单总}}(n) = (T + M) + (n - 1)\big(\max(T, C) + M\big) + C = \begin{cases} n(T + M) + C, & T \ge C \\ T + n(C + M), & T &lt; C \end{cases}
     $$

2. **双缓冲（Double Buffer / 缓冲对换）**：内存中设 $2$ 个缓冲区（$A$ 与 $B$）。
   - **并发突破**：设备填满 $A$ 后立刻转头去填 $B$，同时 OS 把 $A$ 的数据搬到用户工作区（$M$）并交由 CPU 处理（$C$）。于是 $M$ **不再挡住设备**，$M$ 被推到 CPU 侧与 $C$ 串联成 $(C + M)$，整条设备侧 $T$ 与 CPU 侧 $(C + M)$ 完全两级流水并行！
   - **每块稳态平均耗时**：
     $$
     T_{\text{双稳态}} = \max(T, C + M)
     $$
   - **连续输入并处理完 $n$ 块的总时间**：首块充入缓冲区 $A$ 耗时 $T$ 后开启两级并行流转，历经 $n - 1$ 个稳态节拍后，最后一块进入工作区还需完成 $M + C$：
     $$
     T_{\text{双总}}(n) = T + (n - 1)\max(T, C + M) + (M + C) = \begin{cases} nT + M + C, & T \ge C + M \\ T + n(M + C), & T &lt; C + M \end{cases}
     $$

> **★考点（真题计算双雄：2011#31 & 2013#27）**：
> - **2011#31**：已知读取 $10$ 个磁盘块（$n = 10$），$T = 100\ \mu\text{s}$，$M = 50\ \mu\text{s}$，$C = 50\ \mu\text{s}$。
>   - **单缓冲**：$T \ge C$，稳态周期 $100 + 50 = 150\ \mu\text{s}$，总时间 $= 10 \times (100 + 50) + 50 = 1550\ \mu\text{s}$（若误乘 10 会错算成 $1500\ \mu\text{s}$）。
>   - **双缓冲**：$T = C + M = 100\ \mu\text{s}$，总时间 $= 10 \times 100 + 50 + 50 = 1100\ \mu\text{s}$。
> - **2013#27**：系统缓冲区与用户工作区均采用单缓冲，读入并分析 $2$ 个数据块（$n = 2$），$T = 100$，$M = 5$，$C = 90$。
>   - 因 $T = 100 > C = 90$，总时间 $= 2 \times (100 + 5) + 90 = 300$（时间线：第 1 块 `0～100` 读入、`100～105` 拷贝、`105～195` 分析；第 2 块在 `105～205` 并行读入、`205～210` 拷贝、`210～300` 分析完毕）。

3. **双机通信与一般缓冲区数 $n \ge 2$ 的本质结论**：
   - **双机通信**：两台主机各只设**单缓冲区**时，同一时刻只能实现**单向**传输（接收方未处理取空前无法兼作发送缓冲）；各配**双缓冲区**（一收一发）才可实现同一时刻的**全双工双向**传输。
   - **多缓冲区（$n \ge 2$）并不能突破稳态上限**：无论循环缓冲配 $2$ 个还是 $8$ 个缓冲区，两级流水的稳态平均每块耗时恒为 $\max(T, C + M)$（速度上限被卡在设备侧 $T$ 与 CPU 侧 $C + M$ 较慢的那一方）。多配缓冲区买来的是**抗速率突发波动的平滑度**；反之，若外设以恒定高速源源不断吐数据且 $C + M > T$，长期吞吐不足最终仍会导致缓冲区溢出丢数据。

<figure class="cpd-figure not-content" id="os-c7-fig-9">
  <svg viewBox="0 0 720 370" role="img" aria-label="单缓冲与双缓冲流水线时空甘特图及2011真题算例对照">
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="114" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="134" width="692" height="106" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="248" width="692" height="110" rx="7"/>
    <rect class="fig-box-blue" x="120" y="42" width="100" height="24" rx="3"/>
    <rect class="fig-box-orange" x="220" y="42" width="50" height="24" rx="3"/>
    <rect class="fig-box-blue" x="270" y="42" width="100" height="24" rx="3"/>
    <rect class="fig-box-orange" x="370" y="42" width="50" height="24" rx="3"/>
    <rect class="fig-box-blue" x="420" y="42" width="100" height="24" rx="3"/>
    <rect class="fig-box-orange" x="520" y="42" width="50" height="24" rx="3"/>
    <rect class="fig-box-green" x="270" y="72" width="50" height="24" rx="3"/>
    <rect class="fig-box-green" x="420" y="72" width="50" height="24" rx="3"/>
    <rect class="fig-box-green" x="570" y="72" width="50" height="24" rx="3"/>
    <line class="fig-line-dashed" x1="270" y1="40" x2="270" y2="104"/>
    <line class="fig-line-dashed" x1="420" y1="40" x2="420" y2="104"/>
    <line class="fig-line-dashed" x1="620" y1="40" x2="620" y2="104"/>
    <rect class="fig-box-blue" x="120" y="164" width="40" height="24" rx="3"/>
    <rect class="fig-box-orange" x="160" y="164" width="20" height="24" rx="3"/>
    <rect class="fig-box-blue" x="180" y="164" width="40" height="24" rx="3"/>
    <rect class="fig-box-orange" x="260" y="164" width="20" height="24" rx="3"/>
    <rect class="fig-box-blue" x="280" y="164" width="40" height="24" rx="3"/>
    <rect class="fig-box-orange" x="360" y="164" width="20" height="24" rx="3"/>
    <rect class="fig-box-green" x="180" y="194" width="80" height="24" rx="3"/>
    <rect class="fig-box-green" x="280" y="194" width="80" height="24" rx="3"/>
    <rect class="fig-box-green" x="380" y="194" width="80" height="24" rx="3"/>
    <line class="fig-line-dashed" x1="260" y1="162" x2="260" y2="226"/>
    <line class="fig-line-dashed" x1="360" y1="162" x2="360" y2="226"/>
    <rect class="fig-box-blue" x="120" y="276" width="100" height="22" rx="3"/>
    <rect class="fig-box-orange" x="220" y="276" width="50" height="22" rx="3"/>
    <rect class="fig-box-blue" x="320" y="276" width="100" height="22" rx="3"/>
    <rect class="fig-box-orange" x="420" y="276" width="50" height="22" rx="3"/>
    <rect class="fig-box-blue" x="220" y="302" width="100" height="22" rx="3"/>
    <rect class="fig-box-orange" x="320" y="302" width="50" height="22" rx="3"/>
    <rect class="fig-box-blue" x="420" y="302" width="100" height="22" rx="3"/>
    <rect class="fig-box-green" x="270" y="328" width="50" height="22" rx="3"/>
    <rect class="fig-box-green" x="370" y="328" width="50" height="22" rx="3"/>
    <rect class="fig-box-green" x="470" y="328" width="50" height="22" rx="3"/>
    <text class="fig-title" x="26" y="31" font-size="11">① 单缓冲 T ≥ C（2011#31：T=100, M=50, C=50 → 稳态周期 T+M = 150，10块总耗 1550）</text>
    <text class="fig-muted" x="26" y="58" font-size="9.5">唯一缓冲区</text>
    <text class="fig-muted" x="26" y="88" font-size="9.5">CPU 工作区</text>
    <text class="fig-blue" x="170" y="58" font-size="9.5" text-anchor="middle">T1 (100)</text>
    <text class="fig-orange" x="245" y="58" font-size="9" text-anchor="middle">M1</text>
    <text class="fig-blue" x="320" y="58" font-size="9.5" text-anchor="middle">T2 (100)</text>
    <text class="fig-orange" x="395" y="58" font-size="9" text-anchor="middle">M2</text>
    <text class="fig-blue" x="470" y="58" font-size="9.5" text-anchor="middle">T3 (100)</text>
    <text class="fig-orange" x="545" y="58" font-size="9" text-anchor="middle">M3</text>
    <text class="fig-green" x="295" y="88" font-size="9" text-anchor="middle">C1</text>
    <text class="fig-green" x="445" y="88" font-size="9" text-anchor="middle">C2</text>
    <text class="fig-green" x="595" y="88" font-size="9" text-anchor="middle">C3</text>
    <text class="fig-red" x="345" y="116" font-size="9.2" text-anchor="middle">M1 占住缓冲区挡住 T2；稳态周期 T+M = 150，最后一块单加 C = 50</text>
    <text class="fig-title" x="26" y="153" font-size="11">② 单缓冲 C &gt; T（示例：T=40, M=20, C=80 → 稳态周期 C+M = 100）</text>
    <text class="fig-muted" x="26" y="180" font-size="9.5">唯一缓冲区</text>
    <text class="fig-muted" x="26" y="210" font-size="9.5">CPU 工作区</text>
    <text class="fig-blue" x="140" y="180" font-size="9" text-anchor="middle">T1</text>
    <text class="fig-orange" x="170" y="180" font-size="8.5" text-anchor="middle">M1</text>
    <text class="fig-blue" x="200" y="180" font-size="9" text-anchor="middle">T2</text>
    <text class="fig-muted" x="240" y="180" font-size="7.8" text-anchor="middle">等C1</text>
    <text class="fig-orange" x="270" y="180" font-size="8.5" text-anchor="middle">M2</text>
    <text class="fig-blue" x="300" y="180" font-size="9" text-anchor="middle">T3</text>
    <text class="fig-muted" x="340" y="180" font-size="7.8" text-anchor="middle">等C2</text>
    <text class="fig-orange" x="370" y="180" font-size="8.5" text-anchor="middle">M3</text>
    <text class="fig-green" x="220" y="210" font-size="9.5" text-anchor="middle">C1 (80)</text>
    <text class="fig-green" x="320" y="210" font-size="9.5" text-anchor="middle">C2 (80)</text>
    <text class="fig-green" x="420" y="210" font-size="9.5" text-anchor="middle">C3 (80)</text>
    <text class="fig-accent" x="575" y="198" font-size="9.2" text-anchor="middle">T2 满后需等工作区 C1 完</text>
    <text class="fig-muted" x="575" y="216" font-size="9.2" text-anchor="middle">公式统一：T+M+(n-1)(max(T,C)+M)+C</text>
    <text class="fig-title" x="26" y="266" font-size="11">③ 双缓冲（2011#31：T=100, M=50, C=50 → M1 与 T2 并行，稳态周期 100，10块总耗 1100 ★）</text>
    <text class="fig-muted" x="26" y="291" font-size="9.5">缓冲区 A</text>
    <text class="fig-muted" x="26" y="317" font-size="9.5">缓冲区 B</text>
    <text class="fig-muted" x="26" y="343" font-size="9.5">CPU 工作区</text>
    <text class="fig-blue" x="170" y="291" font-size="9" text-anchor="middle">T1 (100)</text>
    <text class="fig-orange" x="245" y="291" font-size="9" text-anchor="middle">M1</text>
    <text class="fig-blue" x="370" y="291" font-size="9" text-anchor="middle">T3 (100)</text>
    <text class="fig-orange" x="445" y="291" font-size="9" text-anchor="middle">M3</text>
    <text class="fig-blue" x="270" y="317" font-size="9" text-anchor="middle">T2 (100)</text>
    <text class="fig-orange" x="345" y="317" font-size="9" text-anchor="middle">M2</text>
    <text class="fig-blue" x="470" y="317" font-size="9" text-anchor="middle">T4 (100)</text>
    <text class="fig-green" x="295" y="343" font-size="9" text-anchor="middle">C1</text>
    <text class="fig-green" x="395" y="343" font-size="9" text-anchor="middle">C2</text>
    <text class="fig-green" x="495" y="343" font-size="9" text-anchor="middle">C3</text>
    <text class="fig-blue" x="615" y="302" font-size="9.2" text-anchor="middle">M 不再挡住设备！</text>
    <text class="fig-muted" x="615" y="320" font-size="9" text-anchor="middle">总时间：T+(n-1)max(T,C+M)+M+C</text>
    <text class="fig-muted" x="615" y="338" font-size="9" text-anchor="middle">10 块：100+9×100+100 = 1100</text>
  </svg>
  <figcaption>图 7-9　单缓冲（M 阻断设备）与双缓冲（M 并入 CPU 流水侧）时空甘特图及真题公式推导</figcaption>
</figure>

#### 7.5.3 循环缓冲与公用缓冲池

1. **循环缓冲（环形缓冲区）**：将多个大小相同的缓冲区链成环状队列，共三类状态缓冲区与三个指针：
   - **三类状态**：**`R`**（空缓冲区，可供输入进程写入）、**`G`**（已装满数据，待计算进程取用）、**`C`**（计算进程正在使用的现行工作缓冲区）。
   - **三类指针**：**`Nexti`**（指向输入进程下次可用的空缓冲区 `R`）、**`Nextg`**（指向计算进程下次可取的满缓冲区 `G`）、**`Current`**（指向现行工作缓冲区 `C` 中的当前读取单元）。
   - **追赶阻塞（两种“撞车”）**：
     - **`Nexti` 追上 `Nextg`**：输入太快把空缓冲区全填满，**输入进程阻塞**（系统**受计算限制**），直至计算进程调用 `Releasebuf` 释放空缓冲区。
     - **`Nextg` 追上 `Nexti`**：计算太快把满缓冲区全抽空，**计算进程阻塞**（系统**受 I/O 限制**），直至输入进程填满一块调用 `Releasebuf`。

2. **公用缓冲池（Buffer Pool）**：为避免每个进程独占专用缓冲造成的内存碎片与浪费，OS 在内核统一管理一组**既可用于输入又可用于输出**的公用缓冲区。每个缓冲区含**缓冲首部**（缓冲区号、设备号、块号、同步信号量、链接指针）与**缓冲体**。
   - **三个队列**：空缓冲队列 **`emq`**、装满输入数据的输入队列 **`inq`**、装满输出数据的输出队列 **`outq`**。
   - **四种工作缓冲区流转**：
     1. **收容输入（`hin`）**：从 `emq` 队首摘空缓冲 $\to$ 装入外设输入数据 $\to$ 挂入 **`inq`** 队尾。
     2. **提取输入（`sin`）**：从 `inq` 队首摘满缓冲 $\to$ CPU 取走数据 $\to$ 挂回 **`emq`** 队尾。
     3. **收容输出（`hout`）**：从 `emq` 队首摘空缓冲 $\to$ 装入 CPU 输出数据 $\to$ 挂入 **`outq`** 队尾。
     4. **提取输出（`sout`）**：从 `outq` 队首摘满缓冲 $\to$ 送往外设输出 $\to$ 挂回 **`emq`** 队尾。
   - **同步互斥原语（防死锁铁律）**：缓冲池队列本身是临界资源，为每条队列配互斥信号量 $MS(\text{type})$ 与资源数信号量 $RS(\text{type})$ 。调用 `Getbuf(type)` 时，**必须先 `Wait(RS)` 再 `Wait(MS)`**，取出后立即 `Signal(MS)`；调用 `Putbuf(type, B)` 时，`Wait(MS) → Addbuf → Signal(MS) → Signal(RS)`（类比生产者–消费者：**同步资源信号量必须写在互斥信号量外层**，写反必死锁！）。

<figure class="cpd-figure not-content" id="os-c7-fig-10">
  <svg viewBox="0 0 720 320" role="img" aria-label="循环缓冲区追赶阻塞机制与公用缓冲池三队列四工作流图">
    <defs>
      <marker id="os-c7-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="276" height="296" rx="7"/>
    <rect class="fig-box-subtle" x="302" y="12" width="404" height="296" rx="7"/>
    <circle class="fig-box-dashed" cx="152" cy="134" r="66"/>
    <rect class="fig-box-green" x="128" y="54" width="48" height="26" rx="4"/>
    <rect class="fig-box-blue" x="196" y="92" width="44" height="26" rx="4"/>
    <rect class="fig-box-blue" x="196" y="152" width="44" height="26" rx="4"/>
    <rect class="fig-box-orange" x="124" y="188" width="56" height="26" rx="4"/>
    <rect class="fig-box" x="64" y="152" width="44" height="26" rx="4"/>
    <rect class="fig-box" x="64" y="92" width="44" height="26" rx="4"/>
    <line class="fig-line-accent" x1="184" y1="54" x2="174" y2="62" marker-end="url(#os-c7-arr-10)"/>
    <line class="fig-line-accent" x1="252" y1="192" x2="236" y2="179" marker-end="url(#os-c7-arr-10)"/>
    <line class="fig-line-accent" x1="176" y1="224" x2="162" y2="215" marker-end="url(#os-c7-arr-10)"/>
    <rect class="fig-box" x="26" y="238" width="252" height="58" rx="4"/>
    <rect class="fig-box-green" x="320" y="52" width="120" height="44" rx="4"/>
    <rect class="fig-box-blue" x="564" y="52" width="126" height="44" rx="4"/>
    <rect class="fig-box-orange" x="442" y="128" width="124" height="44" rx="4"/>
    <rect class="fig-box-purple" x="320" y="200" width="120" height="44" rx="4"/>
    <rect class="fig-box-red" x="564" y="200" width="126" height="44" rx="4"/>
    <rect class="fig-box-accent" x="312" y="254" width="384" height="42" rx="4"/>
    <path class="fig-line-accent" d="M 442 142 L 380 142 L 380 98" marker-end="url(#os-c7-arr-10)"/>
    <path class="fig-line-accent" d="M 440 74 L 562 74" marker-end="url(#os-c7-arr-10)"/>
    <path class="fig-line-green" d="M 674 96 L 674 142 L 568 142" marker-end="url(#os-c7-arr-10)"/>
    <path class="fig-line-accent" d="M 442 158 L 380 158 L 380 198" marker-end="url(#os-c7-arr-10)"/>
    <path class="fig-line-accent" d="M 440 222 L 562 222" marker-end="url(#os-c7-arr-10)"/>
    <path class="fig-line-green" d="M 674 200 L 674 158 L 568 158" marker-end="url(#os-c7-arr-10)"/>
    <text class="fig-title" x="26" y="33" font-size="11.5">① 循环缓冲（R 空 / G 满 / C 工作）</text>
    <text class="fig-green" x="152" y="71" font-size="10" text-anchor="middle">R (空)</text>
    <text class="fig-blue" x="218" y="109" font-size="10" text-anchor="middle">G1</text>
    <text class="fig-blue" x="218" y="169" font-size="10" text-anchor="middle">G2</text>
    <text class="fig-orange" x="152" y="205" font-size="9.5" text-anchor="middle">C (现行)</text>
    <text class="fig-label" x="86" y="169" font-size="10" text-anchor="middle">R</text>
    <text class="fig-label" x="86" y="109" font-size="10" text-anchor="middle">R</text>
    <text class="fig-accent" x="206" y="54" font-size="9.5">Nexti</text>
    <text class="fig-blue" x="260" y="203" font-size="9.2" text-anchor="middle">Nextg</text>
    <text class="fig-orange" x="180" y="230" font-size="9.5">Current</text>
    <text class="fig-label" x="34" y="255" font-size="9.2">• Nexti 追上 Nextg：空缓冲用尽 → 输入阻塞</text>
    <text class="fig-label" x="34" y="272" font-size="9.2">• Nextg 追上 Nexti：满缓冲用尽 → 计算阻塞</text>
    <text class="fig-muted" x="34" y="288" font-size="8.8">（分别对应系统受计算限制 vs 受 I/O 限制）</text>
    <text class="fig-title" x="316" y="33" font-size="11.5">② 公用缓冲池三队列与四工作流（emq / inq / outq）</text>
    <text class="fig-muted" x="502" y="66" font-size="8.6" text-anchor="middle">Putbuf(inq)</text>
    <text class="fig-muted" x="502" y="87" font-size="8.4" text-anchor="middle">收容满后入队</text>
    <text class="fig-green" x="380" y="72" font-size="10" text-anchor="middle">hin 收容输入缓冲</text>
    <text class="fig-muted" x="380" y="88" font-size="8.5" text-anchor="middle">外设→inq</text>
    <text class="fig-blue" x="627" y="72" font-size="10" text-anchor="middle">inq 输入满队列</text>
    <text class="fig-muted" x="627" y="88" font-size="8.5" text-anchor="middle">挂满待处理数据</text>
    <text class="fig-green" x="620" y="116" font-size="9" text-anchor="middle">提取输入 sin</text>
    <text class="fig-muted" x="620" y="130" font-size="8.2" text-anchor="middle">CPU 取走→归还</text>
    <text class="fig-orange" x="504" y="147" font-size="10.2" text-anchor="middle">emq 空缓冲队列</text>
    <text class="fig-muted" x="504" y="164" font-size="8.5" text-anchor="middle">可用空闲缓冲区</text>
    <text class="fig-green" x="620" y="177" font-size="9" text-anchor="middle">提取输出 sout</text>
    <text class="fig-muted" x="620" y="191" font-size="8.2" text-anchor="middle">送外设→归还</text>
    <text class="fig-purple" x="380" y="220" font-size="10" text-anchor="middle">hout 收容输出缓冲</text>
    <text class="fig-muted" x="380" y="236" font-size="8.5" text-anchor="middle">CPU→outq</text>
    <text class="fig-red" x="627" y="220" font-size="10" text-anchor="middle">outq 输出满队列</text>
    <text class="fig-muted" x="627" y="236" font-size="8.5" text-anchor="middle">待送往外设数据</text>
    <text class="fig-muted" x="502" y="214" font-size="8.6" text-anchor="middle">Putbuf(outq)</text>
    <text class="fig-muted" x="502" y="235" font-size="8.4" text-anchor="middle">装满后入队</text>
    <text class="fig-accent" x="504" y="272" font-size="8.6" text-anchor="middle">★ Getbuf 锁顺序铁律：先 Wait(RS) 再 Wait(MS) → Takebuf → Signal(MS)</text>
    <text class="fig-muted" x="504" y="288" font-size="8.4" text-anchor="middle">Putbuf：Wait(MS) → Addbuf → Signal(MS) → Signal(RS)（防先占锁再等资源死锁）</text>
  </svg>
  <figcaption>图 7-10　循环缓冲区双指针追赶阻塞条件与公用缓冲池三队列四工作流状态转换</figcaption>
</figure>

---

### 7.6 机械硬盘（HDD）物理结构、性能指标与延迟优化 ★

#### 7.6.1 物理结构与 CHS / LBA 地址映射

机械硬盘（HDD）由密封于真空或氦气腔内的多个盘片（Platter）、旋转主轴电机、音圈马达磁臂与悬浮磁头构成：

- **盘片与盘面（Surface）**：每张盘片有上下两个磁性涂层面（注意部分磁盘最外顶面/底面可能不作数据面，故按题目给出的有效盘面数计算），每个有效盘面对应 $1$ 个悬浮磁头（Head）。
- **磁道（Track）**：单个盘面上同心圆环，通常从最外圈向最内圈依次编号为 $0, 1, 2, \dots$，相邻磁道之间留有空白的<strong>磁道间隙（Track Gap）</strong>防止磁干扰。
  - **等扇区理想模型 vs 现代 ZBR 环带记录**：早期磁盘每条磁道扇区数相同，因外圈周长 $2\pi R$ 大而比特数一样，故**内圈位密度高、外圈位密度低**；现代磁盘改用<strong>区位记录（ZBR）</strong>划分环带，使**外层环带磁道拥有更多扇区**——故<strong>“外圈读速比内圈快”仅在现代磁盘上成立</strong>（同转一圈扫过更多扇区）。
- **扇区（Sector）**：磁道被切分为等弧长扇区，是**磁盘物理读写的最小单位**（常见 $512\text{ B}$ 或 $4\text{ KB}$；哪怕只写 $1\text{ B}$ 也需占满并重写整扇区）。若干相邻扇区可合并为一个文件系统逻辑块（**簇 / Cluster**）。
- **柱面（Cylinder）**：**跨盘面概念**——所有盘面上同一半径（相同磁道号）的磁道共同构成一个圆柱面。因所有磁头固定在同一根磁臂上**同进同退**，**寻道以柱面为单位**。

> **★考点（三维 CHS 地址排列顺序，2019#44）**：磁盘物理地址格式必为 **`(柱面号, 盘面号/磁头号, 扇区号)`**，必须将**柱面号放最前、盘面号居中、扇区号在后**！原因是：**同一个柱面内切换盘面仅需电信号切换磁头（微秒级），无需物理移动磁臂**；只有跨柱面才触发毫秒级寻道。因此存放连续数据块时，优先填满同一柱面的全部盘面，再移往下一柱面。

**容量与 LBA $\to$ CHS 连除取余换算**：

- **非格式化容量** $= \text{盘面数} \times \text{每面磁道数} \times \text{每道磁化单元数}$。
- **格式化容量** $= \text{盘面数} \times \text{柱面数} \times \text{每道扇区数} \times \text{每扇区数据字节数}$。格式化容量**恒小于**非格式化容量，因低级格式化写入了扇区间隙（Gap）、同步字段（SYNCH）、ID 标识符头（磁道号/磁头号/扇区号）和 CRC/ECC 校验码（例如经典温盘每扇区物理占 $600\text{ B}$ 仅 $512\text{ B}$ 存数据，格式化效率为 $512/600 \approx 85.3\%$）。
- **LBA $\to$ CHS 通用换算公式**（设盘面数即每柱面磁道数为 $H$，每磁道扇区数为 $S$，逻辑块号 $\text{LBA}$ 从 $0$ 开始）：
  $$
  \text{柱面号 } C = \left\lfloor \frac{\text{LBA}}{H \times S} \right\rfloor,\quad \text{盘面号 } H_i = \left\lfloor \frac{\text{LBA} \bmod (H \times S)}{S} \right\rfloor,\quad \text{扇区号 } S_i = \text{LBA} \bmod S
  $$

> **★考点算例（2019#44 大题精解：簇号 $\to$ 物理地址 & 0-based 序数陷阱）**：某磁盘有 $300$ 个柱面（$0\sim 299$），每柱面 $10$ 个磁道（即 $10$ 个盘面 $0\sim 9$），每磁道 $200$ 个扇区（$0\sim 199$），扇区大小 $512\text{ B}$，$1$ 簇 $= 2$ 扇区（$1\text{ KB}$）。
> 1. **磁盘总容量**：$300 \times 10 \times 200 \times 512\text{ B} = 307{,}200{,}000\text{ B} = 3 \times 10^5\text{ KB}$（约 $292.97\text{ MB}$，按 $10^3$ 换算为 $307.2\text{ MB}$）。
> 2. **SSTF 调度次序**：当前磁头在 $85$ 号柱面，求访问簇号 `100260, 60005, 101660, 110560` 的顺序。因每柱面含 $\frac{10 \times 200}{2} = 1000$ 簇，$85$ 号柱面覆盖簇号 `85000～85999`，故无需换算全地址即可由簇号间距直观比较出对应柱面为 `100, 60, 101, 110`，SSTF 次序为 **`100260 → 101660 → 110560 → 60005`**。
> 3. **“第 100530 簇”的物理地址**：注意“第 100530 簇”是 **1-based 序数**，而柱面/盘面/扇区号均从 $0$ 起编，故对应的 **0-based 簇号** $= 100530 - 1 = 100529$！
>    - 柱面号：$\lfloor 100529 / 1000 \rfloor = 100$，余 $529$；
>    - 每磁道（盘面）含 $200 / 2 = 100$ 簇，故盘面（磁道）号：$\lfloor 529 / 100 \rfloor = 5$，余 $29$（该磁道内 $0$-based 第 $29$ 簇）；
>    - 扇区号：$29 \times 2 = 58$ 与 $59$（即物理地址为 **`100` 号柱面、`5` 号盘面（磁道）、`58`～`59` 号扇区**；簇号与物理地址的转换由**磁盘驱动程序**完成）。

#### 7.6.2 磁盘读写访问时间与传输速率

一次磁盘读写总时间由三大块（外加电路级控制器延迟）构成：

$$
T_{\text{访问}} = T_{\text{寻道}} + T_{\text{旋转延迟}} + T_{\text{传输}} (+ T_{\text{控制器延迟}})
$$

- **寻道时间** $T_{\text{寻道}}$：磁臂带动磁头径向移动跨越柱面的机械运动时间，典型量级 **3～15 ms**。
  - **审题防坑**：若题干给出“**平均寻道时间** $T_s$”，则每进行一次跨磁道寻道直接计 $T_s$，**不要再乘以跨越磁道数**；只有题干给出“启动时间 $s$ ＋ 跨过每条磁道时间 $m$”，才按 $s + m \times n$ 计算。
- **旋转延迟** $T_{\text{旋转}}$：等目标扇区随主轴旋转到磁头正下方的时间。若转速为 $r$ 转/秒（题干常给 $\text{RPM}$，即转/分，需先算一圈毫秒数 $\frac{60000}{\text{RPM}}$），因扇区均匀随机落于圆周，平均旋转延迟为**转半圈的时间**：
  $$
  T_{\text{旋转平均}} = \frac{1}{2r} = \frac{60000}{2 \times \text{RPM}}\text{ ms}
  $$
- **传输时间** $T_{\text{传输}}$：目标字节流在磁头下扫过并读出的时间。设每磁道总字节数为 $N$，需读写字节数为 $b$（或按扇区占比 $\frac{\text{请求扇区数}}{\text{每道扇区数}} \times \text{一圈时间}$，或 $\frac{b}{\text{传输速率}}$）：
  $$
  T_{\text{传输}} = \frac{b}{r N}
  $$
- **理想数据传输率**：$R_{\text{传}} = r \times N$（单位：$\text{B/s}$）。

> **★考点算例（顺序访问 vs 随机访问 & 2010#45 真题）**：
> - **顺序 vs 随机差 15.4 倍**：磁盘转速 $10000\text{ RPM}$（转一圈 $6\text{ ms}$，平均旋转延迟 $3\text{ ms}$），平均寻道 $4.5\text{ ms}$，每道 $300$ 扇区（单扇区 $t_{\text{sector}} = 6/300 = 0.02\text{ ms}$），读 $8\text{ KB}$（$16$ 扇区）。
>   - **连续放于同一磁道**：只需寻道 $1$ 次、旋转延迟 $1$ 次，随后 $16$ 个扇区连着划过磁头：
>     $T_{\text{顺序}} = 4.5 + 3 + 16 \times 0.02 = 7.82\text{ ms}$。
>   - **分散在 $16$ 条不同磁道**：每个扇区均需单独寻道与等待半圈：
>     $T_{\text{随机}} = 16 \times (4.5 + 3 + 0.02) = 120.32\text{ ms} \approx 15.4 \times T_{\text{顺序}}$。
> - **2010#45（跨多磁道读写累加旋转延迟）**：转速 $6000\text{ RPM}$（一圈 $10\text{ ms}$，平均旋转延迟 $5\text{ ms}$），每道 $100$ 扇区（单扇区 $0.1\text{ ms}$），相邻磁道移动时间 $1\text{ ms}$，依次访问 `100` 起始的 `30, 50, 90, 120` 四个不同磁道各 $1$ 扇区（用 C-SCAN 优化即 C-LOOK：100→120→30→50→90，移动 $20+90+20+40=170$ 道）。
>   - 寻道总时间 $= 170 \times 1 = 170\text{ ms}$；
>   - 因访问了 **4 个不同磁道**，旋转延迟与读取均发生 $4$ 次：旋转延迟 $= 4 \times 5 = 20\text{ ms}$，传输 $= 4 \times 0.1 = 0.4\text{ ms}$，总计 $190.4\text{ ms}$！

<figure class="cpd-figure not-content" id="os-c7-fig-11">
  <svg viewBox="0 0 720 300" role="img" aria-label="机械硬盘三维结构盘面磁道扇区柱面与扇区低级格式化骨架">
    <defs>
      <marker id="os-c7-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="386" height="276" rx="7"/>
    <rect class="fig-box-subtle" x="412" y="12" width="294" height="276" rx="7"/>
    <ellipse class="fig-box" cx="198" cy="186" rx="94" ry="34"/>
    <ellipse class="fig-box-blue" cx="198" cy="116" rx="94" ry="34"/>
    <ellipse class="fig-box-dashed" cx="198" cy="116" rx="66" ry="23"/>
    <ellipse class="fig-box-dashed" cx="198" cy="186" rx="66" ry="23"/>
    <ellipse class="fig-box-dashed" cx="198" cy="116" rx="38" ry="13"/>
    <line class="fig-line-dashed" x1="132" y1="116" x2="132" y2="186" stroke="var(--sl-color-red)"/>
    <line class="fig-line-dashed" x1="264" y1="116" x2="264" y2="186" stroke="var(--sl-color-red)"/>
    <rect class="fig-box" x="190" y="64" width="16" height="148" rx="3"/>
    <rect class="fig-box-orange" x="330" y="76" width="24" height="142" rx="4"/>
    <line class="fig-line-accent" x1="330" y1="106" x2="256" y2="106" marker-end="url(#os-c7-arr-11)"/>
    <line class="fig-line-accent" x1="330" y1="128" x2="256" y2="128" marker-end="url(#os-c7-arr-11)"/>
    <line class="fig-line-accent" x1="330" y1="176" x2="256" y2="176" marker-end="url(#os-c7-arr-11)"/>
    <line class="fig-line-accent" x1="330" y1="198" x2="256" y2="198" marker-end="url(#os-c7-arr-11)"/>
    <circle class="fig-dot" cx="256" cy="106" r="3.5"/>
    <circle class="fig-dot" cx="256" cy="128" r="3.5"/>
    <circle class="fig-dot" cx="256" cy="176" r="3.5"/>
    <circle class="fig-dot" cx="256" cy="198" r="3.5"/>
    <line class="fig-line-dashed" x1="82" y1="100" x2="104" y2="112"/>
    <line class="fig-line-dashed" x1="82" y1="184" x2="104" y2="184"/>
    <line class="fig-line-dashed" x1="84" y1="150" x2="130" y2="150" stroke="var(--sl-color-red)"/>
    <rect class="fig-box-accent" x="28" y="236" width="358" height="38" rx="4"/>
    <rect class="fig-box" x="426" y="48" width="266" height="36" rx="4"/>
    <rect class="fig-box-orange" x="426" y="94" width="96" height="38" rx="4"/>
    <rect class="fig-box-blue" x="526" y="94" width="106" height="38" rx="4"/>
    <rect class="fig-box-green" x="636" y="94" width="56" height="38" rx="4"/>
    <rect class="fig-box" x="426" y="144" width="266" height="62" rx="4"/>
    <rect class="fig-box-purple" x="426" y="216" width="266" height="58" rx="4"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① HDD 盘片、盘面、磁道、柱面与同进同退磁头</text>
    <text class="fig-muted" x="198" y="57" font-size="9" text-anchor="middle">主轴（同步旋转）</text>
    <text class="fig-blue" x="22" y="102" font-size="9.5">盘面 0 / 1</text>
    <text class="fig-muted" x="22" y="118" font-size="8.6">0 号磁道(外)</text>
    <text class="fig-label" x="22" y="188" font-size="9.5">盘面 2 / 3</text>
    <text class="fig-red" x="52" y="153" font-size="9" text-anchor="middle">同一柱面</text>
    <text class="fig-orange" x="372" y="140" font-size="9.5" text-anchor="middle">磁臂</text>
    <text class="fig-muted" x="372" y="156" font-size="8.5" text-anchor="middle">同进</text>
    <text class="fig-muted" x="372" y="170" font-size="8.5" text-anchor="middle">同退</text>
    <text class="fig-accent" x="207" y="252" font-size="9.5" text-anchor="middle">★ CHS 物理地址必按 (柱面号, 盘面号, 扇区号) 排列</text>
    <text class="fig-muted" x="207" y="266" font-size="8.5" text-anchor="middle">同柱面换盘面仅电子切磁头（无机械寻道），故柱面号放最前</text>
    <text class="fig-title" x="426" y="33" font-size="11.5">② 扇区低级格式化结构（以温盘 600B 为例）</text>
    <text class="fig-label" x="559" y="64" font-size="9.5" text-anchor="middle">一条磁道 = 扇区0 | Gap | 扇区1 | ... | 扇区29</text>
    <text class="fig-muted" x="559" y="78" font-size="8.5" text-anchor="middle">每扇区物理占 600 B，数据区仅 512 B（效约 85.3%）</text>
    <text class="fig-orange" x="474" y="111" font-size="9.2" text-anchor="middle">Gap1+ID 头</text>
    <text class="fig-muted" x="474" y="125" font-size="8.2" text-anchor="middle">C/H/S + CRC</text>
    <text class="fig-blue" x="579" y="111" font-size="9.2" text-anchor="middle">Data 数据区</text>
    <text class="fig-muted" x="579" y="125" font-size="8.2" text-anchor="middle">512 B (1 扇区)</text>
    <text class="fig-green" x="664" y="111" font-size="9.2" text-anchor="middle">ECC</text>
    <text class="fig-muted" x="664" y="125" font-size="8.2" text-anchor="middle">Gap3</text>
    <text class="fig-label" x="436" y="162" font-size="9.5">• 间隙（Gap）让旋转中的磁头辨识扇区起止边界</text>
    <text class="fig-muted" x="436" y="179" font-size="8.8">• 格式化容量 &lt; 非格式化容量（因 ID/Gap/CRC 占位）</text>
    <text class="fig-muted" x="436" y="196" font-size="8.8">• 现代 ZBR 环带记录：外圈扇区更多 → 外圈比内圈快</text>
    <text class="fig-purple" x="436" y="234" font-size="9.5">LBA → CHS 连除取余公式：</text>
    <text class="fig-label" x="436" y="250" font-size="9">C = ⌊LBA/(H×S)⌋，H_i = ⌊(LBA mod (H×S))/S⌋</text>
    <text class="fig-muted" x="436" y="264" font-size="8.8">S_i = LBA mod S（注：第 k 个为 1-based，须先减 1）</text>
  </svg>
  <figcaption>图 7-11　机械硬盘三维几何结构（柱面与磁头同进同退）及低级格式化扇区骨架</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c7-fig-12">
  <svg viewBox="0 0 720 264" role="img" aria-label="磁盘读写访问时间三段分解及顺序读与随机读定量对比">
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="114" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="136" width="692" height="116" rx="7"/>
    <rect class="fig-box-red" x="28" y="48" width="240" height="44" rx="4"/>
    <rect class="fig-box-orange" x="272" y="48" width="184" height="44" rx="4"/>
    <rect class="fig-box-blue" x="460" y="48" width="118" height="44" rx="4"/>
    <rect class="fig-box" x="582" y="48" width="110" height="44" rx="4"/>
    <rect class="fig-box-green" x="28" y="170" width="324" height="68" rx="4"/>
    <rect class="fig-box-red" x="368" y="170" width="324" height="68" rx="4"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 一次磁盘读写总访问时间三段分解（仅“寻道时间”与调度次序有关 ★）</text>
    <text class="fig-red" x="148" y="67" font-size="10.2" text-anchor="middle">寻道时间 T_seek（占大头）</text>
    <text class="fig-muted" x="148" y="83" font-size="8.8" text-anchor="middle">磁臂机械移到目标柱面（几～十几 ms）</text>
    <text class="fig-orange" x="364" y="67" font-size="10.2" text-anchor="middle">旋转延迟 T_rot = 1/(2r)</text>
    <text class="fig-muted" x="364" y="83" font-size="8.8" text-anchor="middle">平均转半圈：60000/(2×RPM) ms</text>
    <text class="fig-blue" x="519" y="67" font-size="10.2" text-anchor="middle">传输时间 T_trans</text>
    <text class="fig-muted" x="519" y="83" font-size="8.8" text-anchor="middle">b / (r×N)（微秒级）</text>
    <text class="fig-label" x="637" y="67" font-size="9.5" text-anchor="middle">控制器延迟</text>
    <text class="fig-muted" x="637" y="83" font-size="8.5" text-anchor="middle">电路处理（若题目给定）</text>
    <text class="fig-accent" x="360" y="114" font-size="9.5" text-anchor="middle">注：旋转延迟仅由转速定，传输时间仅由数据量定；故磁盘调度算法只能优化“寻道时间”</text>
    <text class="fig-title" x="28" y="156" font-size="11.5">② 量化对比：10000 RPM 盘读 8 KB（16 扇区），平均寻道 4.5 ms，每道 300 扇区</text>
    <text class="fig-green" x="190" y="190" font-size="10.2" text-anchor="middle">A. 同一磁道连续读（顺序访问）</text>
    <text class="fig-label" x="190" y="208" font-size="9.5" text-anchor="middle">1 次寻道 + 1 次旋转 + 16 × 0.02 ms</text>
    <text class="fig-green" x="190" y="226" font-size="9" text-anchor="middle">= 4.5 + 3.0 + 0.32 = 7.82 ms</text>
    <text class="fig-red" x="530" y="190" font-size="10.2" text-anchor="middle">B. 分散于 16 条磁道（随机访问）</text>
    <text class="fig-label" x="530" y="208" font-size="9.5" text-anchor="middle">16 × (1 次寻道 + 1 次旋转 + 1 扇区传输)</text>
    <text class="fig-red" x="530" y="226" font-size="9" text-anchor="middle">= 16 × (4.5 + 3.0 + 0.02) = 120.32 ms（慢 15.4 倍）</text>
  </svg>
  <figcaption>图 7-12　磁盘读写总时间三段分解与同磁道顺序读 vs 跨磁道随机读定量性能对比</figcaption>
</figure>

#### 7.6.3 磁盘初始化、分区、系统引导与坏块管理

一块全新出厂的空白硬盘必须依次经过三步初始化才能写入文件（**2017#29、2021#46、2022 真题顺序**）：

1. **物理格式化（低级格式化）**：通常由**厂商在出厂前**完成——在磁记录表面划分出磁道与扇区、选定扇区大小（512 B 或 4 KB）、写入扇区头控制信息与 **ECC/CRC 校验码位数**、测试并标记出厂坏扇区。此时磁盘有了可寻址物理扇区，但尚无任何逻辑分区与文件系统。
2. **磁盘分区**：将物理盘划为多个逻辑分区，使各分区可独立运行不同文件系统（如双系统）。传统分区表保存在整盘 **0 号扇区主引导记录（MBR）** 中，MBR 包含引导代码与 **4 个表项的分区表**（最多 $4$ 个主分区，或 $3$ 个主分区 $+ 1$ 个作为容器的**扩展分区**再链式划分多个**逻辑分区**），且必须将安装 OS 的某主分区设为**活动分区**；现代大容量盘改用 **GPT**（默认支持最多 $128$ 个分区）。**裸盘（raw disk）** 指分区后不建文件系统直接交由数据库或交换区按线性扇区数组使用。
3. **逻辑格式化（高级格式化）**：针对**每个分区**建立一个空文件系统（如 NTFS、ext4），按序写入**引导块（PBR）**、**超级块（Superblock，记录全局容量与各区起始偏移，丢失致整个分区不可读故常有副本）**、**空闲空间管理结构（位示图/空闲表等）**、**FCB/inode 区**以及**根目录**（2017#29 必考点！）。

**系统开机引导链（2021#46）**：
**ROM 固件（BIOS/UEFI）自检 POST** $\to$ 读整盘 0 号扇区 **MBR 中的 Bootloader** $\to$ 解析分区表找到活动分区的**引导扇区（PBR / Boot Sector）** $\to$ 加载 OS 初始化程序与内核。因此硬盘作启动盘的完整准备顺序必为：**物理格式化 $\to$ 分区 $\to$ 逻辑格式化 $\to$ 安装操作系统**。

**坏块（Bad Block）管理**：实质是“通过某种机制令系统不再使用无法读写的损坏扇区”：
- **软件层面标记**：OS（如 FAT 表、文件系统）将坏块标记为“已占用”，从此不再分配（OS 可见）。
- **硬件自动扇区备用（重映射）**：磁盘控制器在低级格式化时预留一批<strong>备用扇区（Spare Sector）</strong>并维护内部坏块映射表；发现坏扇区时由控制器自动将原逻辑扇区**重映射**到备用扇区，**逻辑地址不变且对操作系统完全透明**（代价是跨区域访问会多一次寻道）。

<figure class="cpd-figure not-content" id="os-c7-fig-13">
  <svg viewBox="0 0 720 296" role="img" aria-label="磁盘物理格式化到分区到逻辑格式化三阶段与坏块备用扇区重映射">
    <defs>
      <marker id="os-c7-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="162" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="184" width="692" height="100" rx="7"/>
    <rect class="fig-box-orange" x="28" y="48" width="204" height="112" rx="5"/>
    <rect class="fig-box-blue" x="256" y="48" width="208" height="112" rx="5"/>
    <rect class="fig-box-green" x="488" y="48" width="204" height="112" rx="5"/>
    <line class="fig-line-accent" x1="232" y1="104" x2="254" y2="104" marker-end="url(#os-c7-arr-13)"/>
    <line class="fig-line-accent" x1="464" y1="104" x2="486" y2="104" marker-end="url(#os-c7-arr-13)"/>
    <rect class="fig-box" x="28" y="216" width="318" height="54" rx="4"/>
    <rect class="fig-box-purple" x="370" y="216" width="322" height="54" rx="4"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 新磁盘初始化三步曲（2017#29 / 2021#46 顺序不可颠倒）</text>
    <text class="fig-orange" x="130" y="68" font-size="10.2" text-anchor="middle">1. 物理格式化（低级格式化）</text>
    <text class="fig-muted" x="130" y="86" font-size="9" text-anchor="middle">• 厂商出厂前对整盘做一次</text>
    <text class="fig-muted" x="130" y="102" font-size="9" text-anchor="middle">• 划分磁道/扇区，定扇区大小</text>
    <text class="fig-muted" x="130" y="118" font-size="9" text-anchor="middle">• 写间隙、ID 头及 CRC 校验位</text>
    <text class="fig-muted" x="130" y="134" font-size="9" text-anchor="middle">• 检测并标记出厂坏扇区</text>
    <text class="fig-blue" x="360" y="68" font-size="10.2" text-anchor="middle">2. 磁盘分区（MBR / GPT）</text>
    <text class="fig-muted" x="360" y="86" font-size="9" text-anchor="middle">• 0 号扇区写入 MBR 引导+分区表</text>
    <text class="fig-muted" x="360" y="102" font-size="9" text-anchor="middle">• 划 C/D 盘，标 1 个活动分区</text>
    <text class="fig-muted" x="360" y="118" font-size="9" text-anchor="middle">• MBR 最多 4 主(含 1 扩展容器)</text>
    <text class="fig-muted" x="360" y="134" font-size="9" text-anchor="middle">• 逻辑划分，不提升 I/O 性能</text>
    <text class="fig-green" x="590" y="68" font-size="10.2" text-anchor="middle">3. 逻辑格式化（高级格式化）</text>
    <text class="fig-muted" x="590" y="86" font-size="9" text-anchor="middle">• 按分区各自建立空文件系统</text>
    <text class="fig-muted" x="590" y="102" font-size="9" text-anchor="middle">• 写入：引导块 PBR + 超级块</text>
    <text class="fig-muted" x="590" y="118" font-size="9" text-anchor="middle">• 空闲管理结构（位示图等）</text>
    <text class="fig-muted" x="590" y="134" font-size="9" text-anchor="middle">• FCB/inode 区 + 根目录</text>
    <text class="fig-title" x="28" y="204" font-size="11.5">② 坏块管理：让系统避开损坏扇区的两条路径</text>
    <text class="fig-label" x="187" y="236" font-size="9.8" text-anchor="middle">路径 A（软件层）：OS 文件分配表标记</text>
    <text class="fig-muted" x="187" y="254" font-size="8.8" text-anchor="middle">如在 FAT 表将坏块标为“已占用”，OS 可见但不再分配</text>
    <text class="fig-purple" x="531" y="236" font-size="9.8" text-anchor="middle">路径 B（硬件层）：控制器“扇区备用”透明重映射</text>
    <text class="fig-muted" x="531" y="254" font-size="8.8" text-anchor="middle">坏扇区重映射到预留备用扇区，逻辑块号不变（多 1 次寻道）</text>
  </svg>
  <figcaption>图 7-13　磁盘初始化三阶段产出对比与软件/硬件两类坏块处理机制</figcaption>
</figure>

#### 7.6.4 减少旋转延迟的方法：交替编号与柱面错位命名

磁盘是**连续自转**的机械设备（读完扇区后主轴不会停下来等 CPU/控制器），而磁头读入一个扇区后控制器必须经过一段短暂处理/校验时间 $t_p$ 才能继续接收下一扇区。若把逻辑相邻扇区在物理上紧挨排列（`0, 1, 2, ...`），在读完扇区 `0` 进行 $t_p$ 处理期间，紧邻的扇区 `1` 已从磁头下划过，系统**被迫多等整整一圈**才能重新读到 `1` 号扇区！

- **单磁道扇区交替编号（扇区交错因子）**：让逻辑相邻的扇区在物理上间隔 $k = \lceil t_p / t_{\text{sector}} \rceil$ 个物理扇区，使处理完当前扇区时，下一个逻辑扇区恰好旋转至磁头下方：
  $$
  \text{交替因子（Interleave Factor）} = k + 1 = \left\lceil \frac{t_p}{t_{\text{sector}}} \right\rceil + 1
  $$
  例如：一条磁道有 $8$ 个扇区，$t_{\text{sector}} = 0.02\text{ ms}$，$t_p = 0.015\text{ ms}$，则 $k = 1$，交替因子为 **2**，物理位置 `0～7` 上逻辑编号排为 **`0, 4, 1, 5, 2, 6, 3, 7`**。注：现代磁盘控制器自带高速大缓存，一次可将整条磁道读入缓存，故现代硬盘交替因子普遍为 $1$（不再需要交错）。
- **同一柱面跨盘面错位命名**：同一柱面各盘面绑定在同一主轴上**同步旋转**，读完 $0$ 号盘面最后一个扇区（如 `7` 号）并处理及切换磁头到 $1$ 号盘面期间，$1$ 号盘面的相同物理位置也已滑过磁头；若将 $1$ 号盘面的逻辑 `0` 号扇区顺旋转方向**错位偏移**放置，切换完磁头时 $1$ 号盘面的 `0` 号扇区恰转到磁头下方，再次省去一整圈等待！

<figure class="cpd-figure not-content" id="os-c7-fig-14">
  <svg viewBox="0 0 720 278" role="img" aria-label="减少旋转延迟的扇区交替编号与柱面盘面错位命名原理">
    <defs>
      <marker id="os-c7-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="356" height="254" rx="7"/>
    <rect class="fig-box-subtle" x="382" y="12" width="324" height="254" rx="7"/>
    <rect class="fig-box-blue" x="28" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="68" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="108" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="148" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="188" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="228" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="268" y="68" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="308" y="68" width="38" height="30" rx="3"/>
    <path class="fig-line-accent" d="M 47 100 Q 87 128 127 100" fill="none" marker-end="url(#os-c7-arr-14)"/>
    <path class="fig-line-accent" d="M 127 100 Q 167 128 207 100" fill="none" marker-end="url(#os-c7-arr-14)"/>
    <path class="fig-line-accent" d="M 207 100 Q 247 128 287 100" fill="none" marker-end="url(#os-c7-arr-14)"/>
    <rect class="fig-box" x="28" y="160" width="328" height="92" rx="4"/>
    <rect class="fig-box-blue" x="454" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="484" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="514" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="544" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="574" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="604" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="634" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box-orange" x="664" y="66" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="454" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box-green" x="484" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="514" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="544" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="574" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="604" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="634" y="136" width="28" height="26" rx="3"/>
    <rect class="fig-box" x="664" y="136" width="28" height="26" rx="3"/>
    <path class="fig-line-green" d="M 678 92 L 678 100 L 498 100 L 498 134" marker-end="url(#os-c7-arr-14)"/>
    <rect class="fig-box" x="396" y="176" width="296" height="76" rx="4"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 单磁道交替编号（交替因子 = 2，跳过 1 扇区）</text>
    <text class="fig-muted" x="28" y="56" font-size="9">物理序 0～7 展开（圆周自左向右转过磁头）</text>
    <text class="fig-blue" x="47" y="87" font-size="10.5" text-anchor="middle">0</text>
    <text class="fig-muted" x="87" y="87" font-size="10.5" text-anchor="middle">4</text>
    <text class="fig-blue" x="127" y="87" font-size="10.5" text-anchor="middle">1</text>
    <text class="fig-muted" x="167" y="87" font-size="10.5" text-anchor="middle">5</text>
    <text class="fig-blue" x="207" y="87" font-size="10.5" text-anchor="middle">2</text>
    <text class="fig-muted" x="247" y="87" font-size="10.5" text-anchor="middle">6</text>
    <text class="fig-blue" x="287" y="87" font-size="10.5" text-anchor="middle">3</text>
    <text class="fig-muted" x="327" y="87" font-size="10.5" text-anchor="middle">7</text>
    <text class="fig-accent" x="168" y="142" font-size="9.2" text-anchor="middle">读完 0 需短暂处理 t_p，划过物理1(4) 恰迎上逻辑 1！</text>
    <text class="fig-label" x="38" y="182" font-size="9.5">• 交替因子 = ⌈t_p / t_sector⌉ + 1</text>
    <text class="fig-muted" x="38" y="200" font-size="8.8">• 不交错时刚读完 0，扇区 1 已滑过，被迫空等一整圈</text>
    <text class="fig-muted" x="38" y="218" font-size="8.8">• 现代盘控制器带大容量缓存一次整道读，交替因子 = 1</text>
    <text class="fig-muted" x="38" y="236" font-size="8.8">• 第 1 圈依次读 0,1,2,3，第 2 圈读 4,5,6,7，仅需 2 圈</text>
    <text class="fig-title" x="396" y="33" font-size="11.5">② 同一柱面跨盘面错位命名（同轴同步旋转）</text>
    <text class="fig-label" x="396" y="83" font-size="9.5">盘面 0</text>
    <text class="fig-blue" x="468" y="83" font-size="9.5" text-anchor="middle">0</text>
    <text class="fig-muted" x="498" y="83" font-size="9.5" text-anchor="middle">1</text>
    <text class="fig-muted" x="528" y="83" font-size="9.5" text-anchor="middle">2</text>
    <text class="fig-muted" x="558" y="83" font-size="9.5" text-anchor="middle">3</text>
    <text class="fig-muted" x="588" y="83" font-size="9.5" text-anchor="middle">4</text>
    <text class="fig-muted" x="618" y="83" font-size="9.5" text-anchor="middle">5</text>
    <text class="fig-muted" x="648" y="83" font-size="9.5" text-anchor="middle">6</text>
    <text class="fig-orange" x="678" y="83" font-size="9.5" text-anchor="middle">7</text>
    <text class="fig-label" x="396" y="153" font-size="9.5">盘面 1</text>
    <text class="fig-muted" x="468" y="153" font-size="9.5" text-anchor="middle">7</text>
    <text class="fig-green" x="498" y="153" font-size="9.5" text-anchor="middle">0</text>
    <text class="fig-muted" x="528" y="153" font-size="9.5" text-anchor="middle">1</text>
    <text class="fig-muted" x="558" y="153" font-size="9.5" text-anchor="middle">2</text>
    <text class="fig-muted" x="588" y="153" font-size="9.5" text-anchor="middle">3</text>
    <text class="fig-muted" x="618" y="153" font-size="9.5" text-anchor="middle">4</text>
    <text class="fig-muted" x="648" y="153" font-size="9.5" text-anchor="middle">5</text>
    <text class="fig-muted" x="678" y="153" font-size="9.5" text-anchor="middle">6</text>
    <text class="fig-green" x="596" y="120" font-size="8.2" text-anchor="middle">读完盘面 0 扇区 7 → 切磁头+处理跨过 1 扇区</text>
    <text class="fig-label" x="406" y="194" font-size="9.2">• 盘面 1 的 0 号扇区向右错位 1 格</text>
    <text class="fig-muted" x="406" y="211" font-size="8.8">• 切完磁头并处理就绪时，盘面 1 扇区 0 恰转到磁头下</text>
    <text class="fig-muted" x="406" y="227" font-size="8.8">• 避免了跨盘面读取时再空等一整圈旋转延迟</text>
    <text class="fig-muted" x="406" y="243" font-size="8.8">• 两者核心均为“以空间布局换取消除多余旋转圈数”</text>
  </svg>
  <figcaption>图 7-14　减少旋转延迟的两类磁盘几何布局：同道扇区交替编号与跨盘面扇区错位命名</figcaption>
</figure>

---

### 7.7 磁盘调度算法与磁臂黏着 ★

在访问时间三段中，**只有寻道时间与磁盘请求的服务顺序有关**。设当前磁头位于 **`53`** 号柱面，磁道总范围 **`0～199`**，当前向<strong>磁道号增大方向（<code>↑</code>）</strong>移动，等待服务的请求队列依次为：`98, 183, 37, 122, 14, 124, 65, 67`。

#### 7.7.1 六种基础磁盘调度算法演进与对比

六种算法构成一条“针对前一代缺陷逐级修补”的演化链：
**FCFS**（乱序横跳、寻道极长） $\Rightarrow$ **SSTF**（贪心选最近，寻道极短，但远处请求可能**饥饿**） $\Rightarrow$ **SCAN**（单调往返到端点消除饥饿，但刚扫过的请求最坏要等 $2T$，且会空跑到磁道端点） $\Rightarrow$ 改良刚扫过的公平性催生 **C-SCAN**（单向扫完跳回起点）；消除端点空程催生 **LOOK**；两者合并即为 **C-LOOK**（实际 OS 常用）。

| 算法 | 本例访问序列（起点 53，向 ↑） | 总寻道距离（磁道数） | 平均寻道 | 依赖初始方向 | 会饥饿 | 折返位置 | 等待公平性 |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **FCFS** | `53→98→183→37→122→14→124→65→67` | $45+85+146+85+108+110+59+2 = \mathbf{640}$ | $80.0$ | 否 | 否 | 无 | 绝对公平；**唯一不黏着** |
| **SSTF** | `53→65→67→37→14→98→122→124→183` | $12+2+30+23+84+24+2+59 = \mathbf{236}$ | $29.5$ | 否 | **会 ★** | 无 | 差（歧视边缘磁道） |
| **SCAN** | `53→65→67→98→122→124→183→199→37→14` | $(199-53)+(199-14) = 146+185 = \mathbf{331}$ | $41.38$ | **是** | 否（注） | **磁道端点 `199`** | 折返端最坏等 $2T$ |
| **C-SCAN** | `53→65→67→98→122→124→183→199→0→14→37` | $146+199+37 = \mathbf{382}$（若回程不计则 $183$） | $47.75$ | **是** | 否（注） | **端点 `199` 跳至 `0`** | **最均匀**（$T+S_{\max}$） |
| **LOOK** | `53→65→67→98→122→124→183→37→14` | $(183-53)+(183-14) = 130+169 = \mathbf{299}$ | $37.38$ | **是** | 否（注） | **最远请求 `183`** | 同 SCAN，无空程 |
| **C-LOOK** | `53→65→67→98→122→124→183→14→37` | $130+169+23 = \mathbf{322}$（若回程不计则 $153$） | $40.25$ | **是** | 否（注） | **最远请求 `183` 跳 `14`** | 同 C-SCAN，无空程 |

> **★考点（考场“审题三圈”防丢分铁律）**：面对 408 磁盘调度题（2009#29、2010#45、2015#32、2021#26、2024#32），动笔前必须在题干圈出三点：
> 1. **初始磁头位置**与**当前移动方向**（往增大还是减小方向移动？同一序列方向反则全盘改写）；
> 2. **磁盘总磁道范围**（`0～199` 还是 `0～399`？决定 SCAN/C-SCAN 跑到哪个端点）；
> 3. **SCAN 还是 LOOK**——若题干只说“扫描算法/电梯算法”且明确给出磁道最大/最小边界，通常按到达端点计算（或留意题干是否注明“到达最远请求即折返”，若注明则为 LOOK/C-LOOK；而在 2010#45 等题中未给磁道总数上限时则按 C-LOOK 理解直接从 `120` 跳回 `30`）；C-SCAN **从端点跳回另一端的距离在常规题中计入总寻道距离**，除非题干明确声明“返程不计”。

<figure class="cpd-figure not-content" id="os-c7-fig-15">
  <svg viewBox="0 0 720 476" role="img" aria-label="六种磁盘调度算法FCFS、SSTF、SCAN、C-SCAN、LOOK、C-LOOK磁头移动轨迹对比折线图">
    <defs>
      <marker id="os-c7-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="5.5" markerHeight="5.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="338" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="12" width="338" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="166" width="338" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="166" width="338" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="14" y="320" width="338" height="144" rx="6"/>
    <rect class="fig-box-subtle" x="368" y="320" width="338" height="144" rx="6"/>
    <line class="fig-divider" x1="30" y1="50" x2="334" y2="50"/>
    <polyline class="fig-line" stroke="var(--sl-color-red)" points="111,58 180,68 310,78 86,88 217,98 51,108 220,118 129,128 132,138"/>
    <circle class="fig-dot" cx="111" cy="58" r="2.5"/><circle class="fig-dot" cx="180" cy="68" r="2.5"/><circle class="fig-dot" cx="310" cy="78" r="2.5"/><circle class="fig-dot" cx="86" cy="88" r="2.5"/><circle class="fig-dot" cx="217" cy="98" r="2.5"/><circle class="fig-dot" cx="51" cy="108" r="2.5"/><circle class="fig-dot" cx="220" cy="118" r="2.5"/><circle class="fig-dot" cx="129" cy="128" r="2.5"/><circle class="fig-dot" cx="132" cy="138" r="2.5"/>
    <line class="fig-divider" x1="384" y1="50" x2="688" y2="50"/>
    <polyline class="fig-line" stroke="var(--sl-color-green)" points="465,58 483,68 486,78 440,88 405,98 534,108 571,118 574,128 664,138"/>
    <circle class="fig-green-fill" cx="465" cy="58" r="2.5"/><circle class="fig-green-fill" cx="483" cy="68" r="2.5"/><circle class="fig-green-fill" cx="486" cy="78" r="2.5"/><circle class="fig-green-fill" cx="440" cy="88" r="2.5"/><circle class="fig-green-fill" cx="405" cy="98" r="2.5"/><circle class="fig-green-fill" cx="534" cy="108" r="2.5"/><circle class="fig-green-fill" cx="571" cy="118" r="2.5"/><circle class="fig-green-fill" cx="574" cy="128" r="2.5"/><circle class="fig-green-fill" cx="664" cy="138" r="2.5"/>
    <line class="fig-divider" x1="30" y1="204" x2="334" y2="204"/>
    <polyline class="fig-line" stroke="var(--sl-color-blue)" points="111,212 129,220 132,228 180,236 217,244 220,252 310,260 334,268 86,277 51,286"/>
    <circle class="fig-dot" cx="111" cy="212" r="2.5"/><circle class="fig-dot" cx="129" cy="220" r="2.5"/><circle class="fig-dot" cx="132" cy="228" r="2.5"/><circle class="fig-dot" cx="180" cy="236" r="2.5"/><circle class="fig-dot" cx="217" cy="244" r="2.5"/><circle class="fig-dot" cx="220" cy="252" r="2.5"/><circle class="fig-dot" cx="310" cy="260" r="2.5"/><circle class="fig-dot" cx="334" cy="268" r="3"/><circle class="fig-dot" cx="86" cy="277" r="2.5"/><circle class="fig-dot" cx="51" cy="286" r="2.5"/>
    <line class="fig-divider" x1="384" y1="204" x2="688" y2="204"/>
    <polyline class="fig-line" stroke="var(--sl-color-purple)" points="465,212 483,218 486,224 534,230 571,236 574,242 664,248 688,254"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-purple)" x1="688" y1="254" x2="384" y2="264" marker-end="url(#os-c7-arr-15)"/>
    <polyline class="fig-line" stroke="var(--sl-color-purple)" points="384,264 405,273 440,282"/>
    <circle class="fig-dot" cx="465" cy="212" r="2.5"/><circle class="fig-dot" cx="483" cy="218" r="2.5"/><circle class="fig-dot" cx="486" cy="224" r="2.5"/><circle class="fig-dot" cx="534" cy="230" r="2.5"/><circle class="fig-dot" cx="571" cy="236" r="2.5"/><circle class="fig-dot" cx="574" cy="242" r="2.5"/><circle class="fig-dot" cx="664" cy="248" r="2.5"/><circle class="fig-dot" cx="688" cy="254" r="3"/><circle class="fig-dot" cx="384" cy="264" r="3"/><circle class="fig-dot" cx="405" cy="273" r="2.5"/><circle class="fig-dot" cx="440" cy="282" r="2.5"/>
    <line class="fig-divider" x1="30" y1="358" x2="334" y2="358"/>
    <polyline class="fig-line" stroke="var(--sl-color-orange)" points="111,366 129,374 132,382 180,390 217,398 220,406 310,414 86,424 51,434"/>
    <circle class="fig-dot" cx="111" cy="366" r="2.5"/><circle class="fig-dot" cx="129" cy="374" r="2.5"/><circle class="fig-dot" cx="132" cy="382" r="2.5"/><circle class="fig-dot" cx="180" cy="390" r="2.5"/><circle class="fig-dot" cx="217" cy="398" r="2.5"/><circle class="fig-dot" cx="220" cy="406" r="2.5"/><circle class="fig-dot" cx="310" cy="414" r="3"/><circle class="fig-dot" cx="86" cy="424" r="2.5"/><circle class="fig-dot" cx="51" cy="434" r="2.5"/>
    <line class="fig-divider" x1="384" y1="358" x2="688" y2="358"/>
    <polyline class="fig-line" stroke="var(--sl-color-accent)" points="465,366 483,373 486,380 534,387 571,394 574,401 664,408"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-accent)" x1="664" y1="408" x2="405" y2="418" marker-end="url(#os-c7-arr-15)"/>
    <polyline class="fig-line" stroke="var(--sl-color-accent)" points="405,418 440,428"/>
    <circle class="fig-dot" cx="465" cy="366" r="2.5"/><circle class="fig-dot" cx="483" cy="373" r="2.5"/><circle class="fig-dot" cx="486" cy="380" r="2.5"/><circle class="fig-dot" cx="534" cy="387" r="2.5"/><circle class="fig-dot" cx="571" cy="394" r="2.5"/><circle class="fig-dot" cx="574" cy="401" r="2.5"/><circle class="fig-dot" cx="664" cy="408" r="3"/><circle class="fig-dot" cx="405" cy="418" r="3"/><circle class="fig-dot" cx="440" cy="428" r="2.5"/>
    <text class="fig-red" x="26" y="30" font-size="10.8">1. FCFS（总移动 640 道·绝不饥饿不黏着）</text>
    <text class="fig-muted" x="30" y="45" font-size="8.2">0</text><text class="fig-muted" x="111" y="45" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="307" y="45" font-size="8" text-anchor="middle">183</text><text class="fig-muted" x="334" y="45" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-green" x="380" y="30" font-size="10.8">2. SSTF（总移动 236 道·最短但会饥饿 ★）</text>
    <text class="fig-muted" x="384" y="45" font-size="8.2">0</text><text class="fig-muted" x="465" y="45" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="661" y="45" font-size="8" text-anchor="middle">183</text><text class="fig-muted" x="688" y="45" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-blue" x="26" y="184" font-size="10.8">3. SCAN 电梯（总 331 道·空跑到 199 再折返）</text>
    <text class="fig-muted" x="30" y="199" font-size="8.2">0</text><text class="fig-muted" x="111" y="199" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="334" y="199" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-blue" x="210" y="300" font-size="8.5" text-anchor="middle">必须走到磁道端点 199 再折返</text>
    <text class="fig-purple" x="380" y="184" font-size="10.8">4. C-SCAN（总 382 道·199→0 返程不服务 ★）</text>
    <text class="fig-muted" x="384" y="199" font-size="8.2">0</text><text class="fig-muted" x="465" y="199" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="688" y="199" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-purple" x="550" y="300" font-size="8.5" text-anchor="middle">虚线 199→0 空跳（等待最均匀）</text>
    <text class="fig-orange" x="26" y="338" font-size="10.8">5. LOOK（总 299 道·只到最远请求 183 折返）</text>
    <text class="fig-muted" x="30" y="353" font-size="8.2">0</text><text class="fig-muted" x="111" y="353" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="307" y="353" font-size="8" text-anchor="middle">183</text><text class="fig-muted" x="334" y="353" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-orange" x="210" y="454" font-size="8.5" text-anchor="middle">止于最远请求 183，省掉 183↔199 空程</text>
    <text class="fig-accent" x="380" y="338" font-size="10.8">6. C-LOOK（总 322 道·183 直接跳至最小请求 14）</text>
    <text class="fig-muted" x="384" y="353" font-size="8.2">0</text><text class="fig-muted" x="405" y="353" font-size="8.2" text-anchor="middle">14</text><text class="fig-muted" x="465" y="353" font-size="8.2" text-anchor="middle">53</text><text class="fig-muted" x="661" y="353" font-size="8" text-anchor="middle">183</text><text class="fig-muted" x="688" y="353" font-size="8.2" text-anchor="end">199</text>
    <text class="fig-accent" x="550" y="454" font-size="8.5" text-anchor="middle">183 直接跳回 14（实际 OS 实用主流）</text>
  </svg>
  <figcaption>图 7-15　同一起点（53，范围 0～199，方向↑）请求队列 [98,183,37,122,14,124,65,67] 在六种算法下的磁头轨迹对照</figcaption>
</figure>

#### 7.7.2 磁臂黏着现象与 N-Step-SCAN / FSCAN 破局（2018#30）

**磁臂黏着（Arm Stickiness）**：指系统总是密集访问当前同一磁道（或极近邻磁道），导致磁臂长期粘附在原地，迟迟不向前移动响应其他磁道请求的恶性现象。

- **★为何 SCAN / C-SCAN 也会发生磁臂黏着？（2018#30 核心辨析）**
  教材一般说 SCAN 不会“饥饿”，那是指**非同一磁道源源不断插入**的常态情景；当某进程**反复请求磁头当前正停留的同一磁道** $k$（如当前在 155 道，队列里不断插来 155 道新请求）时，**SSTF** 因距离 $0$ 永远优先服务 155，**SCAN / C-SCAN** 因在“当前方向前方（含原地 $0$ 距离）”依然有未处理请求 155，也会反复留守在 155 道停滞不前！
- **基础算法中唯一不会发生磁臂黏着的是 FCFS**：因为 FCFS 严格按**请求到达的时间戳**排队，后到的同磁道请求只能排在队尾，绝不能插队到先到的其他磁道请求前面！
- **破解磁臂黏着的两大队列冻结算法**：核心思想均为<strong>“冻结当前批，新到请求另存他队”</strong>：
  1. **N-Step-SCAN**：将磁盘请求队列拆分为若干长度最大为 $N$ 的子队列，**子队列之间按 FCFS** 调度，**子队列内部按 SCAN** 扫描；在扫描某子队列期间新到达的请求一律放入后续队列，保证磁头必然按 SCAN 扫完当前冻结队列并前进。边界退化：$N = 1$ 时退化为 **FCFS**，$N \to \infty$ 时趋近于普通 **SCAN**。
  2. **FSCAN（N-Step-SCAN 的双队列特例）**：仅设**两个队列**——开始扫描时当前全部请求放入队列 1 并冻结，按 SCAN 服务；扫描期间新到的一切请求全部装入队列 2；待队列 1 清零后再切换扫描队列 2。

<figure class="cpd-figure not-content" id="os-c7-fig-16">
  <svg viewBox="0 0 720 264" role="img" aria-label="磁臂黏着现象成因与N-Step-SCAN和FSCAN冻结队列破解原理">
    <defs>
      <marker id="os-c7-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="336" height="240" rx="7"/>
    <rect class="fig-box-subtle" x="362" y="12" width="344" height="240" rx="7"/>
    <rect class="fig-box-red" x="28" y="48" width="308" height="84" rx="5"/>
    <rect class="fig-box-green" x="28" y="146" width="308" height="92" rx="5"/>
    <rect class="fig-box-blue" x="376" y="48" width="316" height="68" rx="5"/>
    <rect class="fig-box-orange" x="376" y="130" width="316" height="62" rx="5"/>
    <rect class="fig-box" x="376" y="204" width="316" height="36" rx="4"/>
    <path class="fig-line-dashed" d="M 556 128 L 556 118" stroke="var(--sl-color-orange)"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 磁臂黏着成因（2018#30 考点 ★）</text>
    <text class="fig-red" x="182" y="68" font-size="10.2" text-anchor="middle">SSTF / SCAN / C-SCAN 均会黏着！</text>
    <text class="fig-label" x="182" y="88" font-size="9.2" text-anchor="middle">当前在 155 道，进程源源不断发来新 155 请求</text>
    <text class="fig-muted" x="182" y="106" font-size="9" text-anchor="middle">→ 距离 0（或当前方向未离去）持续插队</text>
    <text class="fig-muted" x="182" y="122" font-size="9" text-anchor="middle">→ 磁臂卡死在 155，远处请求 [50, 180] 被晾死</text>
    <text class="fig-green" x="182" y="166" font-size="10.2" text-anchor="middle">只有 FCFS 绝不会磁臂黏着 ★</text>
    <text class="fig-label" x="182" y="186" font-size="9.2" text-anchor="middle">到达顺序：[155, 50, 180] ← 后到 155 排在队尾</text>
    <text class="fig-muted" x="182" y="204" font-size="9" text-anchor="middle">严守到达时间戳，新 155 绝不能插到 50 之前</text>
    <text class="fig-muted" x="182" y="222" font-size="9" text-anchor="middle">（注：饿死是特定请求总落选；黏着是磁头卡在原道）</text>
    <text class="fig-title" x="376" y="33" font-size="11.5">② 破解手段：N-Step-SCAN 与 FSCAN（冻结批）</text>
    <text class="fig-blue" x="534" y="68" font-size="10" text-anchor="middle">队列 1（已冻结，队内按 SCAN 服务）</text>
    <text class="fig-label" x="534" y="86" font-size="9.2" text-anchor="middle">[50, 155, 167, 180] → 扫完即止，磁臂必前移！</text>
    <text class="fig-muted" x="534" y="104" font-size="8.8" text-anchor="middle">N-Step-SCAN：每子队列上限 N；队间按 FCFS</text>
    <text class="fig-orange" x="534" y="150" font-size="10" text-anchor="middle">队列 2（隔离区：接收扫描期间所有新请求）</text>
    <text class="fig-label" x="534" y="168" font-size="9.2" text-anchor="middle">[155, 155, 155, ...] 全部暂存，待队列 1 空后切入</text>
    <text class="fig-muted" x="534" y="184" font-size="8.8" text-anchor="middle">FSCAN = 双队列版，完全隔离新插队请求</text>
    <text class="fig-accent" x="534" y="226" font-size="9.5" text-anchor="middle">边界结论：N = 1 退化为 FCFS；N 很大时趋近 SCAN</text>
  </svg>
  <figcaption>图 7-16　磁臂黏着现象（SSTF/SCAN/C-SCAN 卡在原道 vs FCFS 免疫）与 N-Step-SCAN / FSCAN 冻结隔离原理</figcaption>
</figure>

---

### 7.8 固态硬盘（SSD）与磨损均衡 ★

> **★考点（2026 新大纲五（三）2 固态硬盘）**：核心考查**读写性能特性**与**磨损均衡**，以及它与操作系统职责的分工边界（2025#32）。

#### 7.8.1 内部组成、三条物理约束与读写性能特性

固态硬盘（SSD）以半导体闪存芯片取代了机械硬盘的旋转盘片与磁臂，无任何机械运动部件，由两大部分组成：
1. **闪存芯片阵列（NAND Flash）**：内部组织为多个**块（Block，通常含 $32\sim 128$ 页，大小 $16\text{ KB}\sim 512\text{ KB}$）**，每块包含多个**页（Page，大小 $512\text{ B}\sim 4\text{ KB}$）**。按每存储单元存放比特数分为 **SLC（1 bit，寿命约 $10$ 万次擦除）**、**MLC（2 bit，约 $1$ 万次）**、**TLC（3 bit，约 $3000$ 次）**、**QLC（4 bit，寿命最短成本最低）**。
2. **闪存翻译层（FTL，Flash Translation Layer）**：即 SSD 控制器固件，等价于 HDD 的磁盘控制器，负责 LBA 到物理页的地址映射、垃圾回收（GC）、磨损均衡及坏块管理。

SSD 的全部行为均受限于**三条底层物理铁律**：
- **铁律 ①（粒度不对称）**：**读写以“页（Page）”为单位，而擦除以“块（Block）”为单位**。
- **铁律 ②（禁止覆盖写）**：向浮栅晶体管写入时**只能把 `1` 编程为 `0`**，若要把 `0` 改回 `1`，必须先对**整块**施高压擦除复位为全 `1`。
- **铁律 ③（擦除次数有限）**：每经过几千到上万次擦除，氧化层绝缘能力退化即变成不可用的坏块。

由此直接导出 **SSD 读写性能的核心特性**：
- **随机读 $\approx$ 顺序读（均极快）**：没有寻道时间与旋转延迟，访问任意物理页均微秒级电信号完成。
- **读写严重不对称（读 $\ll$ 写 $\ll$ 擦）**：**写操作显著慢于读操作**（因涉及校验、写前检查及背后触发的擦除与数据搬迁；试题若说“SSD 读写速度一样快”，**必错！**）。
- **随机写显著慢于顺序写**：随机小写入会在各块内留下零散无效页，迫使后续更频繁地进行垃圾回收搬运，加剧延迟与写放大。
- **高带宽依赖多通道、多芯片（Die）并行**堆叠。

#### 7.8.2 FTL 异地更新、垃圾回收（GC）、写放大（WAF）与 TRIM

假如没有 FTL 而在原地强行改写某页（如改 Block 0 的 Page 1），就必须把同块内其余有效页先读进缓存 $\to$ 擦除整块 $\to$ 再写回全部页（想改 $4\text{ KB}$ 却写了整个 $1\text{ MB}$ 块！）。**FTL 的核心做法一句话概括：“别原地覆盖，换个空闲页写入（异地更新），再把逻辑地址重新指过去，将旧物理页标为无效（Invalid）。”**

这句设计直接推导出整条因果链：**不能覆盖写 $\Rightarrow$ FTL 异地更新 $\Rightarrow$ 产生无效页（垃圾） $\Rightarrow$ 必须后台执行垃圾回收（GC） $\Rightarrow$ GC 要搬走待擦块内仍有效的页 $\Rightarrow$ 闪存侧实际写入量大于主机请求写入量（写入放大） $\Rightarrow$ 擦写寿命更快耗尽 $\Rightarrow$ 必须做磨损均衡！**

- **写放大系数（WAF，Write Amplification Factor）**：
  $$
  \text{WAF} = \frac{\text{闪存实际写入的数据量}}{\text{主机请求写入的数据量}} \ge 1
  $$
- **垃圾回收（GC）三步**：① 挑选**无效页最多、且已擦除次数较少**的物理块（兼顾搬运最小与磨损均衡）；② 将该块中仍然**有效**的页搬迁复制到其他空闲页并更新映射表；③ 对该块执行**整块擦除**回收为空闲块池。
- **三种映射粒度对比**：**页级映射**（最灵活、写放大最小，但映射表体积过大难以全驻 SSD DRAM）、**块级映射**（表极小，但块内偏移固定导致退化回读-改-擦-写）、**混合映射**（主体按块级映射，另留少量按页级映射的“日志块”吸收随机写，平衡表体积与写放大）。
- **TRIM 命令（OS $\leftrightarrow$ SSD 信息协同）**：OS 删除文件时通常只清空目录项与空闲位图而**不擦除磁盘数据块**，导致 SSD 以为这些物理页仍然有效而在 GC 时白白反复搬迁。启用 **TRIM** 后，文件系统在删文件时主动向 SSD 通知作废逻辑块范围，FTL 直接标记对应物理页为无效，免除无效搬运、降低写放大并恢复随机写性能（需文件系统、驱动、SSD 固件三方支持，且 TRIM 后数据不可恢复）。

#### 7.8.3 磨损均衡（Wear Leveling）与寿命量化 ★

> **★考点**：**磨损均衡解决的是擦除次数的“空间分布均匀”问题，而非减少擦除总次数**。它**完全由 SSD 控制器内部的 FTL 硬件/固件实现，既不是操作系统的职责，更不是文件系统的功能**（2025#32 考点！）。

1. **动态磨损均衡（Dynamic Wear Leveling）**：仅当有**新数据写入**时，FTL 从当前空闲块池中优先挑选**已擦除次数最少**的闪存块来写。
   - **局限**：那些存放着长期不变“**冷数据**”（如系统文件、静态影音）的块始终不被改写，因而擦除次数永远极低且不参与轮换；真正参与写轮换的只是剩余少量自由块，磨损仍集中于局部。
2. **静态磨损均衡（Static Wear Leveling，更先进！）**：在动态均衡基础上更进一步——控制器后台定期监测各块磨损计数，**主动把长期不改的冷数据迁移到已擦除次数较多的老块上安放**，从而把老实闲着的“低磨损年轻块”解放出来承受高频热写入，实现**全盘所有块的均匀磨损**（代价是迁移冷数据略微增大 WAF）。

> **★考点算例（均衡 vs 不均衡寿命差 32 倍）**：一块 $256\text{ GB}$ TLC SSD，每块擦除寿命 $3000$ 次，$\text{WAF} = 4$，应用每天向主机侧写入 $50\text{ GB}$ 数据。
> 1. **闪存侧总可承受写入量**：$256\text{ GB} \times 3000 = 768{,}000\text{ GB} = 750\text{ TB}$。
> 2. **折算为主机侧总可写量（除以 $\text{WAF}$）**：$\frac{750\text{ TB}}{4} = 187.5\text{ TB}$。
> 3. **若磨损完全均衡**：全盘块同步磨损，可撑 $\frac{187.5 \times 1024\text{ GB}}{50\text{ GB/天}} = 3840\text{ 天} \approx \mathbf{10.5\text{ 年}}$。
> 4. **若不做磨损均衡，热点写入集中在同一片 $8\text{ GB}$ 块区**：仅这 $8\text{ GB}$ 可承受 $\frac{8 \times 3000}{4} = 6000\text{ GB}$ 主机写入，可撑 $\frac{6000}{50} =$ <strong>120 天（4 个月）</strong>即报废——其余 $248\text{ GB}$ 全新块一次也帮不上忙，整盘寿命差距高达 **32 倍**！

#### 7.8.4 SSD 与 HDD 全面对照及对 OS 机制的影响

| 对比项目 | 固态硬盘（SSD） | 机械硬盘（HDD） | 操作系统层适配变化（2025#32） |
| --- | --- | --- | --- |
| **物理介质与基本单元** | NAND Flash 半导体；**页读写、块擦除** | 磁性盘片+机械臂；**扇区读写** | 文件系统只需管统一逻辑盘块大小（2025#32 正确项） |
| **读写对称性** | **不对称（读 $\ll$ 写 $\ll$ 擦）**，写明显慢于读 | 基本对称 | 页面置换优先淘汰**未修改页**（改进型 CLOCK 在 SSD 收益更大） |
| **覆盖写能力** | **不能原地覆盖**（写只能 $1 \to 0$） | 可以直接覆写 | 删除文件向设备发 **TRIM** 通知作废页，降低写放大 |
| **磁盘调度算法** | **基本失效**（无寻道时间，Linux 用 `none`/`noop` 仅做公平与优先级仲裁） | 必须调度（SCAN/LOOK/SSTF 优化寻道） | 2025#32：文件系统**不负责**“降低寻道时间”，也不负责“磨损均衡” |
| **数据分布要求** | 随机读 $\approx$ 顺序读（顺序写仍有利降写放大） | 连续同柱面存放极大提升顺序读速 | 不再执着按柱面连续排布以避寻道 |
| **物理寿命与抗震噪音** | 受擦除次数上限约束；抗震静音功耗低 | 受机械马达轴承磨损；怕震动有噪音 | 频繁刷盘的 Swap 对换区/日志会加速 SSD 块磨损 |

<figure class="cpd-figure not-content" id="os-c7-fig-17">
  <svg viewBox="0 0 720 314" role="img" aria-label="固态硬盘SSD内部结构、FTL异地更新、垃圾回收GC与写入放大因果链">
    <defs>
      <marker id="os-c7-arr-17" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="692" height="172" rx="7"/>
    <rect class="fig-box-subtle" x="14" y="194" width="692" height="108" rx="7"/>
    <rect class="fig-box" x="28" y="54" width="96" height="90" rx="5"/>
    <rect class="fig-box-blue" x="150" y="48" width="166" height="122" rx="5"/>
    <rect class="fig-box-orange" x="344" y="48" width="164" height="122" rx="5"/>
    <rect class="fig-box-green" x="526" y="48" width="166" height="122" rx="5"/>
    <line class="fig-line-accent" x1="124" y1="84" x2="148" y2="84" marker-end="url(#os-c7-arr-17)"/>
    <line class="fig-line-accent" x1="124" y1="124" x2="148" y2="124" marker-end="url(#os-c7-arr-17)"/>
    <line class="fig-line-accent" x1="316" y1="90" x2="342" y2="90" marker-end="url(#os-c7-arr-17)"/>
    <path class="fig-line-green" d="M 426 150 L 426 161 L 609 161 L 609 134" marker-end="url(#os-c7-arr-17)"/>
    <rect class="fig-box-red" x="358" y="76" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="430" y="76" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="358" y="106" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="430" y="106" width="64" height="24" rx="3"/>
    <rect class="fig-box-green" x="540" y="76" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="614" y="76" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="540" y="106" width="64" height="24" rx="3"/>
    <rect class="fig-box-blue" x="614" y="106" width="64" height="24" rx="3"/>
    <rect class="fig-box" x="28" y="226" width="110" height="40" rx="4"/>
    <rect class="fig-box-blue" x="156" y="226" width="124" height="40" rx="4"/>
    <rect class="fig-box-orange" x="298" y="226" width="122" height="40" rx="4"/>
    <rect class="fig-box-red" x="438" y="226" width="122" height="40" rx="4"/>
    <rect class="fig-box-green" x="578" y="226" width="114" height="40" rx="4"/>
    <line class="fig-line-accent" x1="138" y1="246" x2="154" y2="246" marker-end="url(#os-c7-arr-17)"/>
    <line class="fig-line-accent" x1="280" y1="246" x2="296" y2="246" marker-end="url(#os-c7-arr-17)"/>
    <line class="fig-line-accent" x1="420" y1="246" x2="436" y2="246" marker-end="url(#os-c7-arr-17)"/>
    <line class="fig-line-accent" x1="560" y1="246" x2="576" y2="246" marker-end="url(#os-c7-arr-17)"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① SSD 架构与 FTL 异地更新 + GC 原理（页读写、块擦除、只能 1→0）</text>
    <text class="fig-label" x="76" y="84" font-size="10" text-anchor="middle">主机 OS</text>
    <text class="fig-muted" x="76" y="102" font-size="8.8" text-anchor="middle">发 LBA 读写</text>
    <text class="fig-muted" x="76" y="126" font-size="8.8" text-anchor="middle">删文件发 TRIM</text>
    <text class="fig-blue" x="233" y="66" font-size="10" text-anchor="middle">FTL 闪存翻译层</text>
    <text class="fig-label" x="233" y="85" font-size="9" text-anchor="middle">LBA 5 → 改指向 Block 1 P0</text>
    <text class="fig-muted" x="233" y="102" font-size="8.5" text-anchor="middle">维护 L2P 映射表</text>
    <text class="fig-muted" x="233" y="120" font-size="8.5" text-anchor="middle">控制垃圾回收 GC 调度</text>
    <text class="fig-muted" x="233" y="138" font-size="8.5" text-anchor="middle">硬件级磨损均衡 ★</text>
    <text class="fig-muted" x="233" y="156" font-size="8.5" text-anchor="middle">（非 OS 文件系统职责）</text>
    <text class="fig-orange" x="426" y="66" font-size="9.8" text-anchor="middle">闪存 Block 0（待 GC）</text>
    <text class="fig-red" x="390" y="92" font-size="8.5" text-anchor="middle">P0 无效</text>
    <text class="fig-blue" x="462" y="92" font-size="8.5" text-anchor="middle">P1 有效</text>
    <text class="fig-blue" x="390" y="122" font-size="8.5" text-anchor="middle">P2 有效</text>
    <text class="fig-blue" x="462" y="122" font-size="8.5" text-anchor="middle">P3 有效</text>
    <text class="fig-red" x="426" y="144" font-size="8.5" text-anchor="middle">搬走 P1～P3 后整块擦除</text>
    <text class="fig-green" x="609" y="66" font-size="9.8" text-anchor="middle">闪存 Block 1（空闲目标）</text>
    <text class="fig-green" x="572" y="92" font-size="8.5" text-anchor="middle">P0 新写</text>
    <text class="fig-blue" x="646" y="92" font-size="8.5" text-anchor="middle">搬入 P1</text>
    <text class="fig-blue" x="572" y="122" font-size="8.5" text-anchor="middle">搬入 P2</text>
    <text class="fig-blue" x="646" y="122" font-size="8.5" text-anchor="middle">搬入 P3</text>
    <text class="fig-title" x="28" y="213" font-size="11.5">② 因果推演全链：为什么 SSD 会存在写放大与磨损均衡？</text>
    <text class="fig-label" x="83" y="244" font-size="9.2" text-anchor="middle">不能覆盖写</text>
    <text class="fig-muted" x="83" y="258" font-size="8.2" text-anchor="middle">只能 1→0、块擦</text>
    <text class="fig-blue" x="218" y="244" font-size="9.2" text-anchor="middle">FTL 异地更新</text>
    <text class="fig-muted" x="218" y="258" font-size="8.2" text-anchor="middle">写新页、旧页废</text>
    <text class="fig-orange" x="359" y="244" font-size="9.2" text-anchor="middle">垃圾回收 GC</text>
    <text class="fig-muted" x="359" y="258" font-size="8.2" text-anchor="middle">搬有效页+擦整块</text>
    <text class="fig-red" x="499" y="244" font-size="9.2" text-anchor="middle">写入放大 WAF&gt;1</text>
    <text class="fig-muted" x="499" y="258" font-size="8.2" text-anchor="middle">闪存实际写 &gt; 主机</text>
    <text class="fig-green" x="635" y="244" font-size="9.2" text-anchor="middle">磨损均衡</text>
    <text class="fig-muted" x="635" y="258" font-size="8.2" text-anchor="middle">均摊擦写寿命</text>
    <text class="fig-accent" x="360" y="290" font-size="9.5" text-anchor="middle">★ 读写特性：随机读 ≈ 顺序读（无寻道）；但读 ≪ 写 ≪ 擦，随机写因 GC 慢于顺序写</text>
  </svg>
  <figcaption>图 7-17　SSD 闪存翻译层（FTL）异地更新机制、垃圾回收（GC）与写入放大因果链</figcaption>
</figure>

<figure class="cpd-figure not-content" id="os-c7-fig-18">
  <svg viewBox="0 0 720 278" role="img" aria-label="动态磨损均衡与静态磨损均衡工作机制及寿命对比">
    <defs>
      <marker id="os-c7-arr-18" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="14" y="12" width="340" height="254" rx="7"/>
    <rect class="fig-box-subtle" x="366" y="12" width="340" height="254" rx="7"/>
    <rect class="fig-box-blue" x="28" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-red" x="108" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-green" x="188" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-red" x="268" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box" x="28" y="160" width="312" height="92" rx="4"/>
    <rect class="fig-box-green" x="380" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-orange" x="460" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-green" x="540" y="72" width="70" height="72" rx="4"/>
    <rect class="fig-box-orange" x="620" y="72" width="70" height="72" rx="4"/>
    <path class="fig-line-accent" d="M 415 70 Q 535 52 655 70" fill="none" marker-end="url(#os-c7-arr-18)"/>
    <rect class="fig-box" x="380" y="160" width="312" height="92" rx="4"/>
    <text class="fig-title" x="28" y="33" font-size="11.5">① 动态磨损均衡（仅挑擦除少的新块写）</text>
    <text class="fig-muted" x="184" y="52" font-size="9" text-anchor="middle">冷数据占据块长期不释放，热区局部磨损</text>
    <text class="fig-blue" x="63" y="92" font-size="9.5" text-anchor="middle">Block 0</text>
    <text class="fig-muted" x="63" y="110" font-size="8.8" text-anchor="middle">冷数据占领</text>
    <text class="fig-blue" x="63" y="128" font-size="9" text-anchor="middle">10 次</text>
    <text class="fig-red" x="143" y="92" font-size="9.5" text-anchor="middle">Block 1</text>
    <text class="fig-muted" x="143" y="110" font-size="8.8" text-anchor="middle">热区轮换</text>
    <text class="fig-red" x="143" y="128" font-size="9" text-anchor="middle">2800 次</text>
    <text class="fig-green" x="223" y="92" font-size="9.5" text-anchor="middle">Block 2</text>
    <text class="fig-muted" x="223" y="110" font-size="8.8" text-anchor="middle">新写优先挑</text>
    <text class="fig-green" x="223" y="128" font-size="9" text-anchor="middle">320 次</text>
    <text class="fig-red" x="303" y="92" font-size="9.5" text-anchor="middle">Block 3</text>
    <text class="fig-muted" x="303" y="110" font-size="8.8" text-anchor="middle">热区轮换</text>
    <text class="fig-red" x="303" y="128" font-size="9" text-anchor="middle">2750 次</text>
    <text class="fig-label" x="38" y="180" font-size="9.2">• 仅写新数据时选空闲块中磨损最小者</text>
    <text class="fig-red" x="38" y="198" font-size="9">• 缺陷：冷数据占住的 Block 0 永不参与轮换</text>
    <text class="fig-muted" x="38" y="216" font-size="8.8">• 可参与轮换块变少，局部块先报废（局部均衡）</text>
    <text class="fig-muted" x="38" y="234" font-size="8.8">• 不均衡算例：热点 8GB 日写 50GB 仅撑 4 个月</text>
    <text class="fig-title" x="380" y="33" font-size="11.5">② 静态磨损均衡（主动搬冷数据，全盘拉平 ★）</text>
    <text class="fig-accent" x="535" y="50" font-size="8.8" text-anchor="middle">主动把冷数据迁至老块，腾出 Block 0</text>
    <text class="fig-green" x="415" y="92" font-size="9.5" text-anchor="middle">Block 0</text>
    <text class="fig-muted" x="415" y="110" font-size="8.8" text-anchor="middle">腾出承接热写</text>
    <text class="fig-green" x="415" y="128" font-size="9" text-anchor="middle">10→1400 次</text>
    <text class="fig-orange" x="495" y="92" font-size="9.5" text-anchor="middle">Block 1</text>
    <text class="fig-muted" x="495" y="110" font-size="8.8" text-anchor="middle">全盘协同</text>
    <text class="fig-orange" x="495" y="128" font-size="9" text-anchor="middle">1520 次</text>
    <text class="fig-green" x="575" y="92" font-size="9.5" text-anchor="middle">Block 2</text>
    <text class="fig-muted" x="575" y="110" font-size="8.8" text-anchor="middle">全盘协同</text>
    <text class="fig-green" x="575" y="128" font-size="9" text-anchor="middle">1480 次</text>
    <text class="fig-orange" x="655" y="92" font-size="9.5" text-anchor="middle">Block 3</text>
    <text class="fig-muted" x="655" y="110" font-size="8.8" text-anchor="middle">承接冷数据</text>
    <text class="fig-orange" x="655" y="128" font-size="9" text-anchor="middle">1550 次</text>
    <text class="fig-green" x="390" y="180" font-size="9.2">• 更先进：定期搬冷数据至老块，释放年轻块</text>
    <text class="fig-label" x="390" y="198" font-size="9">• 解决分布而非总量，略增 WAF 但延寿显著</text>
    <text class="fig-muted" x="390" y="216" font-size="8.8">• 256GB TLC 均衡后寿命达 10.5 年（提升 32 倍）</text>
    <text class="fig-red" x="390" y="234" font-size="8.8">★ 2025#32 考点：由 SSD 控制器 FTL 实现，非 FS</text>
  </svg>
  <figcaption>图 7-18　动态磨损均衡 vs 静态磨损均衡（释放冷数据块）机理及整盘寿命倍增效应</figcaption>
</figure>

---

### 7.9 本章高频考点速记与 408 真题索引总览

> **★考点（本章 10 条保命红线）**：
> 1. **块设备 vs 字符设备**看<strong>“能否寻址（随机访问）”</strong>而非快慢（2026#31）；只有块设备才需磁盘调度。
> 2. **硬件中断保存断点（`PC`、`PSW`）与切态取向量**；**OS 初始化向量表（数组）、保存现场（通用寄存器）与屏蔽字、执行 ISR**（2012#24、2015#23、2020#25、2023#24）。
> 3. **键盘/鼠标输入四段流**：控制器搬进数据寄存器 $\to$ 中断处理程序/驱动搬进**内核缓冲区**（ISR 结束停靠点） $\to$ 系统调用返回拷进用户缓冲区（2010#32、2024#31、2026#32）。
> 4. **I/O 软件四层先后顺序**：用户层 $\to$ 设备独立性软件（系统调用处理） $\to$ **设备驱动程序** $\to$ **中断处理程序**（2011#26、2012#26、2013#25、2023#46）；**只有驱动程序触碰硬件寄存器且与控制方式紧密相关**（2022#32）。
> 5. **程序员打开设备使用逻辑设备名**，由 **LUT** 映射（2009#32、2020#30）；设备分配考量**类型、权限、占用状态、映射关系**四要素（2023#32），安全分配因立即阻塞摒弃“请求和保持”。
> 6. **SPOOLing 假脱机**由后台**输入/输出进程**控制外设与磁盘井间的数据传送，**绝非用户作业控制**（2016#31）；破坏**互斥**条件，将独占设备改造为共享虚拟设备。
> 7. **单缓冲与双缓冲**：单缓冲每块 $\max(T,C)+M$ ，总时间 $T+M+(n-1)(\max(T,C)+M)+C$ ；双缓冲每块 $\max(T,C+M)$ ，总时间 $T+(n-1)\max(T,C+M)+M+C$ （2011#31、2013#27）；内存设置磁盘缓冲主要目的是**减少磁盘 I/O 次数**（2015#28）。
> 8. **磁盘格式化三阶段**：低级（物理）格式化定扇区/校验位数 $\to$ 分区（MBR/活动分区，逻辑划分不提速 2012#32） $\to$ 逻辑（高级）格式化建引导块/超级块/空闲管理/inode/根目录（2017#29、2021#46）。
> 9. **磁盘调度与磁臂黏着**：仅**SSTF** 会饥饿；**SCAN** 空跑到端点而 **LOOK** 止于最远请求（2009#29、2015#32、2021#26、2024#32）；**SSTF/SCAN/C-SCAN** 均会磁臂黏着，**FCFS 唯一不黏着**（2018#30），**N-Step-SCAN / FSCAN** 靠冻结批破解。
> 10. **SSD 磨损均衡**：页读写、块擦除、只能 `1→0`；**磨损均衡由 SSD 控制器的 FTL 实现**而非文件系统，SSD 无寻道时间（2025#32）。

| 真题考号 | 所属知识点 | 核心命题落脚点与防坑提示 |
| --- | --- | --- |
| **09#23** | 并行性与控制方式 | 单核下 CPU 与设备/通道、设备与设备可并行；**进程与进程只能并发** |
| **09#29 / 15#32** | SCAN 算法 | 先圈定起始磁道与方向，注意是否空跑到边界端点 |
| **09#32 / 20#30** | 设备独立性与 LUT | 打开设备用**逻辑设备名**；换物理设备只改 LUT 不改应用；可用文件名访问设备 |
| **10#32 / 24#31 / 26#32** | 中断数据流停靠 | 按键最先获得信息的是 **ISR**；ISR 结束时数据在**内核缓冲区**（控制器搬至 DBR、驱动搬入内核缓冲） |
| **10#45** | 位示图 + C-SCAN + 旋转 | $2\text{ KB}$ 管理 $16384$ 块；6000 RPM 一圈 $10\text{ ms}$；跨 $4$ 磁道付 **4 次**平均旋转延迟 $+ 4$ 次读扇区 |
| **11#26 / 12#26 / 13#25** | I/O 软件四层顺序 | 必先**设备驱动程序**启动请求，再**中断处理程序**响应完成；计算 CHS 地址归驱动 |
| **11#31 / 13#27** | 单双缓冲时空计算 | 2011#31 单缓冲 $1550\ \mu\text{s}$ / 双缓冲 $1100\ \mu\text{s}$；2013#27 两块单缓冲耗时 $300$（末块单算） |
| **12#24 / 15#23 / 20#25** | 中断软硬件分工 | 断点 `PC`/`PSW` 归硬件（子程序不保 PSW）；通用寄存器/屏蔽字/VECTOR 初始化/ISR 归 OS |
| **12#32 / 15#28** | 磁盘缓存目的 | 内存设磁盘缓冲区主要为**减少磁盘 I/O 次数**；**划多分区不能改善磁盘 I/O 性能** |
| **16#31** | SPOOLing 假脱机 | 设备与井间传送由**输入/输出进程**完成，**非用户作业控制** |
| **17#29 / 21#46** | 格式化与系统引导 | 校验码位数在物理格式化定，根目录与空闲管理在逻辑格式化建；引导链 ROM→MBR→PBR→OS |
| **17#32** | DMA 工作步骤 | 初始化启动 $\to$ 传块至内存 $\to$ DMA 发中断 $\to$ 执行结束 ISR |
| **18#29** | 时钟中断 ISR | 更新内核时钟变量、当前进程 CPU 时间及剩余时间片 |
| **18#30** | 磁臂黏着 | 总是访问同一磁道致其余请求无响应；**FCFS** 绝不发生磁臂黏着 |
| **19#44** | 磁盘容量 + SSTF + CHS | 容量 $3\times 10^5\text{ KB}$；SSTF 用簇号比较；**第 $100530$ 簇**（0-based `100529`）位于 `(100, 5, 58～59)`，驱动转换地址 |
| **21#26 / 24#32** | SSTF / C-SCAN 计算 | 严格按序列逐段取绝对值求和；C-SCAN 返程不服务但跳回距离通常计入 |
| **22#32 / 26#31** | 设备驱动程序 | 与控制方式密切相关、执行时可阻塞自身（22#32）；块设备与字符设备绝非同种 I/O 方式（26#31） |
| **23#24** | 中断向量表 | 需按号 $O(1)$ 随机访问定长表项，最适合用**数组**存储 |
| **23#32** | 设备分配考量 | **类型 + 访问权限 + 占用状态 + 逻辑物理映射**四者缺一不可 |
| **23#46** | 键盘输入大题 | `read` 无数据立即阻塞切走；按键进 ISR 时进程阻塞态、CPU 内核态；驱动搬入系统缓冲再唤醒就绪 |
| **25#32** | SSD vs HDD 与文件系统 | **磨损均衡归 SSD FTL**、**无寻道时间**；文件系统两者皆可提供的为统一逻辑盘块大小 |
