diff --git a/translations/zh_CN/chapters/part1/chapter-01.md b/translations/zh_CN/chapters/part1/chapter-01.md index a5eae48..56e2d60 100644 --- a/translations/zh_CN/chapters/part1/chapter-01.md +++ b/translations/zh_CN/chapters/part1/chapter-01.md @@ -27,7 +27,7 @@ language: "zh-CN" 这种对答案的追寻引领我走向了FreeBSD。最令我着迷的不仅是系统的运作方式,更是我可以接触其源代码。这不仅仅是一个供使用的操作系统,而是一个我可以逐行研读的系统。这种可能性成为我日益增长的热情的燃料。 -起初,我只能在大学的机器上探索FreeBSD。白天,我的时间被化学学习占据,但我渴望有更多时间来更深入地研究它。我不能让这种好奇心干扰我的学业。我来自 humble 背景,是家族中第一个上大学的人,我自豪地肩负着这份责任。 +起初,我只能在大学的机器上探索FreeBSD。白天,我的时间被化学学习占据,但我渴望有更多时间来更深入地研究它。我不能让这种好奇心干扰我的学业。我来自一个平凡的家庭,是家族中第一个上大学的人,我自豪地肩负着这份责任。 在那些早年岁月里,我没有属于自己的电脑。在有限的经济条件下,我勉强维持着离家在外的基本生活。将近两年的时间里,我对FreeBSD的学习是在化学学院图书馆里进行的,我如饥似渴地阅读能找到的每一份关于Unix和系统编程的文档。但由于没有自己的机器,我无法将许多所学内容付诸实践。 @@ -92,11 +92,11 @@ FreeBSD还有一种**强烈的守护意识**。项目中的开发者不仅仅是 ### 澄清误解 -一个常见的误解是认为FreeBSD是"又一个Linux"。它不是。虽然两者都有UNIX根源,但FreeBSD采取了非常不同的方法。 +一个常见的误解是认为FreeBSD是“又一个Linux”。它不是。虽然两者都有UNIX根源,但FreeBSD采取了非常不同的方法。 Linux是一个内核,结合了来自许多独立项目的用户空间工具。相比之下,FreeBSD作为一个**完整的操作系统**开发,内核、库、编译器工具链和核心实用程序在单一项目下一起维护。这种统一设计使FreeBSD感觉一致和凝聚,在组件之间移动时更少意外。 -另一个误解是FreeBSD"只适合服务器"。虽然它确实在服务器环境中备受信任,但FreeBSD也运行在台式机、笔记本电脑和嵌入式系统上。它的灵活性是它能在其他UNIX变体消失时存活并演化数十年的原因之一。 +另一个误解是FreeBSD“只适合服务器”。虽然它确实在服务器环境中备受信任,但FreeBSD也运行在台式机、笔记本电脑和嵌入式系统上。它的灵活性是它能在其他UNIX变体消失时存活并演化数十年的原因之一。 ### 现实世界的应用 @@ -108,7 +108,7 @@ FreeBSD无处不在,虽然常常不可见。当你从Netflix流媒体观看节 ### 为什么选择FreeBSD进行驱动开发? -对于学习设备驱动程序的人来说,FreeBSD提供了一种罕见的平衡。其代码库现代且可用于生产,但与许多替代品相比,它更干净、更易接近。开发者经常形容FreeBSD的内核是"可读的",这个特点在你刚刚起步时至关重要。 +对于学习设备驱动程序的人来说,FreeBSD提供了一种罕见的平衡。其代码库现代且可用于生产,但与许多替代品相比,它更干净、更易接近。开发者经常形容FreeBSD的内核是“可读的”,这个特点在你刚刚起步时至关重要。 该项目也有强大的文档传统。FreeBSD手册、手册页和开发者指南提供了在其他开源内核中难以找到的指导水平。这意味着你不会对事物如何组合在一起感到困惑。 @@ -206,7 +206,7 @@ FreeBSD的优势之一是其**模块化设计**。驱动程序可以作为内核 ### 强烈推荐实验 -每章都包含动手实验,大多数章节包含推动超越实验的挑战练习。**实验是强烈推荐的。** 这是散文转化为反射的地方。内核编程以其他学科罕有的方式奖励肌肉记忆:相同的attach模式、相同的清理链、相同的锁定形状在章节与章节、驱动与驱动中反复出现。输入这些模式、编译它们、将它们加载到运行中的内核、并故意让它们失败,是内化它们的单一最有效方式。 +每章都包含动手实验,大多数章节包含推动超越实验的挑战练习。**实验是强烈推荐的。** 这是散文转化为反射的地方。内核编程以其他学科罕有的方式奖励肌肉记忆:相同的附加模式、相同的清理链、相同的锁定形状在章节与章节、驱动与驱动中反复出现。输入这些模式、编译它们、将它们加载到运行中的内核、并故意让它们失败,是内化它们的单一最有效方式。 学习是自定节奏的,最终由你掌控。如果一章是信息性的且材料已经熟悉,略读是一个公平的选择。但当一章要求你加载模块并观察其行为时,抵制绕过练习阅读的冲动。运行过实验和没运行过的读者之间的差异往往在几章后显现,要么是顺利进展,要么是安静的困惑。 diff --git a/translations/zh_CN/chapters/part1/chapter-02.md b/translations/zh_CN/chapters/part1/chapter-02.md index 7996b27..1aef5ef 100644 --- a/translations/zh_CN/chapters/part1/chapter-02.md +++ b/translations/zh_CN/chapters/part1/chapter-02.md @@ -15,7 +15,7 @@ language: "zh-CN" # 搭建你的实验环境 -在开始编写代码或探索 FreeBSD 内部机制之前,我们需要一个可以安全地进行实验、犯错和学习的地方。这个地方就是你的**实验环境**(lab environment)。在本章中,我们将创建你在本书其余部分将使用的基础:一个配置好用于驱动程序开发的 FreeBSD 系统。 +在开始编写代码或探索 FreeBSD 内部机制之前,我们需要一个可以安全地进行实验、犯错和学习的地方。这个地方就是你的**实验环境**。在本章中,我们将创建你在本书其余部分将使用的基础:一个配置好用于驱动程序开发的 FreeBSD 系统。 把本章想象成准备你的**工作室**。就像木匠在制作家具之前需要合适的工作台、工具和安全装备一样,你需要一个可靠的 FreeBSD 安装、正确的开发工具,以及在出现问题时能够快速恢复的方法。内核编程是毫不留情的;驱动程序中的一个小错误就可能导致整个系统崩溃。拥有一个专门的实验环境意味着这些崩溃成为学习过程的一部分,而不是灾难。 @@ -66,11 +66,11 @@ language: "zh-CN" - **低成本**:不需要专门的硬件。 - **可移植**:你可以在计算机之间移动你的虚拟机。 -### 般机:当你需要真实的东西时 +### 裸机:当你需要真实的东西时 有时只有真正的硬件才行,例如,如果你想为 PCIe 卡或需要直接访问机器总线的 USB 设备开发驱动程序。在这些情况下,在虚拟机中测试可能不够,因为并非所有虚拟化解决方案都能可靠地传递硬件。 -如果你有一台旧的备用 PC,在那里安装 FreeBSD 可以为你提供最接近现实的测试环境。但请记住:般机设置没有虚拟机那样的安全网。如果你导致内核崩溃,机器会重启,你需要手动恢复。这就是为什么我建议从虚拟机开始,即使你最终会转向般机进行特定的硬件项目。 +如果你有一台旧的备用 PC,在那里安装 FreeBSD 可以为你提供最接近现实的测试环境。但请记住:裸机设置没有虚拟机那样的安全。如果你导致内核崩溃,机器会重启,你需要手动恢复。这就是为什么我建议从虚拟机开始,即使你最终会转向般机进行特定的硬件项目。 ### 现实世界的例子 @@ -100,7 +100,7 @@ language: "zh-CN" 既然你理解了为什么专门的实验环境很重要,下一个问题是:**你应该在哪里构建它?** FreeBSD 可以以两种主要方式运行你的实验: 1. **在虚拟机(VM)内部**,运行在你现有操作系统之上。 -2. **直接在物理硬件上**(通常称为*般机*)。 +2. **直接在物理硬件上**(通常称为*裸机*)。 两种选择都可行,并且都在现实世界的 FreeBSD 开发中广泛使用。正确的选择取决于你的目标、你的硬件和你的舒适程度。让我们并排比较它们。 @@ -124,7 +124,7 @@ language: "zh-CN" - 你没有备用硬件可以专用。 - 你预期在学习过程中经常导致内核崩溃(你会的)。 -### 般机:真家伙 +### 裸机:真家伙 **直接在硬件上**运行 FreeBSD 是你能获得的最接近"真实的东西"。这意味着 FreeBSD 作为机器上唯一的操作系统启动,直接与 CPU、内存、存储和外设通信。 @@ -132,7 +132,7 @@ language: "zh-CN" - **真正的硬件测试**:在为 PCIe、USB 或其他物理设备开发驱动程序时必不可少。 - **性能**:没有虚拟机开销。你可以完全访问系统资源。 -- **准确性**:一些错误只会在般机上出现,特别是与时序相关的问题。 +- **准确性**:一些错误只会在裸机上出现,特别是与时序相关的问题。 劣势: @@ -140,7 +140,7 @@ language: "zh-CN" - **恢复需要时间**:如果你损坏了操作系统,可能需要重新安装 FreeBSD。 - **需要专用硬件**:你需要一台可以完全用于实验的备用 PC 或笔记本电脑。 -**何时选择般机:** +**何时选择裸机:** - 你计划为在虚拟机中不能很好工作的硬件开发驱动程序。 - 你已经有一台可以完全用于 FreeBSD 的备用机器。 @@ -148,11 +148,11 @@ language: "zh-CN" ### 混合策略 -许多专业开发者**两者都用**。他们在虚拟机中进行大部分实验和原型设计,那里安全快速,只有当驱动程序足够稳定可以针对真实硬件测试时才转向般机。你不必永远只选择一种,你可以今天从虚拟机开始,以后如果需要再添加般机。 +许多专业开发者**两者都用**。他们在虚拟机中进行大部分实验和原型设计,那里安全快速,只有当驱动程序足够稳定可以针对真实硬件测试时才转向裸机。你不必永远只选择一种,你可以今天从虚拟机开始,以后如果需要再添加裸机。 ### 快速比较表 -| 特性 | 虚拟机 | 般机 | +| 特性 | 虚拟机 | 裸机 | | ----------------- | ------------------------------ | ---------------------------- | | **安全性** | 很高(快照、回滚) | 低(需要手动恢复) | | **性能** | 稍低(开销) | 完整系统性能 | @@ -164,10 +164,10 @@ language: "zh-CN" ### 动手实验:决定你的路径 1. 查看你当前的资源。你是否有一台可以用于 FreeBSD 实验的备用笔记本电脑或台式机? - - 如果是 -> 般机对你来说是一个选择。 + - 如果是 -> 裸机对你来说是一个选择。 - 如果否 -> 虚拟机是完美的起点。 2. 在你的**实验日志**中写下: - - 你将使用哪个选项(虚拟机还是般机)。 + - 你将使用哪个选项(虚拟机还是裸机)。 - 你选择它的原因。 - 你预期的任何限制(例如,"使用虚拟机,可能还无法测试 USB 直通")。 3. 如果你选择虚拟机,请记下你将使用哪个虚拟机监控程序(VirtualBox、VMware、bhyve 等)。 @@ -176,13 +176,13 @@ language: "zh-CN" ### 小结 -我们比较了虚拟机和般机设置,看到了各自的优势和权衡。对于大多数初学者来说,从虚拟机开始是安全性、便利性和灵活性的最佳平衡。如果你以后需要与真实硬件交互,可以将般机系统添加到你的工具箱中。 +我们比较了虚拟机和裸机设置,看到了各自的优势和权衡。对于大多数初学者来说,从虚拟机开始是安全性、便利性和灵活性的最佳平衡。如果你以后需要与真实硬件交互,可以将裸机系统添加到你的工具箱中。 -在下一节中,我们将卷起袖子,进行实际的 **FreeBSD 14.3 安装**,首先在虚拟机中,然后我们将涵盖般机安装的关键点。这就是你的实验环境真正开始成形的地方。 +在下一节中,我们将卷起袖子,进行实际的 **FreeBSD 14.3 安装**,首先在虚拟机中,然后我们将涵盖裸机安装的关键点。这就是你的实验环境真正开始成形的地方。 -## 安装 FreeBSD(虚拟机和般机) +## 安装 FreeBSD(虚拟机和裸机) -此时,你已经选择是在**虚拟机**还是**般机**上设置 FreeBSD。现在是时候实际安装将作为我们所有实验基础的操作系统了。我们将专注于 **FreeBSD 14.3**,这是本文写作时最新的稳定版本,这样你所做的一切都与本书中的示例相匹配。 +此时,你已经选择是在**虚拟机**还是**裸机**上设置 FreeBSD。现在是时候实际安装将作为我们所有实验基础的操作系统了。我们将专注于 **FreeBSD 14.3**,这是本文写作时最新的稳定版本,这样你所做的一切都与本书中的示例相匹配。 FreeBSD 的安装程序是基于文本的,但不要被它吓倒,它很简单,在不到 20 分钟内你将拥有一个准备好开发的系统。 @@ -376,7 +376,7 @@ https://www.virtualbox.org/wiki/Downloads ![image-20250823192732830](https://freebsd.edsonbrandi.com/images/image-20250823192732830.png) -### 在般机上安装 FreeBSD +### 在裸机上安装 FreeBSD 如果你使用的是备用 PC 或笔记本电脑,你需要从可启动的 USB 闪存盘直接安装 FreeBSD。方法如下: @@ -440,7 +440,7 @@ FreeBSD 启动后,按照上述相同的安装程序步骤操作,我们在那 ### 小结 -你刚刚完成了最重要的里程碑之一:在你的专用实验环境中安装 FreeBSD 14.3。无论是在虚拟机还是般机上,你现在都有了一个可以安全地破坏、修复和重建的干净系统,供你学习。 +你刚刚完成了最重要的里程碑之一:在你的专用实验环境中安装 FreeBSD 14.3。无论是在虚拟机还是裸机上,你现在都有了一个可以安全地破坏、修复和重建的干净系统,供你学习。 在下一节中,我们将介绍安装后应该立即进行的**初始配置**:设置网络、启用基本服务以及为开发工作准备系统。 @@ -626,7 +626,7 @@ ifconfig_em0="DHCP" ```sh set skip on lo - ext_if = "em0" # 虚拟机通常使用 vtnet0;在般机上你可能会看到 em0/re0/igb0 等。 + ext_if = "em0" # 虚拟机通常使用 vtnet0;在裸机上你可能会看到 em0/re0/igb0 等。 tcp_services = "{ ssh }" block in all @@ -995,7 +995,7 @@ SRCS= hello_world.c # zfs rollback zroot/vm@clean-install ``` -### 般机上的快照 +### 裸机上的快照 如果你直接在硬件上运行 FreeBSD,你没有 GUI 快照的便利。但如果你用 **ZFS** 安装 FreeBSD,你仍然可以访问相同的快照工具。 @@ -1013,7 +1013,7 @@ SRCS= hello_world.c # zfs rollback -r zroot@clean-install ``` -ZFS 快照是即时的,不会复制数据,它们只跟踪更改。对于严肃的般机实验环境,强烈推荐使用 ZFS。 +ZFS 快照是即时的,不会复制数据,它们只跟踪更改。对于严肃的裸机实验环境,强烈推荐使用 ZFS。 如果你用 **UFS** 而不是 ZFS 安装,你将没有快照功能。在这种情况下,依赖**备份**(见下文),如果你想要这个安全网,也许以后考虑用 ZFS 重新安装。 @@ -1049,7 +1049,7 @@ ZFS 快照是即时的,不会复制数据,它们只跟踪更改。对于严 - 在客户机内删除一个测试文件。 - 回滚 ZFS 快照。 -3. 如果你在使用 ZFS 的般机上: +3. 如果你在使用 ZFS 的裸机上: - 拍摄快照 `zroot@before-break`。 - 删除一个测试文件。 @@ -1334,7 +1334,7 @@ causing a panic when unloading. Added a guard condition. 在本章中,你: - 理解了为什么**安全的实验环境**对驱动程序开发至关重要。 -- 为你的情况选择了正确的设置——**虚拟机**或**般机**。 +- 为你的情况选择了正确的设置——**虚拟机**或**裸机**。 - 逐步安装了 **FreeBSD 14.3**。 - 执行了**初始配置**,包括网络、用户和基本加固。 - 安装了必要的**开发工具**:编译器、调试器、Git 和编辑器。 @@ -1355,7 +1355,7 @@ causing a panic when unloading. Added a guard condition. ### 练习 1. **快照** - - 拍摄你的虚拟机快照或般机上的 ZFS 快照。 + - 拍摄你的虚拟机快照或裸机上的 ZFS 快照。 - 故意进行更改(例如,删除 `/tmp/testfile`)。 - 回滚并验证系统已恢复。 2. **版本控制** diff --git a/translations/zh_CN/chapters/part1/chapter-03.md b/translations/zh_CN/chapters/part1/chapter-03.md index 14d6f31..b264516 100644 --- a/translations/zh_CN/chapters/part1/chapter-03.md +++ b/translations/zh_CN/chapters/part1/chapter-03.md @@ -917,9 +917,9 @@ uid=1001(dev) gid=1001(dev) groups=1001(dev), 0(wheel) 1. 创建一个名为 `proj` 的组: - ``` + ``` # pw groupadd proj - ``` + ``` 2. 将两个用户添加到组: diff --git a/translations/zh_CN/chapters/part1/chapter-06.md b/translations/zh_CN/chapters/part1/chapter-06.md index cf97bad..7f1f724 100644 --- a/translations/zh_CN/chapters/part1/chapter-06.md +++ b/translations/zh_CN/chapters/part1/chapter-06.md @@ -2007,12 +2007,12 @@ mydriver_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -**The d_close signature**: +**d_close 的签名**: ```c typedef int d_close_t(struct cdev *dev, int fflag, int devtype, struct thread *td); ``` -**Typical close function**: +**典型的 close 函数**: ```c static int mydriver_close(struct cdev *dev, int fflag, int devtype, struct thread *td) @@ -2030,39 +2030,39 @@ mydriver_close(struct cdev *dev, int fflag, int devtype, struct thread *td) } ``` -**When to use open/close**: +**何时使用 open/close**: -- **Initialize per-session state** (buffers, cursors) -- **Enforce exclusive access** (only one opener at a time) -- **Reset hardware state** on open/close -- **Track usage** for debugging +- **初始化每次会话的状态**(缓冲区、游标) +- **强制独占访问**(同一时间只允许一个打开者) +- **在打开/关闭时重置硬件状态** +- **跟踪使用情况**用于调试 -**When you can skip them**: +**何时可以跳过它们**: -- Device doesn't need setup on open -- Hardware is always ready (like /dev/null) +- 设备在打开时不需要设置 +- 硬件始终就绪(如 /dev/null) -### read/write: Moving Bytes Safely +### read/write:安全地移动字节 -Read and write are the heart of data transfer for character devices. The kernel provides a **uio (user I/O) structure** to abstract the buffer and handle copying safely between kernel and user space. +read 和 write 是字符设备数据传输的核心。内核提供了一个 **uio(用户 I/O)结构**来抽象缓冲区,并安全地处理内核空间与用户空间之间的数据拷贝。 -**The d_read signature**: +**d_read 的签名**: ```c typedef int d_read_t(struct cdev *dev, struct uio *uio, int ioflag); ``` -**The d_write signature**: +**d_write 的签名**: ```c typedef int d_write_t(struct cdev *dev, struct uio *uio, int ioflag); ``` -**Parameters**: +**参数**: -- `dev` - Your cdev -- `uio` - User I/O structure (describes buffer, offset, remaining bytes) -- `ioflag` - I/O flags (IO_NDELAY for non-blocking, etc.) +- `dev` - 你的 cdev +- `uio` - 用户 I/O 结构(描述缓冲区、偏移量、剩余字节数) +- `ioflag` - I/O 标志(如 IO_NDELAY 表示非阻塞等) -**Simple read example**: +**简单的 read 示例**: ```c static int mydriver_read(struct cdev *dev, struct uio *uio, int ioflag) @@ -2089,7 +2089,7 @@ mydriver_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Simple write example**: +**简单的 write 示例**: ```c static int mydriver_write(struct cdev *dev, struct uio *uio, int ioflag) @@ -2119,50 +2119,50 @@ mydriver_write(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Key functions for I/O**: +**I/O 的关键函数**: -**uiomove()** - Copy between kernel buffer and user space +**uiomove()** - 在内核缓冲区和用户空间之间拷贝数据 ```c int uiomove(void *cp, int n, struct uio *uio); ``` -**uio_resid** - Remaining bytes to transfer +**uio_resid** - 剩余需要传输的字节数 ```c if (uio->uio_resid == 0) return (0); /* Nothing to do */ ``` -**Why uio exists** +**为什么需要 uio** - It handles: +它负责处理: -- Multi-segment buffers (scatter-gather) -- Partial transfers -- Offset tracking -- Safe copying between kernel and user space +- 多段缓冲区(分散-聚集) +- 部分传输 +- 偏移量跟踪 +- 内核与用户空间之间的安全拷贝 -### ioctl: Control Paths +### ioctl:控制路径 -Ioctl (I/O control) is the **Swiss Army knife** of device operations. It handles anything that doesn't fit read/write: configuration, querying status, triggering actions, etc. +Ioctl(I/O 控制)是设备操作的**瑞士军刀**。它处理所有不适合 read/write 的操作:配置、查询状态、触发动作等。 -**The d_ioctl signature**: +**d_ioctl 的签名**: ```c typedef int d_ioctl_t(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td); ``` -**Parameters**: +**参数**: -- `dev` - Your cdev -- `cmd` - Command code (user-defined constant) -- `data` - Pointer to data structure (already copied from user space by kernel) -- `fflag` - File flags -- `td` - Thread +- `dev` - 你的 cdev +- `cmd` - 命令码(用户自定义常量) +- `data` - 指向数据结构的指针(已由内核从用户空间拷贝) +- `fflag` - 文件标志 +- `td` - 线程 -**Defining ioctl commands** +**定义 ioctl 命令** -Use the `_IO`, `_IOR`, `_IOW`, `_IOWR` macros: +使用 `_IO`、`_IOR`、`_IOW`、`_IOWR` 宏: ```c #include @@ -2180,9 +2180,9 @@ Use the `_IO`, `_IOR`, `_IOW`, `_IOWR` macros: #define MYDRV_EXCHANGE _IOWR('M', 3, struct mydrv_data) ``` -**The `'M'` is your "magic number"** (unique letter identifying your driver). Pick one not used by system ioctls. +**`'M'` 是你的"魔数"**(用于唯一标识你的驱动的字母)。请选择一个未被系统 ioctl 使用的字母。 -**Implementing ioctl**: +**实现 ioctl**: ```c static int mydriver_ioctl(struct cdev *dev, u_long cmd, caddr_t data, @@ -2221,15 +2221,15 @@ mydriver_ioctl(struct cdev *dev, u_long cmd, caddr_t data, } ``` -**Best practices**: +**最佳实践**: -- Always return **ENOTTY** for unknown commands -- **Validate all input** (ranges, pointers, etc.) -- Use meaningful names for commands -- Document your ioctl interface (man page or header comments) -- Don't assume data pointers are valid (kernel already validated them) +- 对于未知命令始终返回 **ENOTTY** +- **验证所有输入**(范围、指针等) +- 为命令使用有意义的名称 +- 为你的 ioctl 接口编写文档(手册页或头文件注释) +- 不要假设数据指针有效(内核已经验证过它们) -**Real example** from `/usr/src/sys/dev/usb/misc/uled.c`: +**真实示例**,来自 `/usr/src/sys/dev/usb/misc/uled.c`: ```c static int @@ -2284,22 +2284,22 @@ uled_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) } ``` -### poll/kqfilter: Readiness Notifications +### poll/kqfilter:就绪通知 -Poll and kqfilter support **event-driven I/O**, allowing programs to wait efficiently for your device to be ready for reading or writing. +Poll 和 kqfilter 支持**事件驱动 I/O**,允许程序高效地等待你的设备准备好进行读取或写入。 -**When you need these**: +**何时需要这些**: -- Your device may not be ready immediately (hardware buffer empty/full) -- You want to support `select()`, `poll()`, or `kqueue()` system calls -- Non-blocking I/O makes sense for your device +- 你的设备可能不会立即就绪(硬件缓冲区为空/已满) +- 你想支持 `select()`、`poll()` 或 `kqueue()` 系统调用 +- 非阻塞 I/O 对你的设备有意义 -**The d_poll signature**: +**d_poll 的签名**: ```c typedef int d_poll_t(struct cdev *dev, int events, struct thread *td); ``` -**Basic implementation**: +**基本实现**: ```c static int mydriver_poll(struct cdev *dev, int events, struct thread *td) @@ -2327,43 +2327,43 @@ mydriver_poll(struct cdev *dev, int events, struct thread *td) } ``` -**When hardware becomes ready**, wake up waiters: +**当硬件就绪时**,唤醒等待者: ```c /* In your interrupt handler or completion routine: */ selwakeup(&sc->rsel); /* Wake readers */ selwakeup(&sc->wsel); /* Wake writers */ ``` -**The d_kqfilter signature** (kqueue support): +**d_kqfilter 的签名**(kqueue 支持): ```c typedef int d_kqfilter_t(struct cdev *dev, struct knote *kn); ``` -Kqueue is more complex. For beginners, **implementing poll is sufficient**. Kqueue details belong in advanced chapters. +Kqueue 更为复杂。对于初学者来说,**实现 poll 就足够了**。Kqueue 的详细内容属于高级章节。 -### mmap: When Mapping Makes Sense +### mmap:何时使用映射 -Mmap allows user programs to **map device memory directly into their address space**. This is useful but advanced. +Mmap 允许用户程序**将设备内存直接映射到其地址空间**。这很有用但也比较高级。 -**When to support mmap**: +**何时支持 mmap**: -- Hardware has a large memory region (framebuffer, DMA buffers) -- Performance is critical (avoid copy overhead) -- User space needs direct access to hardware registers (dangerous!) +- 硬件有大容量内存区域(帧缓冲区、DMA 缓冲区) +- 性能至关重要(避免拷贝开销) +- 用户空间需要直接访问硬件寄存器(危险!) -**When NOT to support mmap**: +**何时不支持 mmap**: -- Security concerns (exposing kernel or hardware memory) -- Synchronization complexity (cache coherency, DMA ordering) -- It's overkill for simple devices +- 安全考虑(暴露内核或硬件内存) +- 同步复杂性(缓存一致性、DMA 排序) +- 对于简单设备来说是大材小用 -**The d_mmap signature**: +**d_mmap 的签名**: ```c typedef int d_mmap_t(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, int nprot, vm_memattr_t *memattr); ``` -**Basic implementation**: +**基本实现**: ```c static int mydriver_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, @@ -2382,38 +2382,38 @@ mydriver_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, } ``` -**For beginners**: Defer mmap implementation until you actually need it. Most drivers don't. +**对于初学者**:在你真正需要之前,推迟 mmap 的实现。大多数驱动程序不需要它。 -### Back-pointers (si_drv1, etc.) +### 反向指针(si_drv1 等) -You've seen `dev->si_drv1` throughout this section. This is how you **store your softc pointer** in the cdev so you can retrieve it later. +在本节中你已经看到了 `dev->si_drv1` 的用法。这就是你**将 softc 指针存储在 cdev 中**以便后续检索的方式。 -**Setting the back-pointer** (in attach): +**设置反向指针**(在 attach 中): ```c sc->cdev = make_dev(&mydriver_cdevsw, unit, UID_ROOT, GID_WHEEL, 0600, "mydriver%d", unit); sc->cdev->si_drv1 = sc; /* Store our softc */ ``` -**Retrieving it** (in every entry point): +**检索它**(在每个入口点中): ```c struct mydriver_softc *sc = dev->si_drv1; ``` -**Available back-pointers**: +**可用的反向指针**: -- `si_drv1` - Primary driver data (typically your softc) -- `si_drv2` - Secondary data (if needed) +- `si_drv1` - 主要驱动数据(通常是你的 softc) +- `si_drv2` - 辅助数据(如果需要) -**Why not just device_get_softc()?** +**为什么不直接使用 device_get_softc()?** -Because cdev entry points receive a `struct cdev *`, not a `device_t`. The `si_drv1` field is the bridge. +因为 cdev 入口点接收的是 `struct cdev *`,而不是 `device_t`。`si_drv1` 字段就是连接它们的桥梁。 -### Permissions and Ownership +### 权限和所有权 -When creating device nodes, set appropriate permissions to balance usability and security. +创建设备节点时,设置适当的权限以平衡可用性和安全性。 -**make_dev parameters**: +**make_dev 参数**: ```c struct cdev * @@ -2421,50 +2421,50 @@ make_dev(struct cdevsw *devsw, int unit, uid_t uid, gid_t gid, int perms, const char *fmt, ...); ``` -**Common permission patterns**: +**常见权限模式**: -**Root-only device** (hardware control, dangerous operations): +**仅 root 可访问的设备**(硬件控制、危险操作): ```c make_dev(&mydrv_cdevsw, unit, UID_ROOT, GID_WHEEL, 0600, "mydriver%d", unit); ``` -Permissions: `rw-------` (owner=root) +权限:`rw-------`(所有者=root) -**User-accessible read-only**: +**用户可访问的只读设备**: ```c make_dev(&mydrv_cdevsw, unit, UID_ROOT, GID_WHEEL, 0444, "mysensor%d", unit); ``` -Permissions: `r--r--r--` (everyone can read) +权限:`r--r--r--`(所有人可读) -**Group-accessible device** (e.g., audio): +**组可访问的设备**(如音频): ```c make_dev(&mydrv_cdevsw, unit, UID_ROOT, GID_OPERATOR, 0660, "myaudio%d", unit); ``` -Permissions: `rw-rw----` (root and operator group) +权限:`rw-rw----`(root 和 operator 组) -**Public device** (like `/dev/null`): +**公共设备**(如 `/dev/null`): ```c make_dev(&mydrv_cdevsw, unit, UID_ROOT, GID_WHEEL, 0666, "mynull", unit); ``` -Permissions: `rw-rw-rw-` (everyone) +权限:`rw-rw-rw-`(所有人) -**Security principle**: Start restrictive (0600) and only open up when necessary and safe. +**安全原则**:从严格限制开始(0600),只在必要且安全时才开放权限。 -**Summary** +**小结** -Character device entry points route user-space I/O to your driver: +字符设备入口点将用户空间 I/O 路由到你的驱动程序: -- **cdevsw**: Routing table mapping system calls to your functions -- **open/close**: Initialize and clean up per-session state -- **read/write**: Transfer data using uiomove() and struct uio -- **ioctl**: Configuration and control commands -- **poll/kqfilter**: Event-driven readiness notifications (advanced) -- **mmap**: Direct memory mapping (advanced, security-sensitive) -- **si_drv1**: Back-pointer to retrieve your softc -- **Permissions**: Set appropriate access controls with make_dev() +- **cdevsw**:将系统调用映射到你的函数的路由表 +- **open/close**:初始化和清理每次会话的状态 +- **read/write**:使用 uiomove() 和 struct uio 传输数据 +- **ioctl**:配置和控制命令 +- **poll/kqfilter**:事件驱动的就绪通知(高级) +- **mmap**:直接内存映射(高级,安全敏感) +- **si_drv1**:用于检索 softc 的反向指针 +- **权限**:使用 make_dev() 设置适当的访问控制 -**Next**, we'll look at **alternative surfaces** for network and storage drivers, which present very different interfaces. +**接下来**,我们将了解网络和存储驱动程序的**替代表面**,它们呈现出截然不同的接口。 -> **If you need a pause, this is a good place.** You have just crossed the halfway point of the chapter. Everything up to here, the big picture, the driver families, the softc and kobj method tables, the Newbus lifecycle, and the full character-device I/O surface, is enough foundation to revisit later as a single unit. The sections that follow shift focus: alternative surfaces for network and storage, a safe preview of resources and registers, device-node creation and destruction, module packaging, logging, and a guided tour of real tiny drivers. If your attention is still fresh, continue straight on. If it is flagging, close the book, write one or two sentences in your lab logbook about what clicked, and come back to this marker tomorrow. Neither choice is wrong. +> **如果你需要休息,这是一个好地方。** 你刚刚跨越了本章的中点。到目前为止的所有内容——大局图、驱动程序家族、softc 和 kobj 方法表、Newbus 生命周期,以及完整的字符设备 I/O 表面——足以作为一个整体单元日后回顾。接下来的部分将转移焦点:网络和存储的替代表面、资源和寄存器的安全预览、设备节点的创建和销毁、模块打包、日志记录,以及真实微型驱动程序的导览。如果你的注意力仍然充沛,继续往下读。如果已经疲倦,合上书,在实验日志中写一两句关于你收获的话,明天再回到这个标记处。两种选择都没有错。 ## 替代表面:网络和存储(快速导览) @@ -3067,35 +3067,35 @@ if (error != 0) { **何时创建设备节点**:通常在你的**连接**函数中,在硬件初始化成功之后。 -### Minors and Naming Conventions +### 次设备号和命名约定 -**Minor numbers** identify which instance of your driver a device node represents. The kernel assigns them automatically based on the `unit` parameter you pass to `make_dev()`. +**次设备号**标识设备节点代表的驱动程序实例。内核根据你传递给 `make_dev()` 的 `unit` 参数自动分配它们。 -**Naming conventions**: +**命名约定**: -- **Single instance**: `mydriver` (no number) -- **Multiple instances**: `mydriver0`, `mydriver1`, etc. -- **Sub-devices**: `mydriver0.ctl`, `mydriver0a`, `mydriver0b` -- **Subdirectories**: Use `/` in name: `"led/%s"` creates `/dev/led/foo` +- **单一实例**:`mydriver`(无编号) +- **多个实例**:`mydriver0`、`mydriver1` 等 +- **子设备**:`mydriver0.ctl`、`mydriver0a`、`mydriver0b` +- **子目录**:在名称中使用 `/`:`"led/%s"` 创建 `/dev/led/foo` -**Examples from FreeBSD**: +**FreeBSD 中的示例**: -- `/dev/null`, `/dev/zero` - Single, unnumbered -- `/dev/cuau0`, `/dev/cuau1` - Serial ports, numbered -- `/dev/ada0`, `/dev/ada1` - Disks, numbered -- `/dev/pts/0` - Pseudo-terminal in subdirectory +- `/dev/null`、`/dev/zero` - 单一,无编号 +- `/dev/cuau0`、`/dev/cuau1` - 串口,带编号 +- `/dev/ada0`、`/dev/ada1` - 磁盘,带编号 +- `/dev/pts/0` - 子目录中的伪终端 -**Best practices**: +**最佳实践**: -- Use device number from `device_get_unit()` for consistency -- Follow established naming patterns (users expect them) -- Use descriptive names (not just `/dev/dev0`) +- 使用 `device_get_unit()` 获取设备号以保持一致性 +- 遵循已有的命名模式(用户期望这些模式) +- 使用描述性名称(不要只用 `/dev/dev0`) -### destroy_dev: Cleaning Up +### destroy_dev:清理 -When your driver detaches, you must remove device nodes to prevent stale entries in `/dev`. +当你的驱动程序分离时,必须删除设备节点以防止 `/dev` 中出现过期条目。 -**Simple cleanup**: +**简单清理**: ```c if (sc->cdev != NULL) { @@ -3104,11 +3104,11 @@ if (sc->cdev != NULL) { } ``` -**What `destroy_dev()` actually does**: It removes the node from `/dev`, blocks new callers from entering any of your `cdevsw` methods, and then **waits for threads currently executing inside your `d_open`, `d_read`, `d_write`, `d_ioctl`, and friends to leave**. Open file descriptors may still exist after it returns, but the kernel guarantees none of your methods are running or will ever run again for that `cdev`. Because it can sleep, `destroy_dev()` must be called from a sleepable context and **never from inside a `d_close` handler or while holding a mutex**. +**`destroy_dev()` 实际做了什么**:它从 `/dev` 中删除节点,阻止新的调用者进入你的任何 `cdevsw` 方法,然后**等待当前正在你的 `d_open`、`d_read`、`d_write`、`d_ioctl` 等方法中执行的线程离开**。在它返回后,打开的文件描述符可能仍然存在,但内核保证你的任何方法都不会再运行或再次为该 `cdev` 运行。因为它可能睡眠,`destroy_dev()` 必须从可睡眠的上下文中调用,**永远不要在 `d_close` 处理程序内部或持有互斥锁时调用**。 -**When you cannot call `destroy_dev()` directly: destroy_dev_sched()** +**当你不能直接调用 `destroy_dev()` 时:destroy_dev_sched()** -If you need to tear the node down from a context where you cannot sleep, or from inside a cdev method itself, schedule the destruction instead: +如果你需要在一个不能睡眠的上下文中拆除节点,或者从 cdev 方法内部拆除,请改为调度销毁: ```c if (sc->cdev != NULL) { @@ -3117,11 +3117,11 @@ if (sc->cdev != NULL) { } ``` -`destroy_dev_sched()` returns immediately; the kernel calls `destroy_dev()` on your behalf from a safe worker thread. For ordinary `DEVICE_DETACH` paths the plain `destroy_dev()` is the right choice and what you will use most often. +`destroy_dev_sched()` 立即返回;内核会代表你从一个安全的工作线程中调用 `destroy_dev()`。对于普通的 `DEVICE_DETACH` 路径,直接使用 `destroy_dev()` 是正确的选择,也是你最常使用的。 -**When to destroy**: Always in your **detach** function, before releasing other resources that the cdev methods might still touch. +**何时销毁**:始终在你的 **detach** 函数中,在释放 cdev 方法可能仍在使用的其他资源之前。 -**Complete example pattern**: +**完整的示例模式**: ```c static int @@ -3148,13 +3148,13 @@ mydriver_detach(device_t dev) } ``` -### devctl/devmatch: Runtime Events +### devctl/devmatch:运行时事件 -FreeBSD provides **devctl** and **devmatch** for monitoring device events and matching drivers to hardware. +FreeBSD 提供 **devctl** 和 **devmatch** 用于监控设备事件和将驱动程序匹配到硬件。 -**devctl**: Event notification system +**devctl**:事件通知系统 -Programs can listen to `/dev/devctl` for device events: +程序可以监听 `/dev/devctl` 来获取设备事件: ```bash % sudo service devd stop @@ -3167,13 +3167,13 @@ Programs can listen to `/dev/devctl` for device events: % sudo service devd start ``` -**Events your driver generates**: +**你的驱动程序生成的事件**: -- Device node creation (automatically when you call make_dev) -- Device node destruction (automatically when you call destroy_dev) -- Attach/detach (via devctl_notify) +- 设备节点创建(调用 make_dev 时自动发生) +- 设备节点销毁(调用 destroy_dev 时自动发生) +- 连接/分离(通过 devctl_notify) -**Manual notification** (optional): +**手动通知**(可选): ```c #include @@ -3187,9 +3187,9 @@ snprintf(buf, sizeof(buf), "status=%d", sc->status); devctl_notify("MYDRIVER", "STATUS", device_get_nameunit(dev), buf); ``` -**devmatch**: Automatic driver loading +**devmatch**:自动驱动加载 -The `devmatch` utility scans unattached devices and suggests (or loads) appropriate drivers: +`devmatch` 工具扫描未连接的设备并建议(或加载)适当的驱动程序: ```bash % devmatch @@ -3197,82 +3197,82 @@ kldload -n if_em kldload -n snd_hda ``` -Your driver participates automatically when you use `DRIVER_MODULE` correctly. The kernel's device database (generated at build time) tracks which drivers match which hardware IDs. +当你正确使用 `DRIVER_MODULE` 时,你的驱动程序会自动参与。内核的设备数据库(在构建时生成)跟踪哪些驱动程序匹配哪些硬件 ID。 -**Summary** +**小结** -**Creating device nodes**: +**创建设备节点**: -- Use `make_dev()` or `make_dev_s()` in attach -- Set ownership and permissions appropriately -- Store softc back-pointer in `si_drv1` +- 在 attach 中使用 `make_dev()` 或 `make_dev_s()` +- 适当设置所有权和权限 +- 在 `si_drv1` 中存储 softc 反向指针 -**Destroying device nodes**: +**销毁设备节点**: -- Use `destroy_dev_sched()` in detach for safety -- Always destroy before releasing other resources +- 在 detach 中使用 `destroy_dev_sched()` 以确保安全 +- 始终在释放其他资源之前销毁 -**Device events**: +**设备事件**: -- devctl monitors create/destroy events -- devmatch auto-loads drivers for unattached devices +- devctl 监控创建/销毁事件 +- devmatch 自动为未连接的设备加载驱动程序 -**Next**, we'll explore module packaging and the load/unload lifecycle. +**接下来**,我们将探讨模块封装和加载/卸载生命周期。 ## 模块封装和生命周期(加载、初始化、卸载) -Your driver doesn't just exist in source form, it's compiled into a **kernel module** (`.ko` file) that can be dynamically loaded and unloaded. This section explains what a module is, how the lifecycle works, and how to handle load/unload events gracefully. +你的驱动程序不仅仅以源代码形式存在,它被编译成一个**内核模块**(`.ko` 文件),可以动态加载和卸载。本节解释什么是模块、生命周期如何工作,以及如何优雅地处理加载/卸载事件。 -### What a Kernel Module (.ko) Is +### 什么是内核模块(.ko) -A **kernel module** is compiled, relocatable code that the kernel can load at runtime without rebooting. Think of it as a plugin for the kernel. +**内核模块**是已编译的可重定位代码,内核可以在运行时无需重启即可加载。可以把它看作内核的插件。 -**File extension**: `.ko` (kernel object) +**文件扩展名**:`.ko`(内核对象) -**Example**: `mydriver.ko` +**示例**:`mydriver.ko` -**What's inside**: +**内部包含**: -- Your driver code (probe, attach, detach, entry points) -- Module metadata (name, version, dependencies) -- Symbol table (for linking with kernel symbols) -- Relocation information +- 你的驱动代码(probe、attach、detach、入口点) +- 模块元数据(名称、版本、依赖关系) +- 符号表(用于与内核符号链接) +- 重定位信息 -**How it's built**: +**如何构建**: ```bash % cd mydriver % make ``` -FreeBSD's build system (`/usr/src/share/mk/bsd.kmod.mk`) compiles your source and links it into a `.ko` file. When you run `make`, the installed copy at `/usr/share/mk/bsd.kmod.mk` is the one actually consulted; the two files are kept in sync by the FreeBSD build. +FreeBSD 的构建系统(`/usr/src/share/mk/bsd.kmod.mk`)编译你的源代码并将其链接为 `.ko` 文件。当你运行 `make` 时,实际查阅的是安装副本 `/usr/share/mk/bsd.kmod.mk`;这两个文件由 FreeBSD 构建系统保持同步。 -**Why modules matter**: +**为什么模块很重要**: -- **No reboot needed**: Load/unload drivers without restarting -- **Smaller kernel**: Only load drivers for hardware you have -- **Development speed**: Test changes quickly -- **Modularity**: Each driver is independent +- **无需重启**:不用重启即可加载/卸载驱动程序 +- **更小的内核**:只加载你拥有的硬件的驱动程序 +- **开发速度**:快速测试修改 +- **模块化**:每个驱动程序都是独立的 -**Built-in vs. module**: Drivers can be compiled directly into the kernel (monolithic) or as modules. For development and learning, **always use modules**. +**内置 vs. 模块**:驱动程序可以直接编译到内核中(单片式)或作为模块。对于开发和学习,**始终使用模块**。 -### The Module Event Handler +### 模块事件处理程序 -When a module is loaded or unloaded, the kernel calls your **module event handler** to give you a chance to initialize or clean up. +当模块被加载或卸载时,内核调用你的**模块事件处理程序**,让你有机会进行初始化或清理。 -**The module event handler signature**: +**模块事件处理程序签名**: ```c typedef int (*modeventhand_t)(module_t mod, int /*modeventtype_t*/ type, void *data); ``` -**Event types**: +**事件类型**: -- `MOD_LOAD` - Module is being loaded -- `MOD_UNLOAD` - Module is being unloaded -- `MOD_QUIESCE` - Kernel is checking if unload is safe -- `MOD_SHUTDOWN` - System is shutting down +- `MOD_LOAD` - 模块正在被加载 +- `MOD_UNLOAD` - 模块正在被卸载 +- `MOD_QUIESCE` - 内核正在检查卸载是否安全 +- `MOD_SHUTDOWN` - 系统正在关机 -**Typical module event handler**: +**典型的模块事件处理程序**: ```c static int @@ -3313,7 +3313,7 @@ mydriver_modevent(module_t mod, int type, void *data) } ``` -**Registering the handler** (for pseudo-devices without Newbus): +**注册处理程序**(对于不使用 Newbus 的伪设备): ```c static moduledata_t mydriver_mod = { @@ -3326,13 +3326,13 @@ DECLARE_MODULE(mydriver, mydriver_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(mydriver, 1); ``` -`DECLARE_MODULE` is the lowest-level of these macros and works for any kernel module. For character-device pseudo-drivers, the kernel also provides `DEV_MODULE`, a thin wrapper that expands to `DECLARE_MODULE` with the right subsystem and order preset. You will see `DEV_MODULE(null, null_modevent, NULL);` in `/usr/src/sys/dev/null/null.c`, for example. +`DECLARE_MODULE` 是这些宏中最低层的,适用于任何内核模块。对于字符设备伪驱动程序,内核还提供了 `DEV_MODULE`,这是一个薄封装,扩展为带有正确子系统和顺序预设的 `DECLARE_MODULE`。例如,你会在 `/usr/src/sys/dev/null/null.c` 中看到 `DEV_MODULE(null, null_modevent, NULL);`。 -**For Newbus drivers**: The `DRIVER_MODULE` macro handles most of this automatically. You typically don't need a separate module event handler unless you have global initialization beyond per-device state. +**对于 Newbus 驱动程序**:`DRIVER_MODULE` 宏会自动处理大部分工作。除非你有超出每设备状态的全局初始化,否则通常不需要单独的模块事件处理程序。 -**Example: Pseudo-device with module event handler** +**示例:带有模块事件处理程序的伪设备** -From `/usr/src/sys/dev/null/null.c` (simplified): +来自 `/usr/src/sys/dev/null/null.c`(简化版): ```c static int null_modevent(module_t mod __unused, int type, void *data __unused) @@ -3372,41 +3372,41 @@ DEV_MODULE(null, null_modevent, NULL); MODULE_VERSION(null, 1); ``` -This creates `/dev/full`, `/dev/null`, and `/dev/zero` when loaded, and destroys all three when unloaded. +这在加载时创建 `/dev/full`、`/dev/null` 和 `/dev/zero`,在卸载时销毁所有三个设备。 -### Declaring Dependencies & Versions +### 声明依赖和版本 -If your driver depends on other kernel modules, declare those dependencies explicitly so the kernel loads them in the correct order. +如果你的驱动程序依赖于其他内核模块,请显式声明这些依赖关系,以便内核按正确的顺序加载它们。 -**MODULE_DEPEND macro**: +**MODULE_DEPEND 宏**: ```c MODULE_DEPEND(mydriver, usb, 1, 1, 1); MODULE_DEPEND(mydriver, netgraph, 5, 7, 9); ``` -**Parameters**: +**参数**: -- `mydriver` - Your module name -- `usb` - Module you depend on -- `1` - Minimum acceptable version -- `1` - Preferred version -- `1` - Maximum acceptable version +- `mydriver` - 你的模块名称 +- `usb` - 你依赖的模块 +- `1` - 最低可接受版本 +- `1` - 首选版本 +- `1` - 最高可接受版本 -**Why this matters** +**为什么这很重要** -If you try to load `mydriver` without `usb` being loaded, the kernel will either: +如果你尝试在 `usb` 未加载的情况下加载 `mydriver`,内核将: -- Auto-load `usb` first (if available) -- Refuse to load `mydriver` with an error +- 首先自动加载 `usb`(如果可用) +- 或者拒绝加载 `mydriver` 并报错 -**MODULE_VERSION macro**: +**MODULE_VERSION 宏**: ```c MODULE_VERSION(mydriver, 1); ``` -This declares your module's version. Increment it when you make breaking changes to interfaces that other modules might depend on. +这声明了你的模块版本。当你对其他模块可能依赖的接口进行破坏性更改时,请递增它。 -**Dependency examples**: +**依赖示例**: ```c /* USB device driver */ @@ -3417,42 +3417,42 @@ MODULE_DEPEND(umass, cam, 1, 1, 1); MODULE_DEPEND(ng_ether, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION); ``` -**When to declare dependencies**: +**何时声明依赖**: -- You call functions from another module -- You use data structures defined in another module -- Your driver won't work without another subsystem +- 你调用另一个模块中的函数 +- 你使用另一个模块中定义的数据结构 +- 你的驱动程序在没有另一个子系统的情况下无法工作 -**Common dependencies**: +**常见依赖**: -- `usb` - USB subsystem -- `pci` - PCI bus support -- `cam` - Storage subsystem (CAM) -- `netgraph` - Network graph framework -- `sound` - Sound subsystem +- `usb` - USB 子系统 +- `pci` - PCI 总线支持 +- `cam` - 存储子系统(CAM) +- `netgraph` - 网络图框架 +- `sound` - 声音子系统 -### kldload/kldunload Flow and Logs +### kldload/kldunload 流程和日志 -Let's trace what happens when you load and unload a module. +让我们跟踪加载和卸载模块时发生的事情。 -**Loading a module**: +**加载模块**: ```bash % sudo kldload mydriver ``` -**Kernel flow**: +**内核流程**: -1. Reads `mydriver.ko` from filesystem -2. Verifies ELF format and signature -3. Resolves symbol dependencies -4. Links module into kernel -5. Calls module event handler with `MOD_LOAD` -6. For Newbus drivers: immediately probes for matching devices -7. If devices match: calls attach for each -8. Module is now active +1. 从文件系统读取 `mydriver.ko` +2. 验证 ELF 格式和签名 +3. 解析符号依赖 +4. 将模块链接到内核 +5. 使用 `MOD_LOAD` 调用模块事件处理程序 +6. 对于 Newbus 驱动程序:立即探测匹配的设备 +7. 如果设备匹配:为每个设备调用 attach +8. 模块现在处于活动状态 -**Check if loaded**: +**检查是否已加载**: ```bash % kldstat @@ -3461,7 +3461,7 @@ Id Refs Address Size Name 2 1 0xffffffff81e6f000 5000 mydriver.ko ``` -**View kernel messages**: +**查看内核消息**: ```bash % dmesg | tail -5 @@ -3470,175 +3470,175 @@ mydriver0: Hardware version 1.2 mydriver0: Attached successfully ``` -**Unloading a module**: +**卸载模块**: ```bash % sudo kldunload mydriver ``` -**Kernel flow**: +**内核流程**: -1. Calls module event handler with `MOD_QUIESCE` (optional check) -2. If EBUSY returned: refuses to unload -3. For Newbus drivers: calls detach for all attached devices -4. Calls module event handler with `MOD_UNLOAD` -5. Unlinks module from kernel -6. Frees module memory +1. 使用 `MOD_QUIESCE` 调用模块事件处理程序(可选检查) +2. 如果返回 EBUSY:拒绝卸载 +3. 对于 Newbus 驱动程序:调用所有已连接设备的分离函数 +4. 使用 `MOD_UNLOAD` 调用模块事件处理程序 +5. 从内核中解除模块的链接 +6. 释放模块内存 -**Common unload failures**: +**常见卸载失败原因**: ```bash % sudo kldunload mydriver kldunload: can't unload file: Device busy ``` -**Why**: +**原因**: -- Device nodes still open -- Module is depended on by other modules -- Driver returned EBUSY from detach +- 设备节点仍然打开 +- 模块被其他模块依赖 +- 驱动程序在 detach 中返回了 EBUSY -**Force unload** (dangerous, only for testing): +**强制卸载**(危险,仅用于测试): ```bash % sudo kldunload -f mydriver ``` -This skips safety checks. Use only in a VM when testing! +这会跳过安全检查。仅在虚拟机中测试时使用! -### Troubleshooting Loads +### 加载故障排除 -**Problem**: Module won't load +**问题**:模块无法加载 -**Check 1: Missing symbols** +**检查 1:缺少符号** ```bash % sudo kldload ./mydriver.ko link_elf: symbol usb_ifconfig undefined ``` -**Solution**: Add `MODULE_DEPEND(mydriver, usb, 1, 1, 1)` and ensure USB module is loaded. +**解决方案**:添加 `MODULE_DEPEND(mydriver, usb, 1, 1, 1)` 并确保 USB 模块已加载。 -**Check 2: Module not found** +**检查 2:找不到模块** ```bash % sudo kldload mydriver kldload: can't load mydriver: No such file or directory ``` -**Solution**: Either provide full path (`./mydriver.ko`) or copy to `/boot/modules/`. +**解决方案**:提供完整路径(`./mydriver.ko`)或复制到 `/boot/modules/`。 -**Check 3: Permission denied** +**检查 3:权限被拒绝** ```bash % kldload mydriver.ko kldload: Operation not permitted ``` -**Solution**: Use `sudo` or become root. +**解决方案**:使用 `sudo` 或切换为 root。 -**Check 4: Version mismatch** +**检查 4:版本不匹配** ```bash % sudo kldload mydriver.ko kldload: can't load mydriver: Exec format error ``` -**Solution**: Module was compiled for different FreeBSD version. Rebuild against your running kernel. +**解决方案**:模块是为不同版本的 FreeBSD 编译的。请针对你正在运行的内核重新编译。 -**Check 5: Duplicate symbols** +**检查 5:重复符号** ```bash % sudo kldload mydriver.ko link_elf: symbol mydriver_probe defined in both mydriver.ko and olddriver.ko ``` -**Solution**: Name collision. Unload conflicting module or rename your functions. +**解决方案**:名称冲突。卸载冲突的模块或重命名你的函数。 -**Debugging tips**: +**调试技巧**: -**1. Verbose loading**: +**1. 详细加载**: ```bash % sudo kldload -v mydriver.ko ``` -**2. Check module metadata**: +**2. 检查模块元数据**: ```bash % kldstat -v | grep mydriver ``` -**3. View symbols**: +**3. 查看符号**: ```bash % nm mydriver.ko | grep mydriver_probe ``` -**4. Test in VM**: +**4. 在虚拟机中测试**: -Always test new drivers in a VM, never on your main system. Crashes are expected during development! +始终在虚拟机中测试新驱动程序,永远不要在你的主系统上。开发过程中崩溃是正常的! -**5. Watch kernel log in real-time**: +**5. 实时查看内核日志**: ```bash % tail -f /var/log/messages ``` -**Summary** +**小结** -**Kernel modules**: +**内核模块**: -- `.ko` files containing driver code -- Can be loaded/unloaded dynamically -- No reboot needed for testing +- 包含驱动代码的 `.ko` 文件 +- 可以动态加载/卸载 +- 测试无需重启 -**Module event handler**: +**模块事件处理程序**: -- Handles MOD_LOAD, MOD_UNLOAD events -- Initialize/cleanup global state -- Can refuse unload with EBUSY +- 处理 MOD_LOAD、MOD_UNLOAD 事件 +- 初始化/清理全局状态 +- 可以用 EBUSY 拒绝卸载 -**Dependencies**: +**依赖**: -- Declare with MODULE_DEPEND -- Version with MODULE_VERSION -- Kernel enforces load order +- 使用 MODULE_DEPEND 声明 +- 使用 MODULE_VERSION 标记版本 +- 内核强制执行加载顺序 -**Troubleshooting**: +**故障排除**: -- Missing symbols -> add dependencies -- Can't unload -> check for open devices or dependencies -- Always test in VM during development +- 缺少符号 -> 添加依赖 +- 无法卸载 -> 检查是否有打开的设备或依赖 +- 开发时始终在虚拟机中测试 -**Next**, we'll discuss logging, errors, and user-facing behavior. +**接下来**,我们将讨论日志记录、错误和面向用户的行为。 ## 日志、错误和面向用户的行为 -Your driver isn't just code, it's part of the user experience. Clear logging, consistent error reporting, and useful diagnostics separate professional drivers from amateur ones. This section covers how to be a good citizen of the FreeBSD kernel. +你的驱动程序不仅仅是代码,它是用户体验的一部分。清晰的日志记录、一致的错误报告和有用的诊断信息是专业驱动程序与业余驱动程序的区别。本节介绍如何成为 FreeBSD 内核的良好公民。 -### Logging Etiquette (device_printf, rate-limiting hints) +### 日志礼仪(device_printf、速率限制提示) -**The cardinal rule**: Log enough to be useful, but not so much that you spam the console or fill logs. +**首要规则**:记录足够多的有用信息,但不要多到刷屏控制台或填满日志。 -**Use device_printf() for device-related messages**: +**使用 device_printf() 记录与设备相关的消息**: ```c device_printf(dev, "Attached successfully\\n"); device_printf(dev, "Hardware error: status=0x%x\\n", status); ``` -**Output**: +**输出**: ```text mydriver0: Attached successfully mydriver0: Hardware error: status=0x42 ``` -**When to log**: +**何时记录日志**: -**Attach**: ONE line summarizing successful attachment +**Attach**:一行总结成功连接 ```c device_printf(dev, "Attached (hw ver %d.%d)\\n", major, minor); ``` -**Errors**: ALWAYS log failures with context +**错误**:始终记录失败并附加上下文 ```c if (error != 0) { @@ -3647,23 +3647,23 @@ if (error != 0) { } ``` -**Configuration changes**: Log significant state changes +**配置更改**:记录重要的状态变化 ```c device_printf(dev, "Link up: 1000 Mbps full-duplex\\n"); device_printf(dev, "Entering power-save mode\\n"); ``` -**When NOT to log**: +**何时不要记录日志**: -**Per-packet/per-I/O**: NEVER log on every packet or read/write +**每个包/每次 I/O**:永远不要在每个包或每次 read/write 时记录 ```c /* BAD: This will flood the log */ device_printf(dev, "Received packet, length=%d\\n", len); ``` -**Verbose debugging info**: Not in production code +**详细的调试信息**:不要在生产代码中出现 ```c /* BAD: Too verbose */ @@ -3672,9 +3672,9 @@ device_printf(dev, "Step 2\\n"); device_printf(dev, "Reading register 0x%x\\n", reg); ``` -**Rate-limiting for repetitive events**: +**重复事件的速率限制**: -If an error can occur repeatedly (hardware timeout, overflow), rate-limit: +如果一个错误可能反复发生(硬件超时、溢出),请使用速率限制: ```c static struct timeval last_overflow_msg; @@ -3685,11 +3685,11 @@ if (ppsratecheck(&last_overflow_msg, NULL, 1)) { } ``` -**Using printf vs. device_printf**: +**使用 printf 还是 device_printf**: -- **device_printf**: For messages about a specific device +- **device_printf**:用于关于特定设备的消息 -- **printf**: For messages about module or subsystem +- **printf**:用于关于模块或子系统的消息 ```c /* On module load */ @@ -3699,16 +3699,16 @@ printf("mydriver: version 1.2 loaded\\n"); device_printf(dev, "Attached successfully\\n"); ``` -**Log levels** (for future reference) +**日志级别**(供将来参考) -FreeBSD kernel doesn't have explicit log levels like syslog, but conventions exist: +FreeBSD 内核没有像 syslog 那样的显式日志级别,但存在约定: -- Critical errors: Always log -- Warnings: Log with "warning:" prefix -- Info: Log major state changes -- Debug: Compile-time conditional (MYDRV_DEBUG) +- 关键错误:始终记录 +- 警告:使用 "warning:" 前缀记录 +- 信息:记录重要的状态变化 +- 调试:编译时条件(MYDRV_DEBUG) -**Example from real driver** (`/usr/src/sys/dev/uart/uart_core.c`): +**来自真实驱动程序的示例**(`/usr/src/sys/dev/uart/uart_core.c`): ```c static void @@ -3738,25 +3738,25 @@ uart_pps_print_mode(struct uart_softc *sc) } ``` -### Return Codes and Conventions +### 返回码和约定 -FreeBSD uses standard **errno** codes for error reporting. Using them consistently makes your driver predictable and debuggable. +FreeBSD 使用标准的 **errno** 码进行错误报告。一致地使用它们使你的驱动程序行为可预测且易于调试。 -**Common errno codes** (from ``): +**常见 errno 码**(来自 ``): -| Code | Value | Meaning | When to Use | +| 代码 | 值 | 含义 | 何时使用 | |------|-------|---------|-------------| -| `0` | 0 | Success | Operation succeeded | -| `ENOMEM` | 12 | Out of memory | malloc/bus_alloc_resource failed | -| `ENODEV` | 19 | No such device | Hardware not present/responding | -| `EINVAL` | 22 | Invalid argument | Bad parameter from user | -| `EIO` | 5 | Input/output error | Hardware communication failed | -| `EBUSY` | 16 | Device busy | Can't detach, resource in use | -| `ETIMEDOUT` | 60 | Timeout | Hardware didn't respond | -| `ENOTTY` | 25 | Not a typewriter | Invalid ioctl command | -| `ENXIO` | 6 | No such device/address | Probe rejected device | +| `0` | 0 | 成功 | 操作成功 | +| `ENOMEM` | 12 | 内存不足 | malloc/bus_alloc_resource 失败 | +| `ENODEV` | 19 | 无此设备 | 硬件不存在/无响应 | +| `EINVAL` | 22 | 无效参数 | 来自用户的错误参数 | +| `EIO` | 5 | 输入/输出错误 | 硬件通信失败 | +| `EBUSY` | 16 | 设备忙 | 无法分离,资源正在使用 | +| `ETIMEDOUT` | 60 | 超时 | 硬件未响应 | +| `ENOTTY` | 25 | 非打字机 | 无效的 ioctl 命令 | +| `ENXIO` | 6 | 无此设备/地址 | 探测拒绝了设备 | -**In probe**: +**在 probe 中**: ```c if (vendor_id == MY_VENDOR && device_id == MY_DEVICE) @@ -3765,7 +3765,7 @@ else return (ENXIO); /* Not my device */ ``` -**In attach**: +**在 attach 中**: ```c sc->mem_res = bus_alloc_resource_any(...); @@ -3779,7 +3779,7 @@ if (error != 0) return (0); /* Success */ ``` -**In entry points** (read/write/ioctl): +**在入口点中**(read/write/ioctl): ```c /* Invalid parameter */ @@ -3798,7 +3798,7 @@ if (timeout) return (0); ``` -**In ioctl**: +**在 ioctl 中**: ```c switch (cmd) { @@ -3813,13 +3813,13 @@ default: } ``` -**Summary**: +**总结**: -- `0` = success (always) -- Positive errno = failure -- Negative values = special meanings in some contexts (like probe priorities) +- `0` = 成功(始终) +- 正 errno = 失败 +- 负值 = 在某些上下文中有特殊含义(如探测优先级) -**User-space sees these**: +**用户空间看到的**: ```c int fd = open("/dev/mydriver0", O_RDWR); @@ -3828,20 +3828,20 @@ if (fd < 0) { } ``` -### Lightweight Observability with sysctl +### 使用 sysctl 实现轻量级可观测性 -**sysctl** provides a way to expose driver state and statistics **without requiring a debugger or special tools**. It's invaluable for troubleshooting and monitoring. +**sysctl** 提供了一种**无需调试器或特殊工具**就能暴露驱动程序状态和统计数据的方式。它对于故障排除和监控非常有价值。 -**Why sysctl is useful**: +**为什么 sysctl 很有用**: -- Users can check driver state from shell -- Monitoring tools can scrape values -- No device open required -- Zero overhead when not accessed +- 用户可以从 shell 检查驱动程序状态 +- 监控工具可以抓取数值 +- 不需要打开设备 +- 未访问时零开销 -**Example: Exposing statistics** +**示例:暴露统计数据** -**In softc**: +**在 softc 中**: ```c struct mydriver_softc { @@ -3853,7 +3853,7 @@ struct mydriver_softc { }; ``` -**In attach, create sysctl nodes**: +**在 attach 中,创建 sysctl 节点**: ```c struct sysctl_ctx_list *ctx; @@ -3881,7 +3881,7 @@ SYSCTL_ADD_U32(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "Current link speed (Mbps)"); ``` -**User access**: +**用户访问**: ```bash % sysctl dev.mydriver.0 @@ -3891,7 +3891,7 @@ dev.mydriver.0.errors: 5 dev.mydriver.0.speed: 1000 ``` -**Read-write sysctl** (for configuration): +**读写 sysctl**(用于配置): ```c static int @@ -3921,64 +3921,64 @@ SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, mydriver_sysctl_debug, "I", "Debug level (0-9)"); ``` -**User can change it**: +**用户可以修改它**: ```bash % sysctl dev.mydriver.0.debug=3 dev.mydriver.0.debug: 0 -> 3 ``` -**Best practices**: +**最佳实践**: -- Expose counters and state (read-only) -- Use clear, descriptive names -- Add description strings -- Group related sysctls under subtrees -- Don't expose sensitive data (keys, passwords) -- Don't make sysctls for every variable (only useful ones) +- 暴露计数器和状态(只读) +- 使用清晰、描述性的名称 +- 添加描述字符串 +- 将相关的 sysctl 分组到子树下 +- 不要暴露敏感数据(密钥、密码) +- 不要为每个变量都创建 sysctl(只创建有用的) -**Cleanup**: Sysctl nodes are automatically cleaned up when device detaches (if you used `device_get_sysctl_ctx()`). +**清理**:当设备分离时,sysctl 节点会自动清理(如果你使用了 `device_get_sysctl_ctx()`)。 -**Summary** +**小结** -**Logging etiquette**: +**日志礼仪**: -- One line on attach, always log errors -- Never log per-packet/per-I/O -- Rate-limit repetitive messages -- Use device_printf for device messages +- attach 时记录一行,始终记录错误 +- 永远不要在每个包/每次 I/O 时记录 +- 对重复消息进行速率限制 +- 使用 device_printf 记录设备消息 -**Return codes**: +**返回码**: -- 0 = success -- Standard errno codes (ENOMEM, EINVAL, EIO, etc.) -- Be consistent and predictable +- 0 = 成功 +- 标准 errno 码(ENOMEM、EINVAL、EIO 等) +- 保持一致和可预测 -**sysctl observability**: +**sysctl 可观测性**: -- Expose statistics and state for monitoring -- Read-only for counters, read-write for config -- Zero overhead when not used -- Auto-cleanup on detach +- 暴露统计数据和状态用于监控 +- 计数器只读,配置可读写 +- 未使用时零开销 +- 分离时自动清理 -**Next**, we'll take a **read-only tour of tiny real drivers** to see these patterns in practice. +**接下来**,我们将进行**真实微型驱动程序的只读导览**,在实践中看到这些模式。 ## 真实微型驱动程序的只读导览(FreeBSD 14.3) -Now that you understand driver structure conceptually, let's tour **real FreeBSD drivers** to see these patterns in practice. We'll examine four small, clean examples, pointing out exactly where probe, attach, entry points, and other structures live. This is **read-only**, you'll implement your own in Chapter 7. For now, **recognize and understand**. +现在你已经从概念上理解了驱动程序的结构,让我们导览**真实的 FreeBSD 驱动程序**,在实践中看到这些模式。我们将检查四个小而清晰的示例,准确指出 probe、attach、入口点和其他结构的位置。这是**只读**的,你将在第 7 章实现自己的驱动程序。现在,**识别和理解**。 -### Tour 1 - The canonical character trio `/dev/null`, `/dev/zero`, and `/dev/full` +### 导览 1 - 经典的字符设备三件套 `/dev/null`、`/dev/zero` 和 `/dev/full` -Open the file: +打开文件: ```sh % cd /usr/src/sys/dev/null % less null.c ``` -We'll walk top-to-bottom: headers -> globals -> `cdevsw` -> `write/read/ioctl` paths -> module event that creates and destroys the devfs nodes. +我们将从上到下遍历:头文件 -> 全局变量 -> `cdevsw` -> `write/read/ioctl` 路径 -> 创建和销毁 devfs 节点的模块事件。 -#### 1) Includes + minimal globals (we'll be creating devfs nodes) +#### 1) 头文件 + 最少的全局变量(我们将要创建 devfs 节点) ```c 32: #include @@ -4009,11 +4009,11 @@ We'll walk top-to-bottom: headers -> globals -> `cdevsw` -> `write/read/io 57: ``` -##### Headers and Global Device Pointers +##### 头文件和全局设备指针 -The null driver begins with standard kernel headers and forward declarations that establish the foundation for three related but distinct character devices. +null 驱动程序以标准内核头文件和前向声明开始,为三个相关但不同的字符设备奠定了基础。 -##### Header Inclusions +##### 头文件包含 ```c #include @@ -4032,29 +4032,29 @@ The null driver begins with standard kernel headers and forward declarations tha #include ``` -These headers provide the kernel infrastructure needed for character device drivers: +这些头文件提供了字符设备驱动程序所需的内核基础设施: -**``** and **``**: Fundamental system definitions including compiler directives, basic types, and system-wide constants. Every kernel source file includes these first. +**``** 和 **``**:基本系统定义,包括编译器指令、基本类型和系统范围的常量。每个内核源文件都首先包含这些头文件。 -**``**: Core kernel functions like `printf()`, `panic()`, and `bzero()`. This is the kernel's equivalent of `` in userspace. +**``**:核心内核函数,如 `printf()`、`panic()` 和 `bzero()`。这是内核中等同于用户空间 `` 的头文件。 -**``**: Character and block device configuration structures, particularly `cdevsw` (character device switch table) and related types. This header defines the `d_open_t`, `d_read_t`, `d_write_t` function pointer types used throughout the driver. +**``**:字符和块设备配置结构,特别是 `cdevsw`(字符设备开关表)和相关类型。此头文件定义了驱动程序中使用的 `d_open_t`、`d_read_t`、`d_write_t` 函数指针类型。 -**``**: User I/O operations. The `struct uio` type describes data transfers between kernel and userspace, tracking buffer location, size, and direction. The `uiomove()` function declared here performs the actual data copying. +**``**:用户 I/O 操作。`struct uio` 类型描述内核与用户空间之间的数据传输,跟踪缓冲区位置、大小和方向。此处声明的 `uiomove()` 函数执行实际的数据拷贝。 -**``**: Kernel startup and module infrastructure, including module event types (`MOD_LOAD`, `MOD_UNLOAD`) and the `SYSINIT` framework for initialization ordering. +**``**:内核启动和模块基础设施,包括模块事件类型(`MOD_LOAD`、`MOD_UNLOAD`)和用于初始化排序的 `SYSINIT` 框架。 -**``**: Kernel memory allocation. Though this driver doesn't dynamically allocate memory, the header is included for completeness. +**``**:内核内存分配。虽然此驱动程序不动态分配内存,但为完整性包含了此头文件。 -**``**: Module loading and unloading infrastructure. Provides `DEV_MODULE` and related macros for registering loadable kernel modules. +**``**:模块加载和卸载基础设施。提供 `DEV_MODULE` 和相关宏用于注册可加载的内核模块。 -**``** and **``**: Disk and bus subsystem interfaces. The null driver includes these for kernel dump (`DIOCSKERNELDUMP`) ioctl support. +**``** 和 **``**:磁盘和总线子系统接口。null 驱动程序包含这些用于内核转储(`DIOCSKERNELDUMP`)ioctl 支持。 -**``**: File I/O control commands. Defines `FIONBIO` (set non-blocking I/O) and `FIOASYNC` (set asynchronous I/O) ioctls that the driver must handle. +**``**:文件 I/O 控制命令。定义了驱动程序必须处理的 `FIONBIO`(设置非阻塞 I/O)和 `FIOASYNC`(设置异步 I/O)ioctl。 -**``** and **``**: Architecture-specific definitions. The `vmparam.h` header provides `ZERO_REGION_SIZE` and `zero_region`, a kernel virtual memory region pre-filled with zeros that `/dev/zero` uses for efficient reads. +**``** 和 **``**:架构特定的定义。`vmparam.h` 头文件提供 `ZERO_REGION_SIZE` 和 `zero_region`,这是一个预填充零的内核虚拟内存区域,`/dev/zero` 使用它进行高效读取。 -##### Device Structure Pointers +##### 设备结构指针 ```c /* For use with destroy_dev(9). */ @@ -4063,19 +4063,19 @@ static struct cdev *null_dev; static struct cdev *zero_dev; ``` -These three global pointers store references to the character device structures created during module load. Each pointer represents one device node in `/dev`: +这三个全局指针存储模块加载期间创建的字符设备结构的引用。每个指针代表 `/dev` 中的一个设备节点: -**`full_dev`**: Points to the `/dev/full` device structure. This device simulates a full disk, reads succeed but writes always fail with `ENOSPC` (no space left on device). +**`full_dev`**:指向 `/dev/full` 设备结构。该设备模拟满磁盘,读取成功但写入始终因 `ENOSPC`(设备上没有剩余空间)而失败。 -**`null_dev`**: Points to the `/dev/null` device structure, the classic "bit bucket" that discards all written data and returns immediate end-of-file on reads. +**`null_dev`**:指向 `/dev/null` 设备结构,经典的"比特桶",丢弃所有写入的数据并在读取时立即返回文件结束。 -**`zero_dev`**: Points to the `/dev/zero` device structure, which returns an infinite stream of zero bytes when read and discards writes like `/dev/null`. +**`zero_dev`**:指向 `/dev/zero` 设备结构,读取时返回无限的零字节流,写入时像 `/dev/null` 一样丢弃数据。 -The comment references `destroy_dev(9)`, indicating these pointers are needed for cleanup during module unload. The `make_dev_credf()` function called during `MOD_LOAD` returns `struct cdev *` values stored here, and `destroy_dev()` called during `MOD_UNLOAD` uses these pointers to remove the device nodes. +注释引用了 `destroy_dev(9)`,表明这些指针用于模块卸载期间的清理。在 `MOD_LOAD` 期间调用的 `make_dev_credf()` 函数返回存储在此处的 `struct cdev *` 值,而在 `MOD_UNLOAD` 期间调用的 `destroy_dev()` 使用这些指针删除设备节点。 -The `static` storage class limits these variables to this source file, no other kernel code can access them directly. This encapsulation prevents unintended external modification. +`static` 存储类将这些变量限制在此源文件中,其他内核代码无法直接访问它们。这种封装防止了意外的外部修改。 -##### Function Forward Declarations +##### 函数前向声明 ```c static d_write_t full_write; @@ -4085,35 +4085,35 @@ static d_ioctl_t zero_ioctl; static d_read_t zero_read; ``` -These forward declarations establish function signatures before the `cdevsw` structures that reference them. Each declaration uses a typedef from ``: +这些前向声明在引用它们的 `cdevsw` 结构之前建立了函数签名。每个声明使用 `` 中的 typedef: -**`d_write_t`**: Write operation signature: `int (*d_write)(struct cdev *dev, struct uio *uio, int ioflag)` +**`d_write_t`**:写入操作签名:`int (*d_write)(struct cdev *dev, struct uio *uio, int ioflag)` -**`d_ioctl_t`**: Ioctl operation signature: `int (*d_ioctl)(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)` +**`d_ioctl_t`**:Ioctl 操作签名:`int (*d_ioctl)(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)` -**`d_read_t`**: Read operation signature: `int (*d_read)(struct cdev *dev, struct uio *uio, int ioflag)` +**`d_read_t`**:读取操作签名:`int (*d_read)(struct cdev *dev, struct uio *uio, int ioflag)` -Notice the declarations needed: +注意所需的声明: -- Two write functions (`full_write`, `null_write`) because `/dev/full` and `/dev/null` behave differently on write -- Two ioctl functions (`null_ioctl`, `zero_ioctl`) because they handle slightly different ioctl commands -- One read function (`zero_read`) used by both `/dev/zero` and `/dev/full` (both return zeros) +- 两个写入函数(`full_write`、`null_write`),因为 `/dev/full` 和 `/dev/null` 在写入时行为不同 +- 两个 ioctl 函数(`null_ioctl`、`zero_ioctl`),因为它们处理略有不同的 ioctl 命令 +- 一个读取函数(`zero_read`),被 `/dev/zero` 和 `/dev/full` 共用(都返回零) -Notably absent: no `d_open_t` or `d_close_t` declarations. These devices don't need open or close handlers, they have no per-file-descriptor state to initialize or clean up. Opening `/dev/null` requires no setup; closing it requires no teardown. The kernel's default handlers suffice. +值得注意的是:没有 `d_open_t` 或 `d_close_t` 声明。这些设备不需要打开或关闭处理程序,它们没有每文件描述符的状态需要初始化或清理。打开 `/dev/null` 不需要设置;关闭它不需要拆卸。内核的默认处理程序就足够了。 -Also absent: `/dev/null` doesn't need a read function. The `cdevsw` for `/dev/null` uses `(d_read_t *)nullop`, a kernel-provided function that immediately returns success with zero bytes read, signaling end-of-file. +同样没有:`/dev/null` 不需要读取函数。`/dev/null` 的 `cdevsw` 使用 `(d_read_t *)nullop`,一个内核提供的函数,立即返回成功且读取零字节,表示文件结束。 -##### Design Simplicity +##### 设计简洁性 -This header section's simplicity reflects the devices' conceptual simplicity. Three device pointers and five function declarations are sufficient because these devices: +此头文件部分的简洁性反映了设备的概念简洁性。三个设备指针和五个函数声明就足够了,因为这些设备: -- Maintain no state (no per-device data structures needed) -- Perform trivial operations (reads return zeros, writes succeed or fail immediately) -- Don't interact with complex kernel subsystems +- 不维护状态(不需要每设备数据结构) +- 执行简单操作(读取返回零,写入立即成功或失败) +- 不与复杂的内核子系统交互 -This minimal complexity makes null.c an ideal starting point for understanding character device drivers, the concepts are clear without excessive infrastructure. +这种最小的复杂性使 null.c 成为理解字符设备驱动程序的理想起点——概念清晰,没有过多的基础设施。 -#### 2) `cdevsw`: wiring system calls to your driver functions +#### 2) `cdevsw`:将系统调用连接到你的驱动程序函数 ```c 58: static struct cdevsw full_cdevsw = { @@ -4140,11 +4140,11 @@ This minimal complexity makes null.c an ideal starting point for understanding c 81: }; ``` -##### Character Device Switch Tables +##### 字符设备开关表 -The `cdevsw` (character device switch) structures are the kernel's dispatch tables for character device operations. Each structure maps system call operation, `read(2)`, `write(2)` and `ioctl(2)` to driver-specific functions. The null driver defines three separate `cdevsw` structures, one for each device, allowing them to share some implementations while differing where their behavior diverges. +`cdevsw`(字符设备开关)结构是内核用于字符设备操作的分派表。每个结构将系统调用操作(`read(2)`、`write(2)` 和 `ioctl(2)`)映射到驱动程序特定的函数。null 驱动程序定义了三个独立的 `cdevsw` 结构,每个设备一个,允许它们共享一些实现,同时在行为不同的地方有所区别。 -##### The `/dev/full` Device Switch +##### `/dev/full` 设备开关 ```c static struct cdevsw full_cdevsw = { @@ -4156,21 +4156,21 @@ static struct cdevsw full_cdevsw = { }; ``` -The `/dev/full` device simulates a filesystem that's completely full. Its `cdevsw` establishes this behavior through function pointer assignments: +`/dev/full` 设备模拟一个完全满的文件系统。其 `cdevsw` 通过函数指针赋值建立这种行为: -**`d_version = D_VERSION`**: Every `cdevsw` must specify this version constant, ensuring binary compatibility between the driver and the kernel's device framework. The kernel checks this field during device creation and rejects mismatched versions. +**`d_version = D_VERSION`**:每个 `cdevsw` 必须指定此版本常量,确保驱动程序与内核设备框架之间的二进制兼容性。内核在设备创建期间检查此字段并拒绝不匹配的版本。 -**`d_read = zero_read`**: Read operations return an infinite stream of zero bytes, identical to `/dev/zero`. The same function serves both devices since their read behavior is identical. +**`d_read = zero_read`**:读取操作返回无限的零字节流,与 `/dev/zero` 相同。同一个函数服务于两个设备,因为它们的读取行为相同。 -**`d_write = full_write`**: Write operations always fail with `ENOSPC` (no space left on device), simulating a full disk. This is the distinguishing characteristic of `/dev/full`. +**`d_write = full_write`**:写入操作始终因 `ENOSPC`(设备上没有剩余空间)而失败,模拟满磁盘。这是 `/dev/full` 的显著特征。 -**`d_ioctl = zero_ioctl`**: The ioctl handler processes control operations like `FIONBIO` (non-blocking mode) and `FIOASYNC` (async I/O). +**`d_ioctl = zero_ioctl`**:ioctl 处理程序处理控制操作,如 `FIONBIO`(非阻塞模式)和 `FIOASYNC`(异步 I/O)。 -**`d_name = "full"`**: The device name string appears in kernel messages and identifies the device in system accounting. This string determines the device node name created in `/dev`. +**`d_name = "full"`**:设备名称字符串出现在内核消息中,并在系统记账中标识设备。此字符串决定了在 `/dev` 中创建的设备节点名称。 -Fields not specified (like `d_open`, `d_close`, `d_poll`) default to NULL, causing the kernel to use built-in default handlers. For simple devices with no state, these defaults are sufficient. +未指定的字段(如 `d_open`、`d_close`、`d_poll`)默认为 NULL,使内核使用内置的默认处理程序。对于没有状态的简单设备,这些默认值就足够了。 -##### The `/dev/null` Device Switch +##### `/dev/null` 设备开关 ```c static struct cdevsw null_cdevsw = { @@ -4182,15 +4182,15 @@ static struct cdevsw null_cdevsw = { }; ``` -The `/dev/null` device is the classic Unix bit bucket that discards writes and immediately signals end-of-file on reads: +`/dev/null` 设备是经典的 Unix 比特桶,丢弃写入并在读取时立即发出文件结束信号: -**`d_read = (d_read_t \*)nullop`**: The `nullop` function is a kernel-provided no-op that returns zero immediately, signaling end-of-file to the application. Any `read(2)` on `/dev/null` returns 0 bytes without blocking. The cast to `(d_read_t *)` satisfies the type checker, `nullop` has a generic signature that works for any device operation. +**`d_read = (d_read_t \*)nullop`**:`nullop` 函数是内核提供的空操作,立即返回零,向应用程序发出文件结束信号。对 `/dev/null` 的任何 `read(2)` 都返回 0 字节而不阻塞。转换为 `(d_read_t *)` 满足类型检查器——`nullop` 有一个通用签名,适用于任何设备操作。 -**`d_write = null_write`**: Write operations succeed immediately, updating the `uio` structure to indicate all data was consumed, but the data is discarded. Applications see successful writes, but nothing is stored or transmitted. +**`d_write = null_write`**:写入操作立即成功,更新 `uio` 结构以指示所有数据已被消耗,但数据被丢弃。应用程序看到成功的写入,但没有存储或传输任何内容。 -**`d_ioctl = null_ioctl`**: A separate ioctl handler from `/dev/full` and `/dev/zero` because `/dev/null` supports the `DIOCSKERNELDUMP` ioctl for kernel crash dump configuration. This ioctl removes all kernel dump devices, effectively disabling crash dumps. +**`d_ioctl = null_ioctl`**:与 `/dev/full` 和 `/dev/zero` 的 ioctl 处理程序不同,因为 `/dev/null` 支持 `DIOCSKERNELDUMP` ioctl 用于内核崩溃转储配置。此 ioctl 移除所有内核转储设备,有效地禁用崩溃转储。 -##### The `/dev/zero` Device Switch +##### `/dev/zero` 设备开关 ```c static struct cdevsw zero_cdevsw = { @@ -4203,55 +4203,55 @@ static struct cdevsw zero_cdevsw = { }; ``` -The `/dev/zero` device provides an infinite source of zero bytes and discards writes: +`/dev/zero` 设备提供无限的零字节源并丢弃写入: -**`d_read = zero_read`**: Returns zero bytes as fast as the application can read them. The implementation uses a pre-zeroed kernel memory region for efficiency rather than zeroing a buffer on every read. +**`d_read = zero_read`**:以应用程序能读取的最快速度返回零字节。实现使用预清零的内核内存区域以提高效率,而不是在每次读取时清零缓冲区。 -**`d_write = null_write`**: Shares the write implementation with `/dev/null`, writes are discarded, allowing applications to measure write performance or discard unwanted output. +**`d_write = null_write`**:与 `/dev/null` 共享写入实现——写入被丢弃,允许应用程序测量写入性能或丢弃不需要的输出。 -**`d_ioctl = zero_ioctl`**: Handles standard terminal ioctls like `FIONBIO` and `FIOASYNC`, rejecting others with `ENOIOCTL`. +**`d_ioctl = zero_ioctl`**:处理标准终端 ioctl,如 `FIONBIO` 和 `FIOASYNC`,用 `ENOIOCTL` 拒绝其他命令。 -**`d_flags = D_MMAP_ANON`**: This flag enables a critical optimization for memory mapping. When an application calls `mmap(2)` on `/dev/zero`, the kernel doesn't actually map the device; instead, it creates anonymous memory (memory not backed by any file or device). This behavior allows applications to use `/dev/zero` for portable anonymous memory allocation: +**`d_flags = D_MMAP_ANON`**:此标志启用内存映射的关键优化。当应用程序对 `/dev/zero` 调用 `mmap(2)` 时,内核实际上并不映射设备;相反,它创建匿名内存(不由任何文件或设备支持的内存)。此行为允许应用程序使用 `/dev/zero` 进行可移植的匿名内存分配: ```c void *mem = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, open("/dev/zero", O_RDWR), 0); ``` -The `D_MMAP_ANON` flag tells the kernel to substitute anonymous memory allocation for the mapping, providing zero-filled pages without involving the device driver. This pattern was historically important before `MAP_ANON` was standardized, and remains supported for compatibility. +`D_MMAP_ANON` 标志告诉内核用匿名内存分配替代映射,提供零填充页面而不涉及设备驱动程序。这种模式在 `MAP_ANON` 被标准化之前非常重要,现在仍然为了兼容性而支持。 -##### Function Sharing and Reuse +##### 函数共享和重用 -Notice the strategic sharing of implementations: +注意策略性的实现共享: -**`zero_read`**: Used by both `/dev/full` and `/dev/zero` because both devices return zeros when read. +**`zero_read`**:被 `/dev/full` 和 `/dev/zero` 共同使用,因为两个设备在读取时都返回零。 -**`null_write`**: Used by both `/dev/null` and `/dev/zero` because both discard written data. +**`null_write`**:被 `/dev/null` 和 `/dev/zero` 共同使用,因为两者都丢弃写入的数据。 -**`zero_ioctl`**: Used by both `/dev/full` and `/dev/zero` because they support the same basic ioctl operations. +**`zero_ioctl`**:被 `/dev/full` 和 `/dev/zero` 共同使用,因为它们支持相同的基本 ioctl 操作。 -**`null_ioctl`**: Used only by `/dev/null` because it alone supports kernel dump configuration. +**`null_ioctl`**:仅被 `/dev/null` 使用,因为只有它支持内核转储配置。 -**`full_write`**: Used only by `/dev/full` because it alone fails writes with `ENOSPC`. +**`full_write`**:仅被 `/dev/full` 使用,因为只有它用 `ENOSPC` 使写入失败。 -This sharing eliminates code duplication while preserving behavioral differences. The three devices require only five functions total (two write, two ioctl, one read) despite having three complete `cdevsw` structures. +这种共享消除了代码重复,同时保留了行为差异。三个设备只需要五个函数(两个写入、两个 ioctl、一个读取),尽管有三个完整的 `cdevsw` 结构。 -##### The `cdevsw` as Contract +##### `cdevsw` 作为契约 -Each `cdevsw` structure defines a contract between the kernel and the driver. When userspace calls `read(fd, buf, len)` on `/dev/zero`: +每个 `cdevsw` 结构定义了内核与驱动程序之间的契约。当用户空间对 `/dev/zero` 调用 `read(fd, buf, len)` 时: -1. The kernel identifies the file descriptor's associated device -2. Looks up the `cdevsw` for that device (`zero_cdevsw`) -3. Calls the function pointer in `d_read` (`zero_read`) -4. Returns the result to userspace +1. 内核识别文件描述符关联的设备 +2. 查找该设备的 `cdevsw`(`zero_cdevsw`) +3. 调用 `d_read` 中的函数指针(`zero_read`) +4. 将结果返回给用户空间 -This indirection through function pointers enables polymorphism in C: the same system call interface invokes different implementations based on which device is accessed. The kernel doesn't need to know the specifics of `/dev/zero`, it just calls the function registered in the switch table. +这种通过函数指针的间接调用在 C 中实现了多态:相同的系统调用接口根据访问的设备调用不同的实现。内核不需要知道 `/dev/zero` 的细节,它只调用在开关表中注册的函数。 -##### Static Storage and Encapsulation +##### 静态存储和封装 -All three `cdevsw` structures use `static` storage class, limiting their visibility to this source file. The structures are referenced by address during device creation (`make_dev_credf(&full_cdevsw, ...)`), but external code cannot modify them. This encapsulation ensures behavioral consistency, no other driver can accidentally override `/dev/null`'s write behavior. +所有三个 `cdevsw` 结构都使用 `static` 存储类,将其可见性限制在此源文件中。这些结构在设备创建期间通过地址引用(`make_dev_credf(&full_cdevsw, ...)`),但外部代码无法修改它们。这种封装确保了行为一致性——没有其他驱动程序能意外覆盖 `/dev/null` 的写入行为。 -#### 3) Write paths: "discard everything" vs "no space left" +#### 3) 写入路径:"丢弃一切" vs "没有剩余空间" ```c 83: /* ARGSUSED */ @@ -4271,11 +4271,11 @@ All three `cdevsw` structures use `static` storage class, limiting their visibil 98: } ``` -##### Write Operation Implementations +##### 写入操作实现 -The write functions demonstrate two contrasting approaches to handling output: unconditional failure and unconditional success with data discard. These simple implementations reveal fundamental patterns in device driver design. +写入函数展示了两种截然不同的输出处理方式:无条件失败和无条件成功但丢弃数据。这些简单的实现揭示了设备驱动程序设计的基本模式。 -##### The `/dev/full` Write: Simulating No Space +##### `/dev/full` 的写入:模拟无空间 ```c /* ARGSUSED */ @@ -4287,30 +4287,30 @@ full_write(struct cdev *dev __unused, struct uio *uio __unused, int flags __unus } ``` -The `/dev/full` write function is deliberately trivial, it immediately returns `ENOSPC` (error number 28, "No space left on device") without examining its arguments or performing any operations. +`/dev/full` 的写入函数故意设计得极其简单——它立即返回 `ENOSPC`(错误号 28,"设备上没有剩余空间"),不检查任何参数或执行任何操作。 -**Function signature**: All `d_write_t` functions receive three parameters: +**函数签名**:所有 `d_write_t` 函数接收三个参数: -- `struct cdev *dev` - the device being written to -- `struct uio *uio` - describes the user's write buffer (location, size, offset) -- `int flags` - I/O flags like `O_NONBLOCK` or `O_DIRECT` +- `struct cdev *dev` - 正在被写入的设备 +- `struct uio *uio` - 描述用户的写入缓冲区(位置、大小、偏移量) +- `int flags` - I/O 标志,如 `O_NONBLOCK` 或 `O_DIRECT` -**The `__unused` attribute**: Each parameter is marked `__unused`, a compiler directive indicating the parameter is intentionally ignored. This prevents "unused parameter" warnings during compilation. The directive documents that the function's behavior doesn't depend on which device instance is accessed, what data the user provided, or what flags were specified. +**`__unused` 属性**:每个参数都标记为 `__unused`,这是一个编译器指令,表示参数被故意忽略。这防止了编译期间的"未使用参数"警告。该指令记录了函数的行为不依赖于访问的设备实例、用户提供的数据或指定的标志。 -**The `/\* ARGSUSED \*/` comment**: This traditional lint directive predates modern compiler attributes, serving the same purpose for older static analysis tools. It signals "arguments unused by design, not by mistake." The comment and `__unused` attributes are redundant but maintain compatibility with multiple code analysis tools. +**`/\* ARGSUSED \*/` 注释**:这个传统的 lint 指令早于现代编译器属性,为较旧的静态分析工具服务于相同的目的。它表示"参数未使用是有意设计,而非疏忽。"该注释和 `__unused` 属性是冗余的,但保持与多种代码分析工具的兼容性。 -**Return value `ENOSPC`**: This errno value tells userspace that the write failed because no space remains. To the application, `/dev/full` appears as a storage device that's completely full. This behavior is useful for testing how programs handle write failures, many applications don't properly check write return values, leading to silent data loss when disks fill. Testing against `/dev/full` exposes these bugs. +**返回值 `ENOSPC`**:此 errno 值告诉用户空间写入失败是因为没有剩余空间。对于应用程序来说,`/dev/full` 表现为一个完全满的存储设备。此行为对于测试程序如何处理写入失败很有用——许多应用程序不正确检查写入返回值,导致磁盘满时出现静默数据丢失。针对 `/dev/full` 进行测试可以暴露这些 bug。 -**Why not process the `uio`?**: Normal device drivers would call `uiomove()` to consume data from the user's buffer and update `uio->uio_resid` to reflect bytes written. The `/dev/full` driver skips this entirely because it's simulating a failure condition where no bytes were written. Returning an error without touching `uio` signals "zero bytes written, operation failed." +**为什么不处理 `uio`?**:正常的设备驱动程序会调用 `uiomove()` 从用户缓冲区消耗数据并更新 `uio->uio_resid` 以反映写入的字节数。`/dev/full` 驱动程序完全跳过这些,因为它模拟的是没有写入任何字节的失败条件。返回错误而不触碰 `uio` 表示"写入零字节,操作失败。" -Applications see: +应用程序看到的是: ```c ssize_t n = write(fd, buf, 100); // n == -1, errno == ENOSPC ``` -##### The `/dev/null` and `/dev/zero` Write: Discarding Data +##### `/dev/null` 和 `/dev/zero` 的写入:丢弃数据 ```c /* ARGSUSED */ @@ -4323,64 +4323,64 @@ null_write(struct cdev *dev __unused, struct uio *uio, int flags __unused) } ``` -The `null_write` function (used by both `/dev/null` and `/dev/zero`) implements the classic bit bucket behavior: accept all data, discard everything, report success. +`null_write` 函数(被 `/dev/null` 和 `/dev/zero` 共同使用)实现了经典的比特桶行为:接受所有数据,丢弃一切,报告成功。 -**Marking data consumed**: The single operation `uio->uio_resid = 0` is the key to this function's behavior. The `uio_resid` field tracks how many bytes remain to be transferred. Setting it to zero tells the kernel "all requested bytes were successfully written," even though the driver never actually accessed the user's buffer. +**标记数据已消耗**:单一操作 `uio->uio_resid = 0` 是此函数行为的关键。`uio_resid` 字段跟踪剩余需要传输的字节数。将其设置为零告诉内核"所有请求的字节都已成功写入",即使驱动程序从未实际访问过用户缓冲区。 -**Why this works**: The kernel's write system call implementation checks `uio_resid` to determine how many bytes were written. If a driver sets `uio_resid` to zero and returns success (0), the kernel calculates: +**为什么这样做**:内核的写入系统调用实现检查 `uio_resid` 以确定写入了多少字节。如果驱动程序将 `uio_resid` 设置为零并返回成功(0),内核计算: ```c bytes_written = original_resid - current_resid = original_resid - 0 - = original_resid // all bytes written + = original_resid // 所有字节已写入 ``` -The application's `write(2)` call returns the full byte count requested, indicating complete success. +应用程序的 `write(2)` 调用返回请求的完整字节数,表示完全成功。 -**No actual data transfer**: Unlike normal drivers that call `uiomove()` to copy data from userspace, `null_write` never accesses the user's buffer. The data remains in userspace, untouched and unread. The driver simply lies about having consumed it. This is safe because the data is being discarded anyway, there's no point copying data into kernel memory just to throw it away. +**没有实际的数据传输**:与调用 `uiomove()` 从用户空间拷贝数据的普通驱动程序不同,`null_write` 从不访问用户的缓冲区。数据保留在用户空间,未触及、未读取。驱动程序只是谎称已消耗了数据。这是安全的,因为数据反正要被丢弃——没有理由将数据拷贝到内核内存中只是为了扔掉。 -**Return value zero**: Returning 0 signals success. Combined with `uio_resid = 0`, this creates the illusion of a perfectly functioning write operation that accepted all data. +**返回值零**:返回 0 表示成功。结合 `uio_resid = 0`,这创造了完美运作的写入操作的假象,接受了所有数据。 -**Why `uio` isn't marked `__unused`**: The function modifies `uio->uio_resid`, so the parameter is actively used. Only `dev` and `flags` are ignored and marked `__unused`. +**为什么 `uio` 没有标记 `__unused`**:函数修改了 `uio->uio_resid`,所以参数被主动使用。只有 `dev` 和 `flags` 被忽略并标记为 `__unused`。 -Applications see: +应用程序看到的是: ```c ssize_t n = write(fd, buf, 100); // n == 100, all bytes "written" ``` -##### Performance Implications +##### 性能影响 -The `null_write` optimization is significant for performance-sensitive applications. Consider a program redirecting gigabytes of unwanted output to `/dev/null`: +`null_write` 的优化对于性能敏感的应用程序非常重要。考虑一个将千兆字节不需要的输出重定向到 `/dev/null` 的程序: ```bash % ./generate_logs > /dev/null ``` -If the driver actually copied data from userspace (via `uiomove()`), this would waste CPU cycles and memory bandwidth copying data that's immediately discarded. By setting `uio_resid = 0` without touching the buffer, the driver eliminates this overhead entirely. The application fills its userspace buffer, calls `write(2)`, the kernel immediately returns success, and the CPU never accesses the buffer content. +如果驱动程序实际从用户空间拷贝数据(通过 `uiomove()`),这将浪费 CPU 周期和内存带宽来拷贝立即被丢弃的数据。通过在不触及缓冲区的情况下设置 `uio_resid = 0`,驱动程序完全消除了这种开销。应用程序填充其用户空间缓冲区,调用 `write(2)`,内核立即返回成功,CPU 从不访问缓冲区内容。 -##### Contrast in Error Handling Philosophy +##### 错误处理哲学的对比 -These two functions embody different design philosophies: +这两个函数体现了不同的设计哲学: -**`full_write`**: Simulate a failure condition for testing purposes. Real error, immediate rejection. +**`full_write`**:模拟失败条件用于测试。真实的错误,立即拒绝。 -**`null_write`**: Maximize performance by doing nothing. Fake success, instant return. +**`null_write`**:通过什么都不做来最大化性能。虚假的成功,即时返回。 -Both are correct implementations of their respective device semantics. The simplicity of these functions, five lines combined, demonstrates that device drivers don't need to be complex to be useful. Sometimes the best implementation is the one that does the least work necessary to satisfy the interface contract. +两者都是各自设备语义的正确实现。这些函数的简单性——总共五行代码——证明了设备驱动程序不需要复杂才有用。有时最好的实现是做最少必要的工作来满足接口契约。 -##### Interface Contract Satisfaction +##### 接口契约满足 -Both functions satisfy the `d_write_t` contract: +两个函数都满足 `d_write_t` 契约: -- Accept a device pointer, uio descriptor, and flags -- Return 0 for success or errno for failure -- Update `uio_resid` to reflect bytes consumed (or leave it unchanged if none were consumed) +- 接受设备指针、uio 描述符和标志 +- 返回 0 表示成功或 errno 表示失败 +- 更新 `uio_resid` 以反映消耗的字节数(如果未消耗则保持不变) -The `cdevsw` function pointers enforce this contract at compile time. Any function not matching the `d_write_t` signature would cause a compilation error when assigned to `d_write` in the `cdevsw` structure. This type safety ensures all write implementations follow the same calling convention, allowing the kernel to invoke them uniformly. +`cdevsw` 函数指针在编译时强制执行此契约。任何不匹配 `d_write_t` 签名的函数在分配给 `cdevsw` 结构中的 `d_write` 时都会导致编译错误。这种类型安全确保所有写入实现遵循相同的调用约定,允许内核统一调用它们。 -#### 4) IOCTLs: accept a tiny, sensible subset; reject the rest +#### 4) IOCTL:接受一个小的、合理的子集;拒绝其余的 ```c 100: /* ARGSUSED */ @@ -4431,11 +4431,11 @@ The `cdevsw` function pointers enforce this contract at compile time. Any functi 146: } ``` -##### Ioctl Operation Implementations +##### Ioctl 操作实现 -The ioctl (I/O control) functions handle device-specific control operations beyond standard read and write. While read and write transfer data, ioctl performs configuration, status queries, and special operations. The null driver implements two ioctl handlers that differ only in their support for kernel crash dump configuration. +ioctl(I/O 控制)函数处理标准读写之外的设备特定控制操作。读写传输数据,而 ioctl 执行配置、状态查询和特殊操作。null 驱动程序实现了两个 ioctl 处理程序,仅在内核崩溃转储配置的支持上有所不同。 -##### The `/dev/null` Ioctl Handler +##### `/dev/null` 的 Ioctl 处理程序 ```c /* ARGSUSED */ @@ -4466,19 +4466,19 @@ null_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data __unused, } ``` -**Function signature**: The `d_ioctl_t` type requires five parameters: +**函数签名**:`d_ioctl_t` 类型需要五个参数: -- `struct cdev *dev` - the device being controlled -- `u_long cmd` - the ioctl command number -- `caddr_t data` - pointer to command-specific data (in/out parameter) -- `int flags` - file descriptor flags from the original `open(2)` -- `struct thread *td` - the calling thread (for credential checks, signal delivery) +- `struct cdev *dev` - 被控制的设备 +- `u_long cmd` - ioctl 命令号 +- `caddr_t data` - 指向命令特定数据的指针(输入/输出参数) +- `int flags` - 来自原始 `open(2)` 的文件描述符标志 +- `struct thread *td` - 调用线程(用于凭证检查、信号传递) -Most parameters are marked `__unused` because this simple device doesn't need per-instance state (`dev`), doesn't examine most command data (`data` for some commands), and doesn't check flags or thread credentials. +大多数参数标记为 `__unused`,因为这个简单设备不需要每实例状态(`dev`),不检查大多数命令数据(某些命令的 `data`),也不检查标志或线程凭证。 -**Command dispatch via switch**: The function uses a `switch` statement to handle different ioctl commands, each identified by a unique constant. The pattern `switch (cmd)` followed by `case` labels is universal in ioctl handlers. +**通过 switch 进行命令分派**:函数使用 `switch` 语句处理不同的 ioctl 命令,每个命令由唯一常量标识。`switch (cmd)` 后跟 `case` 标签的模式在 ioctl 处理程序中是通用的。 -##### Kernel Dump Configuration: `DIOCSKERNELDUMP` +##### 内核转储配置:`DIOCSKERNELDUMP` ```c case DIOCSKERNELDUMP: @@ -4488,33 +4488,33 @@ case DIOCSKERNELDUMP: break; ``` -This case handles kernel crash dump configuration. When the system crashes, the kernel writes diagnostic information (memory contents, register state, stack traces) to a designated dump device, typically a disk partition or swap space. The `DIOCSKERNELDUMP` ioctl configures this dump device. +此分支处理内核崩溃转储配置。当系统崩溃时,内核将诊断信息(内存内容、寄存器状态、栈跟踪)写入指定的转储设备,通常是磁盘分区或交换空间。`DIOCSKERNELDUMP` ioctl 配置此转储设备。 -**Why `/dev/null` for crash dumps?**: The idiom `ioctl(fd, DIOCSKERNELDUMP, &args)` on `/dev/null` serves a specific purpose: disabling all kernel dumps. By directing dumps to the bit bucket, administrators can prevent crash dump collection entirely (useful for security-sensitive systems or when disk space is constrained). +**为什么用 `/dev/null` 做崩溃转储?**:在 `/dev/null` 上使用 `ioctl(fd, DIOCSKERNELDUMP, &args)` 有特定目的:禁用所有内核转储。通过将转储导向比特桶,管理员可以完全阻止崩溃转储收集(对于安全敏感的系统或磁盘空间受限时很有用)。 -**Preparing the argument structure**: `bzero(&kda, sizeof(kda))` zeros the `diocskerneldump_arg` structure, ensuring all fields start in a known state. This is defensive programming, uninitialized stack memory might contain random values that could confuse the dump subsystem. +**准备参数结构**:`bzero(&kda, sizeof(kda))` 将 `diocskerneldump_arg` 结构清零,确保所有字段从已知状态开始。这是防御性编程——未初始化的栈内存可能包含随机值,可能混淆转储子系统。 -**Removing all dump devices**: `kda.kda_index = KDA_REMOVE_ALL` sets the magic index value indicating "remove all configured dump devices, don't add a new one." The constant `KDA_REMOVE_ALL` signals special semantics distinct from specifying a particular device index. +**移除所有转储设备**:`kda.kda_index = KDA_REMOVE_ALL` 设置魔术索引值,表示"移除所有已配置的转储设备,不要添加新的。"常量 `KDA_REMOVE_ALL` 表示与指定特定设备索引不同的特殊语义。 -**Calling the dump subsystem**: `dumper_remove(NULL, &kda)` invokes the kernel's dump management function. The first parameter (NULL) indicates no specific device is being removed, the `kda_index` field provides the directive. The function returns 0 on success or an error code on failure. +**调用转储子系统**:`dumper_remove(NULL, &kda)` 调用内核的转储管理函数。第一个参数(NULL)表示没有特定设备被移除——`kda_index` 字段提供了指令。函数成功返回 0,失败返回错误码。 -##### Non-Blocking I/O: `FIONBIO` +##### 非阻塞 I/O:`FIONBIO` ```c case FIONBIO: break; ``` -The `FIONBIO` ioctl sets or clears non-blocking mode on the file descriptor. The `data` parameter points to an integer: non-zero enables non-blocking mode, zero disables it. +`FIONBIO` ioctl 在文件描述符上设置或清除非阻塞模式。`data` 参数指向一个整数:非零启用非阻塞模式,零禁用它。 -**Why do nothing?**: The handler simply breaks without performing any operation. This is correct because `/dev/null` operations never block: +**为什么什么都不做?**:处理程序只是 break 而不执行任何操作。这是正确的,因为 `/dev/null` 操作从不阻塞: -- Reads immediately return end-of-file (0 bytes) -- Writes immediately succeed (all bytes consumed) +- 读取立即返回文件结束(0 字节) +- 写入立即成功(所有字节被消耗) -There's no condition under which a `/dev/null` operation would block, so non-blocking mode is meaningless. The ioctl succeeds (returns 0) but has no effect, maintaining compatibility with applications that configure non-blocking mode without causing errors. +在任何条件下 `/dev/null` 操作都不会阻塞,所以非阻塞模式没有意义。ioctl 成功(返回 0)但没有效果,保持了与配置非阻塞模式的应用程序的兼容性而不引起错误。 -##### Asynchronous I/O: `FIOASYNC` +##### 异步 I/O:`FIOASYNC` ```c case FIOASYNC: @@ -4523,28 +4523,28 @@ case FIOASYNC: break; ``` -The `FIOASYNC` ioctl enables or disables asynchronous I/O notification. When enabled, the kernel sends `SIGIO` signals to the process when the device becomes readable or writable. +`FIOASYNC` ioctl 启用或禁用异步 I/O 通知。启用时,内核在设备变为可读或可写时向进程发送 `SIGIO` 信号。 -**Parameter interpretation**: The `data` parameter points to an integer. Zero means disable async I/O, non-zero means enable it. +**参数解释**:`data` 参数指向一个整数。零表示禁用异步 I/O,非零表示启用。 -**Rejecting async I/O**: The handler checks if the application is trying to enable async I/O (`*(int *)data != 0`). If so, it returns `EINVAL` (invalid argument), rejecting the request. +**拒绝异步 I/O**:处理程序检查应用程序是否试图启用异步 I/O(`*(int *)data != 0`)。如果是,返回 `EINVAL`(无效参数),拒绝请求。 -**Why reject async I/O?**: Asynchronous I/O only makes sense for devices that can block. Applications enable it to receive notification when a previously-blocked operation can proceed. Since `/dev/null` never blocks, async I/O is meaningless and potentially confusing. Rather than silently accepting a nonsensical configuration, the driver returns an error, alerting the application to the logical error. +**为什么拒绝异步 I/O?**:异步 I/O 只对可能阻塞的设备有意义。应用程序启用它以在先前阻塞的操作可以继续时接收通知。由于 `/dev/null` 从不阻塞,异步 I/O 没有意义且可能造成混淆。驱动程序不是静默接受一个无意义的配置,而是返回错误,提醒应用程序注意逻辑错误。 -**Disabling async I/O succeeds**: If `*(int *)data == 0`, the condition is false, `error` remains 0, and the function returns success. Disabling a feature that was never enabled is harmless. +**禁用异步 I/O 成功**:如果 `*(int *)data == 0`,条件为假,`error` 保持 0,函数返回成功。禁用一个从未启用的功能是无害的。 -##### Unknown Commands: Default Case +##### 未知命令:默认分支 ```c default: error = ENOIOCTL; ``` -Any ioctl command not explicitly handled falls through to the default case, which returns `ENOIOCTL`. This special error code means "this ioctl is not supported by this device." It's distinct from `EINVAL` (invalid argument to a supported ioctl) and `ENOTTY` (inappropriate ioctl for device type, used for terminal operations on non-terminals). +任何未显式处理的 ioctl 命令都落入默认分支,返回 `ENOIOCTL`。这个特殊错误码表示"此设备不支持此 ioctl。"它不同于 `EINVAL`(支持的 ioctl 的无效参数)和 `ENOTTY`(设备类型不适当的 ioctl,用于非终端上的终端操作)。 -The kernel's ioctl infrastructure may retry the operation through other layers when receiving `ENOIOCTL`, allowing generic handlers to process common commands. +内核的 ioctl 基础设施在收到 `ENOIOCTL` 时可能通过其他层重试操作,允许通用处理程序处理常见命令。 -##### The `/dev/zero` Ioctl Handler +##### `/dev/zero` 的 Ioctl 处理程序 ```c /* ARGSUSED */ @@ -4569,29 +4569,29 @@ zero_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data __unused, } ``` -The `zero_ioctl` function is nearly identical to `null_ioctl`, with one critical difference: it doesn't handle `DIOCSKERNELDUMP`. The `/dev/zero` device cannot serve as a kernel dump device (dumps must be stored, not discarded), so the ioctl isn't supported. +`zero_ioctl` 函数与 `null_ioctl` 几乎相同,有一个关键区别:它不处理 `DIOCSKERNELDUMP`。`/dev/zero` 设备不能用作内核转储设备(转储必须存储,不能丢弃),所以不支持此 ioctl。 -The `FIONBIO` and `FIOASYNC` handling is identical, these are standard file descriptor ioctls that all character devices should handle consistently, even if the operations are no-ops. +`FIONBIO` 和 `FIOASYNC` 的处理是相同的——这些是标准文件描述符 ioctl,所有字符设备应一致处理,即使操作是空操作。 -##### Ioctl Design Patterns +##### Ioctl 设计模式 -Several patterns emerge from these implementations: +从这些实现中可以总结出几种模式: -**Explicit handling of no-op operations**: Rather than returning errors for meaningless operations like `FIONBIO` on `/dev/null`, the handlers succeed silently. This maintains compatibility with applications that unconditionally configure file descriptors without checking device type. +**显式处理空操作**:与其为 `/dev/null` 上 `FIONBIO` 这样无意义的操作返回错误,处理程序静默成功。这保持了与无条件配置文件描述符而不检查设备类型的应用程序的兼容性。 -**Rejecting nonsensical configurations**: Async I/O makes no sense for these devices, so the handlers return errors when applications try to enable it. This is a design choice, the handlers could succeed silently, but explicit errors help developers identify logic bugs. +**拒绝无意义的配置**:异步 I/O 对这些设备没有意义,所以处理程序在应用程序尝试启用时返回错误。这是一种设计选择——处理程序可以静默成功,但显式错误有助于开发者识别逻辑 bug。 -**Standard error codes**: `EINVAL` for invalid arguments, `ENOIOCTL` for unsupported commands. These conventions allow userspace to distinguish different failure modes. +**标准错误码**:`EINVAL` 用于无效参数,`ENOIOCTL` 用于不支持的命令。这些约定允许用户空间区分不同的失败模式。 -**Minimal data validation**: The handlers cast `data` pointers and dereference them without extensive validation. This is safe because the kernel's ioctl infrastructure has already verified the pointer is accessible to userspace. Device drivers trust the kernel's argument validation. +**最少的数据验证**:处理程序转换 `data` 指针并解引用它们,无需大量验证。这是安全的,因为内核的 ioctl 基础设施已经验证了指针对用户空间可访问。设备驱动程序信任内核的参数验证。 -##### Why Two Ioctl Functions? +##### 为什么有两个 Ioctl 函数? -The `/dev/full` device uses `zero_ioctl` (not shown using it in the `cdevsw`, but by examining the structures we saw earlier). Only `/dev/null` needs the special dump device handling, so only `null_ioctl` includes the `DIOCSKERNELDUMP` case. This separation avoids polluting the simpler `zero_ioctl` with functionality that only one device needs. +`/dev/full` 设备使用 `zero_ioctl`(在 `cdevsw` 中未显示使用它,但通过我们之前看到的结构可以确认)。只有 `/dev/null` 需要特殊的转储设备处理,所以只有 `null_ioctl` 包含 `DIOCSKERNELDUMP` 分支。这种分离避免了用只有一个设备需要的功能污染更简单的 `zero_ioctl`。 -The code reuse strategy: write the minimal handler (`zero_ioctl`), then extend it for special cases (`null_ioctl`). This keeps each function focused and avoids conditional logic like "if this is `/dev/null`, handle dumps." +代码重用策略:编写最少的处理程序(`zero_ioctl`),然后为特殊情况扩展它(`null_ioctl`)。这保持每个函数的专注性,避免了像"如果这是 `/dev/null`,处理转储"这样的条件逻辑。 -#### 5) Read path: a simple loop driven by `uio->uio_resid` +#### 5) 读取路径:由 `uio->uio_resid` 驱动的简单循环 ```c 148: /* ARGSUSED */ @@ -4616,11 +4616,11 @@ The code reuse strategy: write the minimal handler (`zero_ioctl`), then extend i 167: } ``` -##### Read Operation: Infinite Zeros +##### 读取操作:无限的零 -The `zero_read` function provides an endless stream of zero bytes, serving both `/dev/zero` and `/dev/full`. This implementation demonstrates efficient data transfer using a pre-allocated kernel buffer and the `uiomove()` function for kernel-to-userspace copying. +`zero_read` 函数提供无尽的零字节流,服务于 `/dev/zero` 和 `/dev/full`。此实现展示了使用预分配的内核缓冲区和 `uiomove()` 函数进行高效的内核到用户空间数据拷贝。 -##### Function Structure and Safety Assertion +##### 函数结构和安全断言 ```c /* ARGSUSED */ @@ -4635,37 +4635,37 @@ zero_read(struct cdev *dev __unused, struct uio *uio, int flags __unused) ("Can't be in %s for write", __func__)); ``` -**Function signature**: The `d_read_t` type requires the same parameters as `d_write_t`: +**函数签名**:`d_read_t` 类型需要与 `d_write_t` 相同的参数: -- `struct cdev *dev` - the device being read (unused, marked `__unused`) -- `struct uio *uio` - describes the user's read buffer and tracks transfer progress -- `int flags` - I/O flags (unused for this simple device) +- `struct cdev *dev` - 被读取的设备(未使用,标记为 `__unused`) +- `struct uio *uio` - 描述用户的读取缓冲区并跟踪传输进度 +- `int flags` - I/O 标志(对于此简单设备未使用) -**Local variables**: The function needs minimal state: +**局部变量**:函数需要最少的状态: -- `zbuf` - pointer to the source of zero bytes -- `len` - number of bytes to transfer in each iteration -- `error` - tracks success or failure of transfer operations +- `zbuf` - 零字节源的指针 +- `len` - 每次迭代中要传输的字节数 +- `error` - 跟踪传输操作的成功或失败 -**Sanity check with `KASSERT`**: The assertion verifies that `uio->uio_rw` equals `UIO_READ`, confirming this is actually a read operation. The `uio` structure serves both read and write operations, with the `uio_rw` field indicating direction. +**使用 `KASSERT` 进行健全性检查**:断言验证 `uio->uio_rw` 等于 `UIO_READ`,确认这确实是一个读取操作。`uio` 结构同时服务于读和写操作,`uio_rw` 字段指示方向。 -This assertion catches programming errors during development. If somehow a write operation called this read function, the assertion would trigger a kernel panic with the message "Can't be in zero_read for write." The `__func__` preprocessor macro expands to the current function name, making the error message precise. +此断言在开发期间捕获编程错误。如果由于某种原因写入操作调用了此读取函数,断言将触发内核 panic,消息为"Can't be in zero_read for write"。`__func__` 预处理器宏展开为当前函数名,使错误消息精确。 -In production kernels compiled without debugging, `KASSERT` compiles to nothing, eliminating any runtime overhead. This pattern, defensive checks during development, zero cost in production, is common throughout FreeBSD's kernel. +在没有调试的生产内核中,`KASSERT` 编译为空,消除了任何运行时开销。这种模式——开发期间的防御性检查、生产中零成本——在 FreeBSD 内核中很常见。 -##### Accessing the Pre-Zeroed Buffer +##### 访问预清零缓冲区 ```c zbuf = __DECONST(void *, zero_region); ``` -The `zero_region` variable (declared in ``) points to a region of kernel virtual memory that's permanently filled with zeros. The kernel allocates this region during boot and never modifies it, providing an efficient source of zero bytes without repeatedly zeroing temporary buffers. +`zero_region` 变量(在 `` 中声明)指向一段永久填充零的内核虚拟内存区域。内核在启动时分配此区域并从不修改它,提供了高效的零字节源,无需反复清零临时缓冲区。 -**The `__DECONST` macro**: The `zero_region` is declared `const` to prevent accidental modification. However, `uiomove()` expects a non-const pointer because it's a generic function that handles both read (kernel to user) and write (user to kernel) operations. The `__DECONST` macro removes the const qualifier, essentially telling the compiler "I know this is const, but I need to pass it to a function expecting non-const. Trust me, it won't be modified." +**`__DECONST` 宏**:`zero_region` 被声明为 `const` 以防止意外修改。然而,`uiomove()` 期望非 const 指针,因为它是处理读(内核到用户)和写(用户到内核)操作的通用函数。`__DECONST` 宏移除 const 限定符,本质上是告诉编译器"我知道这是 const,但我需要把它传给期望非 const 的函数。相信我,它不会被修改。" -This is safe because `uiomove()` with a read-direction `uio` only copies data from the kernel buffer to userspace, it never writes to the buffer. The const-cast is a necessary workaround for C's type system limitations. +这是安全的,因为 `uiomove()` 在读方向的 `uio` 中只将数据从内核缓冲区拷贝到用户空间——它从不写入缓冲区。const 转换是 C 类型系统限制的必要变通。 -##### The Transfer Loop +##### 传输循环 ```c while (uio->uio_resid > 0 && error == 0) { @@ -4678,11 +4678,11 @@ while (uio->uio_resid > 0 && error == 0) { return (error); ``` -The loop continues until either the entire read request is satisfied (`uio->uio_resid == 0`) or an error occurs (`error != 0`). +循环持续进行,直到整个读取请求被满足(`uio->uio_resid == 0`)或发生错误(`error != 0`)。 -**Checking remaining bytes**: `uio->uio_resid` tracks how many bytes the application requested but haven't yet been transferred. Initially, this equals the original read size. After each successful transfer, `uiomove()` decrements it. +**检查剩余字节**:`uio->uio_resid` 跟踪应用程序请求但尚未传输的字节数。最初,这等于原始读取大小。每次成功传输后,`uiomove()` 递减它。 -**Limiting transfer size**: The code calculates how many bytes to transfer in this iteration: +**限制传输大小**:代码计算此迭代中要传输的字节数: ```c len = uio->uio_resid; @@ -4690,48 +4690,48 @@ if (len > ZERO_REGION_SIZE) len = ZERO_REGION_SIZE; ``` -If the remaining request exceeds the zero region's size, the transfer is capped at `ZERO_REGION_SIZE`. This limitation exists because the kernel only pre-allocated a finite zero buffer. Typical values for `ZERO_REGION_SIZE` are 64KB or 256KB, large enough for efficiency but small enough not to waste kernel memory. +如果剩余请求超过零区域的大小,传输被限制在 `ZERO_REGION_SIZE`。此限制存在是因为内核只预分配了有限的零缓冲区。`ZERO_REGION_SIZE` 的典型值是 64KB 或 256KB——大到足以提高效率,小到不浪费内核内存。 -**Why this matters**: If an application reads 1MB from `/dev/zero`, the loop executes multiple times, each iteration transferring up to `ZERO_REGION_SIZE` bytes. The same zero buffer is reused for each iteration, eliminating the need to allocate and zero 1MB of kernel memory. +**为什么这很重要**:如果应用程序从 `/dev/zero` 读取 1MB,循环执行多次,每次迭代传输最多 `ZERO_REGION_SIZE` 字节。相同的零缓冲区在每次迭代中重用,消除了分配和清零 1MB 内核内存的需要。 -**Performing the transfer**: `uiomove(zbuf, len, uio)` is the kernel's workhorse function for moving data between kernel and userspace. It: +**执行传输**:`uiomove(zbuf, len, uio)` 是内核在内核和用户空间之间移动数据的主力函数。它: -1. Copies `len` bytes from `zbuf` (kernel memory) to the user's buffer (described by `uio`) -2. Updates `uio->uio_resid` by subtracting `len` (fewer bytes remaining) -3. Advances `uio->uio_offset` by `len` (file position moves forward, though meaningless for `/dev/zero`) -4. Returns 0 on success or an error code on failure (typically `EFAULT` if the user's buffer address is invalid) +1. 将 `len` 字节从 `zbuf`(内核内存)拷贝到用户缓冲区(由 `uio` 描述) +2. 通过减去 `len` 来更新 `uio->uio_resid`(剩余字节减少) +3. 将 `uio->uio_offset` 前进 `len`(文件位置前移,尽管对 `/dev/zero` 没有意义) +4. 成功返回 0,失败返回错误码(通常是 `EFAULT`,如果用户缓冲区地址无效) -If `uiomove()` returns an error, the loop exits immediately and returns the error to the caller. The application receives whatever data was successfully transferred before the error occurred. +如果 `uiomove()` 返回错误,循环立即退出并将错误返回给调用者。应用程序收到在错误发生之前成功传输的任何数据。 -**Loop termination**: The loop exits when: +**循环终止**:循环在以下情况退出: -- **Success**: `uio->uio_resid` reaches zero, meaning all requested bytes were transferred -- **Error**: `uiomove()` failed, typically because the user's buffer pointer was invalid or the process received a signal +- **成功**:`uio->uio_resid` 降为零,表示所有请求的字节已传输 +- **错误**:`uiomove()` 失败,通常是因为用户缓冲区指针无效或进程收到信号 -##### Infinite Stream Semantics +##### 无限流语义 -Notice what's missing from this function: no end-of-file check. Most file reads eventually return 0 bytes, signaling EOF. The `/dev/zero` read function never does this, it always transfers the full requested amount (or fails with an error). +注意此函数缺少什么:没有文件结束检查。大多数文件读取最终返回 0 字节,表示 EOF。`/dev/zero` 的读取函数从不这样做——它始终传输完整的请求量(或因错误失败)。 -From userspace perspective: +从用户空间的角度: ```c char buf[4096]; ssize_t n = read(zero_fd, buf, sizeof(buf)); -// n always equals 4096, never 0 (unless error) +// n 始终等于 4096,从不为 0(除非出错) ``` -This infinite stream property makes `/dev/zero` useful for: +这种无限流特性使 `/dev/zero` 可用于: -- Allocating zero-initialized memory (pre-`MAP_ANON`) -- Generating arbitrary amounts of zero bytes for testing -- Overwriting disk blocks with zeros for data sanitization +- 分配零初始化的内存(`MAP_ANON` 之前) +- 生成任意数量的零字节用于测试 +- 用零覆盖磁盘块进行数据清理 -##### Performance Optimization +##### 性能优化 -The pre-allocated `zero_region` is a significant optimization. Consider the alternative implementation: +预分配的 `zero_region` 是一个重要的优化。考虑替代实现: ```c -// Inefficient approach +// 低效方法 char zeros[4096]; bzero(zeros, sizeof(zeros)); while (uio->uio_resid > 0) { @@ -4740,34 +4740,34 @@ while (uio->uio_resid > 0) { } ``` -This approach would zero a buffer on every function call, wasting CPU cycles. The production implementation zeros the buffer once at boot and reuses it forever, eliminating repeated zeroing overhead. +这种方法会在每次函数调用时清零缓冲区,浪费 CPU 周期。生产实现在启动时清零一次缓冲区并永远重用,消除了重复清零的开销。 -For applications reading gigabytes from `/dev/zero`, this optimization eliminates billions of store instructions, making reads essentially free (bounded only by memory copy speed). +对于从 `/dev/zero` 读取千兆字节的应用程序,此优化消除了数十亿条存储指令,使读取基本上免费(仅受内存拷贝速度限制)。 -##### Shared Between Devices +##### 设备间共享 -Recall from the `cdevsw` structures that both `/dev/zero` and `/dev/full` use `zero_read`. This sharing is correct because both devices should return zeros when read. The device identity (`dev` parameter) is ignored because the behavior is identical regardless of which device is accessed. +回顾 `cdevsw` 结构,`/dev/zero` 和 `/dev/full` 都使用 `zero_read`。这种共享是正确的,因为两个设备在读取时都应返回零。设备标识(`dev` 参数)被忽略,因为无论访问哪个设备,行为都是相同的。 -This implementation demonstrates a key principle: when multiple devices share behavior, implement it once and reference it from multiple switch tables. Code reuse eliminates duplication and ensures consistent behavior across related devices. +此实现展示了一个关键原则:当多个设备共享行为时,实现一次并从多个开关表引用。代码重用消除了重复,确保相关设备之间行为一致。 -##### Error Propagation +##### 错误传播 -If `uiomove()` fails partway through a large read, the function returns the error immediately. The userspace `read(2)` system call sees a short read followed by an error on the next call. For example: +如果 `uiomove()` 在大读取中途失败,函数立即返回错误。用户空间的 `read(2)` 系统调用在下一次调用时会看到短读取后跟错误。例如: ```c -// Reading 128KB when process receives signal after 64KB +// 读取 128KB,进程在 64KB 后收到信号 char buf[128 * 1024]; ssize_t n = read(zero_fd, buf, sizeof(buf)); -// n might equal 65536 (successful partial read) -// errno unset (partial success) +// n 可能等于 65536(成功的部分读取) +// errno 未设置(部分成功) n = read(zero_fd, buf, sizeof(buf)); -// n equals -1, errno equals EINTR (interrupted system call) +// n 等于 -1,errno 等于 EINTR(中断的系统调用) ``` -This error handling is automatic, `uiomove()` detects signals and returns `EINTR`, which the read function propagates to userspace. The driver doesn't need explicit signal handling logic. +此错误处理是自动的——`uiomove()` 检测信号并返回 `EINTR`,读取函数将其传播到用户空间。驱动程序不需要显式的信号处理逻辑。 -#### 6) Module event: create device nodes on load, destroy on unload +#### 6) 模块事件:加载时创建设备节点,卸载时销毁 ```c 169: /* ARGSUSED */ @@ -4805,11 +4805,11 @@ This error handling is automatic, `uiomove()` detects signals and returns `EINTR 202: MODULE_VERSION(null, 1); ``` -##### Module Lifecycle and Registration +##### 模块生命周期和注册 -The final section of the null driver handles module loading, unloading, and registration with the kernel's module system. This code executes when the module is loaded at boot or via `kldload`, and when it's unloaded via `kldunload`. +null 驱动程序的最后一部分处理模块加载、卸载和向内核模块系统注册。此代码在模块启动时加载或通过 `kldload` 加载时执行,在通过 `kldunload` 卸载时执行。 -##### The Module Event Handler +##### 模块事件处理程序 ```c /* ARGSUSED */ @@ -4819,15 +4819,15 @@ null_modevent(module_t mod __unused, int type, void *data __unused) switch(type) { ``` -**Function signature**: Module event handlers receive three parameters: +**函数签名**:模块事件处理程序接收三个参数: -- `module_t mod` - a handle to the module itself (unused here) -- `int type` - the event type: `MOD_LOAD`, `MOD_UNLOAD`, `MOD_SHUTDOWN`, etc. -- `void *data` - event-specific data (unused for this driver) +- `module_t mod` - 模块本身的句柄(此处未使用) +- `int type` - 事件类型:`MOD_LOAD`、`MOD_UNLOAD`、`MOD_SHUTDOWN` 等 +- `void *data` - 事件特定的数据(此驱动程序未使用) -The function returns 0 for success or an errno value for failure. A failed `MOD_LOAD` prevents the module from loading; a failed `MOD_UNLOAD` keeps the module loaded. +函数成功返回 0,失败返回 errno 值。失败的 `MOD_LOAD` 阻止模块加载;失败的 `MOD_UNLOAD` 使模块保持加载。 -##### Module Load: Creating Devices +##### 模块加载:创建设备 ```c case MOD_LOAD: @@ -4842,41 +4842,41 @@ case MOD_LOAD: break; ``` -The `MOD_LOAD` case executes when the module is first loaded, either during boot or when an administrator runs `kldload null`. +`MOD_LOAD` 分支在模块首次加载时执行,无论是在启动期间还是管理员运行 `kldload null` 时。 -**Boot message**: The `if (bootverbose)` check controls whether a message appears during boot. The `bootverbose` variable is set when the system boots with verbose output enabled (via boot loader configuration or kernel option). When true, the driver prints an informational message identifying the devices it provides. +**启动消息**:`if (bootverbose)` 检查控制启动期间是否显示消息。`bootverbose` 变量在系统启用详细输出启动时设置(通过引导加载程序配置或内核选项)。为 true 时,驱动程序打印一条信息消息标识它提供的设备。 -This conditional prevents cluttering the boot output in normal operation while allowing administrators to see driver initialization during diagnostic boots. The message format follows FreeBSD convention: driver name, colon, angle-bracketed device list. +此条件防止在正常操作中混乱引导输出,同时允许管理员在诊断引导期间看到驱动程序初始化。消息格式遵循 FreeBSD 约定:驱动程序名称、冒号、尖括号中的设备列表。 -**Device creation with `make_dev_credf`**: This function creates character device nodes in `/dev`. Each call requires several parameters that control the device's properties: +**使用 `make_dev_credf` 创建设备**:此函数在 `/dev` 中创建字符设备节点。每次调用需要几个控制设备属性的参数: -**`MAKEDEV_ETERNAL_KLD`**: A flag indicating this device should persist until explicitly destroyed. The `ETERNAL` part means the device won't be automatically removed if all references are closed, and `KLD` indicates it's part of a kernel loadable module (as opposed to a statically compiled driver). This flag combination ensures the device nodes remain available as long as the module is loaded, regardless of whether any process has them open. +**`MAKEDEV_ETERNAL_KLD`**:一个标志,指示此设备应持续存在直到显式销毁。`ETERNAL` 部分意味着设备不会在所有引用关闭时自动移除,`KLD` 表示它是内核可加载模块的一部分(与静态编译的驱动程序相对)。此标志组合确保设备节点在模块加载期间保持可用,无论是否有进程打开它们。 -**`&full_cdevsw`** (and similarly for null/zero): Pointer to the character device switch table that defines the device's behavior. This connects the device node to the driver's function implementations. +**`&full_cdevsw`**(null/zero 类似):指向定义设备行为的字符设备开关表的指针。这将设备节点连接到驱动程序的函数实现。 -**`0`**: The device unit number. Since these are singleton devices (only one `/dev/null` exists system-wide), unit 0 is used. Multi-instance devices like `/dev/tty0`, `/dev/tty1` would use different unit numbers. +**`0`**:设备单元号。由于这些是单例设备(系统范围内只有一个 `/dev/null`),使用单元 0。多实例设备如 `/dev/tty0`、`/dev/tty1` 会使用不同的单元号。 -**`NULL`**: Credential pointer for permission checks. NULL means no special credentials are required beyond the standard file permissions. +**`NULL`**:用于权限检查的凭证指针。NULL 表示不需要超出标准文件权限的特殊凭证。 -**`UID_ROOT`**: The device file owner (root, UID 0). This determines who can change the device's permissions or delete it. +**`UID_ROOT`**:设备文件所有者(root,UID 0)。这决定了谁可以更改设备权限或删除它。 -**`GID_WHEEL`**: The device file group (wheel, GID 0). The wheel group traditionally has administrative privileges. +**`GID_WHEEL`**:设备文件组(wheel,GID 0)。wheel 组传统上具有管理权限。 -**`0666`**: The permission mode in octal. This value (readable and writable by owner, group, and others) allows any process to open these devices. Breaking it down: +**`0666`**:八进制权限模式。此值(所有者、组和其他人都可读写)允许任何进程打开这些设备。分解来看: -- Owner (root): read (4) + write (2) = 6 -- Group (wheel): read (4) + write (2) = 6 -- Others: read (4) + write (2) = 6 +- 所有者(root):读(4)+ 写(2)= 6 +- 组(wheel):读(4)+ 写(2)= 6 +- 其他人:读(4)+ 写(2)= 6 -Unlike typical files where world-writable permissions are dangerous, these devices are designed for universal access, any process should be able to write to `/dev/null` or read from `/dev/zero`. +与典型的全局可写文件权限危险不同,这些设备设计为通用访问——任何进程都应该能够写入 `/dev/null` 或从 `/dev/zero` 读取。 -**`"full"`** (and similarly "null", "zero"): The device name string. This creates `/dev/full`, `/dev/null`, and `/dev/zero` respectively. The `make_dev_credf` function automatically prepends `/dev/` to the name. +**`"full"`**(以及类似的 "null"、"zero"):设备名称字符串。这分别创建 `/dev/full`、`/dev/null` 和 `/dev/zero`。`make_dev_credf` 函数自动在名称前添加 `/dev/`。 -**Return value storage**: Each `make_dev_credf` call returns a `struct cdev *` pointer stored in the global variables (`full_dev`, `null_dev`, `zero_dev`). These pointers are essential for the unload handler to remove the devices later. +**返回值存储**:每次 `make_dev_credf` 调用返回一个 `struct cdev *` 指针,存储在全局变量(`full_dev`、`null_dev`、`zero_dev`)中。这些指针对卸载处理程序稍后删除设备至关重要。 -##### Module Unload: Destroying Devices +##### 模块卸载:销毁设备 ```c case MOD_UNLOAD: @@ -4886,127 +4886,127 @@ case MOD_UNLOAD: break; ``` -The `MOD_UNLOAD` case executes when an administrator runs `kldunload null` to remove the module from the kernel. The module system only calls this handler if the module is eligible for unload (no other code references it). +`MOD_UNLOAD` 分支在管理员运行 `kldunload null` 从内核移除模块时执行。模块系统仅当模块符合卸载条件(没有其他代码引用它)时才调用此处理程序。 -**Device destruction**: The `destroy_dev` function removes a device node from `/dev` and deallocates associated kernel structures. Each call uses the pointer saved during `MOD_LOAD`. +**设备销毁**:`destroy_dev` 函数从 `/dev` 移除设备节点并释放关联的内核结构。每次调用使用在 `MOD_LOAD` 期间保存的指针。 -The function handles several cleanup tasks automatically: +该函数自动处理几项清理任务: -- Removes the `/dev` entry so new opens fail with `ENOENT` -- Waits for existing opens to close (or forcibly closes them) -- Frees the `struct cdev` and related memory -- Unregisters the device from kernel accounting +- 移除 `/dev` 条目,使新的打开操作因 `ENOENT` 失败 +- 等待现有的打开操作关闭(或强制关闭它们) +- 释放 `struct cdev` 和相关内存 +- 从内核记账中注销设备 -The order of destruction doesn't matter for these independent devices. If they had dependencies (like one device routing operations to another), destruction order would be critical. +这些独立设备的销毁顺序无关紧要。如果它们有依赖关系(比如一个设备将操作路由到另一个),销毁顺序就会很关键。 -**What if devices are open?**: By default, `destroy_dev` blocks until all file descriptors referring to the device are closed. An administrator attempting `kldunload null` while a process has `/dev/null` open would experience a delay. In practice, `/dev/null` is frequently open (many daemons redirect output there), so unloading this module is rare. +**如果设备仍然打开会怎样?**:默认情况下,`destroy_dev` 会阻塞,直到所有引用该设备的文件描述符关闭。管理员在进程打开了 `/dev/null` 的情况下尝试 `kldunload null` 会经历延迟。实际上,`/dev/null` 经常被打开(许多守护程序将输出重定向到那里),所以卸载此模块很少见。 -##### System Shutdown: No-Op +##### 系统关机:空操作 ```c case MOD_SHUTDOWN: break; ``` -The `MOD_SHUTDOWN` event fires during system shutdown or reboot. The handler does nothing because these devices don't need special shutdown handling: +`MOD_SHUTDOWN` 事件在系统关机或重启时触发。处理程序什么都不做,因为这些设备不需要特殊的关机处理: -- No hardware to disable or park in a safe state -- No data buffers to flush -- No network connections to close gracefully +- 没有硬件需要禁用或置于安全状态 +- 没有数据缓冲区需要刷新 +- 没有网络连接需要优雅关闭 -Simply breaking (falling through to `return (0)`) indicates successful shutdown handling. The devices will cease to exist when the kernel halts; no explicit cleanup is necessary. +简单地 break(落到 `return (0)`)表示成功的关机处理。设备将在内核停止时不存在;不需要显式清理。 -##### Unsupported Events: Error Return +##### 不支持的事件:错误返回 ```c default: return (EOPNOTSUPP); ``` -The default case catches any module event types not explicitly handled. Returning `EOPNOTSUPP` (operation not supported) informs the module system that this event isn't applicable to this driver. +默认分支捕获任何未显式处理的模块事件类型。返回 `EOPNOTSUPP`(操作不支持)通知模块系统此事件不适用于此驱动程序。 -Other possible event types include `MOD_QUIESCE` (prepare for unload, used to check if unload is safe) and driver-specific custom events. This driver doesn't support those, so the default handler rejects them. +其他可能的事件类型包括 `MOD_QUIESCE`(准备卸载,用于检查卸载是否安全)和驱动程序特定的自定义事件。此驱动程序不支持这些,所以默认处理程序拒绝它们。 -**Why not panic?**: An unknown event type isn't a driver bug, the kernel might introduce new event types in future versions. Returning an error is more robust than crashing. +**为什么不 panic?**:未知事件类型不是驱动程序 bug——内核可能在未来版本中引入新的事件类型。返回错误比崩溃更健壮。 -##### Success Return +##### 成功返回 ```c return (0); ``` -After handling any supported event (load, unload, shutdown), the function returns 0 to signal success. This allows the module operation to complete normally. +处理任何支持的事件(加载、卸载、关机)后,函数返回 0 表示成功。这允许模块操作正常完成。 -##### Module Registration Macros +##### 模块注册宏 ```c DEV_MODULE(null, null_modevent, NULL); MODULE_VERSION(null, 1); ``` -These macros register the module with the kernel's module system. +这些宏向内核模块系统注册模块。 -**`DEV_MODULE(null, null_modevent, NULL)`**: Declares a device driver module with three arguments: +**`DEV_MODULE(null, null_modevent, NULL)`**:声明一个设备驱动程序模块,有三个参数: -- `null` - the module name, appearing in `kldstat` output and used with `kldload`/`kldunload` commands -- `null_modevent` - pointer to the event handler function -- `NULL` - optional additional data passed to the event handler (unused here) +- `null` - 模块名称,出现在 `kldstat` 输出中,用于 `kldload`/`kldunload` 命令 +- `null_modevent` - 指向事件处理程序函数的指针 +- `NULL` - 传递给事件处理程序的可选附加数据(此处未使用) -The macro expands to generate data structures that the kernel's linker and module loader recognize. When the module loads, the kernel calls `null_modevent` with `type = MOD_LOAD`. When unloading, it calls with `type = MOD_UNLOAD`. +该宏展开生成内核链接器和模块加载器识别的数据结构。模块加载时,内核调用 `null_modevent` 并传入 `type = MOD_LOAD`。卸载时,以 `type = MOD_UNLOAD` 调用。 -**`MODULE_VERSION(null, 1)`**: Declares the module's version number. The arguments are: +**`MODULE_VERSION(null, 1)`**:声明模块的版本号。参数为: -- `null` - module name (must match `DEV_MODULE`) -- `1` - version number (integer) +- `null` - 模块名称(必须与 `DEV_MODULE` 匹配) +- `1` - 版本号(整数) -Version numbers enable dependency checking. If another module depended on this one, it could specify "requires null version >= 1" to ensure compatibility. For this simple driver, versioning is primarily documentation, it signals that this is the first (and likely only) version of the interface. +版本号启用依赖检查。如果另一个模块依赖于本模块,它可以指定"需要 null 版本 >= 1"以确保兼容性。对于这个简单驱动程序,版本控制主要是文档——它表示这是接口的第一个(也可能是唯一的)版本。 -##### Complete Module Lifecycle +##### 完整的模块生命周期 -The complete lifecycle for this driver: +此驱动程序的完整生命周期: -**At boot or `kldload null`**: +**启动时或 `kldload null`**: -1. Kernel loads the module into memory -2. Processes `DEV_MODULE` registration -3. Calls `null_modevent(mod, MOD_LOAD, NULL)` -4. Handler creates `/dev/full`, `/dev/null`, `/dev/zero` -5. Devices are now available to userspace +1. 内核将模块加载到内存 +2. 处理 `DEV_MODULE` 注册 +3. 调用 `null_modevent(mod, MOD_LOAD, NULL)` +4. 处理程序创建 `/dev/full`、`/dev/null`、`/dev/zero` +5. 设备现在对用户空间可用 -**During operation**: +**运行期间**: -- Applications open, read, write, ioctl the devices -- The `cdevsw` function pointers route operations to driver code -- No module events occur during normal operation +- 应用程序打开、读取、写入、ioctl 这些设备 +- `cdevsw` 函数指针将操作路由到驱动代码 +- 正常操作期间不发生模块事件 -**At `kldunload null`**: +**`kldunload null`**: -1. Kernel checks if unload is safe (no dependencies) -2. Calls `null_modevent(mod, MOD_UNLOAD, NULL)` -3. Handler destroys the three devices -4. Kernel removes module from memory -5. Attempts to open `/dev/null` now fail with `ENOENT` +1. 内核检查卸载是否安全(无依赖) +2. 调用 `null_modevent(mod, MOD_UNLOAD, NULL)` +3. 处理程序销毁三个设备 +4. 内核从内存中移除模块 +5. 尝试打开 `/dev/null` 现在会因 `ENOENT` 失败 -**At system shutdown**: +**系统关机时**: -1. Kernel calls `null_modevent(mod, MOD_SHUTDOWN, NULL)` -2. Handler does nothing (returns success) -3. System continues shutdown sequence -4. Module ceases to exist when kernel halts +1. 内核调用 `null_modevent(mod, MOD_SHUTDOWN, NULL)` +2. 处理程序什么都不做(返回成功) +3. 系统继续关机序列 +4. 内核停止时模块不再存在 -This lifecycle management, explicit load and unload handlers, registration macros, is the standard pattern for all FreeBSD kernel modules. Device drivers, filesystem implementations, network protocols, and system call additions all use the same module event mechanism. +这种生命周期管理——显式的加载和卸载处理程序、注册宏——是所有 FreeBSD 内核模块的标准模式。设备驱动程序、文件系统实现、网络协议和系统调用扩展都使用相同的模块事件机制。 -#### Interactive Exercises - `/dev/null`, `/dev/zero`, and `/dev/full` +#### 交互练习 - `/dev/null`、`/dev/zero` 和 `/dev/full` -**Goal:** Confirm you can read a real driver, map user-visible behavior to kernel code, and explain the minimal character device skeleton. +**目标:** 确认你能阅读真实的驱动程序,将用户可见的行为映射到内核代码,并解释最小的字符设备骨架。 -##### A) Map System Calls to `cdevsw` (Warm-up) +##### A) 将系统调用映射到 `cdevsw`(热身) -1. Which function handles writes to `/dev/full`, and what errno value does it return? Quote the function name and the return statement. What does this error code mean to userspace applications? *Hint:* look at `full_write`. +1. 哪个函数处理对 `/dev/full` 的写入,它返回什么 errno 值?引用函数名和返回语句。这个错误码对用户空间应用程序意味着什么?*提示:* 查看 `full_write`。 -2. Which function handles reads from both `/dev/zero` and `/dev/full`? Quote the relevant `.d_read` assignments from both `cdevsw` structures. Why is it correct for both devices to share the same read handler, what behavior do they have in common? *Hint:* compare the `full_cdevsw` and `zero_cdevsw` structures and read `zero_read`. +2. 哪个函数处理 `/dev/zero` 和 `/dev/full` 的读取?引用两个 `cdevsw` 结构中相关的 `.d_read` 赋值。为什么两个设备共享同一个读取处理程序是正确的,它们有什么共同的行为?*提示:* 比较 `full_cdevsw` 和 `zero_cdevsw` 结构并阅读 `zero_read`。 -3. Create a table listing each `cdevsw`'s name and its read/write function assignments: +3. 创建一个表格,列出每个 `cdevsw` 的名称及其读/写函数分配: | cdevsw | .d_name | .d_read | .d_write | | :---------------- | :------: | :----: | :----: | @@ -5014,163 +5014,164 @@ This lifecycle management, explicit load and unload handlers, registration macro | null_cdevsw | ? | ? | ? | | zero_cdevsw | ? | ? | ? | - Quote each structure. *Hint:* search for the three `*_cdevsw` definitions at the top of the file. + 引用每个结构。*提示:* 在文件顶部搜索三个 `*_cdevsw` 定义。 -##### B) Read Path Reasoning with `uiomove()` +##### B) 使用 `uiomove()` 进行读取路径推理 -1. Locate the `KASSERT` that verifies this is a read operation. Quote the line and explain what would happen if this assertion failed. What does the `__func__` macro provide in the error message? *Hint:* look at the top of `zero_read`. +1. 找到验证这是读取操作的 `KASSERT`。引用该行并解释如果此断言失败会发生什么。`__func__` 宏在错误消息中提供了什么?*提示:* 查看 `zero_read` 的顶部。 -2. Explain the role of `uio->uio_resid` in the while loop condition. What does this field represent, and how does it change during the loop? Quote the while condition. *Hint:* inside `zero_read`. +2. 解释 `uio->uio_resid` 在 while 循环条件中的作用。这个字段代表什么,它在循环期间如何变化?引用 while 条件。*提示:* 在 `zero_read` 内部。 -3. Why does the code limit each transfer to `ZERO_REGION_SIZE` rather than copying all requested bytes at once? What would be the problem with transferring 1MB in a single `uiomove()` call? Quote the if statement that implements this limit. *Hint:* the clamp is the first thing inside the `zero_read` loop body. +3. 为什么代码将每次传输限制为 `ZERO_REGION_SIZE` 而不是一次拷贝所有请求的字节?在单个 `uiomove()` 调用中传输 1MB 有什么问题?引用实现此限制的 if 语句。*提示:* 限制是 `zero_read` 循环体中的第一个操作。 -4. The code references two pre-allocated kernel resources: `zero_region` (a pointer) and `ZERO_REGION_SIZE` (a constant). Quote the lines where each is used. Then use grep to find where `ZERO_REGION_SIZE` is defined: +4. 代码引用了两个预分配的内核资源:`zero_region`(指针)和 `ZERO_REGION_SIZE`(常量)。引用每个被使用的行。然后使用 grep 查找 `ZERO_REGION_SIZE` 的定义位置: ```bash % grep -r "define.*ZERO_REGION_SIZE" /usr/src/sys/amd64/include/ ``` - What is the value on your system? *Hint:* `zero_region` is used inside `zero_read`, and `ZERO_REGION_SIZE` is its size clamp. + 你的系统上这个值是多少?*提示:* `zero_region` 在 `zero_read` 内部使用,`ZERO_REGION_SIZE` 是它的大小限制。 -##### C) Write Path Contrasts +##### C) 写入路径对比 -1. Compare the implementations of `null_write` and `full_write`. For each function, answer: +1. 比较 `null_write` 和 `full_write` 的实现。对于每个函数,回答: -- What does it do with `uio->uio_resid`? -- What value does it return? -- What will a userspace `write(2)` call return? +- 它对 `uio->uio_resid` 做了什么? +- 它返回什么值? +- 用户空间的 `write(2)` 调用会返回什么? - Now verify from userspace: + 现在从用户空间验证: ```bash -# This should succeed, reporting bytes written: +# 这应该成功,报告写入的字节数: % dd if=/dev/zero of=/dev/null bs=64k count=8 2>&1 | grep copied -# This should fail with "No space left on device": +# 这应该因"No space left on device"而失败: % dd if=/dev/zero of=/dev/full bs=1k count=1 2>&1 | grep -i "space" ``` - For each test, identify which write handler was called and quote the specific line that caused the observed behavior. + 对于每个测试,识别调用了哪个写入处理程序,并引用导致观察到的行为的特定行。 -##### D) Minimal `ioctl` Shape +##### D) 最小的 `ioctl` 形状 -1. Create a comparison table of ioctl handling. For `null_ioctl` and `zero_ioctl`, fill in: +1. 创建一个 ioctl 处理的对比表。对于 `null_ioctl` 和 `zero_ioctl`,填写: ```text -Commandnull_ioctl behaviorzero_ioctl behavior +命令null_ioctl 行为zero_ioctl 行为 DIOCSKERNELDUMP?? FIONBIO?? FIOASYNC?? -Unknown command?? +未知命令?? ``` - For each entry, quote the relevant case statement and explain the behavior. + 对于每个条目,引用相关的 case 语句并解释行为。 -2. The `FIOASYNC` case has special handling when enabling async I/O. Quote the conditional check and explain why these devices reject async I/O mode. *Hint:* look at the `FIOASYNC` case in both `null_ioctl` and `zero_ioctl`. +2. `FIOASYNC` 分支在启用异步 I/O 时有特殊处理。引用条件检查并解释为什么这些设备拒绝异步 I/O 模式。*提示:* 查看 `null_ioctl` 和 `zero_ioctl` 中的 `FIOASYNC` 分支。 -##### E) Device Node Lifecycle +##### E) 设备节点生命周期 -1. During `MOD_LOAD`, three device nodes are created via `make_dev_credf()`. For each call (in the `MOD_LOAD` arm of `null_modevent`), identify: +1. 在 `MOD_LOAD` 期间,通过 `make_dev_credf()` 创建三个设备节点。对于每次调用(在 `null_modevent` 的 `MOD_LOAD` 分支中),识别: -- The device name (what appears in /dev/) -- The cdevsw pointer (which function table) -- The permission mode (what does 0666 mean?) -- The owner and group (UID_ROOT, GID_WHEEL) +- 设备名称(在 /dev/ 中出现的名称) +- cdevsw 指针(哪个函数表) +- 权限模式(0666 意味着什么?) +- 所有者和组(UID_ROOT, GID_WHEEL) - Quote one complete `make_dev_credf()` call and label each parameter. + 引用一个完整的 `make_dev_credf()` 调用并标注每个参数。 -2. During `MOD_UNLOAD`, `destroy_dev()` is called three times (in the `MOD_UNLOAD` arm of `null_modevent`). Quote these calls and explain: +2. 在 `MOD_UNLOAD` 期间,`destroy_dev()` 被调用三次(在 `null_modevent` 的 `MOD_UNLOAD` 分支中)。引用这些调用并解释: -- Why do we need the global pointers (`full_dev`, `null_dev`, `zero_dev`)? -- What would happen if we forgot to call `destroy_dev()` during unload? -- Why must the `MOD_LOAD` and `MOD_UNLOAD` operations be symmetric? +- 为什么我们需要全局指针(`full_dev`、`null_dev`、`zero_dev`)? +- 如果我们在卸载期间忘记调用 `destroy_dev()` 会发生什么? +- 为什么 `MOD_LOAD` 和 `MOD_UNLOAD` 操作必须对称? -##### F) Trace from Userspace -1. Verify that `/dev/zero` produces zeros and `/dev/null` consumes data: +##### F) 从用户空间追踪 + +1. 验证 `/dev/zero` 产生零而 `/dev/null` 消耗数据: ```bash % dd if=/dev/zero bs=1k count=1 2>/dev/null | hexdump -C | head -n 2 -# Expected: all zeros (00 00 00 00...) +# 预期:全部为零(00 00 00 00...) % printf 'test data' | dd of=/dev/null 2>/dev/null ; echo "Exit code: $?" -# Expected: Exit code: 0 +# 预期:Exit code: 0 ``` - Explain these results by tracing through: + 通过追踪解释这些结果: -- `zero_read`: Which lines produce the zeros? How does the loop work? -- `null_write`: Which line makes the write "succeed"? What happens to the data? +- `zero_read`:哪些行产生零?循环如何工作? +- `null_write`:哪一行使写入"成功"?数据怎么了? - Quote the specific lines responsible for each behavior. + 引用导致每种行为的特定行。 -2. Read from `/dev/full` and examine what you get: +2. 从 `/dev/full` 读取并检查你得到什么: ```bash % dd if=/dev/full bs=16 count=1 2>/dev/null | hexdump -C ``` - What output do you see? Look at the `full_cdevsw` structure: which `.d_read` function does it use? + 你看到了什么输出?查看 `full_cdevsw` 结构:它使用哪个 `.d_read` 函数? - Why does `/dev/full` return zeros instead of an error? + 为什么 `/dev/full` 返回零而不是错误? -##### G) Module Lifecycle +##### G) 模块生命周期 -1. Look at the `null_modevent` switch statement. List all the case labels and what each one does. Which cases actually perform work versus just returning success? +1. 查看 `null_modevent` switch 语句。列出所有 case 标签以及每个标签的作用。哪些 case 实际执行工作,而哪些只是返回成功? -2. Find the two macros at the end of the file that register this module. Quote them and explain: +2. 找到文件末尾注册此模块的两个宏。引用它们并解释: -- What does `DEV_MODULE` do? -- What does `MODULE_VERSION` do? -- Why do both use the name "null"? +- `DEV_MODULE` 做了什么? +- `MODULE_VERSION` 做了什么? +- 为什么两者都使用名称"null"? -3. The `MAKEDEV_ETERNAL_KLD` flag is used in all three `make_dev_credf()` calls. What does this flag mean, and why is it appropriate for these devices? *Hint:* look at the `make_dev_credf()` calls inside `null_modevent`, and consider what happens if a process has /dev/null open when you try to unload the module. +3. `MAKEDEV_ETERNAL_KLD` 标志在所有三个 `make_dev_credf()` 调用中使用。这个标志意味着什么,为什么它适合这些设备?*提示:* 查看 `null_modevent` 内部的 `make_dev_credf()` 调用,并考虑当你尝试卸载模块时进程打开了 /dev/null 会发生什么。 -#### Stretch (thought experiment) +#### 延伸(思想实验) -**Stretch 1:** Examine `null_write`. The function does two things: sets `uio->uio_resid = 0` and returns 0. +**延伸 1:** 检查 `null_write`。该函数做两件事:设置 `uio->uio_resid = 0` 并返回 0。 -Thought experiment: If we changed the `return (0);` to `return (EIO);` but kept the `uio->uio_resid = 0;` assignment unchanged, what would happen? +思想实验:如果我们将 `return (0);` 改为 `return (EIO);` 但保持 `uio->uio_resid = 0;` 赋值不变,会发生什么? -- What would the kernel think about bytes written? -- What would `write(2)` return to userspace? -- What would errno be set to? +- 内核会怎么看待写入的字节数? +- `write(2)` 会向用户空间返回什么? +- errno 会被设置为什么? - Quote the lines involved and explain the interaction between `uio_resid` and the return value. + 引用涉及的行并解释 `uio_resid` 和返回值之间的交互。 -**Stretch 2:** In `zero_read`, the code limits each transfer to `ZERO_REGION_SIZE`. Quote the if statement where this limit is enforced. +**延伸 2:** 在 `zero_read` 中,代码将每次传输限制为 `ZERO_REGION_SIZE`。引用强制执行此限制的 if 语句。 - Thought experiment: Suppose we removed this check and always did: + 思想实验:假设我们移除此检查,总是这样做: ```c -len = uio->uio_resid; // No limit! +len = uio->uio_resid; // 没有限制! error = uiomove(zbuf, len, uio); ``` - If a user requests 10MB from `/dev/zero`: + 如果用户从 `/dev/zero` 请求 10MB: -- What invariant would make this "work" (not crash)? -- What resource constraint would we be ignoring? -- Why does the current code use a pre-allocated buffer of limited size? +- 什么不变量会使这"工作"(不崩溃)? +- 我们在忽略什么资源约束? +- 为什么当前代码使用有限大小的预分配缓冲区? -**Hint:** The `zero_region` is only `ZERO_REGION_SIZE` bytes. What happens if we try to copy more than that from this fixed-size buffer? +**提示:** `zero_region` 只有 `ZERO_REGION_SIZE` 字节。如果我们试图从这个固定大小的缓冲区拷贝超过它大小的数据会发生什么? -#### Bridge to the next tour +#### 前往下一个导览的过渡 -Before moving on: if you can match each user-visible behavior to the right function in `null.c`, you've internalized the **character-device skeleton** we'll keep meeting. Next we'll look at **`led(4)`**, which remains small but adds a user-visible **control surface** (writes that change state). Keep watching for three things: **how the device node is created**, **how operations are routed**, and **how the driver declines unsupported actions cleanly**. +继续之前:如果你能将每个用户可见的行为匹配到 `null.c` 中的正确函数,你就内化了我们将会不断遇到的**字符设备骨架**。接下来我们将看 **`led(4)`**,它仍然很小,但增加了一个用户可见的**控制表面**(改变状态的写入)。继续关注三件事:**设备节点如何创建**、**操作如何路由**,以及**驱动程序如何干净地拒绝不支持的操作**。 -### Tour 2 - A tiny write-only control surface with timers: `led(4)` +### 导览 2 - 一个带定时器的微型只写控制表面:`led(4)` -Open the file: +打开文件: ```sh % cd /usr/src/sys/dev/led % less led.c ``` -In one file we get a practical pattern for **write-driven device control** backed by a **timer** and per-device state. You'll see: a per-LED softc, global bookkeeping, a periodic **callout** that advances blink patterns, a parser that converts human-friendly commands into compact sequences, a `write(2)` entry point, and minimal create/destroy helpers. +在一个文件中,我们得到了由**定时器**和每设备状态支持的**写入驱动的设备控制**的实用模式。你将看到:每 LED 的 softc、全局簿记、推进闪烁模式的周期性 **callout**、将人类友好的命令转换为紧凑序列的解析器、一个 `write(2)` 入口点,以及最小的创建/销毁辅助函数。 -#### 1.0) Includes +#### 1.0) 头文件 ```c 12: #include @@ -5190,11 +5191,11 @@ In one file we get a practical pattern for **write-driven device control** backe 27: #include ``` -##### Headers and Subsystem Interface +##### 头文件和子系统接口 -The LED driver begins with kernel headers and a subsystem header that establishes its role as an infrastructure component used by other drivers. Unlike the null driver which stands alone, the LED driver provides services to hardware drivers that need to expose status indicators. +LED 驱动程序以内核头文件和一个子系统头文件开始,确立了它作为其他驱动程序使用的基础设施组件的角色。与独立运行的 null 驱动程序不同,LED 驱动程序为需要暴露状态指示器的硬件驱动程序提供服务。 -##### Standard Kernel Headers +##### 标准内核头文件 ```c #include @@ -5213,52 +5214,52 @@ The LED driver begins with kernel headers and a subsystem header that establishe #include ``` -These headers provide the infrastructure for a stateful, timer-driven device driver: +这些头文件为有状态的、定时器驱动的设备驱动程序提供了基础设施: -**``**, **``**, **``**: Fundamental system definitions identical to those in null.c. Every kernel source file begins with these. +**``**、**``**、**``**:与 null.c 中相同的基本系统定义。每个内核源文件都以此开头。 -**``**: Character device configuration, providing `cdevsw` and `make_dev()`. The LED driver uses these to create device nodes dynamically as hardware drivers register LEDs. +**``**:字符设备配置,提供 `cdevsw` 和 `make_dev()`。LED 驱动程序使用它们在硬件驱动程序注册 LED 时动态创建设备节点。 -**``**: Character classification functions like `isdigit()`. The LED driver parses user-supplied strings to control blink patterns, requiring character type checking. +**``**:字符分类函数,如 `isdigit()`。LED 驱动程序解析用户提供的字符串来控制闪烁模式,需要字符类型检查。 -**``**: Kernel initialization infrastructure. This driver uses `SYSINIT` to perform one-time initialization during boot, setting up global resources before any LEDs are registered. +**``**:内核初始化基础设施。此驱动程序使用 `SYSINIT` 在启动期间执行一次性初始化,在任何 LED 注册之前设置全局资源。 -**``**: System limits like `INT_MAX`. The LED driver uses this to configure its unit number allocator with maximum range. +**``**:系统限制,如 `INT_MAX`。LED 驱动程序使用它来配置其单元号分配器的最大范围。 -**``** and **``**: Locking primitives for protecting shared data structures. The driver uses a mutex to protect the LED list and blinker state from concurrent access by timer callbacks and user writes. +**``** 和 **``**:用于保护共享数据结构的锁定原语。驱动程序使用互斥锁来保护 LED 列表和闪烁器状态免受定时器回调和用户写入的并发访问。 -**``**: BSD linked list macros (`LIST_HEAD`, `LIST_FOREACH`, `LIST_INSERT_HEAD`, `LIST_REMOVE`). The driver maintains a global list of all registered LEDs, allowing timer callbacks to iterate and update each one. +**``**:BSD 链表宏(`LIST_HEAD`、`LIST_FOREACH`、`LIST_INSERT_HEAD`、`LIST_REMOVE`)。驱动程序维护所有已注册 LED 的全局列表,允许定时器回调迭代并更新每个 LED。 -**``**: Safe string buffer manipulation. The driver uses `sbuf` to build blink pattern strings from user input, avoiding fixed-size buffer overflows. String buffers automatically grow as needed and provide bounds checking. +**``**:安全字符串缓冲区操作。驱动程序使用 `sbuf` 从用户输入构建闪烁模式字符串,避免固定大小缓冲区溢出。字符串缓冲区根据需要自动增长并提供边界检查。 -**``**: Shared/exclusive locks (reader/writer locks). The driver uses an sx lock to protect device creation and destruction, allowing concurrent reads of the LED list while serializing structural modifications. +**``**:共享/独占锁(读/写锁)。驱动程序使用 sx 锁来保护设备创建和销毁,允许 LED 列表的并发读取,同时序列化结构修改。 -**``**: User I/O operations. Like null.c, this driver needs `struct uio` and `uiomove()` to transfer data between kernel and userspace. +**``**:用户 I/O 操作。与 null.c 一样,此驱动程序需要 `struct uio` 和 `uiomove()` 在内核和用户空间之间传输数据。 -**``**: Kernel memory allocation. Unlike null.c which had no dynamic memory, the LED driver allocates per-LED state structures and duplicates strings for LED names and blink patterns. +**``**:内核内存分配。与没有动态内存的 null.c 不同,LED 驱动程序为每 LED 状态结构分配内存,并复制 LED 名称和闪烁模式的字符串。 -##### Subsystem Interface Header +##### 子系统接口头文件 ```c #include ``` -This header defines the LED subsystem's public API, the interface that other kernel drivers use to register and control LEDs. While the specific contents aren't shown in this source file, typical declarations would include: +此头文件定义了 LED 子系统的公共 API,即其他内核驱动程序用来注册和控制 LED 的接口。虽然此源文件中未显示具体内容,但典型的声明包括: -**`led_t` typedef**: A function pointer type for LED control callbacks. Hardware drivers provide a function matching this signature that turns their physical LED on or off: +**`led_t` typedef**:LED 控制回调的函数指针类型。硬件驱动程序提供匹配此签名的函数来打开或关闭其物理 LED: ```c typedef void led_t(void *priv, int onoff); ``` -**Public functions**: The API that hardware drivers call: +**公共函数**:硬件驱动程序调用的 API: -- `led_create()` - register a new LED, creating a `/dev/led/name` device node -- `led_create_state()` - register an LED with initial state -- `led_destroy()` - unregister an LED when hardware is removed -- `led_set()` - programmatically control an LED from kernel code +- `led_create()` - 注册新 LED,创建 `/dev/led/name` 设备节点 +- `led_create_state()` - 注册带初始状态的 LED +- `led_destroy()` - 在硬件移除时注销 LED +- `led_set()` - 从内核代码以编程方式控制 LED -**Example usage by a hardware driver**: +**硬件驱动程序使用示例**: ```c // In a disk driver's attach function: @@ -5277,23 +5278,23 @@ disk_led_control(void *priv, int onoff) } ``` -##### Architectural Role +##### 架构角色 -The header organization reveals the LED driver's dual nature: +头文件组织揭示了 LED 驱动程序的双重性质: -**As a character device driver**: It includes standard device driver headers (``, ``) to create `/dev/led/*` nodes that userspace can write to. +**作为字符设备驱动程序**:它包含标准设备驱动头文件(``、``)来创建用户空间可以写入的 `/dev/led/*` 节点。 -**As a subsystem**: It includes `` to export an API that other drivers consume. Hardware drivers don't manipulate `/dev/led/*` directly, they call `led_create()` and provide callbacks. +**作为子系统**:它包含 `` 来导出其他驱动程序使用的 API。硬件驱动程序不直接操作 `/dev/led/*`——它们调用 `led_create()` 并提供回调。 -This pattern, a driver that both exposes user-facing devices and provides kernel-facing APIs, appears throughout FreeBSD. Examples include: +这种模式——一个同时暴露面向用户的设备和提供面向内核 API 的驱动程序——在整个 FreeBSD 中都很常见。示例包括: -- The `devctl` driver: creates `/dev/devctl` while providing `devctl_notify()` for kernel event reporting -- The `random` driver: creates `/dev/random` while providing `read_random()` for kernel consumers -- The `mem` driver: creates `/dev/mem` while providing direct memory access functions +- `devctl` 驱动程序:创建 `/dev/devctl` 同时提供 `devctl_notify()` 用于内核事件报告 +- `random` 驱动程序:创建 `/dev/random` 同时提供 `read_random()` 用于内核消费者 +- `mem` 驱动程序:创建 `/dev/mem` 同时提供直接内存访问函数 -The LED driver sits between hardware-specific drivers (which know how to control physical LEDs) and userspace (which wants to control LED patterns). It provides abstraction, hardware drivers implement simple on/off control; the LED subsystem handles complex blink patterns, timing, and user interface. +LED 驱动程序位于硬件特定驱动程序(知道如何控制物理 LED)和用户空间(想要控制 LED 模式)之间。它提供抽象——硬件驱动程序实现简单的开/关控制;LED 子系统处理复杂的闪烁模式、定时和用户界面。 -#### 1.1) Per-LED State (softc) +#### 1.1) 每 LED 状态(softc) ```c 30: struct ledsc { @@ -5311,11 +5312,11 @@ The LED driver sits between hardware-specific drivers (which know how to control 42: }; ``` -##### Per-LED State Structure +##### 每 LED 状态结构 -The `ledsc` structure (LED softc, following FreeBSD naming convention for "software context") contains all per-device state for one registered LED. Unlike the null driver which had no per-device state, the LED driver creates one of these structures for each LED registered in the system, tracking both device identity and current blink pattern execution state. +`ledsc` 结构(LED softc,遵循 FreeBSD"软件上下文"的命名约定)包含一个已注册 LED 的所有每设备状态。与没有每设备状态的 null 驱动程序不同,LED 驱动程序为系统中注册的每个 LED 创建一个这样的结构,跟踪设备标识和当前闪烁模式执行状态。 -##### Structure Definition and Fields +##### 结构定义和字段 ```c struct ledsc { @@ -5333,45 +5334,45 @@ struct ledsc { }; ``` -**`LIST_ENTRY(ledsc) list`**: Linkage for the global LED list. The `LIST_ENTRY` macro (from ``) embeds forward and backward pointers directly in the structure, allowing this LED to be part of a doubly-linked list without separate allocation. The global `led_list` chains together all registered LEDs, enabling timer callbacks to iterate and update each one. +**`LIST_ENTRY(ledsc) list`**:全局 LED 列表的链接。`LIST_ENTRY` 宏(来自 ``)将前向和后向指针直接嵌入结构中,允许此 LED 成为双向链表的一部分而无需单独分配。全局 `led_list` 将所有已注册的 LED 链接在一起,使定时器回调能够迭代并更新每一个。 -**`char *name`**: The LED's name string, duplicated from the hardware driver's registration call. This name appears in the device path `/dev/led/name` and identifies the LED in kernel API calls to `led_set()`. Examples: "disk0", "power", "heartbeat". The string is dynamically allocated and must be freed when the LED is destroyed. +**`char *name`**:LED 的名称字符串,从硬件驱动程序的注册调用中复制。此名称出现在设备路径 `/dev/led/name` 中,并在内核 API 调用 `led_set()` 时标识 LED。示例:"disk0"、"power"、"heartbeat"。该字符串是动态分配的,必须在 LED 销毁时释放。 -**`void *private`**: An opaque pointer passed back to the hardware driver's control function. The hardware driver provides this during `led_create()`, typically pointing to its own device context structure. When the LED subsystem needs to turn the LED on or off, it calls the hardware driver's callback with this pointer, allowing the driver to locate the relevant hardware registers. +**`void *private`**:传回给硬件驱动程序控制函数的不透明指针。硬件驱动程序在 `led_create()` 期间提供此指针,通常指向其自己的设备上下文结构。当 LED 子系统需要打开或关闭 LED 时,它使用此指针调用硬件驱动程序的回调,允许驱动程序定位相关的硬件寄存器。 -**`int unit`**: A unique unit number for this LED, used to construct the device minor number. Allocated from a unit number pool to prevent conflicts when multiple LEDs are registered. Unlike the null driver's fixed unit numbers (0 for all devices), the LED driver dynamically assigns units as LEDs are created. +**`int unit`**:此 LED 的唯一单元号,用于构造设备次设备号。从单元号池分配以防止注册多个 LED 时冲突。与 null 驱动程序的固定单元号(所有设备都为 0)不同,LED 驱动程序在创建 LED 时动态分配单元。 -**`led_t *func`**: Function pointer to the hardware driver's LED control callback. This function has the signature `void (*led_t)(void *priv, int onoff)` where `priv` is the private pointer above and `onoff` is non-zero for "on", zero for "off". This callback is the hardware-specific part, it knows how to manipulate GPIO pins, write to hardware registers, or send USB control transfers to actually light or extinguish the LED. +**`led_t *func`**:指向硬件驱动程序 LED 控制回调的函数指针。此函数的签名为 `void (*led_t)(void *priv, int onoff)`,其中 `priv` 是上面的私有指针,`onoff` 非零表示"开",零表示"关"。此回调是硬件特定的部分——它知道如何操作 GPIO 引脚、写入硬件寄存器或发送 USB 控制传输来实际点亮或熄灭 LED。 -**`struct cdev *dev`**: Pointer to the character device structure representing `/dev/led/name`. This is what `make_dev()` returns during LED creation. The device node allows userspace to write blink patterns to the LED. The pointer is needed later to call `destroy_dev()` when the LED is removed. +**`struct cdev *dev`**:指向表示 `/dev/led/name` 的字符设备结构的指针。这是 `make_dev()` 在 LED 创建期间返回的。设备节点允许用户空间向 LED 写入闪烁模式。稍后需要此指针在 LED 移除时调用 `destroy_dev()`。 -##### Blink Pattern Execution State +##### 闪烁模式执行状态 -The remaining fields track blink pattern execution by the timer callback: +其余字段跟踪定时器回调的闪烁模式执行: -**`struct sbuf *spec`**: The parsed blink specification string buffer. When a user writes a pattern like "f" (flash) or "m...---..." (morse code), the parser converts it to a sequence of timing codes and stores it in this `sbuf`. The string persists as long as the pattern is active, allowing the timer to repeatedly traverse it. +**`struct sbuf *spec`**:解析后的闪烁规范字符串缓冲区。当用户写入类似 "f"(闪烁)或 "m...---..."(摩尔斯码)的模式时,解析器将其转换为定时码序列并存储在此 `sbuf` 中。字符串在模式活动期间持续存在,允许定时器反复遍历它。 -**`char *str`**: Pointer to the beginning of the pattern string (extracted from `spec` via `sbuf_data()`). This is where pattern execution starts and where it loops back after reaching the end. If NULL, no pattern is active and the LED is in static on/off state. +**`char *str`**:指向模式字符串开头的指针(通过 `sbuf_data()` 从 `spec` 中提取)。这是模式执行开始的地方,也是到达末尾后循环回来的地方。如果为 NULL,则没有活动模式,LED 处于静态开/关状态。 -**`char *ptr`**: The current position in the pattern string. The timer callback examines this character to determine what to do next (turn LED on/off, delay for N tenths of a second). After processing each character, `ptr` advances. When it reaches the string terminator, it wraps back to `str` for continuous repetition. +**`char *ptr`**:模式字符串中的当前位置。定时器回调检查此字符以确定下一步做什么(打开/关闭 LED,延迟 N 个十分之一秒)。处理完每个字符后,`ptr` 前进。当到达字符串终止符时,它回到 `str` 进行持续重复。 -**`int count`**: A countdown timer for delay characters. Pattern codes like 'a' through 'j' mean "wait for 1-10 tenths of a second". When the timer encounters such a code, it sets `count` to the delay value and decrements it on each timer tick. While `count > 0`, the timer skips pattern advancement, implementing the delay. +**`int count`**:延迟字符的倒计时器。模式码如 'a' 到 'j' 表示"等待 1-10 个十分之一秒"。当定时器遇到这样的码时,它将 `count` 设置为延迟值并在每个定时器节拍递减。当 `count > 0` 时,定时器跳过模式前进,实现延迟。 -**`time_t last_second`**: Timestamp tracking the last second boundary, used for 'U'/'u' pattern codes that toggle the LED once per second (creating a 1Hz heartbeat pattern). The timer compares `time_second` (kernel's current time) to this field, only updating the LED when the second changes. This prevents multiple updates within the same second if the timer fires faster than 1Hz. +**`time_t last_second`**:跟踪最后一秒边界的时间戳,用于 'U'/'u' 模式码,每秒切换一次 LED(创建 1Hz 心跳模式)。定时器将 `time_second`(内核当前时间)与此字段比较,只在秒变化时更新 LED。这防止了在定时器触发频率高于 1Hz 时在同一秒内多次更新。 -##### Memory Management and Lifecycle +##### 内存管理和生命周期 -Several fields point to dynamically allocated memory: +有几个字段指向动态分配的内存: -- `name` - allocated with `strdup(name, M_LED)` during creation -- `spec` - created with `sbuf_new_auto()` when a pattern is set -- The structure itself is allocated with `malloc(sizeof *sc, M_LED, M_WAITOK | M_ZERO)` +- `name` - 在创建期间使用 `strdup(name, M_LED)` 分配 +- `spec` - 在设置模式时使用 `sbuf_new_auto()` 创建 +- 结构本身使用 `malloc(sizeof *sc, M_LED, M_WAITOK | M_ZERO)` 分配 -All must be freed during `led_destroy()` to prevent memory leaks. The structure's lifetime spans from `led_create()` to `led_destroy()`, potentially lasting the entire system uptime if the hardware driver never unregisters the LED. +所有这些都必须在 `led_destroy()` 期间释放以防止内存泄漏。结构的生命周期从 `led_create()` 到 `led_destroy()`,如果硬件驱动程序从不注销 LED,可能持续整个系统运行时间。 -##### Relationship to Device Node +##### 与设备节点的关系 -The `ledsc` structure and the `/dev/led/name` device node are bidirectionally linked: +`ledsc` 结构和 `/dev/led/name` 设备节点是双向链接的: ```text struct cdev (device node) @@ -5381,26 +5382,26 @@ struct ledsc struct cdev (same device node) ``` -This bidirectional linkage allows: +这种双向链接允许: -- The write handler to find the LED state: `sc = dev->si_drv1` -- The destroy function to remove the device: `destroy_dev(sc->dev)` +- 写入处理程序找到 LED 状态:`sc = dev->si_drv1` +- 销毁函数移除设备:`destroy_dev(sc->dev)` -##### Contrast with null.c +##### 与 null.c 的对比 -The null driver had no equivalent structure because its devices were stateless. The LED driver needs per-device state because: +null 驱动程序没有等效的结构,因为它的设备是无状态的。LED 驱动程序需要每设备状态,因为: -**Identity**: Each LED has a unique name and device node +**标识**:每个 LED 有唯一的名称和设备节点 -**Callback**: Each LED has hardware-specific control logic +**回调**:每个 LED 有硬件特定的控制逻辑 -**Pattern state**: Each LED may be executing a different blink pattern at different positions +**模式状态**:每个 LED 可能正在不同位置执行不同的闪烁模式 -**Timing**: Each LED's delay counters and timestamps are independent +**定时**:每个 LED 的延迟计数器和时间戳是独立的 -This per-device state structure is typical of drivers managing multiple instances of similar hardware. The pattern is universal: one structure per managed entity, containing identity, configuration, and operational state. +这种每设备状态结构是管理多个相似硬件实例的驱动程序的典型模式。该模式是通用的:每个被管理实体一个结构,包含标识、配置和操作状态。 -#### 1.2) Globals +#### 1.2) 全局变量 ```c 44: static struct unrhdr *led_unit; @@ -5412,130 +5413,130 @@ This per-device state structure is typical of drivers managing multiple instance 51: static MALLOC_DEFINE(M_LED, "LED", "LED driver"); ``` -##### Global State and Synchronization +##### 全局状态和同步 -The LED driver maintains several global variables that coordinate all registered LEDs. These globals provide resource allocation, synchronization, timer management, and a registry of active LEDs, infrastructure shared across all LED instances. +LED 驱动程序维护几个全局变量来协调所有已注册的 LED。这些全局变量提供资源分配、同步、定时器管理和活动 LED 注册表——所有 LED 实例共享的基础设施。 -##### Resource Allocator +##### 资源分配器 ```c static struct unrhdr *led_unit; ``` -The unit number handler allocates unique unit numbers for LED devices. Each registered LED receives a distinct unit number used to construct its device minor number, ensuring `/dev/led/disk0` and `/dev/led/power` don't collide even if created simultaneously. +单元号处理器为 LED 设备分配唯一的单元号。每个注册的 LED 接收一个独特的单元号,用于构造其设备次设备号,确保 `/dev/led/disk0` 和 `/dev/led/power` 即使同时创建也不会冲突。 -The `unrhdr` (unit number handler) provides thread-safe allocation and deallocation of integers from a range. During driver initialization, `new_unrhdr(0, INT_MAX, NULL)` creates a pool spanning the entire positive integer range. When hardware drivers call `led_create()`, the code calls `alloc_unr(led_unit)` to obtain the next available unit. When an LED is destroyed, `free_unr(led_unit, sc->unit)` returns the unit to the pool for reuse. +`unrhdr`(单元号处理器)提供从范围中线程安全地分配和释放整数。在驱动程序初始化期间,`new_unrhdr(0, INT_MAX, NULL)` 创建一个跨越整个正整数范围的池。当硬件驱动程序调用 `led_create()` 时,代码调用 `alloc_unr(led_unit)` 获取下一个可用单元。当 LED 被销毁时,`free_unr(led_unit, sc->unit)` 将单元返回池中以供重用。 -This dynamic allocation contrasts with the null driver's fixed units (always 0). The LED driver must handle arbitrary numbers of LEDs appearing and disappearing as hardware is added and removed. +这种动态分配与 null 驱动程序的固定单元(始终为 0)形成对比。LED 驱动程序必须处理随着硬件添加和移除而出现和消失的任意数量的 LED。 -##### Synchronization Primitives +##### 同步原语 ```c static struct mtx led_mtx; static struct sx led_sx; ``` -The driver uses two locks with distinct purposes: +驱动程序使用两个具有不同目的的锁: -**`led_mtx` (mutex)**: Protects the LED list and blink pattern execution state. This lock guards: +**`led_mtx`(互斥锁)**:保护 LED 列表和闪烁模式执行状态。此锁保护: -- The `led_list` linked list as LEDs are added and removed -- The `blinkers` counter tracking active patterns -- Individual `ledsc` fields modified by timer callbacks (`ptr`, `count`, `last_second`) +- LED 添加和移除时的 `led_list` 链表 +- 跟踪活动模式的 `blinkers` 计数器 +- 定时器回调修改的各个 `ledsc` 字段(`ptr`、`count`、`last_second`) -The mutex uses `MTX_DEF` semantics (default, can sleep while held). Timer callbacks acquire this mutex briefly to examine and update LED states. Write operations acquire it to install new blink patterns. +互斥锁使用 `MTX_DEF` 语义(默认,持有时可以睡眠)。定时器回调短暂获取此互斥锁以检查和更新 LED 状态。写入操作获取它以安装新的闪烁模式。 -**`led_sx` (shared/exclusive lock)**: Protects device creation and destruction. This lock serializes: +**`led_sx`(共享/独占锁)**:保护设备创建和销毁。此锁序列化: -- Calls to `make_dev()` and `destroy_dev()` -- Unit number allocation and deallocation -- String duplication for LED names +- 对 `make_dev()` 和 `destroy_dev()` 的调用 +- 单元号分配和释放 +- LED 名称的字符串复制 -Shared/exclusive locks allow multiple readers (threads examining which LEDs exist) to proceed concurrently while writers (threads creating or destroying LEDs) have exclusive access. For the LED driver, creation and destruction are infrequent operations that benefit from being fully serialized with an exclusive lock. +共享/独占锁允许多个读取者(检查哪些 LED 存在的线程)并发进行,而写入者(创建或销毁 LED 的线程)获得独占访问。对于 LED 驱动程序,创建和销毁是不频繁的操作,受益于使用独占锁完全序列化。 -**Why two locks?**: The separation enables concurrency. Timer callbacks need fast access to LED states protected by the mutex, while device creation/destruction requires the heavier sx lock. If a single lock protected everything, timer callbacks would block waiting for slow device operations. The split allows timers to run freely while device management proceeds independently. +**为什么需要两个锁?**:分离启用了并发。定时器回调需要快速访问由互斥锁保护的 LED 状态,而设备创建/销毁需要更重的 sx 锁。如果用单个锁保护一切,定时器回调会因等待慢速设备操作而阻塞。分离允许定时器自由运行,而设备管理独立进行。 -##### LED Registry +##### LED 注册表 ```c static LIST_HEAD(, ledsc) led_list = LIST_HEAD_INITIALIZER(led_list); ``` -The global LED list maintains all registered LEDs in a doubly-linked list. The `LIST_HEAD` macro (from ``) declares a list head structure and `LIST_HEAD_INITIALIZER` sets its initial empty state. +全局 LED 列表将所有已注册的 LED 维护在一个双向链表中。`LIST_HEAD` 宏(来自 ``)声明一个链表头结构,`LIST_HEAD_INITIALIZER` 设置其初始空状态。 -This list serves multiple purposes: +此列表服务于多个目的: -**Timer iteration**: The timer callback walks the list with `LIST_FOREACH(sc, &led_list, list)` to update each active LED's blink pattern. Without this registry, the timer wouldn't know which LEDs exist. +**定时器迭代**:定时器回调使用 `LIST_FOREACH(sc, &led_list, list)` 遍历列表来更新每个活动 LED 的闪烁模式。没有此注册表,定时器不知道哪些 LED 存在。 -**Name lookup**: The `led_set()` function searches the list to find an LED by name when kernel code wants to control an LED programmatically. +**名称查找**:当内核代码想要以编程方式控制 LED 时,`led_set()` 函数搜索列表按名称查找 LED。 -**Cleanup verification**: When the last LED is removed (`LIST_EMPTY(&led_list)`), the driver can stop the timer callback, conserving CPU cycles when no LEDs need servicing. +**清理验证**:当最后一个 LED 被移除(`LIST_EMPTY(&led_list)`)时,驱动程序可以停止定时器回调,在没有 LED 需要服务时节省 CPU 周期。 -The list is protected by `led_mtx` since both timer callbacks and device operations modify it. +列表由 `led_mtx` 保护,因为定时器回调和设备操作都修改它。 -##### Timer Callback Infrastructure +##### 定时器回调基础设施 ```c static struct callout led_ch; static int blinkers = 0; ``` -**`led_ch` (callout)**: A kernel timer that fires periodically to advance blink patterns. When any LED has an active pattern, the timer is scheduled to fire 10 times per second (`hz / 10`, where `hz` is timer ticks per second, typically 1000). Each timer firing calls `led_timeout()` which walks the LED list and updates pattern states. +**`led_ch`(callout)**:一个定期触发的内核定时器,用于推进闪烁模式。当任何 LED 有活动模式时,定时器被调度为每秒触发 10 次(`hz / 10`,其中 `hz` 是每秒定时器节拍数,通常为 1000)。每次定时器触发调用 `led_timeout()`,遍历 LED 列表并更新模式状态。 -The callout remains idle (not scheduled) when no LEDs are blinking, conserving resources. The first LED to receive a blink pattern schedules the timer with `callout_reset(&led_ch, hz / 10, led_timeout, NULL)`. Subsequent patterns don't reschedule, the single timer services all LEDs. +当没有 LED 闪烁时,callout 保持空闲(未被调度),节省资源。第一个接收闪烁模式的 LED 使用 `callout_reset(&led_ch, hz / 10, led_timeout, NULL)` 调度定时器。后续模式不会重新调度——单个定时器服务所有 LED。 -**`blinkers` counter**: Tracks how many LEDs currently have active blink patterns. When a pattern is assigned, `blinkers++`. When a pattern completes or is replaced with static on/off, `blinkers--`. When the counter reaches zero, the timer callback doesn't reschedule itself, stopping the periodic wakeups. +**`blinkers` 计数器**:跟踪当前有多少 LED 有活动闪烁模式。分配模式时 `blinkers++`。模式完成或被静态开/关替换时 `blinkers--`。当计数器达到零时,定时器回调不再重新调度自身,停止定期唤醒。 -This reference counting is critical for performance. Without it, the timer would fire continuously even with no work to do. The counter gates timer activity: schedule when transitioning 0 -> 1, stop when transitioning 1 -> 0. +此引用计数对性能至关重要。没有它,定时器会在没有工作可做时持续触发。计数器控制定时器活动:在 0 -> 1 转换时调度,在 1 -> 0 转换时停止。 -##### Memory Type Declaration +##### 内存类型声明 ```c static MALLOC_DEFINE(M_LED, "LED", "LED driver"); ``` -The `MALLOC_DEFINE` macro registers a memory allocation type for the LED subsystem. All LED-related allocations specify `M_LED`: +`MALLOC_DEFINE` 宏为 LED 子系统注册一个内存分配类型。所有 LED 相关的分配都指定 `M_LED`: -- `malloc(sizeof *sc, M_LED, ...)` for softc structures -- `strdup(name, M_LED)` for LED name strings +- `malloc(sizeof *sc, M_LED, ...)` 用于 softc 结构 +- `strdup(name, M_LED)` 用于 LED 名称字符串 -Memory types enable kernel accounting and debugging: +内存类型启用内核记账和调试: -- `vmstat -m` shows memory consumption per type -- Developers can track whether the LED driver is leaking memory -- Kernel memory debuggers can filter allocations by type +- `vmstat -m` 显示每种类型的内存消耗 +- 开发者可以跟踪 LED 驱动程序是否在泄漏内存 +- 内核内存调试器可以按类型过滤分配 -The three arguments are: +三个参数为: -1. `M_LED` - the C identifier used in `malloc()` calls -2. `"LED"` - short name appearing in accounting output -3. `"LED driver"` - descriptive text for documentation +1. `M_LED` - 在 `malloc()` 调用中使用的 C 标识符 +2. `"LED"` - 出现在记账输出中的短名称 +3. `"LED driver"` - 用于文档的描述文本 -##### Initialization Coordination +##### 初始化协调 -These globals are initialized in a specific sequence during boot: +这些全局变量在启动期间按特定顺序初始化: -1. **Static initialization**: `led_list` and `blinkers` get compile-time initial values -2. **`led_drvinit()` (via `SYSINIT`)**: Allocates `led_unit`, initializes `led_mtx` and `led_sx`, prepares the callout -3. **Runtime**: Hardware drivers call `led_create()` to register LEDs, incrementing `blinkers` and populating `led_list` +1. **静态初始化**:`led_list` 和 `blinkers` 获得编译时初始值 +2. **`led_drvinit()`(通过 `SYSINIT`)**:分配 `led_unit`,初始化 `led_mtx` 和 `led_sx`,准备 callout +3. **运行时**:硬件驱动程序调用 `led_create()` 注册 LED,递增 `blinkers` 并填充 `led_list` -The `static` storage class on all globals limits their visibility to this source file. No other kernel code can directly access these variables, all interactions go through the public API (`led_create()`, `led_destroy()`, `led_set()`). This encapsulation prevents external code from corrupting the LED subsystem's internal state. +所有全局变量上的 `static` 存储类将其可见性限制在此源文件中。其他内核代码不能直接访问这些变量——所有交互都通过公共 API(`led_create()`、`led_destroy()`、`led_set()`)进行。这种封装防止外部代码损坏 LED 子系统的内部状态。 -##### Contrast with null.c +##### 与 null.c 的对比 -The null driver had minimal global state: three device pointers for its fixed devices. The LED driver's globals reflect its dynamic nature: +null 驱动程序只有最少的全局状态:用于其固定设备的三个设备指针。LED 驱动程序的全局变量反映了其动态性质: -- **Resource allocation**: Unit numbers for arbitrary device counts -- **Concurrency**: Two locks for different access patterns -- **Registry**: A list tracking all active LEDs -- **Scheduling**: Timer infrastructure for pattern execution -- **Accounting**: Memory type for allocation tracking +- **资源分配**:用于任意设备数量的单元号 +- **并发**:用于不同访问模式的两个锁 +- **注册表**:跟踪所有活动 LED 的列表 +- **调度**:用于模式执行的定时器基础设施 +- **记账**:用于分配跟踪的内存类型 -This richer global infrastructure supports the LED driver's role as a subsystem managing multiple dynamically-created devices with time-based behaviors, rather than a simple driver exposing fixed stateless devices. +这种更丰富的全局基础设施支持 LED 驱动程序作为管理多个动态创建的具有基于时间行为的设备的子系统的角色,而不是暴露固定无状态设备的简单驱动程序。 -#### 2) The heartbeat: `led_timeout()` advances the pattern +#### 2) 心跳:`led_timeout()` 推进模式 -This **periodic callout** walks all LEDs and advances each one's pattern. Patterns are encoded in ASCII, so the parser and state machine stay tiny. +此**周期性 callout** 遍历所有 LED 并推进每个 LED 的模式。模式以 ASCII 编码,因此解析器和状态机保持小巧。 ```c 54: static void @@ -5574,11 +5575,11 @@ This **periodic callout** walks all LEDs and advances each one's pattern. Patter 87: } ``` -##### Timer Callback: Pattern Execution Engine +##### 定时器回调:模式执行引擎 -The `led_timeout` function is the heart of the LED subsystem's blink pattern execution. Called by the kernel's timer subsystem approximately 10 times per second, it walks the global LED list and advances each active pattern by one step, interpreting a simple pattern language to control LED timing and state. +`led_timeout` 函数是 LED 子系统闪烁模式执行的核心。它被内核的定时器子系统每秒调用约 10 次,遍历全局 LED 列表并将每个活动模式推进一步,解释一种简单的模式语言来控制 LED 的定时和状态。 -##### Function Entry and List Iteration +##### 函数入口与列表遍历 ```c static void @@ -5588,22 +5589,22 @@ led_timeout(void *p) LIST_FOREACH(sc, &led_list, list) { ``` -**Function signature**: Timer callbacks receive a single `void *` argument passed during timer scheduling. This driver doesn't use the argument (it's typically NULL), relying instead on the global LED list to find work. +**函数签名**:定时器回调接收一个在定时器调度期间传入的 `void *` 参数。此驱动程序未使用该参数(通常为 NULL),而是依赖全局 LED 列表来查找工作。 -**Iterating all LEDs**: The `LIST_FOREACH` macro walks the doubly-linked `led_list`, visiting each registered LED. This allows one timer to service multiple independent LEDs, each potentially executing a different blink pattern at a different position. The iteration is safe because the list is protected by `led_mtx` (the callout was initialized with this mutex via `callout_init_mtx()`). +**遍历所有 LED**:`LIST_FOREACH` 宏遍历双向链表 `led_list`,访问每个已注册的 LED。这允许一个定时器服务多个独立的 LED,每个 LED 可能在不同的位置执行不同的闪烁模式。遍历是安全的,因为该列表受到 `led_mtx` 的保护(callout 通过 `callout_init_mtx()` 使用此互斥锁初始化)。 -##### Skipping Inactive LEDs +##### 跳过不活动的 LED ```c if (sc->ptr == NULL) continue; ``` -The `ptr` field indicates whether this LED has an active blink pattern. When NULL, the LED is in static on/off state and needs no timer processing. The callback skips to the next LED immediately. +`ptr` 字段指示此 LED 是否有活动的闪烁模式。当为 NULL 时,LED 处于静态开/关状态,不需要定时器处理。回调会立即跳到下一个 LED。 -This check is the first filter: LEDs without patterns don't consume CPU time. Only LEDs actively blinking require processing on each timer tick. +此检查是第一道过滤器:没有模式的 LED 不会消耗 CPU 时间。只有正在闪烁的 LED 才需要在每个定时器滴答时进行处理。 -##### Handling Delay States +##### 处理延迟状态 ```c if (sc->count > 0) { @@ -5612,13 +5613,13 @@ if (sc->count > 0) { } ``` -The `count` field implements delays in blink patterns. When the pattern interpreter encounters timing codes like 'a' through 'j' (meaning "wait 1-10 tenths of a second"), it sets `count` to the delay value. On subsequent timer ticks, the callback decrements `count` without advancing through the pattern. +`count` 字段实现了闪烁模式中的延迟。当模式解释器遇到像 'a' 到 'j' 这样的定时代码(表示"等待 1-10 个十分之一秒")时,它会将 `count` 设置为延迟值。在后续的定时器滴答中,回调会递减 `count` 而不推进模式。 -**Example**: Pattern code 'c' (wait 3 tenths of a second) sets `count = 2` (the value is 1 less than the intended delay). The next two timer ticks decrement `count` to 1, then 0. On the third tick, `count` is already 0, so this check fails and pattern execution proceeds. +**示例**:模式代码 'c'(等待 3 个十分之一秒)设置 `count = 2`(该值比预期延迟少 1)。接下来两个定时器滴答将 `count` 递减到 1,然后到 0。在第三个滴答时,`count` 已经是 0,因此此检查失败,模式执行继续。 -This mechanism creates precise timing: at 10Hz, each count represents 0.1 seconds. Pattern 'AcAc' produces: LED on, wait 0.3s, LED on again, wait 0.3s, repeat. +此机制实现了精确的定时:在 10Hz 频率下,每个计数代表 0.1 秒。模式 'AcAc' 产生:LED 亮,等待 0.3 秒,LED 再次亮,等待 0.3 秒,重复。 -##### Pattern Termination +##### 模式终止 ```c if (*sc->ptr == '.') { @@ -5628,15 +5629,15 @@ if (*sc->ptr == '.') { } ``` -The period character '.' signals pattern end. Unlike most patterns which loop indefinitely, some user specifications include an explicit terminator. When encountered: +句点字符 '.' 表示模式结束。与大多数无限循环的模式不同,某些用户规格包含显式的终止符。当遇到时: -**Stop pattern execution**: Setting `ptr = NULL` marks this LED as inactive. Future timer ticks will skip it at the first check. +**停止模式执行**:将 `ptr = NULL` 标记此 LED 为不活动状态。未来的定时器滴答将在第一次检查时跳过它。 -**Decrement blinker count**: Reducing `blinkers` tracks that one fewer LED needs servicing. When this counter reaches zero (checked at function end), the timer stops scheduling itself. +**递减闪烁计数器**:减少 `blinkers` 跟踪需要服务的 LED 少了一个。当此计数器达到零时(在函数结束时检查),定时器将停止调度自身。 -**Skip remaining code**: The `continue` jumps to the next LED in the list. The pattern-advance and wrap-around code at the tail of `led_timeout` (the `sc->ptr++` step and the `*sc->ptr == '\0'` rewind) does not execute for terminated patterns. +**跳过剩余代码**:`continue` 跳转到列表中的下一个 LED。`led_timeout` 尾部的模式推进和环绕代码(`sc->ptr++` 步骤和 `*sc->ptr == '\0'` 回绕)不会对已终止的模式执行。 -##### Heartbeat Pattern: Second-Based Toggle +##### 心跳模式:基于秒的切换 ```c else if (*sc->ptr == 'U' || *sc->ptr == 'u') { @@ -5647,20 +5648,20 @@ else if (*sc->ptr == 'U' || *sc->ptr == 'u') { } ``` -The 'U' and 'u' codes create once-per-second toggles, useful for heartbeat indicators showing the system is alive. +'U' 和 'u' 代码创建每秒一次的切换,适用于显示系统活动的心跳指示器。 -**Second boundary detection**: The kernel variable `time_second` holds the current Unix timestamp. Comparing it to `last_second` detects when a second boundary has passed. If the values match, we're still within the same second and the callback skips processing with `continue`. +**秒边界检测**:内核变量 `time_second` 保存当前 Unix 时间戳。将其与 `last_second` 比较可以检测到秒边界是否已过去。如果值匹配,则我们仍在同一秒内,回调使用 `continue` 跳过处理。 -**Recording the transition**: `sc->last_second = time_second` remembers this second, preventing multiple updates if the timer fires multiple times per second (which it does, 10 times per second). +**记录转换**:`sc->last_second = time_second` 记录这一秒,防止定时器每秒多次触发(实际上每秒触发 10 次)时产生多次更新。 -**Updating the LED**: The callback invokes the hardware driver's control function. The second parameter determines LED state: +**更新 LED**:回调调用硬件驱动程序的控制函数。第二个参数决定 LED 状态: -- `*sc->ptr == 'U'` -> true (1) -> LED on -- `*sc->ptr == 'u'` -> false (0) -> LED off +- `*sc->ptr == 'U'` -> true (1) -> LED 亮 +- `*sc->ptr == 'u'` -> false (0) -> LED 灭 -Pattern "Uu" creates a 1Hz toggle: on for one second, off for one second. Pattern "U" alone keeps the LED on but only updates at second boundaries, which may be used for synchronization purposes. +模式 "Uu" 创建 1Hz 切换:亮一秒,灭一秒。模式 "U" 单独让 LED 保持亮但仅在秒边界更新,可用于同步目的。 -##### Off Delay Pattern +##### 关延迟模式 ```c else if (*sc->ptr >= 'a' && *sc->ptr <= 'j') { @@ -5669,21 +5670,21 @@ else if (*sc->ptr >= 'a' && *sc->ptr <= 'j') { } ``` -Lowercase letters 'a' through 'j' mean "turn LED off and wait." This combines two operations: immediate state change plus delay setup. +小写字母 'a' 到 'j' 表示"关闭 LED 并等待"。这结合了两个操作:即时状态改变加上延迟设置。 -**Turning off the LED**: `sc->func(sc->private, 0)` calls the hardware driver's control function with the off command (second parameter is 0). +**关闭 LED**:`sc->func(sc->private, 0)` 使用关闭命令(第二个参数为 0)调用硬件驱动程序的控制函数。 -**Computing the delay**: The expression `(*sc->ptr & 0xf) - 1` extracts the delay duration from the character code. In ASCII: +**计算延迟**:表达式 `(*sc->ptr & 0xf) - 1` 从字符代码中提取延迟时长。在 ASCII 中: -- 'a' is 0x61, `0x61 & 0x0f = 1`, minus 1 = 0 (wait 0.1 seconds) -- 'b' is 0x62, `0x62 & 0x0f = 2`, minus 1 = 1 (wait 0.2 seconds) -- 'c' is 0x63, `0x63 & 0x0f = 3`, minus 1 = 2 (wait 0.3 seconds) +- 'a' 为 0x61,`0x61 & 0x0f = 1`,减 1 = 0(等待 0.1 秒) +- 'b' 为 0x62,`0x62 & 0x0f = 2`,减 1 = 1(等待 0.2 秒) +- 'c' 为 0x63,`0x63 & 0x0f = 3`,减 1 = 2(等待 0.3 秒) - ... -- 'j' is 0x6A, `0x6A & 0x0f = 10`, minus 1 = 9 (wait 1.0 seconds) +- 'j' 为 0x6A,`0x6A & 0x0f = 10`,减 1 = 9(等待 1.0 秒) -The mask `& 0xf` isolates the low 4 bits, which conveniently map 'a'-'j' to values 1-10. Subtracting 1 converts to the countdown format (timer ticks remaining minus one). +掩码 `& 0xf` 隔离低 4 位,方便地将 'a'-'j' 映射到值 1-10。减去 1 转换为倒计时格式(定时器滴答剩余数减一)。 -##### On Delay Pattern +##### 开延迟模式 ```c else if (*sc->ptr >= 'A' && *sc->ptr <= 'J') { @@ -5692,16 +5693,16 @@ else if (*sc->ptr >= 'A' && *sc->ptr <= 'J') { } ``` -Uppercase letters 'A' through 'J' work identically to lowercase, except the LED is turned on instead of off. The delay calculation is the same: +大写字母 'A' 到 'J' 的工作原理与小写字母相同,只是 LED 被打开而不是关闭。延迟计算相同: -- 'A' -> on for 0.1 seconds -- 'B' -> on for 0.2 seconds +- 'A' -> 亮 0.1 秒 +- 'B' -> 亮 0.2 秒 - ... -- 'J' -> on for 1.0 seconds +- 'J' -> 亮 1.0 秒 -Pattern "AaBb" creates: on 0.1s, off 0.1s, on 0.2s, off 0.2s, repeat. Pattern "Aa" is a standard fast blink at ~2.5Hz. +模式 "AaBb" 创建:亮 0.1 秒,灭 0.1 秒,亮 0.2 秒,灭 0.2 秒,重复。模式 "Aa" 是以约 2.5Hz 的标准快速闪烁。 -##### Pattern Advancement and Looping +##### 模式推进与循环 ```c sc->ptr++; @@ -5709,15 +5710,15 @@ if (*sc->ptr == '\0') sc->ptr = sc->str; ``` -After processing the current pattern character (whether it was a heartbeat code or a delay code), the pointer advances to the next character. +处理完当前模式字符(无论是心跳代码还是延迟代码)后,指针前进到下一个字符。 -**Detecting pattern end**: If the new position is the null terminator, the pattern has been fully executed once. Rather than stopping (as the '.' terminator does), most patterns loop indefinitely. +**检测模式结束**:如果新位置是空终止符,表示模式已完整执行一次。与使用 '.' 终止符停止不同,大多数模式会无限循环。 -**Looping back**: `sc->ptr = sc->str` resets to the pattern's beginning. The next timer tick will start over from the first character, creating a repeating cycle. +**循环返回**:`sc->ptr = sc->str` 重置到模式的开始。下一个定时器滴答将从第一个字符重新开始,创建一个重复循环。 -**Example**: Pattern "AjBj" becomes on-1s, on-1s, repeat continuously. The pattern never stops unless replaced by a new write or the LED is destroyed. +**示例**:模式 "AjBj" 产生:亮 1 秒,亮 1 秒,持续重复。除非被新的写入替换或 LED 被销毁,否则模式永不停止。 -##### Timer Rescheduling +##### 定时器重新调度 ```c if (blinkers > 0) @@ -5725,39 +5726,39 @@ if (blinkers > 0) } ``` -After processing all LEDs, the callback decides whether to reschedule itself. If any LED still has an active pattern (`blinkers > 0`), the timer is reset to fire again in `hz / 10` ticks (0.1 seconds). +处理完所有 LED 后,回调决定是否重新调度自身。如果仍有任何 LED 具有活动模式(`blinkers > 0`),则将定时器重置为在 `hz / 10` 个滴答(0.1 秒)后再次触发。 -**Self-perpetuating timer**: Each invocation schedules the next invocation, creating a continuous loop as long as work remains. This is different from a periodic timer that fires unconditionally, the LED timer is work-driven. +**自持续定时器**:每次调用都会调度下一次调用,只要有工作就创建连续循环。这与无条件触发的周期性定时器不同,LED 定时器是工作驱动的。 -**Automatic shutdown**: When the last active pattern terminates (either via '.' or being replaced with static state), `blinkers` drops to 0 and the timer doesn't reschedule. The callback exits and won't run again until a new pattern activates, conserving CPU when all LEDs are static. +**自动关闭**:当最后一个活动模式终止(通过 '.' 或被静态状态替换)时,`blinkers` 降至 0,定时器不再重新调度。回调退出,直到新模式激活才会再次运行,在所有 LED 为静态时节省 CPU。 -**The `hz` variable**: The kernel constant `hz` represents timer ticks per second (typically 1000 on modern systems). Dividing by 10 gives the delay in ticks for one-tenth of a second, matching the pattern language's resolution. +**`hz` 变量**:内核常量 `hz` 表示每秒的定时器滴答数(现代系统上通常为 1000)。除以 10 得到十分之一秒的滴答延迟,与模式语言的分辨率匹配。 -##### Pattern Language Summary +##### 模式语言总结 -The timer interprets a simple language embedded in pattern strings: +定时器解释嵌入在模式字符串中的简单语言: -| Code | Meaning | Duration | +| 代码 | 含义 | 持续时间 | | ------- | ----------- | ------------------ | -| 'a'-'j' | LED off | 0.1-1.0 seconds | -| 'A'-'J' | LED on | 0.1-1.0 seconds | -| 'U' | LED on | At second boundary | -| 'u' | LED off | At second boundary | -| '.' | End pattern | - | +| 'a'-'j' | LED 关 | 0.1-1.0 秒 | +| 'A'-'J' | LED 开 | 0.1-1.0 秒 | +| 'U' | LED 开 | 在秒边界 | +| 'u' | LED 关 | 在秒边界 | +| '.' | 结束模式 | - | -Example patterns and their effects: +示例模式及其效果: -- "Aa" -> blink at ~2.5Hz (0.1s on, 0.1s off) -- "AjAj" -> slow blink at 0.5Hz (1s on, 1s off) -- "AaAaBjBj" -> fast double blink, long pause -- "U" -> steady on, synced to seconds -- "Uu" -> 1Hz toggle +- "Aa" -> 以约 2.5Hz 闪烁(0.1s 开,0.1s 关) +- "AjAj" -> 以 0.5Hz 慢闪(1s 开,1s 关) +- "AaAaBjBj" -> 快速双闪,长暂停 +- "U" -> 稳定开启,与秒同步 +- "Uu" -> 1Hz 切换 -This compact encoding allows complex blink behaviors from short strings, all interpreted by this one timer callback serving all LEDs in the system. +这种紧凑编码允许从短字符串产生复杂的闪烁行为,全部由这一个服务系统中所有 LED 的定时器回调解释。 -#### 3) Apply a new state/pattern: `led_state()` +#### 3) 应用新的状态/模式:`led_state()` -Given a compiled pattern (sbuf) or a simple on/off flag, this function updates the softc and starts or stops the periodic timer. +给定一个编译好的模式(sbuf)或简单的开/关标志,此函数更新 softc 并启动或停止周期性定时器。 ```c 88: static int @@ -5786,11 +5787,11 @@ Given a compiled pattern (sbuf) or a simple on/off flag, this function updates t 112: } ``` -##### LED State Management: Installing Patterns +##### LED 状态管理:安装模式 -The `led_state` function installs a new blink pattern or static state for an LED. It handles the transition between different LED modes, managing memory for pattern strings, updating the blinker counter for timer control, and invoking hardware callbacks when needed. This function is the central state change coordinator called by both the write handler and the kernel API. +`led_state` 函数为 LED 安装新的闪烁模式或静态状态。它处理不同 LED 模式之间的转换,管理模式字符串的内存,更新用于定时器控制的闪烁计数器,并在需要时调用硬件回调。此函数是写入处理程序和内核 API 调用的中央状态变更协调器。 -##### Function Signature and Pattern Swap +##### 函数签名与模式交换 ```c static int @@ -5802,17 +5803,17 @@ led_state(struct ledsc *sc, struct sbuf **sb, int state) sc->spec = *sb; ``` -**Parameters**: The function receives three values: +**参数**:该函数接收三个值: -- `sc` - the LED whose state is being changed -- `sb` - pointer to a pointer to a string buffer containing the new pattern (or NULL for static state) -- `state` - the desired static state (0 or 1) if no pattern is provided +- `sc` - 状态正在被改变的 LED +- `sb` - 指向字符串缓冲区指针的指针,该缓冲区包含新模式(若为 NULL 则为静态状态) +- `state` - 未提供模式时的目标静态状态(0 或 1) -**The double pointer pattern**: The `sb` parameter is `struct sbuf **`, allowing the function to swap buffers with the caller. The function takes ownership of the caller's buffer and returns the old buffer for cleanup. This swap avoids copying pattern strings and ensures proper memory management. +**双指针模式**:`sb` 参数是 `struct sbuf **`,允许函数与调用者交换缓冲区。函数取得调用者缓冲区的所有权,并返回旧缓冲区以供清理。这种交换避免了复制模式字符串,并确保了正确的内存管理。 -**Preserving the old pattern**: `sb2 = sc->spec` saves the current pattern buffer before installing the new one. At function end, this old buffer is returned to the caller via `*sb = sb2`. The caller becomes responsible for freeing it with `sbuf_delete()`. +**保留旧模式**:`sb2 = sc->spec` 在安装新缓冲区之前保存当前的模式缓冲区。在函数末尾,通过 `*sb = sb2` 将此旧缓冲区返回给调用者。调用者负责使用 `sbuf_delete()` 释放它。 -##### Installing a Blink Pattern +##### 安装闪烁模式 ```c if (*sb != NULL) { @@ -5824,19 +5825,19 @@ if (*sb != NULL) { sc->ptr = sc->str; ``` -When the caller provides a pattern (non-NULL `sb`), the function activates pattern mode. +当调用者提供一个模式(非 NULL 的 `sb`)时,函数激活模式模式。 -**Freeing the old string**: If `sc->str` is non-NULL, a previous pattern's string exists and must be freed. The `free(sc->str, M_LED)` call releases this memory back to the kernel heap. The `M_LED` tag matches the allocation type used during `strdup()`, maintaining accounting consistency. +**释放旧字符串**:如果 `sc->str` 非 NULL,则存在之前的模式字符串,必须释放它。调用 `free(sc->str, M_LED)` 将此内存归还给内核堆。标签 `M_LED` 与 `strdup()` 期间使用的分配类型匹配,保持了记账的一致性。 -**Duplicating the new pattern**: `sbuf_data(*sb)` extracts the null-terminated string from the string buffer, and `strdup(name, M_LED)` allocates memory and copies it. The pattern string must persist because the timer callback will traverse it repeatedly, the string buffer itself may be deleted by the caller, so a separate copy is needed. +**复制新模式**:`sbuf_data(*sb)` 从字符串缓冲区提取以空字符结尾的字符串,`strdup(name, M_LED)` 分配内存并复制它。模式字符串必须持久存在,因为定时器回调会反复遍历它;而字符串缓冲区本身可能被调用者删除,因此需要一个独立的副本。 -**Activating the timer**: The check `if (sc->ptr == NULL)` detects whether this LED was previously inactive. If so, incrementing `blinkers++` records that one more LED now needs timer servicing. The timer callback checks this counter at the end of each run; transitioning from 0 to 1 causes the timer to be rescheduled. +**激活定时器**:检查 `if (sc->ptr == NULL)` 检测此 LED 之前是否处于非活动状态。如果是,则递增 `blinkers++`,记录又多了一个需要定时器服务的 LED。定时器回调在每次运行结束时检查此计数器;从 0 变为 1 会导致定时器被重新调度。 -**Starting pattern execution**: `sc->ptr = sc->str` sets the pattern position to the beginning. On the next timer tick, `led_timeout` will process this LED's first pattern character. +**开始模式执行**:`sc->ptr = sc->str` 将模式位置设置为开头。在下一个定时器滴答时,`led_timeout` 将处理此 LED 的第一个模式字符。 -**Why not start the timer here?**: The timer might already be running if other LEDs have active patterns. The `blinkers` counter tracks this: if it was already non-zero, the timer is already scheduled and will process this LED on its next tick. Only when `blinkers` transitions from 0 to 1 (detected in the write handler or `led_set()`) does the timer need explicit scheduling. +**为何不在此处启动定时器?**:如果其他 LED 已有活动模式,定时器可能已经在运行。`blinkers` 计数器跟踪这一点:如果它已经非零,定时器已经被调度,并将在其下一个滴答时处理此 LED。只有当 `blinkers` 从 0 变为 1(在写处理程序或 `led_set()` 中检测)时,才需要显式调度定时器。 -##### Installing Static State +##### 安装静态状态 ```c } else { @@ -5848,43 +5849,43 @@ When the caller provides a pattern (non-NULL `sb`), the function activates patte } ``` -When the caller passes NULL for `sb`, the LED should be set to a static on/off state without blinking. +当调用者为 `sb` 传递 NULL 时,LED 应被设置为静态开/关状态,不闪烁。 -**Clearing pattern state**: Setting `sc->str = NULL` marks that no pattern string exists. This field is checked during cleanup to determine if memory needs freeing. +**清除模式状态**:将 `sc->str = NULL` 标记为不存在模式字符串。在清理期间检查此字段,以确定是否需要释放内存。 -**Deactivating the timer**: The check `if (sc->ptr != NULL)` detects whether this LED was previously executing a pattern. If so, decrementing `blinkers--` records that one fewer LED needs timer servicing. If this was the last active LED, `blinkers` drops to zero and the timer callback won't reschedule itself, stopping timer firings. +**停用定时器**:检查 `if (sc->ptr != NULL)` 检测此 LED 之前是否正在执行模式。如果是,递减 `blinkers--`,记录少了一个需要定时器服务的 LED。如果这是最后一个活动的 LED,`blinkers` 降至零,定时器回调将不会重新调度自身,从而停止定时器触发。 -**Setting to NULL**: `sc->ptr = NULL` marks this LED as inactive. The timer callback's first check (`if (sc->ptr == NULL) continue;`) will skip this LED on all future ticks. +**设置为 NULL**:`sc->ptr = NULL` 将此 LED 标记为非活动。定时器回调的第一个检查(`if (sc->ptr == NULL) continue;`)将在未来的所有滴答中跳过此 LED。 -**Immediate hardware update**: `sc->func(sc->private, state)` invokes the hardware driver's control callback to set the LED to the requested state (0 for off, 1 for on). Unlike pattern mode where the timer controls LED changes, static mode requires immediate hardware update since no timer is involved. +**立即更新硬件**:`sc->func(sc->private, state)` 调用硬件驱动的控制回调,将 LED 设置为请求的状态(0 为关,1 为开)。与由定时器控制 LED 变化的模式模式不同,静态模式需要立即更新硬件,因为不涉及定时器。 -##### Resetting Delay Counter +##### 重置延迟计数器 ```c sc->count = 0; ``` -The delay counter is zeroed regardless of which path was taken. If a pattern is being installed, starting with `count = 0` ensures the first pattern character executes immediately without inherited delay. If static state is being set, zeroing is harmless since the field isn't used when `ptr` is NULL. +无论走哪条路径,延迟计数器都会被清零。如果正在安装模式,以 `count = 0` 开始确保第一个模式字符立即执行,而不会继承延迟。如果正在设置静态状态,清零无害,因为当 `ptr` 为 NULL 时该字段不被使用。 -##### Returning the Old Pattern +##### 返回旧模式 ```c *sb = sb2; return(0); ``` -The function returns the previous pattern buffer through the double pointer. The caller receives either: +函数通过双指针返回之前的模式缓冲区。调用者接收的值要么是: -- NULL if no previous pattern existed -- The old `sbuf` if a pattern is being replaced +- 如果之前没有模式存在则返回 NULL +- 旧的 `sbuf`(如果正在替换一个模式) -The caller must check this returned value and call `sbuf_delete()` if non-NULL to free the buffer's memory. This ownership transfer pattern prevents memory leaks while avoiding unnecessary copying. +调用者必须检查这个返回值,如果非 NULL,则调用 `sbuf_delete()` 来释放缓冲区的内存。这种所有权转移模式可以防止内存泄漏,同时避免不必要的复制。 -The return value 0 signals success. This function currently cannot fail, but returning an error code provides future extensibility if validation or resource allocation were added. +返回值为 0 表示成功。该函数当前不会失败,但返回错误码为将来添加验证或资源分配提供了可扩展性。 -##### State Transition Examples +##### 状态转换示例 -**Setting initial pattern on inactive LED**: +**在非活动 LED 上设置初始模式**: ```text Before: sc->ptr = NULL, sc->spec = NULL, blinkers = 0 @@ -5893,7 +5894,7 @@ After: sc->ptr = sc->str, sc->spec = pattern_sb, blinkers = 1 Old NULL returned to caller ``` -**Replacing one pattern with another**: +**用一个模式替换另一个模式**: ```text Before: sc->ptr = old_str, sc->spec = old_sb, blinkers = 3 @@ -5902,7 +5903,7 @@ After: sc->ptr = new_str, sc->spec = new_sb, blinkers = 3 Old old_sb returned to caller for deletion ``` -**Changing from pattern to static**: +**从模式切换到静态**: ```text Before: sc->ptr = pattern_str, sc->spec = pattern_sb, blinkers = 1 @@ -5912,7 +5913,7 @@ After: sc->ptr = NULL, sc->spec = NULL, blinkers = 0 Old pattern_sb returned to caller for deletion ``` -**Setting static state on already-static LED**: +**在已经是静态的 LED 上设置静态状态**: ```text Before: sc->ptr = NULL, sc->spec = NULL, blinkers = 0 @@ -5922,29 +5923,29 @@ After: sc->ptr = NULL, sc->spec = NULL, blinkers = 0 Old NULL returned to caller ``` -##### Thread Safety Considerations +##### 线程安全注意事项 -This function operates under the protection of `led_mtx`, acquired by the caller (write handler or `led_set()`). The mutex serializes state changes and protects: +此函数在 `led_mtx` 的保护下运行,该互斥锁由调用者(写处理程序或 `led_set()`)获取。互斥锁序列化状态更改并保护: -- The `blinkers` counter from races when multiple LEDs change state simultaneously -- Individual LED fields (`ptr`, `str`, `spec`, `count`) from corruption -- The relationship between `blinkers` count and actual active patterns +- `blinkers` 计数器免受竞态,当多个 LED 同时改变状态时 +- 单个 LED 字段(`ptr`、`str`、`spec`、`count`)免受损坏 +- `blinkers` 计数与实际活动模式之间的关系 -Without the mutex, two simultaneous writes could both increment `blinkers`, creating an incorrect count. Or one thread could free `sc->str` while the timer callback traverses it, causing a use-after-free crash. +没有互斥锁时,两个同时写入可能会同时增加 `blinkers`,导致计数不正确。或者一个线程可能释放 `sc->str`,而定时器回调正在遍历它,导致释放后使用崩溃。 -##### Memory Management Discipline +##### 内存管理规范 -The function demonstrates careful memory management: +该函数展示了谨慎的内存管理: -**Ownership transfer**: The caller gives up the new `sbuf` and receives the old one, establishing clear ownership at all times. +**所有权转移**:调用者放弃新的 `sbuf` 并接收旧的 `sbuf`,从而始终保持明确的所有权。 -**Paired allocation/free**: Every `strdup()` has a corresponding `free()`, preventing leaks even when patterns are repeatedly replaced. +**成对的分配/释放**:每个 `strdup()` 都有对应的 `free()`,即使在模式被重复替换时也能防止泄漏。 -**NULL tolerance**: All checks handle NULL pointers gracefully, allowing transitions to/from uninitialized state without special cases. +**NULL 容错**:所有检查都能优雅地处理 NULL 指针,允许在未初始化状态之间转换而无需特殊情况。 -This discipline prevents the common pattern-replacement bug where updating state leaks the old pattern's memory. +这种纪律防止了常见的模式替换错误,即更新状态时泄漏旧模式的内存。 -#### 4) Parse user commands into patterns: `led_parse()` +#### 4) 将用户命令解析为模式:`led_parse()` ```c 116: static int @@ -5997,11 +5998,11 @@ This discipline prevents the common pattern-replacement bug where updating state 210: } ``` -##### Pattern Parser: User Commands to Internal Codes +##### 模式解析器:从用户命令到内部编码 -The `led_parse` function translates human-friendly pattern specifications from userspace into the internal timing code language that the timer callback interprets. This parser allows users to write simple commands like "f" for flashing or "m...---..." for morse code, which are expanded into sequences of timing codes like "AaAa" or "aAaAaCaCaC". +`led_parse` 函数将来自用户空间的友好模式规范翻译成定时器回调解释的内部定时代码语言。该解析器允许用户编写简单的命令,例如用于闪烁的 "f" 或用于摩尔斯电码的 "m...---...",这些命令被扩展为诸如 "AaAa" 或 "aAaAaCaCaC" 的定时代码序列。 -##### Function Signature and Quick Static Path +##### 函数签名与快速静态路径 ```c static int @@ -6016,17 +6017,17 @@ led_parse(const char *s, struct sbuf **sb, int *state) } ``` -**Parameters**: The parser receives three values: +**参数**:解析器接收三个值: -- `s` - the user's input string from the write operation -- `sb` - pointer to a pointer where the allocated string buffer will be returned -- `state` - pointer where static state (0 or 1) is returned for non-pattern commands +- `s` - 来自写操作的用户输入字符串 +- `sb` - 指向指针的指针,用于返回已分配的字符串缓冲区 +- `state` - 指向用于非模式命令的静态状态(0 或 1)的指针 -**Fast path for static state**: Commands "0" and "1" request static off and on respectively. The expression `*s & 1` extracts the low bit of the ASCII character: '0' (0x30) & 1 = 0, '1' (0x31) & 1 = 1. This value is written to `*state` and the function returns immediately without allocating a string buffer. The caller receives `*sb = NULL` (never assigned) and knows to use `led_state()` with static mode. +**静态状态的快速路径**:命令 "0" 和 "1" 分别请求静态关闭和打开。表达式 `*s & 1` 提取 ASCII 字符的低位:'0' (0x30) & 1 = 0,'1' (0x31) & 1 = 1。该值写入 `*state`,函数立即返回而不分配字符串缓冲区。调用者接收到 `*sb = NULL`(从未赋值),并知道使用 `led_state()` 配合静态模式。 -This fast path handles the most common case efficiently, toggling LEDs on or off without complex timing. +该快速路径高效处理最常见的情况,即打开或关闭 LED 而无需复杂的定时。 -##### String Buffer Allocation +##### 字符串缓冲区分配 ```c *state = 0; @@ -6035,23 +6036,23 @@ if (*sb == NULL) return (ENOMEM); ``` -For pattern commands, a string buffer is needed to build the internal code sequence. +对于模式命令,需要一个字符串缓冲区来构建内部代码序列。 -**Default state**: Setting `*state = 0` provides a default in case the pattern is used, though this value is ignored when `*sb` is non-NULL. +**默认状态**:设置 `*state = 0` 为使用该模式时提供一个默认值,但当 `*sb` 非 NULL 时,此值会被忽略。 -**Creating auto-sizing buffer**: `sbuf_new_auto()` allocates a string buffer that automatically grows as data is appended. This eliminates the need to pre-calculate pattern length. Morse code for a long message might produce a very long code sequence, but the buffer expands as needed. +**创建自动调整大小的缓冲区**:`sbuf_new_auto()` 分配一个字符串缓冲区,该缓冲区会在追加数据时自动增长。这消除了预先计算模式长度的需求。长消息的摩尔斯电码可能会产生很长的代码序列,但缓冲区会根据需要扩展。 -**Handling allocation failure**: If memory is exhausted, the function returns `ENOMEM` immediately. The caller checks this error and propagates it to userspace, where the write operation fails with "Cannot allocate memory." +**处理分配失败**:如果内存耗尽,该函数立即返回 `ENOMEM`。调用者检查此错误并将其传播到用户空间,在那里写入操作失败并返回“无法分配内存”。 -##### Pattern Dispatch +##### 模式分发 ```c switch(s[0]) { ``` -The first character determines the pattern type. Each case implements a different pattern language, expanding user input into timing codes. +第一个字符决定模式类型。每个 case 实现不同的模式语言,将用户输入扩展为时序代码。 -##### Flash Pattern: Simple Blinking +##### 闪烁模式:简单的闪烁 ```c case 'f': /* blink (default 100/100ms); 'f2' => 200/200ms */ @@ -6060,21 +6061,21 @@ case 'f': /* blink (default 100/100ms); 'f2' => 200/200ms */ break; ``` -The 'f' command creates a symmetric blink pattern, with equal on and off times. +'f' 命令创建一个对称的闪烁模式,开和关的时间相等。 -**Speed modifier**: If a digit follows 'f', it specifies the blink speed: +**速度修饰符**:如果 'f' 后面跟着数字,则指定闪烁速度: -- "f" or "f1" -> `i = 0` -> pattern "Aa" -> 0.1s on, 0.1s off (~2.5Hz) -- "f2" -> `i = 1` -> pattern "Bb" -> 0.2s on, 0.2s off (~1.25Hz) -- "f3" -> `i = 2` -> pattern "Cc" -> 0.3s on, 0.3s off (~0.83Hz) +- "f" 或 "f1" -> `i = 0` -> 模式 "Aa" -> 开 0.1 秒,关 0.1 秒(约 2.5Hz) +- "f2" -> `i = 1` -> 模式 "Bb" -> 开 0.2 秒,关 0.2 秒(约 1.25Hz) +- "f3" -> `i = 2` -> 模式 "Cc" -> 开 0.3 秒,关 0.3 秒(约 0.83Hz) - ... -- "f9" -> `i = 8` -> pattern "Ii" -> 0.9s on, 0.9s off (~0.56Hz) +- "f9" -> `i = 8` -> 模式 "Ii" -> 开 0.9 秒,关 0.9 秒(约 0.56Hz) -**Pattern construction**: `sbuf_printf(*sb, "%c%c", 'A' + i, 'a' + i)` generates two characters: an uppercase letter (on state) followed by the corresponding lowercase letter (off state). Both use the same duration, creating symmetric blinking. +**模式构建**:`sbuf_printf(*sb, "%c%c", 'A' + i, 'a' + i)` 生成两个字符:一个大写字母(开状态)后跟相应的小写字母(关状态)。两者使用相同的持续时间,从而创建对称闪烁。 -This simple two-character pattern repeats indefinitely, providing the classic blink indicator effect. +这个简单的两字符模式无限重复,提供经典的闪烁指示灯效果。 -##### Digit Flash Pattern: Counting Blinks +##### 数字闪烁模式:计数闪烁 ```c case 'd': /* "digits": flash out numbers 0..9 */ @@ -6088,24 +6089,24 @@ case 'd': /* "digits": flash out numbers 0..9 */ break; ``` -The 'd' command followed by digits creates patterns that visually "count" by flashing the LED. +'d' 命令后跟数字,通过闪烁 LED 创建视觉“计数”模式。 -**Parsing digits**: The loop advances past the 'd' command character (`s++`) and examines each subsequent character. Non-digits are silently skipped with `continue`, allowing "d1x2y3" to be interpreted as "d123". +**解析数字**:循环跳过 'd' 命令字符(`s++`)并检查每个后续字符。非数字字符通过 `continue` 静默跳过,允许将 "d1x2y3" 解释为 "d123"。 -**Digit mapping**: `i = *s - '0'` converts ASCII digit to numeric value. The special case `if (i == 0) i = 10` treats zero as ten flashes rather than no flashes, making it distinguishable from the inter-digit pause. +**数字映射**:`i = *s - '0'` 将 ASCII 数字转换为数值。特殊情况 `if (i == 0) i = 10` 将零视为十次闪烁而非零次闪烁,使其与数字间暂停区分开。 -**Flash generation**: For digit value `i`: +**闪烁生成**:对于数字值 `i`: -- Generate `i-1` quick flashes: `for (; i > 1; i--) sbuf_cat(*sb, "Aa")` -- Add one longer flash: `sbuf_cat(*sb, "Aj")` +- 生成 `i-1` 次快速闪烁:`for (; i > 1; i--) sbuf_cat(*sb, "Aa")` +- 增加一次较长的闪烁:`sbuf_cat(*sb, "Aj")` -Example for digit 3: two quick flashes "AaAa" plus one 1-second flash "Aj". +数字 3 的示例:两次快速闪烁 "AaAa" 加上一次 1 秒闪烁 "Aj"。 -**Digit separation**: After all digits are processed, `sbuf_cat(*sb, "jj")` appends a 2-second pause before the pattern repeats, clearly separating repetitions. +**数字分隔**:处理完所有数字后,`sbuf_cat(*sb, "jj")` 在模式重复前追加一个 2 秒的暂停,以清晰分隔重复。 -**Result**: Command "d12" generates pattern "AjAjAaAjjj" meaning: 1-second flash (digit 1), pause, quick flash then 1-second flash (digit 2), long pause, repeat. This allows reading numbers from LED blinks, valid for diagnostic codes. +**结果**:命令 "d12" 生成模式 "AjAjAaAjjj",含义为:1 秒闪烁(数字 1)、暂停、快速闪烁然后 1 秒闪烁(数字 2)、长暂停、重复。这使得可以通过 LED 闪烁读取数字,适用于诊断代码。 -##### Morse Code Pattern +##### 莫尔斯电码模式 ```c case 'm': /* Morse: '.' -> short, '-' -> long, ' ' -> space */ @@ -6119,30 +6120,30 @@ case 'm': /* Morse: '.' -> short, '-' -> long, ' ' -> space */ break; ``` -The 'm' command interprets the following characters as morse code elements. +'m' 命令将后续字符解释为摩尔斯电码元素。 -**Morse element mapping**: +**莫尔斯码元素映射**: -- '.' (dot) -> "aA" -> 0.1s off, 0.1s on (short flash) -- '-' (dash) -> "aC" -> 0.1s off, 0.3s on (long flash) -- ' ' (space) -> "b" -> 0.2s off (word separator) -- '\\n' (newline) -> "d" -> 0.4s off (long pause between messages) +- '.'(点)-> "aA" -> 关 0.1 秒,开 0.1 秒(短闪) +- '-'(划)-> "aC" -> 关 0.1 秒,开 0.3 秒(长闪) +- ' '(空格)-> "b" -> 关 0.2 秒(单词分隔符) +- '\\n'(换行符) -> "d" -> 0.4 秒关(消息间的长暂停) -**Standard morse timing**: International morse code specifies: +**标准莫尔斯时序**:国际莫尔斯码规定: -- Dot: 1 unit -- Dash: 3 units -- Gap between elements: 1 unit -- Gap between letters: 3 units (approximated by the trailing pause in each letter) -- Gap between words: 7 units (space character) +- 点:1 个单位 +- 划:3 个单位 +- 元素间间隔:1 个单位 +- 字母间间隔:3 个单位(由每个字母末尾的暂停近似) +- 单词间间隔:7 个单位(空格字符) -The pattern "aA" gives dot (1 unit off, 1 unit on), "aC" gives dash (1 unit off, 3 units on), with each unit being 0.1 seconds. +模式 "aA" 表示点(1 个单位关,1 个单位开),"aC" 表示划(1 个单位关,3 个单位开),每个单位为 0.1 秒。 -**Pattern termination**: `sbuf_cat(*sb, "j")` adds a 1-second pause before the message repeats, separating consecutive transmissions. +**模式终止**:`sbuf_cat(*sb, "j")` 在消息重复前添加一个 1 秒的暂停,以分隔连续传输。 -**Example**: Command "m... ---" (SOS) generates "aAaAaAaCaCaC" meaning: dot-dot-dot, dash-dash-dash, repeat. +**示例**:命令 "m... ---"(SOS)生成 "aAaAaAaCaCaC",含义是:点-点-点,划-划-划,重复。 -##### Error Handling for Unknown Commands +##### 未知命令的错误处理 ```c default: @@ -6151,11 +6152,11 @@ default: } ``` -If the first character doesn't match any known pattern type, the function rejects the command. The allocated string buffer is freed with `sbuf_delete()` to prevent leaks, and `EINVAL` (invalid argument) is returned to indicate bad user input. +如果第一个字符不匹配任何已知模式类型,函数将拒绝该命令。分配的字符串缓冲区通过 `sbuf_delete()` 释放以防止泄漏,并返回 `EINVAL`(无效参数)以指示错误的用户输入。 -The write operation will fail and return -1 to userspace with `errno = EINVAL`, informing the user that their command syntax is incorrect. +写入操作将失败并向用户空间返回 -1,设置 `errno = EINVAL`,告知用户其命令语法不正确。 -##### Finalizing the Pattern String +##### 最终确定模式字符串 ```c error = sbuf_finish(*sb); @@ -6166,33 +6167,33 @@ if (error != 0 || sbuf_len(*sb) == 0) { return (0); ``` -**Sealing the buffer**: `sbuf_finish()` finalizes the string buffer, null-terminating it and marking it read-only. After this call, the buffer's contents can be extracted with `sbuf_data()` but no further appends are allowed. +**封存缓冲区**:`sbuf_finish()` 完成字符串缓冲区的处理,为其添加空字符终止符并标记为只读。调用此函数后,可通过 `sbuf_data()` 提取缓冲区内容,但不再允许追加操作。 -**Validation**: Two error conditions are checked: +**验证**:检查两种错误情况: -- `error != 0` - `sbuf_finish()` failed, typically due to memory exhaustion during a buffer resize -- `sbuf_len(*sb) == 0` - the pattern is empty, which shouldn't happen but is checked defensively +- `error != 0` - `sbuf_finish()` 失败,通常是由于缓冲区调整大小时内存耗尽 +- `sbuf_len(*sb) == 0` - 模式为空,这种情况不应发生,但进行防御性检查 -If either condition holds, the buffer is unusable. Setting `*sb = NULL` signals the caller that no pattern was generated, and the error code is returned. The caller must not attempt to use or free the buffer; it was already freed by `sbuf_finish()` on error. +如果任一条件成立,则缓冲区不可用。将 `*sb` 设置为 `NULL` 向调用者表明未生成任何模式,并返回错误代码。调用者不得尝试使用或释放该缓冲区;出错时 `sbuf_finish()` 已将其释放。 -**Success**: Returning 0 with `*sb` pointing to a valid buffer signals successful parsing. The caller now owns the buffer and must eventually free it with `sbuf_delete()`. +**成功**:返回 0 且 `*sb` 指向有效缓冲区,表示解析成功。调用者现在拥有该缓冲区,并最终必须通过 `sbuf_delete()` 释放它。 -##### Pattern Language Summary +##### 模式语言总结 -The parser supports several pattern languages, each optimized for different use cases: +解析器支持多种模式语言,每种语言针对不同用例进行了优化: -| Command | Purpose | Example | Result | +| 命令 | 用途 | 示例 | 结果 | | --------- | ---------------- | ------- | -------------------- | -| 0, 1 | Static state | "1" | LED on steady | -| f[1-9] | Symmetric blink | "f" | Fast blink | -| d[digits] | Count by flashes | "d42" | 4 flashes, 2 flashes | -| m[morse] | Morse code | "msos" | ... --- ... | +| 0, 1 | 静态状态 | "1" | LED 常亮 | +| f[1-9] | 对称闪烁 | "f" | 快速闪烁 | +| d[数字] | 按闪烁计数 | "d42" | 4 次闪烁, 2 次闪烁 | +| m[摩尔斯] | 摩尔斯电码 | "msos" | ... --- ... | -This variety allows users to express intent naturally without memorizing timing code syntax. The write handler accepts simple commands; the parser expands them to precise timing sequences; the timer executes those sequences. +这种多样性使用户能够自然地表达意图,而无需记忆时序代码语法。写处理程序接受简单命令;解析器将其扩展为精确的时序序列;定时器执行这些序列。 -#### 5.1) The write entry point: `echo "cmd" > /dev/led/` +#### 5.1) 写入口点:`echo "cmd" > /dev/led/` -User space **writes a command string** to the device. The driver parses it and updates the LED's state. The **shape** is exactly what you'll write later: `uiomove()` the user buffer, parse, then update the softc under a lock. +用户空间**将命令字符串写入**设备。驱动程序解析该命令并更新 LED 状态。**步骤**与稍后将要编写的代码完全相同:`uiomove()` 获取用户缓冲区,解析,然后在锁下更新 softc。 ```c 212: static int @@ -6222,11 +6223,11 @@ User space **writes a command string** to the device. The driver parses it and u 237: } ``` -##### Write Handler: User Command Interface +##### 写入处理程序:用户命令接口 -The `led_write` function implements the character device write operation for `/dev/led/*` devices. When a user writes a pattern command like "f" or "m...---..." to an LED device node, this function copies the data from userspace, parses it into an internal format, and installs the new LED pattern. +`led_write` 函数实现了 `/dev/led/*` 设备的字符设备写操作。当用户向 LED 设备节点写入类似 "f" 或 "m...---..." 的模式命令时,该函数将数据从用户空间复制进来,解析为内部格式,并安装新的 LED 模式。 -##### Size Validation and Buffer Allocation +##### 大小验证与缓冲区分配 ```c static int @@ -6243,30 +6244,30 @@ led_write(struct cdev *dev, struct uio *uio, int ioflag) s[uio->uio_resid] = '\0'; ``` -**Size limit enforcement**: The check `uio->uio_resid > 512` rejects writes larger than 512 bytes. LED patterns are short text commands, even complex morse code messages rarely exceed a few dozen characters. This limit prevents memory exhaustion from malicious or buggy programs attempting multi-megabyte writes. +**大小限制执行**:检查 `uio->uio_resid > 512`,拒绝超过 512 字节的写入。LED 模式是短文本命令,即使是复杂的摩尔斯电码消息也极少超过几十个字符。此限制防止恶意或有缺陷的程序尝试写入数兆字节而导致内存耗尽。 -Returning `EINVAL` signals invalid argument to userspace. The write fails immediately without allocating memory or touching the LED state. +返回 `EINVAL` 向用户空间指示无效参数。写入立即失败,不分配内存也不触及 LED 状态。 -**Temporary buffer allocation**: Unlike the null driver's `null_write`, which never accesses user data, the LED driver must examine the written bytes to parse commands. The allocation reserves `uio->uio_resid + 1` bytes, the exact write size plus one byte for null termination. +**临时缓冲区分配**:与从不访问用户数据的空驱动程序的 `null_write` 不同,LED 驱动程序必须检查写入的字节以解析命令。分配预留 `uio->uio_resid + 1` 个字节,即确切写入大小加上一个字节用于空终止符。 -The `M_DEVBUF` allocation type is generic for device driver temporary buffers. The `M_WAITOK` flag allows the allocation to sleep if memory is temporarily unavailable, which is acceptable since this is a blocking write operation with no stringent latency requirements. +`M_DEVBUF` 分配类型是设备驱动程序临时缓冲区的通用类型。`M_WAITOK` 标志允许在内存暂时不可用时分配操作休眠,这是可以接受的,因为这是阻塞写操作,没有严格的延迟要求。 -**Null termination**: Setting `s[uio->uio_resid] = '\0'` ensures the buffer is a proper C string. The `uiomove` call will fill the first `uio->uio_resid` bytes with user data, and this assignment adds the terminator immediately after. String functions like those used in parsing require null-terminated strings. +**空终止符**:设置 `s[uio->uio_resid] = '\0'` 确保缓冲区是合法的 C 字符串。`uiomove` 调用将用用户数据填充前 `uio->uio_resid` 个字节,此赋值紧随其后添加终止符。解析中使用的字符串函数需要空终止字符串。 -##### Copying Data from Userspace +##### 从用户空间复制数据 ```c error = uiomove(s, uio->uio_resid, uio); if (error) { free(s, M_DEVBUF); return (error); } ``` -The `uiomove` function transfers `uio->uio_resid` bytes from the user's buffer (described by `uio`) into the kernel buffer `s`. This is the same function used in the null and zero drivers for data transfer between address spaces. +`uiomove` 函数将 `uio->uio_resid` 个字节从用户缓冲区(由 `uio` 描述)传输到内核缓冲区 `s`。这与空驱动程序和零驱动程序中用于地址空间间数据传输的函数相同。 -**Error handling**: If `uiomove` fails (typically `EFAULT` for an invalid user pointer), the allocated buffer is freed immediately with `free(s, M_DEVBUF)` and the error propagates to userspace. The write fails without modifying LED state, and the temporary buffer doesn't leak. +**错误处理**:如果 `uiomove` 失败(通常因无效用户指针返回 `EFAULT`),则立即用 `free(s, M_DEVBUF)` 释放分配的缓冲区,并将错误传播到用户空间。写入失败而不修改 LED 状态,临时缓冲区不会泄漏。 -This cleanup discipline is critical, kernel code must free allocated memory on all error paths, not just success paths. +这种清理规范至关重要:内核代码必须在所有错误路径上释放分配的内存,而不仅仅是成功路径。 -##### Parsing the Command +##### 解析命令 ```c /* parse -> (sb pattern) or (state only) */ @@ -6275,18 +6276,18 @@ free(s, M_DEVBUF); if (error) return (error); ``` -**Translation to internal format**: The `led_parse` function interprets the user's command string, producing either: +**转换为内部格式**:`led_parse` 函数解释用户命令字符串,产生以下结果之一: -- A string buffer (`sb`) containing timing codes for pattern mode -- A state value (0 or 1) for static on/off mode +- 包含模式模式时序码的字符串缓冲区(`sb`) +- 用于静态开/关模式的状态值(0 或 1) -The parser determines which mode based on the command's first character. Commands like "f", "d", "m" generate patterns; commands "0" and "1" set static state. +解析器根据命令的第一个字符确定模式。像"f"、"d"、"m"这样的命令生成模式;命令"0"和"1"设置静态状态。 -**Immediate cleanup**: The temporary buffer `s` is no longer needed after parsing, whether parsing succeeded or failed, the original command string is no longer required. Freeing it immediately rather than waiting until function end reduces memory consumption in the common case where parsing succeeds and additional processing follows. +**立即清理**:解析完成后,无论成功与否,临时缓冲区 `s` 不再需要,原始命令字符串也不再需要。立即释放它而不是等到函数结束,可以减少内存消耗,这在解析成功并需要后续处理的常见情况下尤其有效。 -**Error propagation**: If parsing fails (unrecognized command, memory exhaustion, empty pattern), the error is returned to userspace. The write operation fails before acquiring locks or modifying LED state. Users see the write fail with `errno` set to the parser's error code (typically `EINVAL` for bad syntax or `ENOMEM` for resource exhaustion). +**错误传播**:如果解析失败(无法识别的命令、内存耗尽、空模式),则错误返回用户空间。写操作在获取锁或修改LED状态之前失败。用户看到写入失败,`errno` 被设置成解析器的错误代码(通常语法错误为 `EINVAL`,资源耗尽为 `ENOMEM`)。 -##### Installing the New State +##### 安装新状态 ```c mtx_lock(&led_mtx); @@ -6296,37 +6297,37 @@ if (sc != NULL) mtx_unlock(&led_mtx); ``` -**Acquiring the lock**: The `led_mtx` mutex protects the LED list and per-LED state from concurrent modification. Multiple threads might write to different LEDs simultaneously, or a write might race with timer callbacks updating blink patterns. The mutex serializes these operations. +**获取锁**:`led_mtx` 互斥锁保护LED链表和每个LED的状态免受并发修改。多个线程可能同时写入不同的LED,或者一次写入可能与更新闪烁模式的定时器回调竞争。该互斥锁序列化这些操作。 -**Retrieving the LED context**: `dev->si_drv1` provides the `ledsc` structure for this device, established during `led_create()`. This pointer links the character device node to its LED state. +**获取LED上下文**:`dev->si_drv1` 提供此设备的 `ledsc` 结构,该结构在 `led_create()` 期间建立。此指针将字符设备节点链接到其LED状态。 -**Defensive NULL check**: The condition `if (sc != NULL)` guards against a race where the LED is being destroyed while a write is in progress. If `led_destroy()` has cleared `si_drv1` but the write handler is still executing, this check prevents dereferencing NULL. In practice, proper reference counting makes this unlikely, but defensive checks prevent kernel panics. +**防御性NULL检查**:条件 `if (sc != NULL)` 防止在写入进行时LED被销毁的竞态。如果 `led_destroy()` 已清除 `si_drv1` 但写处理程序仍在执行,此检查可防止解引用NULL。实践中,适当的引用计数使得这种情况不太可能发生,但防御性检查可防止内核崩溃。 -**State installation**: `led_state(sc, &sb, state)` installs the new pattern or static state. This function: +**状态安装**:`led_state(sc, &sb, state)` 安装新模式或静态状态。此函数: -- Swaps the new pattern buffer with the old one -- Updates `blinkers` counter if the LED transitions between active and inactive -- Calls the hardware driver's callback for static state changes -- Returns the old pattern buffer via the `sb` pointer +- 将新模式缓冲区与旧模式缓冲区交换 +- 如果LED在激活与非激活之间转换,则更新 `blinkers` 计数器 +- 对静态状态变化调用硬件驱动程序回调 +- 通过 `sb` 指针返回旧模式缓冲区 -**Lock release**: After state installation completes, the mutex is released. Other threads blocked on LED operations can now proceed. Lock hold time is minimal, only the state swap and counter update, not the potentially slow parsing that happened earlier. +**释放锁**:状态安装完成后,释放互斥锁。其他被LED操作阻塞的线程现在可以继续执行。锁持有时间最小化,仅包括状态交换和计数器更新,不包括之前可能较慢的解析操作。 -##### Cleanup and Return +##### 清理与返回 ```c if (sb != NULL) sbuf_delete(sb); return (error); ``` -**Freeing the old pattern**: After `led_state` returns, `sb` points to the old pattern buffer (or NULL if no previous pattern existed). The code must free this buffer to prevent memory leaks. Each pattern installation generates one buffer to free from the previous pattern. +**释放旧模式**:`led_state` 返回后,`sb` 指向旧模式缓冲区(如果没有之前的模式则为NULL)。代码必须释放此缓冲区以防止内存泄漏。每次模式安装都会产生一个需要从先前模式释放的缓冲区。 -The check `if (sb != NULL)` handles both initial pattern installation (no previous pattern) and static state commands (parser never allocated a buffer). Only actual pattern buffers need deletion. +检查 `if (sb != NULL)` 既处理初始模式安装(无先前的模式),也处理静态状态命令(解析器从未分配缓冲区)。只有实际的模式缓冲区需要删除。 -**Success return**: Returning `error` (typically 0 for success) completes the write operation. The userspace `write(2)` call returns the number of bytes written (the original `uio->uio_resid`), indicating success. +**成功返回**:返回 `error`(通常为0表示成功)完成写操作。用户空间的 `write(2)` 调用返回写入的字节数(原始 `uio->uio_resid`),表示成功。 -##### Complete Write Flow +##### 完整的写入流程 -The whole sequence from userspace write to LED state change (the flow below uses a theoretical device, to illustrate the flow): +从用户空间写入到LED状态变化的完整序列(下面的流程使用一个理论设备来说明流程): ```text User: echo "f" > /dev/led/disk0 @@ -6362,64 +6363,64 @@ Return success User: write() returns 2 bytes ``` -On the next timer tick (0.1 seconds later), the LED begins blinking at ~2.5Hz, alternating on and off every 0.1 seconds. +在下一个定时器滴答(0.1秒后),LED开始以约2.5Hz的频率闪烁,每0.1秒交替亮灭。 -##### Error Handling Paths +##### 错误处理路径 -The function has multiple error exits, each with proper cleanup: +该函数有多个错误退出点,每个都带有适当的清理: -**Size validation failure**: +**大小验证失败**: ```text Check uio_resid > 512 -> return EINVAL (nothing allocated yet, no cleanup needed) ``` -**Allocation failure**: +**分配失败**: ```text malloc() returns NULL -> kernel panics (M_WAITOK) (M_WAITOK means "wait for memory, never fail") ``` -**Copyin failure**: +**复制失败**: ```text uiomove() fails -> free(s) -> return EFAULT (temporary buffer freed, no other resources allocated) ``` -**Parse failure**: +**解析失败**: ```text led_parse() fails -> free(s) -> return EINVAL (temporary buffer freed, no string buffer created) ``` -**State installation success**: +**状态安装成功**: ```text led_state() succeeds -> sbuf_delete(old) -> return 0 (old pattern freed, new pattern installed) ``` -Every error path frees all allocated resources, preventing memory leaks regardless of where failure occurs. +每个错误路径都会释放所有已分配的资源,无论失败发生在何处,都能防止内存泄漏。 -##### Contrast with null.c +##### 与null.c的对比 -The null driver's `null_write` was trivial: set `uio_resid = 0` and return. The LED driver's write handler is substantially more complex because: +null驱动程序的`null_write`很琐碎:设置`uio_resid = 0`并返回。LED驱动程序的写入处理程序则复杂得多,原因是: -**User input requires parsing**: Commands like "f" and "m..." must be interpreted, not just discarded. +**用户输入需要解析**:像"f"和"m..."这样的命令必须被解释,而不是简单地丢弃。 -**State must be modified**: New patterns affect LED behavior, requiring coordination with timer callbacks. +**状态必须被修改**:新模式会影响LED的行为,需要与定时器回调进行协调。 -**Memory must be managed**: Buffers are allocated, swapped, and freed across function boundaries. +**内存必须被管理**:缓冲区在函数边界间分配、交换和释放。 -**Synchronization is required**: Multiple writers and timer callbacks must coordinate via mutexes. +**需要同步**:多个写入者和定时器回调必须通过互斥锁进行协调。 -This increased complexity reflects the LED driver's role as infrastructure supporting rich user interaction with physical hardware, not just a simple data sink. +这种增加的复杂性反映了LED驱动程序作为基础设施的角色,它支持用户与物理硬件的丰富交互,而不仅仅是一个简单的数据接收端。 -#### 5.2) Kernel API: Programmatic LED Control +#### 5.2) 内核 API:程序化 LED 控制 ```c 240: int @@ -6434,42 +6435,42 @@ This increased complexity reflects the LED driver's role as infrastructure suppo 255: else error = ENOENT; ``` -The `led_set` function provides a kernel-facing API that allows other kernel code to control LEDs without going through the character device interface. This enables drivers, kernel subsystems, and system event handlers to manipulate LEDs directly using the same pattern language available to userspace. +`led_set`函数提供了一个面向内核的API,允许其他内核代码控制LED,而无需通过字符设备接口。这使得驱动程序、内核子系统和系统事件处理程序能够直接使用与用户空间相同的模式语言来操作LED。 -##### Function Signature and Purpose +##### 函数签名与用途 ```c int led_set(char const *name, char const *cmd) ``` -**Parameters**: The function receives two strings: +**参数**:该函数接收两个字符串: -- `name` - the LED identifier, matching the name used during `led_create()` (e.g., "disk0", "power") -- `cmd` - the pattern command string, same syntax as userspace writes (e.g., "f", "1", "m...---...") +- `name` - LED标识符,与`led_create()`中使用的名称匹配(例如,"disk0"、"power") +- `cmd` - 模式命令字符串,语法与用户空间写入相同(例如,"f"、"1"、"m...---...") **Return value**: Zero for success, or an errno value for failure (`EINVAL` for parse errors, `ENOENT` for unknown LED name, `ENOMEM` for allocation failure). -**Use cases**: Kernel code can call this function to: +**使用场景**:内核代码可以调用此函数来: -- Indicate disk activity: `led_set("disk0", "f")` to blink during I/O -- Show system status: `led_set("power", "1")` to turn on power LED after boot completes -- Signal error conditions: `led_set("status", "m...---...")` to flash SOS pattern -- Implement heartbeat: `led_set("heartbeat", "Uu")` for 1Hz toggle showing system liveness +- 指示磁盘活动:`led_set("disk0", "f")` 在I/O期间闪烁 +- 显示系统状态:`led_set("power", "1")` 在启动完成后打开电源LED +- 指示错误状态:`led_set("status", "m...---...")` 闪烁 SOS 模式 +- 实现心跳:`led_set("heartbeat", "Uu")` 以 1Hz 频率切换显示系统活跃状态 -##### Parsing the Command +##### 解析命令 ```c error = led_parse(cmd, &sb, &state); ``` -The function reuses the same parser as the write handler. Pattern strings are interpreted identically whether coming from userspace via `write(2)` or from kernel code via `led_set()`. +该函数复用了与写入处理程序相同的解析器。模式字符串的解释方式相同,无论是来自用户空间的`write(2)`还是来自内核代码的`led_set()`。 -This code reuse ensures consistency; a command that works in one context works in the other. The parser handles all the complexity of expanding "f" to "Aa" or "m..." to "aA", so kernel callers don't need to understand the internal timing code format. +这种代码复用确保了一致性;在一个上下文中有效的命令在另一个上下文中也有效。解析器处理了将"f"扩展为"Aa"或将"m..."扩展为"aA"的所有复杂性,因此内核调用者不需要理解内部定时代码格式。 -If parsing fails (bad command syntax, memory exhaustion), the error is recorded in the `error` variable and checked later. The function continues to acquire the lock even on parse failure because the lock must be held to safely return without leaking the buffer. +如果解析失败(命令语法错误、内存耗尽),错误会记录在`error`变量中并在之后检查。即使在解析失败时,函数也会继续获取锁,因为必须持有锁才能安全返回而不泄漏缓冲区。 -##### Finding the Named LED +##### 查找指定名称的LED ```c LIST_FOREACH(sc, &led_list, list) { @@ -6479,27 +6480,27 @@ if (sc != NULL) error = led_state(sc, &sb, state); else error = ENOENT; ``` -**Linear search**: The `LIST_FOREACH` macro walks the global LED list, comparing each LED's name to the requested name with `strcmp()`. The loop terminates early with `break` when a match is found, leaving `sc` pointing to the matching LED. +**线性搜索**:`LIST_FOREACH`宏遍历全局LED列表,使用`strcmp()`将每个LED的名称与请求的名称进行比较。当找到匹配项时,循环通过`break`提前终止,使`sc`指向匹配的LED。 -**Why linear search?**: For small lists (typically 5-20 LEDs per system), linear search is faster than hash table overhead. The code simplicity and cache-friendly sequential access outweigh the O(n) complexity. Systems with hundreds of LEDs would benefit from a hash table, but such systems are rare. +**为什么用线性搜索?**:对于小型列表(通常每个系统5-20个LED),线性搜索比哈希表的开销更快。代码简单性和缓存友好的顺序访问超过了O(n)复杂度。拥有数百个LED的系统会受益于哈希表,但这样的系统很少见。 -**Handling not found**: If the loop completes without breaking, no LED matched the name and `sc` remains NULL (from the `LIST_FOREACH` initialization). Setting `error = ENOENT` (no such file or directory) signals that the named LED doesn't exist. +**处理未找到的情况**:如果循环完成而没有中断,则没有LED匹配该名称,并且`sc`保持NULL(来自`LIST_FOREACH`的初始化)。设置`error = ENOENT`(没有这样的文件或目录)表示指定的LED不存在。 -**Installing state**: When a match is found (`sc != NULL`), `led_state()` is called to install the new pattern or static state, using the same state installation function as the write handler. The return value overwrites any parse error, if parsing succeeded but state installation failed, the installation error takes precedence. +**安装状态**:当找到匹配项时(`sc != NULL`),调用`led_state()`来安装新模式或静态状态,使用与写入处理程序相同的状态安装函数。返回值会覆盖任何解析错误,如果解析成功但状态安装失败,则安装错误优先。 -##### Critical Code Omitted in Fragment +##### 片段中省略的关键代码 -The provided fragment omits several critical lines visible in the complete function: +提供的片段省略了完整函数中可见的几个关键行: -**Lock acquisition** (before the `LIST_FOREACH` loop in `led_set`): +**锁获取**(在 `led_set` 的 `LIST_FOREACH` 循环之前): ```c mtx_lock(&led_mtx); ``` -The LED list must be locked before traversal to prevent concurrent modifications. If one thread is searching the list while another thread destroys an LED, the search might access freed memory. The mutex serializes list access. +LED 列表在遍历前必须加锁,以防止并发修改。如果一个线程正在搜索列表,而另一个线程销毁了一个 LED,搜索可能访问已释放的内存。互斥锁序列化了对列表的访问。 -**Lock release and cleanup** (after the state-install call in `led_set`): +**锁释放与清理**(在 `led_set` 中调用状态安装之后): ```c mtx_unlock(&led_mtx); @@ -6508,31 +6509,31 @@ if (sb != NULL) return (error); ``` -After the state installation attempt, the mutex is released and the old pattern buffer (returned via `sb` by `led_state()`) is freed. This cleanup mirrors the write handler's buffer management. +在尝试状态安装之后,释放互斥锁并释放旧的模式缓冲区(由 `led_state()` 通过 `sb` 返回)。这种清理方式与写处理程序的缓冲区管理相对应。 -##### Comparison with Write Handler +##### 与写处理程序的比较 -Both `led_write` and `led_set` follow the same pattern: +`led_write` 和 `led_set` 遵循相同的模式: ```text Parse command -> Acquire lock -> Find LED -> Install state -> Release lock -> Cleanup ``` -The key differences: +关键区别: -| Aspect | led_write | led_set | +| 方面 | led_write | led_set | | ------------------ | ---------------------- | -------------------------------------- | -| Caller | Userspace via write(2) | Kernel code | -| Input source | uio structure | Direct string pointers | -| LED identification | dev->si_drv1 | Name lookup | -| Size validation | Limit 512 bytes | No explicit limit (caller responsible) | -| Error reporting | errno to userspace | Return value to caller | +| 调用者 | 用户空间通过 write(2) | 内核代码 | +| 输入来源 | uio 结构 | 直接字符串指针 | +| LED 标识 | dev->si_drv1 | 名称查找 | +| 大小验证 | 限制 512 字节 | 无显式限制(调用者负责) | +| 错误报告 | errno 返回用户空间 | 返回值给调用者 | -The write handler uses the device pointer to find the LED directly (single device, single LED). The kernel API uses name lookup to support arbitrary LED selection from any kernel context. +写处理程序使用设备指针直接找到 LED(单一设备、单一 LED)。内核 API 使用名称查找以支持从任何内核上下文中选择任意 LED。 -##### Example Usage Patterns +##### 使用模式示例 -**Disk driver indicating activity**: +**磁盘驱动程序指示活动**: ```c void @@ -6550,7 +6551,7 @@ disk_complete_io(struct disk_softc *sc) } ``` -**System initialization sequence**: +**系统初始化序列**: ```c void @@ -6562,7 +6563,7 @@ system_boot_complete(void) } ``` -**Error indication**: +**错误指示**: ```c void @@ -6574,11 +6575,11 @@ critical_error_handler(int error_code) } ``` -##### Thread Safety +##### 线程安全 -The function is thread-safe through mutex protection. Multiple threads can call `led_set()` concurrently: +该函数通过互斥锁保护实现线程安全。多个线程可以同时调用 `led_set()`: -**Scenario**: Thread A sets "disk0" to "f" while Thread B sets "power" to "1". +**场景**:线程 A 将 "disk0" 设置为 "f",而线程 B 将 "power" 设置为 "1"。 ```text Thread A Thread B @@ -6594,53 +6595,53 @@ Return Install state Return ``` -The mutex serializes list traversal and state modification, preventing corruption. Both operations complete successfully without interference. +互斥锁序列化列表遍历和状态修改,防止数据损坏。两个操作都能在不互相干扰的情况下成功完成。 -##### Error Handling +##### 错误处理 -The function can fail in several ways: +该函数可能以多种方式失败: -**Parse error**: +**解析错误**: ```c led_set("disk0", "invalid") // Returns EINVAL ``` -**LED not found**: +**LED 未找到**: ```c led_set("nonexistent", "f") // Returns ENOENT ``` -**Memory exhaustion**: +**内存耗尽**: ```c led_set("disk0", "m..." /* very long morse */) // Returns ENOMEM ``` -Kernel callers should check the return value and handle errors appropriately, though in practice LED control failures are rarely fatal, the system continues operating, just without visual indicators. +内核调用者应检查返回值并适当处理错误,尽管在实际中 LED 控制失败很少致命,系统会继续运行,只是没有视觉指示。 -##### Why Both APIs Exist +##### 为什么存在两种 API -The dual interface (character device + kernel API) serves different needs: +双接口(字符设备 + 内核 API)服务于不同需求: -**Character device** (`/dev/led/*`): +**字符设备**(`/dev/led/*`): -- User scripts and programs -- System administrators -- Testing and debugging -- Interactive control +- 用户脚本和程序 +- 系统管理员 +- 测试与调试 +- 交互式控制 -**Kernel API** (`led_set()`): +**内核 API**(`led_set()`): -- Automated responses to events -- Driver-integrated indicators -- System state visualization -- Performance-critical paths (no system call overhead) +- 自动化事件响应 +- 驱动程序集成指示器 +- 系统状态可视化 +- 性能关键路径(无系统调用开销) -This pattern, exposing functionality through both userspace devices and kernel APIs, appears throughout FreeBSD. The LED subsystem provides a clean example of how to structure such dual-interface services. +这种通过用户空间设备和内核 API 暴露功能的模式在 FreeBSD 中随处可见。LED 子系统提供了一个如何构建此类双接口服务的清晰示例。 -#### 6) Hook into devfs and export the write method +#### 6) 连接到 devfs 并导出写入方法 ```c 272: static struct cdevsw led_cdevsw = { @@ -6650,11 +6651,11 @@ This pattern, exposing functionality through both userspace devices and kernel A 276: }; ``` -##### Character Device Switch Table +##### 字符设备开关表 -The `led_cdevsw` structure defines the character device operations for all LED device nodes. Unlike the null driver which had three separate `cdevsw` structures for three devices, the LED driver uses a single `cdevsw` shared by all dynamically created `/dev/led/*` devices. +`led_cdevsw` 结构定义了所有 LED 设备节点的字符设备操作。与空驱动为三个设备分别使用三个单独的 `cdevsw` 结构不同,LED 驱动使用一个由所有动态创建的 `/dev/led/*` 设备共享的单一 `cdevsw`。 -##### Structure Definition +##### 结构定义 ```c static struct cdevsw led_cdevsw = { @@ -6664,29 +6665,29 @@ static struct cdevsw led_cdevsw = { }; ``` -**`d_version = D_VERSION`**: The mandatory version field ensures binary compatibility between the driver and the kernel's device framework. All `cdevsw` structures must include this field. +**`d_version = D_VERSION`**:强制版本字段确保驱动与内核设备框架之间的二进制兼容性。所有 `cdevsw` 结构都必须包含此字段。 -**`d_write = led_write`**: The only operation explicitly defined. When userspace calls `write(2)` on any `/dev/led/*` device, the kernel invokes this function. The `led_write` handler parses pattern commands and updates LED state. +**`d_write = led_write`**:唯一显式定义的操作。当用户空间对任何 `/dev/led/*` 设备调用 `write(2)` 时,内核会调用此函数。`led_write` 处理程序解析模式命令并更新 LED 状态。 -**`d_name = "LED"`**: The device class name appearing in kernel messages and accounting. This string identifies the driver type, though individual devices have their own specific names (like "disk0" or "power"). +**`d_name = "LED"`**:出现在内核消息和统计中的设备类名称。此字符串标识驱动类型,但单个设备有其自己的特定名称(例如 "disk0" 或 "power")。 -##### Minimal Operation Set +##### 最小操作集 -Notice what's **not** defined: +注意哪些**没有**定义: -**No `d_read`**: LEDs are output-only devices. Reading from `/dev/led/disk0` is meaningless, there's no state to query, no data to retrieve. Omitting `d_read` causes read attempts to fail with `ENODEV` (operation not supported by device). +**没有 `d_read`**:LED 仅支持输出的设备。从 `/dev/led/disk0` 读取毫无意义,没有可查询的状态,也没有可检索的数据。省略 `d_read` 会导致读取尝试以 `ENODEV`(设备不支持该操作)失败。 -**No `d_open` / `d_close`**: LED devices require no per-open initialization or cleanup. Multiple processes can write to the same LED simultaneously (serialized by the mutex), and closing the device requires no state teardown. The kernel's default handlers suffice. +**没有 `d_open` / `d_close`**:LED 设备无需每次打开时的初始化或关闭清理。多个进程可以同时向同一个 LED 写入(通过互斥锁串行化),关闭设备无需状态清理。内核的默认处理程序已足够。 -**No `d_ioctl`**: Unlike the null driver which supported terminal ioctls, LED devices have no control operations beyond writing patterns. All configuration happens through the write interface. +**没有 `d_ioctl`**:与支持终端 ioctl 的 null 驱动程序不同,LED 设备除了写入模式外没有控制操作。所有配置通过写接口完成。 -**No `d_poll` / `d_kqfilter`**: LEDs are write-only, so there's no condition to wait for. Polling for writability would always return "ready" since writes never block (beyond mutex acquisition), making poll support useless. +**没有 `d_poll` / `d_kqfilter`**:LED 是只写设备,因此没有可等待的条件。对可写性的轮询总会返回“就绪”,因为写入从不阻塞(除了获取互斥锁),这使得 poll 支持毫无用处。 -This minimalism contrasts with the null driver's more complete interface (which included ioctl handlers) and demonstrates that `cdevsw` structures need only provide operations that make sense for the device type. +这种极简设计与 null 驱动程序更完整的接口(包含 ioctl 处理程序)形成对比,并表明 `cdevsw` 结构只需提供对设备类型有意义的操作。 -##### Shared Across Devices +##### 跨设备共享 -A critical distinction from the null driver: this **single** `cdevsw` serves **all** LED devices. When the system has three LEDs registered: +与 null 驱动程序的一个关键区别:这个**单一**的 `cdevsw` 服务于**所有** LED 设备。当系统注册了三个 LED 时: ```text /dev/led/disk0 -> led_cdevsw @@ -6694,17 +6695,17 @@ A critical distinction from the null driver: this **single** `cdevsw` serves **a /dev/led/status -> led_cdevsw ``` -All three device nodes share the same function pointer table. The `led_write` function determines which LED is being written to by examining `dev->si_drv1`, which points to the specific LED's `ledsc` structure. +所有三个设备节点共享同一个函数指针表。`led_write` 函数通过检查 `dev->si_drv1` 来确定写入哪个 LED,该指针指向具体 LED 的 `ledsc` 结构。 -This sharing is possible because: +这种共享之所以可能,是因为: -- All LEDs support the same operations (write pattern commands) -- Per-device state is accessed through `si_drv1`, not through different functions -- The same parsing and state installation logic applies to every LED +- 所有 LED 支持相同的操作(写入模式命令) +- 每个设备的状态通过 `si_drv1` 访问,而不是通过不同的函数 +- 相同的解析和状态安装逻辑适用于每个 LED -##### Contrast with null.c +##### 与 null.c 的对比 -The null driver defined three separate `cdevsw` structures: +null 驱动程序定义了三个独立的 `cdevsw` 结构: ```c static struct cdevsw full_cdevsw = { ... }; @@ -6712,34 +6713,34 @@ static struct cdevsw null_cdevsw = { ... }; static struct cdevsw zero_cdevsw = { ... }; ``` -Each had different function assignments because the devices had different behavior (full_write vs. null_write, nullop vs. zero_read). The devices were fundamentally different types. +每个结构有不同的函数分配,因为这些设备具有不同的行为(full_write vs. null_write,nullop vs. zero_read)。这些设备是根本不同类型的。 -The LED driver's devices are all the same type, they're LEDs that accept pattern commands. The only differences are: +LED 驱动程序的所有设备都是相同类型,即接受模式命令的 LED。唯一的区别是: -- Device name ("disk0" vs. "power") -- Hardware control callback (different for each physical LED) -- Current pattern state (independent per LED) +- 设备名称("disk0" 与 "power") +- 硬件控制回调(每个物理 LED 不同) +- 当前模式状态(每个 LED 独立) -These differences are stored in per-device `ledsc` structures, not encoded in separate function tables. This design scales elegantly: registering 100 LEDs doesn't require 100 `cdevsw` structures, just 100 `ledsc` instances sharing one `cdevsw`. +这些区别存储在每设备 `ledsc` 结构中,而不是编码在独立的函数表中。这种设计优雅地扩展:注册 100 个 LED 不需要 100 个 `cdevsw` 结构,只需要 100 个共享一个 `cdevsw` 的 `ledsc` 实例。 -##### Usage in Device Creation +##### 在设备创建中的使用 -When a hardware driver calls `led_create()`, the code creates a device node: +当硬件驱动程序调用 `led_create()` 时,代码会创建一个设备节点: ```c sc->dev = make_dev(&led_cdevsw, sc->unit, UID_ROOT, GID_WHEEL, 0600, "led/%s", name); ``` -The `&led_cdevsw` parameter provides the function dispatch table. All created devices reference the same structure, `make_dev()` doesn't copy it, just stores the pointer. This means: +参数 `&led_cdevsw` 提供了函数调度表。所有创建的设备都引用同一个结构,`make_dev()` 不会复制它,只存储指针。这意味着: -- Zero memory overhead per device for the function table -- Changes to led_write (during development) automatically affect all devices -- The `cdevsw` must remain valid for the system's lifetime (hence `static` storage) +- 每个设备在函数表上的内存开销为零 +- 对 `led_write` 的更改(开发期间)会自动影响所有设备 +- `cdevsw` 必须在系统生命周期内保持有效(因此使用 `static` 存储) -##### Device Identification +##### 设备识别 -With all devices sharing one `cdevsw`, how does `led_write` distinguish which LED is being written to? The device linkage: +所有设备共享一个 `cdevsw`,那么 `led_write` 如何区分正在写入的 LED?设备链接机制: ```c // In led_create(): @@ -6750,11 +6751,11 @@ sc->dev->si_drv1 = sc; // Link device to its ledsc sc = dev->si_drv1; // Retrieve the ledsc ``` -The `si_drv1` field (set during `led_create()`) creates a per-device pointer to the unique `ledsc` structure. Though all devices share the same `cdevsw` and thus the same `led_write` function, each invocation receives a different `dev` parameter, which provides access to device-specific state through `si_drv1`. +`si_drv1`字段(在`led_create()`中设置)创建了一个指向唯一`ledsc`结构的每设备指针。尽管所有设备共享相同的`cdevsw`,因而也共享相同的`led_write`函数,但每次调用都会收到不同的`dev`参数,从而可以通过`si_drv1`访问设备特定的状态。 -This pattern, shared function table, per-device state pointer, is the standard approach for drivers managing multiple similar devices. It combines efficiency (one function table) with flexibility (device-specific behavior through the state pointer). +这种模式——共享函数表、每设备状态指针——是管理多个相似设备的驱动程序的标准方法。它结合了效率(一个函数表)和灵活性(通过状态指针实现设备特定行为)。 -#### 7) Create per-LED device nodes +#### 7) 创建每个 LED 的设备节点 ```c 278: struct cdev * @@ -6785,11 +6786,11 @@ This pattern, shared function table, per-device state pointer, is the standard a 309: } ``` -##### LED Registration: Creating Dynamic Devices +##### LED 注册:创建动态设备 -The `led_create` and `led_create_state` functions form the public API that hardware drivers use to register LEDs with the subsystem. These functions allocate resources, create device nodes, and integrate the LED into the global registry, making it accessible to both userspace and kernel code. +`led_create`和`led_create_state`函数构成了公共API,硬件驱动程序使用它们向子系统注册LED。这些函数分配资源、创建设备节点,并将LED集成到全局注册表中,使其对用户空间和内核代码都可访问。 -##### Simple Registration Wrapper +##### 简单注册封装 ```c struct cdev * @@ -6799,16 +6800,16 @@ led_create(led_t *func, void *priv, char const *name) } ``` -The `led_create` function provides a simplified interface for the common case where the LED's initial state doesn't matter. It delegates to `led_create_state` with an initial state of 0 (off), allowing hardware drivers to register LEDs with minimal code: +`led_create`函数为常见情况(LED的初始状态无关紧要)提供了一个简化的接口。它委托给`led_create_state`,初始状态为0(关闭),允许硬件驱动程序以最少的代码注册LED: ```c struct cdev *led; led = led_create(my_led_callback, my_softc, "disk0"); ``` -This convenience wrapper follows the FreeBSD pattern of providing both simple and feature-complete versions of the same API. +这个便捷包装遵循了FreeBSD的模式,即为同一API提供简单版和功能完整版。 -##### Full Registration Function +##### 完整的注册函数 ```c struct cdev * @@ -6817,30 +6818,30 @@ led_create_state(led_t *func, void *priv, char const *name, int state) struct ledsc *sc; ``` -**Parameters**: The function receives four values: +**参数**:该函数接收四个值: -- `func` - callback function that controls the physical LED hardware -- `priv` - opaque pointer passed to the callback, typically the driver's softc -- `name` - string identifying the LED, becomes part of `/dev/led/name` -- `state` - initial LED state: 0 (off), 1 (on), or -1 (don't initialize) +- `func` - 控制物理LED硬件的回调函数 +- `priv` - 传递给回调的不透明指针,通常是驱动程序的`softc` +- `name` - 标识LED的字符串,将成为`/dev/led/name`的一部分 +- `state` - 初始 LED 状态:0(关)、1(开)或 -1(不初始化) -**Return value**: Pointer to the created `struct cdev`, which the hardware driver should store for later use with `led_destroy()`. If creation fails, the function panics (due to `M_WAITOK` allocation) rather than returning NULL. +**返回值**:指向所创建`struct cdev`的指针,硬件驱动程序应存储该指针以供后续与`led_destroy()`一起使用。如果创建失败,该函数会引发panic(由于`M_WAITOK`分配),而不是返回NULL。 -##### Allocating LED State +##### 分配 LED 状态 ```c sc = malloc(sizeof *sc, M_LED, M_WAITOK | M_ZERO); ``` -The softc structure is allocated to track this LED's state. The `M_ZERO` flag zeroes all fields, providing safe defaults: +分配`softc`结构以跟踪此LED的状态。`M_ZERO`标志将所有字段清零,提供安全的默认值: -- Pointer fields (name, dev, spec, str, ptr) are NULL -- Numeric fields (unit, count) are zero -- The `list` entry is zeroed (will be initialized by `LIST_INSERT_HEAD`) +- 指针字段(name, dev, spec, str, ptr)为NULL +- 数字字段(unit, count)为零 +- `list`条目被清零(将由`LIST_INSERT_HEAD`初始化) -The `M_WAITOK` flag means the allocation can sleep waiting for memory, which is acceptable since LED registration happens during driver attach (a blocking context). If memory is truly exhausted, the kernel panics, LED registration is considered essential enough that failure is not recoverable. +`M_WAITOK`标志意味着分配可以等待内存,这是可以接受的,因为LED注册发生在驱动程序attach期间(阻塞上下文)。如果内存真的耗尽,内核会panic;LED注册被认为是足够重要的,以至于失败是不可恢复的。 -##### Device Creation Under Exclusive Lock +##### 在排他锁下创建设备 ```c sx_xlock(&led_sx); @@ -6853,27 +6854,27 @@ sc->dev = make_dev(&led_cdevsw, sc->unit, sx_xunlock(&led_sx); ``` -**Exclusive lock acquisition**: The `sx_xlock` call acquires the shared/exclusive lock in exclusive (write) mode. This serializes all device creation and destruction operations, preventing races where two threads simultaneously create devices with the same name or allocate the same unit number. +**获取排他锁**:`sx_xlock`调用以排他(写入)模式获取共享/排他锁。这将序列化所有设备创建和销毁操作,防止两个线程同时创建同名设备或分配相同单元号时的竞争。 -**Name duplication**: `strdup(name, M_LED)` allocates a copy of the name string. The caller's string may be temporary (stack buffer or string literal), so a persistent copy is needed for the LED's lifetime. This copy will be freed in `led_destroy()`. +**名称复制**:`strdup(name, M_LED)`分配名称字符串的副本。调用者的字符串可能是临时的(栈缓冲区或字符串字面量),因此需要为LED的生命周期保留一个持久副本。该副本将在`led_destroy()`中释放。 -**Unit number allocation**: `alloc_unr(led_unit)` obtains a unique unit number from the global pool. This number becomes the device's minor number, ensuring `/dev/led/disk0` and `/dev/led/power` have distinct device identifiers even though they share the same major number. +**单元号分配**:`alloc_unr(led_unit)`从全局池中获取一个唯一的单元号。该号码成为设备的次编号,确保`/dev/led/disk0`和`/dev/led/power`即使共享相同的主编号,也具有不同的设备标识符。 -**Callback registration**: The `private` and `func` fields are copied from parameters, establishing the connection to the hardware driver's control function. When the LED state changes (via pattern execution or static state command), `sc->func(sc->private, onoff)` will be called to manipulate the physical hardware. +**回调注册**:`private`和`func`字段从参数复制,建立到硬件驱动程序控制函数的连接。当LED状态改变时(通过模式执行或静态状态命令),将调用`sc->func(sc->private, onoff)`来操作物理硬件。 -**Device node creation**: `make_dev` creates `/dev/led/name` with the following properties: +**设备节点创建**:`make_dev`创建`/dev/led/name`,具有以下属性: -- `&led_cdevsw` - shared character device operations (write handler) -- `sc->unit` - unique minor number for this LED -- `UID_ROOT, GID_WHEEL` - owned by root:wheel -- `0600` - read/write for owner only (root), no access for others -- `"led/%s", name` - device path, automatically prepends `/dev/` +- `&led_cdevsw` - 共享字符设备操作(写入处理程序) +- `sc->unit` - 此LED的唯一次编号 +- `UID_ROOT, GID_WHEEL` - 由 root:wheel 拥有 +- `0600` - 仅所有者(root)可读/写,其他人无权限 +- `"led/%s", name` - 设备路径,自动添加 `/dev/` 前缀 -The restrictive permissions (`0600`) prevent unprivileged users from controlling LEDs, which could be a security concern (information leakage through LED patterns) or nuisance (making the power LED blink rapidly). +限制性权限(`0600`)阻止非特权用户控制LED,这可能是一个安全问题(通过LED模式泄露信息)或令人讨厌(使电源LED快速闪烁)。 -**Lock release**: After device creation completes, the exclusive lock is released. Other threads can now create or destroy LEDs. The lock hold time is minimal, just the core allocation and registration, not including the earlier softc allocation which didn't need protection. +**释放锁**:设备创建完成后,释放排他锁。其他线程现在可以创建或销毁LED。锁持有时间最小化,仅为核心分配和注册,不包括之前的`softc`分配(该分配不需要保护)。 -##### Integration Under Mutex +##### 在互斥锁下集成 ```c mtx_lock(&led_mtx); @@ -6884,31 +6885,31 @@ if (state != -1) mtx_unlock(&led_mtx); ``` -**Mutex acquisition**: The `led_mtx` mutex protects the LED list and timer-related state. It's acquired after device creation because multiple locks with different purposes reduces contention, threads creating devices don't block threads modifying LED states. +**获取互斥锁**:`led_mtx`互斥锁保护LED列表和定时器相关状态。它在设备创建之后获取,因为具有不同用途的多个锁可以减少争用;创建设备的线程不会阻塞修改LED状态的线程。 -**Bidirectional linkage**: Setting `sc->dev->si_drv1 = sc` creates the critical link from device node to softc. When `led_write` is called with this device, it can retrieve the softc via `dev->si_drv1`. This linkage must be established before the device is usable. +**双向链接**:设置 `sc->dev->si_drv1 = sc` 建立了从设备节点到软上下文(softc)的关键链接。当 `led_write` 被调用并传入该设备时,可以通过 `dev->si_drv1` 获取软上下文。必须在设备可用之前建立此链接。 -**List insertion**: `LIST_INSERT_HEAD(&led_list, sc, list)` adds the LED to the global registry at the head of the list. The `list` field in the softc was zeroed during allocation, and this macro initializes it properly while linking into the existing list. +**列表插入**:`LIST_INSERT_HEAD(&led_list, sc, list)` 将 LED 添加到全局注册表的列表头部。软上下文中的 `list` 字段在分配时已被清零,此宏在将其链接到现有列表的同时正确初始化该字段。 -Using `LIST_INSERT_HEAD` rather than `LIST_INSERT_TAIL` is arbitrary; order doesn't matter for LED list iteration. Head insertion is slightly faster (no need to find the tail), but the performance difference is negligible. +使用 `LIST_INSERT_HEAD` 而非 `LIST_INSERT_TAIL` 是任意的;对于 LED 列表遍历而言顺序无关紧要。头部插入稍快(无需查找尾部),但性能差异可以忽略不计。 -**Optional initial state**: If `state != -1`, the hardware callback is invoked immediately to set the LED's initial state: +**可选的初始状态**:如果 `state != -1`,则立即调用硬件回调以设置 LED 的初始状态: -- `state != 0` converts any non-zero value to boolean true (LED on) -- `state == 0` means LED off +- `state != 0` 将任何非零值转换为布尔真(LED 亮) +- `state == 0` 表示 LED 灭 -The special value -1 means "don't initialize," leaving the LED in whatever state the hardware defaults to. This is useful when the hardware driver has already configured the LED before registration. +特殊值 -1 表示“不初始化”,将 LED 保持在硬件默认状态。当硬件驱动程序在注册之前已经配置好 LED 时,此值很有用。 -**Lock release**: After list insertion and optional initialization, the mutex is released. The LED is now fully operational; userspace can write to its device node, kernel code can call `led_set()` with its name, and timer callbacks will process any patterns. +**锁释放**:在列表插入和可选的初始化之后,释放互斥锁。此时 LED 已完全可用:用户空间可以写入其设备节点,内核代码可以使用其名称调用 `led_set()`,定时器回调将处理任何模式。 -##### Return Value and Ownership +##### 返回值与所有权 ```c return (sc->dev); } ``` -The function returns the `cdev` pointer, which the hardware driver should store: +该函数返回 `cdev` 指针,硬件驱动程序应保存该指针: ```c struct my_driver_softc { @@ -6925,24 +6926,24 @@ my_driver_attach(device_t dev) } ``` -The hardware driver needs this pointer to call `led_destroy()` during detach. Without storing it, the LED would leak, its device node and resources would persist even after the hardware driver unloads. +硬件驱动程序需要在分离期间调用 `led_destroy()` 时需要此指针。如果不保存它,LED 将泄漏,其设备节点和资源将在硬件驱动程序卸载后仍然存在。 -##### Resource Allocation Summary +##### 资源分配总结 -A successful LED registration allocates: +成功的 LED 注册会分配: -- Softc structure (freed in `led_destroy`) -- Name string copy (freed in `led_destroy`) -- Unit number (returned to pool in `led_destroy`) -- Device node (destroyed in `led_destroy`) +- Softc 结构(在 `led_destroy` 中释放) +- 名称字符串副本(在 `led_destroy` 中释放) +- 单元号(在 `led_destroy` 中返回池中) +- 设备节点(在 `led_destroy` 中销毁) -All resources are cleaned up symmetrically during destruction, preventing leaks when hardware is removed. +所有资源在销毁时对称地清理,防止硬件移除时发生泄漏。 -##### Thread Safety +##### 线程安全 -The two-lock design enables safe concurrent operations: +双锁设计支持安全的并发操作: -**Scenario**: Thread A creates "disk0" while Thread B creates "power". +**场景**:线程 A 创建 "disk0",同时线程 B 创建 "power"。 ```text Thread A Thread B @@ -6957,11 +6958,11 @@ Unlock led_mtx Lock led_mtx Unlock led_mtx ``` -The exclusive lock serializes device creation (preventing name/unit conflicts), while the mutex serializes list modification (preventing list corruption). Both threads complete successfully with two working LEDs. +排他锁序列化设备创建(防止名称/单元冲突),而互斥锁序列化列表修改(防止列表损坏)。两个线程都能成功完成,产生两个正常工作的 LED。 -##### Contrast with null.c +##### 与 null.c 的对比 -The null driver's device creation happened in `null_modevent` during module load: +null 驱动程序的设备创建发生在模块加载时的 `null_modevent` 中: ```c // null.c: static devices created once @@ -6970,7 +6971,7 @@ null_dev = make_dev_credf(..., "null"); zero_dev = make_dev_credf(..., "zero"); ``` -The LED driver's device creation happens dynamically on demand: +LED 驱动程序的设备创建按需动态发生: ```c // led.c: devices created whenever hardware drivers request @@ -6979,10 +6980,10 @@ led_create(func, priv, "power"); // called by power driver led_create(func, priv, "status"); // called by GPIO driver ``` -This dynamic approach scales naturally: the system can have any number of LEDs (zero to hundreds), with devices appearing and disappearing as hardware is added and removed. The subsystem provides infrastructure, but doesn't dictate what LEDs exist, that's determined by which hardware drivers are loaded and what hardware is present. +这种动态方法自然扩展:系统可以拥有任意数量的 LED(从零到数百个),设备随着硬件的添加和移除而出现和消失。子系统提供基础设施,但不决定存在哪些 LED;这取决于加载了哪些硬件驱动程序以及存在哪些硬件。 -#### 8) Destroy per-LED device nodes +#### 8) 销毁每个 LED 的设备节点 ```c 306: void @@ -7009,11 +7010,11 @@ This dynamic approach scales naturally: the system can have any number of LEDs ( 329: } ``` -##### LED Deregistration: Cleanup and Resource Release +##### 取消注册 LED:清理与资源释放 -The `led_destroy` function unregisters an LED from the subsystem, reversing all operations performed during `led_create`. Hardware drivers call this function during detach to cleanly remove LEDs before the underlying hardware disappears, ensuring no dangling references or resource leaks remain. +`led_destroy` 函数从子系统中注销一个 LED,撤销 `led_create` 期间执行的所有操作。硬件驱动程序在分离期间调用此函数,以便在底层硬件消失之前干净地移除 LED,确保没有悬空引用或资源泄漏。 -##### Function Entry and Softc Retrieval +##### 函数入口与 Softc 获取 ```c void @@ -7026,7 +7027,7 @@ led_destroy(struct cdev *dev) dev->si_drv1 = NULL; ``` -**Parameter**: The function receives the `cdev` pointer returned by `led_create`. Hardware drivers typically store this pointer in their own softc and pass it during cleanup: +**参数**:该函数接收 `led_create` 返回的 `cdev` 指针。硬件驱动程序通常将此指针保存在自己的软上下文中,并在清理时传递它: ```c void @@ -7038,22 +7039,22 @@ my_driver_detach(device_t dev) } ``` -**Mutex acquisition**: The `led_mtx` mutex is acquired first to protect the LED list and timer state. This serializes destruction with ongoing timer callbacks and write operations. +**互斥锁获取**:首先获取 `led_mtx` 互斥锁以保护 LED 列表和定时器状态。这将销毁操作与正在进行的定时器回调和写入操作序列化。 -**Breaking the linkage**: Setting `dev->si_drv1 = NULL` immediately severs the connection between device node and softc. Any write operation that started before this function was called but hasn't yet acquired the mutex will see NULL when it checks `dev->si_drv1` and safely fail rather than accessing freed memory. This defensive programming prevents use-after-free bugs during concurrent operations. +**断开链接**:设置 `dev->si_drv1 = NULL` 立即切断设备节点与软上下文之间的连接。任何在此函数被调用之前开始但尚未获取互斥锁的写入操作,在检查 `dev->si_drv1` 时将看到 NULL,并安全地失败,而不是访问已释放的内存。这种防御性编程防止并发操作中的释放后使用错误。 -##### Deactivating Pattern Execution +##### 停用模式执行 ```c if (sc->ptr != NULL) blinkers--; ``` -If this LED has an active blink pattern (`ptr != NULL`), the global `blinkers` counter must be decremented. This counter tracks how many LEDs need timer servicing, and removing an active LED reduces that count. +如果该 LED 具有活动闪烁模式(`ptr != NULL`),则必须递减全局 `blinkers` 计数器。该计数器跟踪需要定时器服务的 LED 数量,移除活动 LED 会减少该计数。 -**Timer shutdown logic**: When the counter reaches zero (this was the last blinking LED), the timer callback will notice and stop rescheduling itself. However, there's no explicit timer stop here; the counter update is sufficient. The timer callback checks `blinkers > 0` before each reschedule. +**定时器关闭逻辑**:当计数器归零(这是最后一个闪烁的LED)时,定时器回调会注意到这一点并停止重新调度自身。但这里没有显式的定时器停止操作;计数器更新就足够了。定时器回调在每次重新调度前都会检查 `blinkers > 0`。 -##### Removing from Global Registry +##### 从全局注册表中移除 ```c LIST_REMOVE(sc, list); @@ -7061,21 +7062,21 @@ if (LIST_EMPTY(&led_list)) callout_stop(&led_ch); ``` -**List removal**: `LIST_REMOVE(sc, list)` unlinks this LED from the global list. The macro updates neighboring list entries to skip this node, and future timer callbacks won't see this LED when iterating. +**列表移除**:`LIST_REMOVE(sc, list)` 将该LED从全局列表中解除链接。该宏更新相邻列表条目以跳过此节点,未来定时器回调在遍历时将看不到这个LED。 -**Explicit timer stop**: If the list becomes empty after removal, `callout_stop(&led_ch)` explicitly stops the timer. This is an optimization, waiting for the timer to notice `blinkers == 0` would work, but stopping immediately when all LEDs are gone is more efficient. +**显式定时器停止**:如果移除后列表变为空,`callout_stop(&led_ch)` 会显式停止定时器。这是一种优化——等待定时器自行发现 `blinkers == 0` 也能工作,但在所有LED都消失时立即停止更高效。 -The `callout_stop` function is safe to call on an already-stopped timer (it does nothing), so the check for empty list is just an optimization to avoid the function call when unnecessary. +`callout_stop` 函数在已停止的定时器上调用是安全的(它什么也不做),因此对空列表的检查只是一个避免不必要函数调用的优化。 -**Lock release**: After list modification and timer management, the mutex is released: +**锁释放**:列表修改和定时器管理完成后,释放互斥锁: ```c mtx_unlock(&led_mtx); ``` -The remaining cleanup doesn't require mutex protection since this LED is now invisible to timer callbacks and write operations. +剩余的清理工作不需要互斥锁保护,因为该LED对定时器回调和写操作已不可见。 -##### Resource Deallocation Under Exclusive Lock +##### 在排他锁下释放资源 ```c sx_xlock(&led_sx); @@ -7088,49 +7089,49 @@ free(sc, M_LED); sx_xunlock(&led_sx); ``` -**Exclusive lock acquisition**: The `led_sx` lock serializes device creation and destruction. Acquiring it exclusively prevents new devices from being created while this one is being destroyed, avoiding races where the freed unit number or name might be immediately reused. +**排他锁获取**:`led_sx` 锁对设备创建和销毁进行序列化。排他获取该锁阻止在销毁过程中创建新设备,从而避免释放的单元号或名称被立即重用导致的竞争。 -**Unit number return**: `free_unr(led_unit, sc->unit)` returns the unit number to the pool, making it available for future LED registrations. Without this, unit numbers would leak and eventually exhaust the available range. +**单元号归还**:`free_unr(led_unit, sc->unit)` 将单元号归还到池中,使其可用于未来的LED注册。如果没有这一步,单元号会泄漏并最终耗尽可用范围。 -**Device node destruction**: `destroy_dev(dev)` removes `/dev/led/name` from the filesystem and deallocates the `cdev` structure. This function blocks until all open file descriptors to the device are closed, ensuring no write operations are in progress. +**设备节点销毁**:`destroy_dev(dev)` 从文件系统中移除 `/dev/led/name`,并释放 `cdev` 结构。该函数会阻塞,直到设备的所有打开文件描述符都被关闭,确保没有写操作正在进行。 -After `destroy_dev` returns, the device no longer exists in `/dev`, and any future attempts to open it will fail with `ENOENT` (no such file or directory). +`destroy_dev` 返回后,该设备在 `/dev` 中不再存在,任何未来尝试打开它的操作都将失败并返回 `ENOENT`(没有这样的文件或目录)。 -**Pattern buffer cleanup**: If an active pattern exists (`sc->spec != NULL`), its string buffer is freed with `sbuf_delete`. This handles the case where an LED is destroyed while a blink pattern is running. +**模式缓冲区清理**:如果存在活动的模式(`sc->spec != NULL`),则使用 `sbuf_delete` 释放其字符串缓冲区。这处理了LED在闪烁模式运行时被销毁的情况。 -**Name string cleanup**: `free(sc->name, M_LED)` releases the duplicated name string allocated during `led_create`. The `M_LED` type tag matches the allocation, maintaining accounting consistency. +**名称字符串清理**:`free(sc->name, M_LED)` 释放 `led_create` 期间分配的名称副本。类型标签 `M_LED` 与分配匹配,保持记账一致性。 -**Softc deallocation**: `free(sc, M_LED)` releases the LED state structure itself. After this call, the `sc` pointer is invalid and must not be accessed. +**软实例释放**:`free(sc, M_LED)` 释放LED状态结构本身。此调用后,`sc` 指针无效,不得再被访问。 -**Lock release**: The exclusive lock is released, allowing other device operations to proceed. All resources associated with this LED have been freed. +**锁释放**:释放排他锁,允许其他设备操作继续进行。与该LED关联的所有资源都已释放。 -##### Symmetric Cleanup +##### 对称清理 -The destruction sequence precisely reverses creation: +销毁序列精确逆转了创建过程: -| Creation Step | Destruction Step | +| 创建步骤 | 销毁步骤 | | ------------------------------- | ------------------------------- | -| Allocate softc | Free softc | -| Duplicate name | Free name | -| Allocate unit | Free unit | -| Create device node | Destroy device node | -| Insert into list | Remove from list | -| Increment blinkers (if pattern) | Decrement blinkers (if pattern) | +| 分配 softc | 释放 softc | +| 复制名称 | 释放名称 | +| 分配单元 | 释放单元 | +| 创建设备节点 | 销毁设备节点 | +| 插入到列表 | 从列表移除 | +| 递增闪烁计数(如果有模式) | 递减闪烁计数(如果有模式) | -This symmetry ensures complete cleanup with no resource leaks. Every allocation has a corresponding deallocation, every list insertion has a removal, every increment has a decrement. +这种对称性确保了完全清理,没有资源泄漏。每个分配都有对应的释放,每个列表插入都有移除,每个递增都有递减。 -##### Handling Active LEDs +##### 处理活动中的 LED -If an LED is destroyed while actively blinking, the function handles this cleanly: +如果LED在活跃闪烁时被销毁,该函数会干净地处理: -**Before destruction**: +**销毁前**: ```text LED state: ptr = "AaAa", spec = sbuf, blinkers = 1 Timer: scheduled, will fire in 0.1s ``` -**During destruction**: +**销毁期间**: ```text Mutex locked @@ -7142,7 +7143,7 @@ Timer fires, sees empty list, doesn't reschedule sbuf_delete (frees pattern) ``` -**After destruction**: +**销毁之后**: ```text LED state: freed @@ -7150,13 +7151,13 @@ Timer: stopped Device: removed from /dev ``` -The LED's pattern is interrupted mid-execution, but no crashes or leaks occur. The hardware LED is left in whatever state it was in at destruction time, turning it off explicitly is the hardware driver's responsibility if desired. +LED 的模式会在执行过程中被中断,但不会发生崩溃或内存泄漏。硬件 LED 会保持在销毁时的状态,如果需要将其显式关闭,这属于硬件驱动程序的职责。 -##### Thread Safety Considerations +##### 线程安全注意事项 -The two-phase locking (mutex then exclusive lock) prevents several race conditions: +两阶段锁定(先互斥锁再排他锁)避免了多种竞态条件: -**Race 1: Write vs. Destroy** +**竞态 1:写入与销毁** ```text Thread A (write) Thread B (destroy) @@ -7172,9 +7173,9 @@ Unlock led_mtx [write returns] Return error destroy_dev() completes ``` -The write operation safely detects the destroyed LED via the NULL check and returns an error without accessing freed memory. +写操作通过 NULL 检查安全地检测到已销毁的 LED,并返回错误,而不会访问已释放的内存。 -**Race 2: Timer vs. Destroy** +**竞态 2:定时器与销毁** ```text Timer callback running led_destroy() called @@ -7187,11 +7188,11 @@ Move to next LED [timer continues] Free softc ``` -The timer finishes processing the LED before it's removed from the list. The mutex ensures the LED isn't freed while the timer is accessing it. +定时器在 LED 从列表中移除之前完成对其的处理。互斥锁确保定时器访问 LED 时,LED 不会被释放。 -##### Contrast with null.c +##### 与 null.c 的对比 -The null driver's cleanup in `MOD_UNLOAD` was simple: +空驱动在 `MOD_UNLOAD` 中的清理很简单: ```c destroy_dev(full_dev); @@ -7199,21 +7200,21 @@ destroy_dev(null_dev); destroy_dev(zero_dev); ``` -Three fixed devices, three destroy calls, done. The LED driver's cleanup is more complex because: +三个固定设备,三次销毁调用,完成。LED 驱动的清理更复杂,因为: -**Dynamic lifecycle**: LEDs are created and destroyed individually as hardware appears and disappears, not all at once during module unload. +**动态生命周期**:LED 随着硬件的出现和消失而独立创建和销毁,而不是在模块卸载时一次性处理。 -**Active state**: LEDs may have running timers and allocated patterns that need cleanup. +**活动状态**:LED 可能有正在运行的定时器和已分配的模式需要清理。 -**Reference counting**: The `blinkers` counter must be maintained correctly for timer management. +**引用计数**:`blinkers` 计数器必须正确维护,以进行定时器管理。 -**List management**: Removal from the global registry requires proper list manipulation. +**列表管理**:从全局注册表中移除需要进行正确的列表操作。 -This additional complexity is the cost of supporting dynamic device creation, the subsystem must handle arbitrary sequences of create/destroy operations without leaking resources or corrupting state. +这些额外的复杂性是支持创建设备动态的代价;子系统必须处理任意顺序的创建/销毁操作,而不泄漏资源或破坏状态。 -##### Usage Example +##### 使用示例 -A complete hardware driver lifecycle: +一个完整的硬件驱动程序生命周期: ```c // During attach @@ -7228,9 +7229,9 @@ led_destroy(sc->led_dev); // All resources freed ``` -After `led_destroy` returns, the hardware driver can safely unload without leaving orphaned LED state in the kernel. +在 `led_destroy` 返回后,硬件驱动程序可以安全地卸载,而不会在内核中留下孤立的 LED 状态。 -#### 9) Driver init: set up bookkeeping and the callout +#### 9) 驱动初始化:设置簿记与定时回调 ```c 331: static void @@ -7244,11 +7245,11 @@ After `led_destroy` returns, the hardware driver can safely unload without leavi 341: SYSINIT(leddev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, led_drvinit, NULL); ``` -##### Driver Initialization and Registration +##### 驱动程序初始化与注册 -The final section of the LED driver handles one-time initialization during system boot. This code sets up the global infrastructure needed before any LEDs can be registered, establishing the foundation that all subsequent operations rely on. +LED 驱动的最后一部分负责系统启动时的一次性初始化。该代码设置注册任何 LED 之前所需的全局基础设施,为所有后续操作奠定基础。 -##### Initialization Function +##### 初始化函数 ```c static void @@ -7261,69 +7262,69 @@ led_drvinit(void *unused) } ``` -**Function signature**: Initialization functions registered with `SYSINIT` receive a single `void *` argument for optional data. The LED driver doesn't need any initialization parameters, so the argument is unused and named accordingly. +**函数签名**:使用 `SYSINIT` 注册的初始化函数接收一个 `void *` 参数用于可选数据。LED 驱动不需要任何初始化参数,因此该参数未使用,并以此命名。 -**Unit number allocator creation**: `new_unrhdr(0, INT_MAX, NULL)` creates a unit number pool that can allocate integers from 0 to `INT_MAX` (typically 2,147,483,647). Each LED registered will receive a unique number from this range, used as the device minor number. The NULL parameter indicates no mutex protects this allocator; external locking (via `led_sx`) will serialize access instead. +**单元号分配器创建**:`new_unrhdr(0, INT_MAX, NULL)` 创建一个单元号池,可以分配从 0 到 `INT_MAX`(通常为 2,147,483,647)的整数。每个注册的 LED 将从此范围获得一个唯一编号,用作设备次设备号。NULL 参数表示没有互斥锁保护此分配器;外部锁定(通过 `led_sx`)将对访问进行序列化。 -**Mutex initialization**: `mtx_init(&led_mtx, "LED mtx", NULL, MTX_DEF)` initializes the mutex that protects: +**互斥锁初始化**:`mtx_init(&led_mtx, "LED mtx", NULL, MTX_DEF)` 初始化保护以下内容的互斥锁: -- The LED list during insertions, removals, and traversals -- The `blinkers` counter -- Per-LED pattern execution state +- 插入、移除和遍历时的 LED 列表 +- `blinkers` 计数器 +- 每个 LED 的模式执行状态 -The parameters specify: +参数指定: -- `&led_mtx` - the mutex structure to initialize -- `"LED mtx"` - name appearing in lock debugging and analysis tools -- `NULL` - no witness data (advanced lock-order checking not needed) -- `MTX_DEF` - default mutex type (can sleep while held, standard recursion rules) +- `&led_mtx` - 要初始化的互斥锁结构 +- `"LED mtx"` - 出现在锁调试和分析工具中的名称 +- `NULL` - 无 witness 数据(不需要高级锁顺序检查) +- `MTX_DEF` - 默认互斥锁类型(持有时可睡眠,标准递归规则) -**Shared/exclusive lock initialization**: `sx_init(&led_sx, "LED sx")` initializes the lock that protects device creation and destruction. The simpler parameter list reflects that sx locks have fewer options than mutexes; they're always sleepable and non-recursive. +**共享/排他锁初始化**:`sx_init(&led_sx, "LED sx")` 初始化保护设备创建和销毁的锁。更简单的参数列表反映了 sx 锁相比互斥锁选项更少;它们始终是可睡眠且非递归的。 -**Timer initialization**: `callout_init_mtx(&led_ch, &led_mtx, 0)` prepares the timer callback infrastructure. The parameters specify: +**定时器初始化**:`callout_init_mtx(&led_ch, &led_mtx, 0)` 准备定时器回调基础设施。参数指定: -- `&led_ch` - the callout structure to initialize -- `&led_mtx` - the mutex held when timer callbacks execute -- `0` - flags (none needed) +- `&led_ch` - 要初始化的 callout 结构 +- `&led_mtx` - 定时器回调执行时持有的互斥锁 +- `0` - 标志(不需要) -This initialization associates the timer with the mutex, so timer callbacks automatically hold `led_mtx` while executing. This simplifies locking in `led_timeout`, it doesn't need to acquire the mutex explicitly because the callout infrastructure does it automatically. +此初始化将定时器与互斥锁关联,因此定时器回调在执行时自动持有 `led_mtx`。这简化了 `led_timeout` 中的锁定,它无需显式获取互斥锁,因为 callout 基础设施会自动完成。 -##### Boot-Time Registration +##### 启动时注册 ```c SYSINIT(leddev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, led_drvinit, NULL); ``` -The `SYSINIT` macro registers the initialization function with the kernel's boot sequence. The kernel calls registered functions in order during startup, ensuring dependencies are satisfied. +`SYSINIT` 宏将初始化函数注册到内核的启动序列中。内核在启动期间按顺序调用已注册的函数,确保依赖关系得到满足。 -**Macro parameters**: +**宏参数**: -**`leddev`**: A unique identifier for this initialization. Must be unique across the entire kernel to prevent collisions. The name doesn't affect behavior, it's purely for identification in debugging. +**`leddev`**:此次初始化的唯一标识符。必须在整个内核中唯一,以防止冲突。名称不影响行为,仅用于调试标识。 -**`SI_SUB_DRIVERS`**: The subsystem level. The kernel initialization happens in phases (we will see a simplified list, the `...` in the list below means that we have skipped some phases): +**`SI_SUB_DRIVERS`**:子系统层级。内核初始化分阶段进行(我们将看到一个简化的列表,下面列表中的 `...` 表示我们跳过了某些阶段): -- `SI_SUB_TUNABLES` - system tunables -- `SI_SUB_COPYRIGHT` - display copyright -- `SI_SUB_VM` - virtual memory -- `SI_SUB_KMEM` - kernel memory allocator +- `SI_SUB_TUNABLES` - 系统可调参数 +- `SI_SUB_COPYRIGHT` - 显示版权信息 +- `SI_SUB_VM` - 虚拟内存 +- `SI_SUB_KMEM` - 内核内存分配器 - ... -- `SI_SUB_DRIVERS` - device drivers +- `SI_SUB_DRIVERS` - 设备驱动程序 - ... -- `SI_SUB_RUN_SCHEDULER` - start scheduler +- `SI_SUB_RUN_SCHEDULER` - 启动调度器 -The LED driver initializes during the driver phase, after core kernel services (memory allocation, locking primitives) are available but before devices start attaching. +LED 驱动程序在驱动阶段初始化,此时核心内核服务(内存分配、锁定原语)已可用,但设备尚未开始连接。 -**`SI_ORDER_MIDDLE`**: The order within the subsystem. Multiple initializers in the same subsystem execute in order from `SI_ORDER_FIRST` through `SI_ORDER_ANY` to `SI_ORDER_LAST`. Using `MIDDLE` places the LED driver in the middle of the driver initialization phase, not critical to go first, but not dependent on everything else either. +**`SI_ORDER_MIDDLE`**:子系统内的顺序。同一子系统中的多个初始化器按顺序执行,从 `SI_ORDER_FIRST` 到 `SI_ORDER_ANY` 再到 `SI_ORDER_LAST`。使用 `MIDDLE` 将 LED 驱动程序置于驱动初始化阶段的中间,不一定要先执行,但也不依赖于其他所有内容。 -**`led_drvinit`**: Pointer to the initialization function. +**`led_drvinit`**:指向初始化函数的指针。 -**`NULL`**: No argument data to pass to the function. +**`NULL`**:不向函数传递参数数据。 -##### Initialization Ordering +##### 初始化顺序 -The `SYSINIT` mechanism ensures proper initialization order: +`SYSINIT` 机制确保正确的初始化顺序: -**Before LED init**: +**在 LED 初始化之前**: ```text Memory allocator running (malloc works) @@ -7332,7 +7333,7 @@ Timer subsystem operational (callout_init works) Device filesystem ready (make_dev will work later) ``` -**During LED init**: +**在 LED 初始化期间**: ```text led_drvinit() called @@ -7342,7 +7343,7 @@ Initialize locks Prepare timer infrastructure ``` -**After LED init**: +**在 LED 初始化之后**: ```text Hardware drivers attach @@ -7352,11 +7353,11 @@ Call led_create() Use the already-initialized infrastructure ``` -Without `SYSINIT`, hardware drivers that call `led_create()` during their attach functions would crash attempting to use uninitialized locks or allocate from a NULL unit number pool. +如果没有 `SYSINIT`,在其连接函数中调用 `led_create()` 的硬件驱动程序会在尝试使用未初始化的锁或从 NULL 单元号池分配时崩溃。 -##### Contrast with null.c Module Load +##### 与 null.c 模块加载的对比 -The null driver used module event handlers: +空驱动程序使用了模块事件处理程序: ```c static int @@ -7375,37 +7376,37 @@ null_modevent(module_t mod, int type, void *data) DEV_MODULE(null, null_modevent, NULL); ``` -Module events fire when loadable modules are loaded or unloaded. The LED driver uses `SYSINIT` instead because: +当可加载模块被加载或卸载时,模块事件被触发。LED 驱动程序改用 `SYSINIT`,原因如下: -**Always needed**: The LED subsystem is infrastructure that other drivers depend on. It should initialize early during boot, not wait for explicit module loading. +**始终需要**:LED 子系统是其他驱动程序依赖的基础设施。它应在引导早期初始化,而非等待显式的模块加载。 -**No unload**: The LED subsystem doesn't provide a module unload handler. Once initialized, it remains available for the system's lifetime. Unloading would be complex, all registered LEDs would need to be destroyed, which requires coordinating with potentially many hardware drivers. +**不可卸载**:LED 子系统不提供模块卸载处理程序。一旦初始化,它将在系统整个生命周期内保持可用。卸载将非常复杂,所有已注册的 LED 都需要被销毁,这需要与众多硬件驱动程序协调。 -**Separate concerns**: `SYSINIT` handles initialization, while individual LEDs are created/destroyed dynamically as hardware appears/disappears. The null driver conflated initialization with device creation (both happened in `MOD_LOAD`), while the LED driver separates them. +**关注点分离**:`SYSINIT` 负责初始化,而单个 LED 随硬件的出现/消失动态创建/销毁。空驱动程序将初始化与设备创建混为一谈(两者均在 `MOD_LOAD` 中发生),而 LED 驱动程序则将它们分离开来。 -##### What's Not Initialized +##### 未初始化的内容 -Notice what this function **doesn't** do: +请注意此函数**未**执行的操作: -**No LED creation**: Unlike the null driver which created its three devices during initialization, the LED driver creates no devices here. Device creation is demand-driven via `led_create()` calls from hardware drivers. +**不创建 LED**:与空驱动程序在初始化期间创建其三个设备不同,LED 驱动程序在此处不创建设备。设备创建由硬件驱动程序通过 `led_create()` 调用按需驱动。 -**No list initialization**: The global `led_list` was statically initialized: +**不初始化链表**:全局 `led_list` 已静态初始化: ```c static LIST_HEAD(, ledsc) led_list = LIST_HEAD_INITIALIZER(led_list); ``` -Static initialization suffices for list heads, they're just pointer structures that start empty. +静态初始化足以用于链表头,它们只是起始为空指针结构。 -**No blinkers initialization**: The `blinkers` counter was declared `static int`, giving it an initial value of 0 automatically. No explicit initialization needed. +**不初始化闪烁器**:`blinkers` 计数器声明为 `static int`,自动赋予初始值 0。无需显式初始化。 -**No timer scheduling**: The timer callback starts inactive. It's only scheduled when the first LED receives a blink pattern, not during driver initialization. +**不调度定时器**:定时器回调初始处于非活动状态。仅当第一个 LED 接收到闪烁模式时才会调度它,而非在驱动程序初始化期间。 -This minimal initialization reflects good design: do the minimum necessary work at boot, defer everything else until actually needed. +这种最小初始化体现了良好设计:在引导时做最少必要的工作,将所有其他工作推迟到实际需要时。 -##### Complete Boot Sequence +##### 完整的启动序列 -The full sequence from power-on to working LEDs: +从开机到 LED 正常工作的完整序列: ```text 1. Kernel starts @@ -7425,320 +7426,147 @@ The full sequence from power-on to working LEDs: - LEDs blink and indicate status ``` -The LED subsystem is ready before hardware drivers need it, and hardware drivers can register LEDs at any point during or after boot without worrying about initialization order. +LED 子系统在硬件驱动程序需要之前就已就绪,硬件驱动程序可以在引导期间或之后任意时刻注册 LED,而无需担心初始化顺序。 -##### Why This Matters +##### 为何如此重要 -This initialization pattern, early infrastructure setup via `SYSINIT`, late device creation on demand, is fundamental to FreeBSD's modular architecture. It allows: +这种通过 `SYSINIT` 提前搭建基础设施、后期按需创建设备的初始化模式,是 FreeBSD 模块化架构的基础。它允许: -**Flexibility**: Hardware drivers don't need to coordinate initialization order. The LED subsystem is always ready when they need it. +**灵活性**:硬件驱动程序无需协调初始化顺序。LED 子系统在它们需要时始终可用。 -**Scalability**: The subsystem doesn't pre-allocate resources for devices that might not exist. Memory usage scales with actual hardware. +**可扩展性**:子系统不会预先为可能不存在的设备分配资源。内存使用量随实际硬件数量而变化。 -**Modularity**: Hardware drivers depend only on the LED API, not on implementation details. The subsystem can change internally without affecting drivers. +**模块化**:硬件驱动程序仅依赖 LED API,而非实现细节。子系统可在内部更改而不影响驱动程序。 -**Reliability**: Initialization failures (like memory exhaustion during `new_unrhdr`) are fatal panics rather than obscure later crashes, making problems immediately visible during boot. +**可靠性**:初始化失败(例如 `new_unrhdr` 期间内存耗尽)会导致致命 panic,而非后续难以追踪的崩溃,使问题在引导期间立即显现。 -This design philosophy, initialize infrastructure early, create instances lazily, appears throughout the FreeBSD kernel and is worth understanding for anyone implementing subsystems or drivers. +这种设计理念——早期初始化基础设施、延迟创建实例——贯穿 FreeBSD 内核,对于任何实现子系统或驱动程序的开发者而言都值得理解。 -#### Interactive Exercises for `led(4)` +#### `led(4)` 的交互练习 -**Goal:** Understand dynamic device creation, timer-based state machines, and pattern parsing. This driver builds on concepts from the null driver but adds stateful pattern execution and kernel API design. +**目标:** 理解动态设备创建、基于定时器的状态机和模式解析。此驱动程序建立在 null 驱动程序概念的基础上,但增加了有状态的模式执行和内核 API 设计。 -##### A) Structure and Global State +##### A) 结构和全局状态 -1. Examine the `struct ledsc` definition near the top of `led.c`. This structure contains both device identity and pattern execution state. Create a table categorizing the fields: +1. 检查 `led.c` 顶部附近的 `struct ledsc` 定义。此结构包含设备标识和模式执行状态。创建一个表格分类这些字段: -| Field | Purpose | Category | +| 字段 | 目的 | 类别 | | ----- | ------- | ----------------- | -| list | ? | Linkage | -| name | ? | Identity | -| ptr | ? | Pattern execution | +| list | ? | 链接 | +| name | ? | 标识 | +| ptr | ? | 模式执行 | | ... | ... | ... | - Quote the fields related to pattern execution (`str`, `ptr`, `count`, `last_second`) and explain the role of each in one sentence. + 引用与模式执行相关的字段(`str`、`ptr`、`count`、`last_second`),并用一句话解释每个字段的作用。 -2. Locate the file-scope statics that follow `struct ledsc` (`led_unit`, `led_mtx`, `led_sx`, `led_list`, `led_ch`, `blinkers`, and the `M_LED` `MALLOC_DEFINE`). For each one, explain its purpose: +2. 找到 `struct ledsc` 之后的文件范围静态变量(`led_unit`、`led_mtx`、`led_sx`、`led_list`、`led_ch`、`blinkers` 以及 `M_LED` `MALLOC_DEFINE`)。对于每一个,解释其目的: -- `led_unit` - what does this allocate? -- `led_mtx` vs. `led_sx` - why two locks? What does each protect? -- `led_list` - who iterates this and when? -- `led_ch` - what triggers this? -- `blinkers` - what happens when this reaches 0? +- `led_unit` - 这分配什么? +- `led_mtx` 与 `led_sx` - 为什么两个锁?每个保护什么? +- `led_list` - 谁在什么时候遍历它? +- `led_ch` - 什么触发它? +- `blinkers` - 当它达到 0 时会发生什么? -Quote the declaration lines. + 引用声明行。 -3. Examine the `led_cdevsw` structure. Which operation is defined? Which operations are notably absent (compare to null.c)? What appears under `/dev` when LEDs are created? +3. 检查 `led_cdevsw` 结构。定义了哪个操作?哪些操作明显缺失(与 null.c 比较)?创建 LED 时 `/dev` 下出现什么? -##### B) Write-to-Blink Path +##### B) 写入到闪烁的路径 -1. Trace the data flow in `led_write()`: +1. 追踪 `led_write()` 中的数据流: -- Find the size check - what's the limit and why? -- Find the buffer allocation - why `uio_resid + 1`? -- Find the `uiomove()` call - what's being copied? -- Find the parse call - what does it produce? -- Find the state update - what lock is held? +- 找到大小检查 - 限制是什么,为什么? +- 找到缓冲区分配 - 为什么是 `uio_resid + 1`? +- 找到 `uiomove()` 调用 - 正在拷贝什么? +- 找到解析调用 - 它产生什么? +- 找到状态更新 - 持有什么锁? -Quote each step and write one sentence explaining its purpose. + 引用每个步骤并写一句话解释其目的。 -2. In `led_state()`, trace two paths: +2. 在 `led_state()` 中,追踪两条路径: -**Path 1** - Installing a pattern (sb != NULL): +**路径 1** - 安装模式(sb != NULL): -- Which fields change in the softc? -- When is `blinkers` incremented? -- What does `sc->ptr = sc->str` accomplish? +- softc 中哪些字段发生变化? +- `blinkers` 何时递增? +- `sc->ptr = sc->str` 实现了什么? -**Path 2** - Setting static state (sb == NULL): +**路径 2** - 设置静态状态(sb == NULL): -- Which fields change? -- When is `blinkers` decremented? -- Why call `sc->func()` here but not in Path 1? +- 哪些字段发生变化? +#### 延伸(思想实验) -Quote the key lines for each path. +1. 定时器自重新调度逻辑(`led_timeout` 末尾的 `if (blinkers > 0)` 守卫加上 `callout_reset(&led_ch, hz / 10, led_timeout, p)`): -3. Explain the timer-to-pattern connection: - -- When `blinkers` goes from 0 -> 1, what must happen? (Hint: who schedules the timer?) -- When `blinkers` goes from 1 -> 0, what must happen? (Hint: look for `LIST_EMPTY(&led_list)` and the adjacent `callout_stop(&led_ch)` call in `led_destroy`.) -- Why doesn't `led_state()` directly schedule the timer? - -##### C) Timer Callback State Machine - -1. In `led_timeout()`, explain the pattern interpreter: - -Create a table showing what each code does: - -| Code | LED Action | Duration Setup | Example | -| ------- | ---------- | -------------- | --------------- | -| 'A'-'J' | ? | count = ? | 'C' means? | -| 'a'-'j' | ? | count = ? | 'c' means? | -| 'U'/'u' | ? | Special timing | What's checked? | -| '.' | ? | N/A | What happens? | - -Quote the lines implementing each case. - -2. The `count` field implements delays: - -- When is `count` set to non-zero? Quote the line. -- When is `count` decremented? Quote the line. -- Why does the pattern advance skip when `count > 0`? - -Trace pattern "Ac" (on 0.1s, off 0.3s) through three timer ticks: - -- Tick 1: What happens? -- Tick 2: What happens? -- Tick 3: What happens? - -3. Find the timer rescheduling logic at the tail of `led_timeout` (the `if (blinkers > 0)` guard followed by `callout_reset(&led_ch, hz / 10, led_timeout, p)`): - -- What condition must be true for rescheduling? -- What's the delay (`hz / 10` means what in seconds)? -- Why doesn't the timer reschedule when `blinkers == 0`? - -##### D) Pattern Parsing DSL - -1. For the flash command "f2" (the `case 'f':` arm inside `led_parse`): - -- What does the digit '2' map to (i = ?)? -- What two-character string is generated? -- How long is each phase in timer ticks? -- What frequency does this produce? - -Quote the lines and calculate the blink rate. - -2. For the Morse command "m...---..." (the `case 'm':` arm inside `led_parse`): - -- What string is generated for '.' (dot)? -- What string is generated for '-' (dash)? -- What string is generated for ' ' (space)? -- What string is generated for '\\n' (newline)? - -Quote the `sbuf_cat()` calls and explain how this implements standard Morse timing (dot = 1 unit, dash = 3 units). - -3. For the digit command "d12" (the `case 'd':` arm inside `led_parse`): - -- How is digit '1' represented in flashes? -- How is digit '2' represented in flashes? -- Why is '0' treated as 10 instead of 0? -- What separates repetitions of the pattern? - -Quote the loop and explain the formula for flash count. - -##### E) Dynamic Device Lifecycle - -1. In `led_create_state()`, identify the initialization sequence: - -- What's allocated first and with what flags? -- Which lock is acquired for device creation? Why exclusive? -- What parameters does `make_dev()` receive? What path is created? -- Which lock protects list insertion? Why different from device creation? -- When is the hardware callback invoked, and what does `state != -1` mean? - -Quote each phase and explain the lock separation. - -2. In `led_destroy()`, trace the cleanup: - -- Why is `dev->si_drv1` set to NULL immediately? -- When is `blinkers` decremented? -- Why call `callout_stop()` only when list becomes empty? -- Which resources are freed under which lock? - -Create a table mapping each `led_create()` allocation to its corresponding `led_destroy()` deallocation. - -3. Explain the two-phase locking: - -- Why acquire `led_mtx` first, then release it before acquiring `led_sx`? -- What would happen if we held `led_mtx` during `destroy_dev()`? -- Could we use just one lock for everything? What would be the downsides? - -##### F) Kernel API vs. Device Write - -1. Compare `led_write()` and `led_set()`: - -- Both call `led_parse()` and `led_state()` - what's different about how they find the LED? -- `led_write()` has size limits - does `led_set()` need them? Why or why not? -- Who typically calls each function? Give examples. - -Quote the LED lookup logic in both functions. - -2. Find the `led_cdevsw` declaration and explain why it's shared: - -- How many `cdevsw` structures exist for N LEDs? -- How does `led_write()` know which LED it's writing to? -- Compare this to null.c which had three separate `cdevsw` structures. - -##### G) System Integration - -1. Examine the initialization (`led_drvinit` and its `SYSINIT` registration): - -- What does `SYSINIT` do and when does it run? -- What are the four resources initialized in `led_drvinit()`? -- Why is the callout associated with `led_mtx`? -- What's NOT initialized here (compare to null.c's `MOD_LOAD`)? - -2. Find where the driver registers with `SYSINIT`: - -- What's the subsystem level (`SI_SUB_DRIVERS`)? -- Why not use `DEV_MODULE` like null.c did? -- Can this driver be unloaded? Why or why not? - -##### H) Safe Experiments (optional, only if you have a system with physical LEDs) - -1. If your system has LEDs in `/dev/led`, try these (as root in a VM): - -```bash -# List available LEDs -ls -l /dev/led/ - -# Fast blink -echo "f" > /dev/led/SOME_LED_NAME - -# Slow blink -echo "f5" > /dev/led/SOME_LED_NAME - -# Morse code SOS -echo "m...---..." > /dev/led/SOME_LED_NAME - -# Static on -echo "1" > /dev/led/SOME_LED_NAME - -# Static off -echo "0" > /dev/led/SOME_LED_NAME -``` - -For each test: - -- Which parse case handles the command? -- What internal pattern string is generated? -- Estimate the timing you observe and verify against the code. - -2. Try invalid commands and explain the errors: - -```bash -# Too long -perl -e 'print "f" x 600' > /dev/led/SOME_LED_NAME -# What error? Which line checks this? - -# Invalid syntax -echo "xyz" > /dev/led/SOME_LED_NAME -# What error? Which case handles this? -``` - -#### Stretch (thought experiments) - -1. The timer self-rescheduling logic (the `if (blinkers > 0)` guard plus `callout_reset(&led_ch, hz / 10, led_timeout, p)` at the tail of `led_timeout`): - -Suppose we removed the `if (blinkers > 0)` check and always called: +假设我们移除 `if (blinkers > 0)` 检查,总是调用: ```c callout_reset(&led_ch, hz / 10, led_timeout, p); ``` -Trace what happens when: +追踪当以下情况发生时会发生什么: -- User writes "f" to an LED (timer starts) -- Pattern runs for 5 seconds -- User writes "0" to stop blinking (blinkers -> 0) +- 用户向 LED 写入 "f"(定时器启动) +- 模式运行 5 秒 +- 用户写入 "0" 停止闪烁(blinkers -> 0) -What's the symptom? Where's the wasted resource? Why does the current check prevent this? +症状是什么?浪费的资源在哪里?为什么当前的检查能防止这种情况? -2. The write size limit (the `if (uio->uio_resid > 512) return (EINVAL);` check in `led_write`): +2. 写入大小限制(`led_write` 中的 `if (uio->uio_resid > 512) return (EINVAL);` 检查): -The code rejects writes over 512 bytes. Consider removing this check: +代码拒绝超过 512 字节的写入。考虑移除此检查: -- What's the immediate risk with `malloc(uio->uio_resid, ...)`? -- The parser then allocates an `sbuf` - what's the risk there? -- Could an attacker cause a denial of service? How? -- Why is 512 bytes plenty for any legitimate LED pattern? +- `malloc(uio->uio_resid, ...)` 的即时风险是什么? +- 解析器然后分配一个 `sbuf` - 那里的风险是什么? +- 攻击者能否造成拒绝服务?如何? +- 为什么 512 字节对任何合法的 LED 模式都足够了? -Point to the current guard and explain the defense-in-depth principle. +指出当前的守卫并解释纵深防御原则。 -3. The two-lock design: +3. 双锁设计: -Suppose we replaced both `led_mtx` and `led_sx` with a single mutex. What would break? +假设我们用单个互斥锁替换 `led_mtx` 和 `led_sx`。什么会出问题? -Scenario 1: `led_create()` calls `make_dev()` while holding the lock, and `make_dev()` blocks. What happens to timer callbacks during this time? +场景 1:`led_create()` 在持有锁时调用 `make_dev()`,而 `make_dev()` 阻塞。此期间定时器回调会怎样? -Scenario 2: A write operation holds the lock while parsing a complex pattern. What happens to other LEDs' timer updates? +场景 2:写入操作在解析复杂模式时持有锁。其他 LED 的定时器更新会怎样? -Explain why separating device structure operations (`led_sx`) from state operations (`led_mtx`) improves concurrency. +解释为什么将设备结构操作(`led_sx`)与状态操作(`led_mtx`)分离能改善并发性。 -**Note:** If your system doesn't have physical LEDs, you can still trace through the code and understand the patterns. The mental model of "timer walks list -> interprets codes -> calls callbacks" is the key lesson, not seeing actual lights blink. +**注意:** 如果你的系统没有物理 LED,你仍然可以通过代码追踪并理解这些模式。"定时器遍历列表 -> 解释代码 -> 调用回调"的心智模型是关键课程,而不是看到实际的灯闪烁。 -#### Bridge to the next tour +#### 前往下一个导览的过渡 -If you can walk the path from **user `write()`** to a **timer-driven state machine** and back to **device teardown**, you've internalized the write-centric character-device shape with timers and sbuf-powered parsing. Next we'll look at a slightly different shape: a **network interface pseudo-device** that binds into the **ifnet** stack (`if_tuntap.c`). Keep your eyes on three things: how the driver **registers** with a larger subsystem, how **I/O is routed** through that subsystem's callbacks, and how **open/close/lifecycle** differs from the small `/dev` patterns you've just mastered. +如果你能从**用户 `write()`** 到**定时器驱动的状态机**再回到**设备拆卸**的路径走一遍,你就内化了带有定时器和 sbuf 驱动解析的以写入为中心的字符设备形态。接下来我们将看一个稍有不同的形态:一个绑定到 **ifnet** 协议栈的**网络接口伪设备**(`if_tuntap.c`)。继续关注三件事:驱动程序如何向更大的子系统**注册**、I/O 如何通过该子系统的回调**路由**,以及 **open/close/生命周期**与你刚刚掌握的小型 `/dev` 模式有何不同。 -> **Checkpoint.** You have now walked through the full shape of a simple driver: the Newbus lifecycle, `cdevsw` entry points, `make_dev()` and devctl, module packaging with `bsd.kmod.mk`, and two real character drivers, the null/zero/full trio and `led(4)`. The rest of the chapter turns to drivers that plug into larger subsystems: the `tun(4)/tap(4)` pseudo-NIC that binds into the ifnet stack, the PCI-backed `uart(4)` glue driver, the synthesis that pulls four tours into one mental model, and the blueprints and labs that turn reading into practice. If you want to close the book and come back, this is a natural pause. +> **检查点。** 你现在已经走过了简单驱动程序的完整形态:Newbus 生命周期、`cdevsw` 入口点、`make_dev()` 和 devctl、使用 `bsd.kmod.mk` 的模块封装,以及两个真实的字符驱动程序——null/zero/full 三件套和 `led(4)`。本章其余部分转向插入更大子系统的驱动程序:绑定到 ifnet 协议栈的 `tun(4)/tap(4)` 伪网卡、PCI 支持的 `uart(4)` 粘合驱动程序、将四次导览整合为一个心智模型的综合,以及将阅读转化为实践的蓝图和实验。如果你想合上书稍后回来,这是一个自然的暂停点。 -### Tour 3 - A pseudo-NIC that is also a character device: `tun(4)/tap(4)`: +### 导览 3 - 一个同时也是字符设备的伪网卡:`tun(4)/tap(4)`: -Open the file: +打开文件: ```console % cd /usr/src/sys/net % less if_tuntap.c ``` -This driver is a perfect "small but real" example of integrating a simple character device with a larger kernel **subsystem** (the network stack). It exposes `/dev/tunN`, `/dev/tapN`, and `/dev/vmnetN` character devices, while also registering **ifnet** interfaces that you can `ifconfig`. +此驱动程序是将简单字符设备与更大的内核**子系统**(网络栈)集成的完美"小而真实"的示例。它暴露 `/dev/tunN`、`/dev/tapN` 和 `/dev/vmnetN` 字符设备,同时注册可以用 `ifconfig` 管理的 **ifnet** 接口。 -As you read, keep these "anchors" in mind: +阅读时,记住这些"锚点": -- **Character device surface**: `cdevsw` + `open/read/write/ioctl/poll/kqueue`; -- **Network surface**: `ifnet` + `if_attach` + `bpfattach;` -- **Cloning**: on-demand creation of `/dev/tunN` and the corresponding `ifnet`; +- **字符设备表面**:`cdevsw` + `open/read/write/ioctl/poll/kqueue`; +- **网络表面**:`ifnet` + `if_attach` + `bpfattach`; +- **克隆**:按需创建 `/dev/tunN` 和相应的 `ifnet`; -- how a **`cdevsw`** maps `open/read/write/ioctl` into driver code for three related device names; -- how opening `/dev/tun0` et al. lines up with creating/configuring an **`ifnet`**; -- how data **flows** both ways: packets from kernel -> user via `read(2)`, and user -> kernel via `write(2)`. +- **`cdevsw`** 如何将 `open/read/write/ioctl` 映射到三个相关设备名称的驱动代码; +- 打开 `/dev/tun0` 等如何与创建/配置 **`ifnet`** 对应; +- 数据如何双向**流动**:数据包从内核 -> 用户通过 `read(2)`,用户 -> 内核通过 `write(2)`。 -> **Note** +> **注意** > -> To keep this manageable, code examples below are excerpts from the 2071-line source file. Lines marked with `...` have been omitted. +> 为了保持可管理性,下面的代码示例是 2071 行源文件的节选。标记为 `...` 的行已被省略。 -#### 1) Where the character device surface is declared (the `cdevsw`) +#### 1) 字符设备表面声明的地方(`cdevsw`) ```c 270: static struct tuntap_driver { @@ -7805,11 +7633,11 @@ As you read, keep these "anchors" in mind: ``` -This initial fragment demonstrates a clever design pattern: **one driver implementation serving three related but distinct device types** (tun, tap, and vmnet). +这段初始代码展示了一种巧妙的设计模式:**一个驱动程序实现服务于三种相关但不同的设备类型**(tun、tap 和 vmnet)。 -Let's see how it works: +让我们看看它是如何工作的: -##### The `tuntap_driver` Structure +##### `tuntap_driver` 结构体 ```c struct tuntap_driver { @@ -7823,14 +7651,14 @@ struct tuntap_driver { }; ``` -This structure combines **two kernel subsystems**: +该结构体结合了**两个内核子系统**: -1. **Character device operations** (`cdevsw`) - how userspace interacts with `/dev/tunN`, `/dev/tapN`, `/dev/vmnetN` -2. **Network interface cloning** (`clone_*_fn`) - how the corresponding `ifnet` structures get created +1. **字符设备操作**(`cdevsw`)—— 用户空间如何与 `/dev/tunN`、`/dev/tapN`、`/dev/vmnetN` 交互 +2. **网络接口克隆**(`clone_*_fn`)—— 对应的 `ifnet` 结构体如何被创建 -##### The Critical `cdevsw` Structure +##### 关键的 `cdevsw` 结构体 -The `cdevsw` (character device switch) is FreeBSD's **function dispatch table** for character devices. Think of it as a vtable or interface: +`cdevsw`(字符设备开关)是 FreeBSD 字符设备的**函数分发表**。可将其视为虚函数表或接口: ```c .d_version = D_VERSION // ABI version check @@ -7844,51 +7672,51 @@ The `cdevsw` (character device switch) is FreeBSD's **function dispatch table** .d_name = tunname // Device name ("tun", "tap", "vmnet") ``` -**Key insight**: All three device types share the **same function implementations** (`tunopen`, `tunread`, etc.), but behave differently based on `ident_flags`. +**关键要点**:所有三种设备类型共享**相同的函数实现**(`tunopen`、`tunread` 等),但根据 `ident_flags` 表现不同行为。 -##### The Three Driver Instances +##### 三个驱动程序实例 -##### 1. **TUN** - Layer 3 (IP) tunnel +##### 1. **TUN** - 三层(IP)隧道 ```c .ident_flags = 0 // No flags = plain TUN device .d_name = tunname // "tun" -> /dev/tun0, /dev/tun1, ... ``` -- Point-to-point IP tunnel -- Packets are raw IP (no Ethernet headers) -- Used by VPNs like OpenVPN in TUN mode +- 点对点 IP 隧道 +- 数据包为原始 IP(无以太网头部) +- 用于 OpenVPN 在 TUN 模式下的 VPN -##### 2. **TAP** - Layer 2 (Ethernet) tunnel +##### 2. **TAP** - 二层(以太网)隧道 ```c .ident_flags = TUN_L2 // Layer 2 flag .d_name = tapname // "tap" -> /dev/tap0, /dev/tap1, ... ``` -- Ethernet-level tunnel -- Packets include full Ethernet frames -- Used by VMs, bridges, OpenVPN in TAP mode +- 以太网级隧道 +- 数据包包含完整的以太网帧 +- 由虚拟机、桥接、OpenVPN 的 TAP 模式使用 -##### 3. **VMNET** - VMware compatibility +##### 3. **VMNET** - VMware 兼容性 ```c .ident_flags = TUN_L2 | TUN_VMNET // Layer 2 + VMware semantics .d_name = vmnetname // "vmnet" -> /dev/vmnet0, ... ``` -- Like TAP but with VMware-specific behavior -- Different lifecycle rules (survives interface down) +- 类似 TAP,但具有 VMware 特定行为 +- 不同的生命周期规则(接口关闭后仍然存活) -##### How This Achieves Code Reuse +##### 如何实现代码复用 -Notice that **all three entries use identical function pointers**: +注意到**所有三个条目使用相同的函数指针**: -- `tunopen` handles opening all three device types -- `tunread`/`tunwrite` handle I/O for all three -- The functions check `tp->tun_flags` (derived from `ident_flags`) to determine behavior +- `tunopen` 处理所有三种设备类型的打开操作 +- `tunread`/`tunwrite` 处理所有三种设备的 I/O +- 这些函数检查 `tp->tun_flags`(派生自 `ident_flags`)以确定行为 -For example, in `tunopen`, you'll see: +例如,在 `tunopen` 中,你会看到: ```c if ((tp->tun_flags & TUN_L2) != 0) { @@ -7898,21 +7726,21 @@ if ((tp->tun_flags & TUN_L2) != 0) { } ``` -##### The Cloning Functions +##### 克隆函数 -Each driver has **different clone match functions** but shares create/destroy: +每个驱动程序具有**不同的克隆匹配函数**,但共享创建/销毁逻辑: -- `tun_clone_match` - matches "tun" or "tunN" -- `tap_clone_match` - matches "tap" or "tapN" -- `vmnet_clone_match` - matches "vmnet" or "vmnetN" -- All use `tun_clone_create` - shared creation logic -- All use `tun_clone_destroy` - shared destruction logic +- `tun_clone_match` - 匹配 "tun" 或 "tunN" +- `tap_clone_match` - 匹配 "tap" 或 "tapN" +- `vmnet_clone_match` - 匹配 "vmnet" 或 "vmnetN" +- 全部使用 `tun_clone_create` - 共享的创建逻辑 +- 全部使用 `tun_clone_destroy` - 共享的销毁逻辑 -This lets the kernel automatically create `/dev/tun0` when someone opens it, even if it doesn't exist yet. +这使得内核在有人打开 `/dev/tun0` 时能自动创建它,即使其尚不存在。 -#### 2) From clone request -> `cdev` creation -> `ifnet` attach +#### 2) 从克隆请求 → `cdev` 创建 → `ifnet` 附加 -#### 2.1 Clone creation (`tun_clone_create`): pick name/unit, ensure `cdev`, then hand off to `tuncreate` +#### 2.1 克隆创建(`tun_clone_create`):选择名称/单元,确保 `cdev`,然后交给 `tuncreate` ```c 520: tun_clone_create(struct if_clone *ifc, char *name, size_t len, @@ -7958,9 +7786,9 @@ This lets the kernel automatically create `/dev/tun0` when someone opens it, eve 560: } ``` -The `tun_clone_create` function serves as the bridge between FreeBSD's network interface cloning subsystem and character device creation. This function is invoked when a user executes commands like `ifconfig tun0 create` or `ifconfig tap1 create`, and its responsibility is to create both a character device (`/dev/tun0`) and its corresponding network interface. +`tun_clone_create` 函数作为 FreeBSD 网络接口克隆子系统与字符设备创建之间的桥梁。当用户执行 `ifconfig tun0 create` 或 `ifconfig tap1 create` 等命令时,该函数被调用,其职责是同时创建字符设备(`/dev/tun0`)及其对应的网络接口。 -##### Function Signature and Purpose +##### 函数签名与用途 ```c static int @@ -7968,11 +7796,11 @@ tun_clone_create(struct if_clone *ifc, char *name, size_t len, struct ifc_data *ifd, struct ifnet **ifpp) ``` -The function receives an interface name (like "tun0" or "tap3") and must return a pointer to a newly created `ifnet` structure through the `ifpp` parameter. Success returns 0; errors return the appropriate errno values, such as `EEXIST` or `ENXIO`. +该函数接收一个接口名称(如 "tun0" 或 "tap3"),必须通过 `ifpp` 参数返回一个指向新创建的 `ifnet` 结构的指针。成功返回 0;错误返回相应的 errno 值,例如 `EEXIST` 或 `ENXIO`。 -##### Parsing the Interface Name +##### 解析接口名称 -The first step extracts meaning from the interface name: +第一步从接口名称中提取含义: ```c tunflags = 0; @@ -7981,14 +7809,14 @@ if (err != 0) return (err); ``` -The `tuntap_name2info` helper function parses strings like "tap3" or "vmnet1" to extract: +`tuntap_name2info` 辅助函数解析类似 "tap3" 或 "vmnet1" 的字符串,提取出: -- The **unit number** (3, 1, etc.) -- The **type flags** that determine device behavior (0 for tun, TUN_L2 for tap, TUN_L2|TUN_VMNET for vmnet) +- **单元编号**(3、1 等) +- **类型标志**,决定设备行为(0 代表 tun,TUN_L2 代表 tap,TUN_L2|TUN_VMNET 代表 vmnet) -If the name contains no unit number (e.g., just "tun"), the function returns `-1` for the unit, signaling that any available unit should be allocated. +如果名称不包含单元编号(例如只有 "tun"),该函数对单元返回 `-1`,表示应分配任意可用单元。 -##### Locating the Appropriate Driver +##### 定位合适的驱动程序 ```c drv = tuntap_driver_from_flags(tunflags); @@ -7996,11 +7824,11 @@ if (drv == NULL) return (ENXIO); ``` -The extracted flags determine which entry from the `tuntap_drivers[]` array will handle this device. This lookup returns the `tuntap_driver` structure containing the correct `cdevsw` and device name ("tun", "tap", or "vmnet"). +提取的标志决定 `tuntap_drivers[]` 数组中的哪个条目将处理此设备。该查找返回包含正确 `cdevsw` 和设备名称("tun"、"tap" 或 "vmnet")的 `tuntap_driver` 结构。 -##### Unit Number Allocation +##### 单元号分配 -The driver maintains a unit number allocator (`unrhdr`) to prevent conflicts: +驱动程序维护一个单元编号分配器(`unrhdr`)以防止冲突: ```c if (unit != -1) { @@ -8013,21 +7841,21 @@ if (unit != -1) { } ``` -The `unrhdr` (unit number handler) ensures thread-safe allocation of device minor numbers. When a user requests a specific unit (e.g., "tun3"), `alloc_unr_specific` either reserves that number or returns failure if already allocated. When no specific unit is requested, `alloc_unr` selects the next available number. +`unrhdr`(单元编号处理程序)确保设备次编号的线程安全分配。当用户请求特定单元(例如 "tun3")时,`alloc_unr_specific` 要么保留该编号,要么在已分配时返回失败。当未指定特定单元时,`alloc_unr` 选择下一个可用编号。 -This mechanism prevents race conditions where multiple processes simultaneously attempt to create the same device unit, as the allocation is serialized by the global `tunmtx` mutex. +此机制防止了多个进程同时尝试创建同一设备单元时的竞态条件,因为分配由全局 `tunmtx` 互斥锁序列化。 -##### Name Normalization +##### 名称标准化 -After unit allocation, the function normalizes the interface name: +单元分配后,该函数规范化接口名称: ```c snprintf(name, IFNAMSIZ, "%s%d", drv->cdevsw.d_name, unit); ``` -If the user specified `ifconfig tun create` without a unit number, this formats the name with the newly allocated unit, producing strings like "tun0" or "tun1". The `name` parameter serves as both input and output, the caller's buffer receives the finalized name. +如果用户指定了 `ifconfig tun create` 但未提供单元编号,则会用新分配的单元格式化名称,生成类似 "tun0" 或 "tun1" 的字符串。`name` 参数既作为输入也作为输出,调用者的缓冲区接收最终的名称。 -##### Character Device Creation +##### 字符设备创建 ```c dev = NULL; @@ -8036,16 +7864,16 @@ if (i != 0) i = tun_create_device(drv, unit, NULL, &dev, name); ``` -This section handles an important subtlety: the character device may already exist. The `clone_create` call searches for an existing `/dev/tun0` device node, which might have been created earlier through devfs cloning when a process opened the device path. +本节处理一个重要细节:字符设备可能已存在。`clone_create` 调用搜索现有的 `/dev/tun0` 设备节点,该节点可能是在进程打开设备路径时通过 devfs 克隆提前创建的。 -When `clone_create` returns non-zero (device not found), the code calls `tun_create_device` to construct a new `struct cdev`. This dual-path approach accommodates two creation scenarios: +当 `clone_create` 返回非零(设备未找到)时,代码调用 `tun_create_device` 构造一个新的 `struct cdev`。这种双路径方法适应两种创建场景: -1. A process opens `/dev/tun0` before any network configuration, triggering devfs cloning -2. A user runs `ifconfig tun0 create`, explicitly requesting interface creation +1. 进程在任何网络配置之前打开 `/dev/tun0`,触发 devfs 克隆 +2. 用户运行 `ifconfig tun0 create`,显式请求接口创建 -##### Network Interface Instantiation +##### 网络接口实例化 -The final step connects the character device to the network subsystem: +最后一步将字符设备连接到网络子系统: ```c if (i == 0) { @@ -8056,28 +7884,28 @@ if (i == 0) { } ``` -After successful device creation or lookup: +成功创建或查找设备后: -- `dev_ref(dev)` increments the device's reference count, preventing premature destruction during initialization -- `tuncreate(dev)` allocates and initializes the `ifnet` structure, registering it with the network stack -- `dev->si_drv1` provides the critical linkage, this field points to the `tuntap_softc` structure, which contains both character device state and the `ifnet` pointer -- `*ifpp = tp->tun_ifp` returns the newly created network interface to the if_clone subsystem +- `dev_ref(dev)` 增加设备的引用计数,防止初始化期间过早销毁 +- `tuncreate(dev)` 分配并初始化 `ifnet` 结构,将其注册到网络栈 +- `dev->si_drv1` 提供关键关联,该字段指向 `tuntap_softc` 结构,其中包含字符设备状态和 `ifnet` 指针 +- `*ifpp = tp->tun_ifp` 将新创建的网络接口返回给 if_clone 子系统 -##### Coordination Architecture +##### 协调架构 -The `tun_clone_create` function exemplifies a coordination pattern common in kernel drivers. It performs no heavy lifting itself, instead orchestrating several subsystems: +`tun_clone_create` 函数体现了内核驱动程序中常见的协调模式。它自身不执行繁重工作,而是协调多个子系统: -1. Name parsing determines device type and unit -2. Driver lookup selects the appropriate `cdevsw` dispatch table -3. Unit allocation ensures uniqueness -4. Device lookup or creation establishes the character device presence -5. Interface creation registers with the network stack +1. 名称解析确定设备类型和单元 +2. 驱动程序查找选择相应的 `cdevsw` 分发表 +3. 单元分配确保唯一性 +4. 设备查找或创建确立了字符设备的存在 +5. 接口创建向网络栈注册 -This separation allows two independent creation paths, character device access and network configuration, to converge correctly regardless of invocation order. +这种分离允许两条独立的创建路径(字符设备访问和网络配置)无论调用顺序如何都能正确汇聚。 -The `si_drv1` field serves as the architectural keystone, linking the character device world (`struct cdev`, file operations, `/dev` namespace) with the network world (`struct ifnet`, packet processing, `ifconfig` visibility). Every subsequent operation, whether a `read(2)` system call or packet transmission, will traverse this link to access the shared `tuntap_softc` state. +`si_drv1` 字段充当架构关键,将字符设备世界(`struct cdev`、文件操作、`/dev` 命名空间)与网络世界(`struct ifnet`、数据包处理、`ifconfig` 可见性)连接起来。后续每个操作,无论是 `read(2)` 系统调用还是数据包传输,都将通过这个链接访问共享的 `tuntap_softc` 状态。 -#### 2.2 Create the `cdev` and wire `si_drv1` (`tun_create_device`) +#### 2.2 创建 `cdev` 并关联 `si_drv1` (`tun_create_device`) ```c 807: static int @@ -8121,9 +7949,9 @@ The `si_drv1` field serves as the architectural keystone, linking the character 845: } ``` -The `tun_create_device` function constructs the character device node and its associated driver state. This is the point where `/dev/tun0`, `/dev/tap0`, or `/dev/vmnet0` actually come into existence in the device filesystem. +`tun_create_device` 函数构建字符设备节点及其相关的驱动程序状态。这正是 `/dev/tun0`、`/dev/tap0` 或 `/dev/vmnet0` 在设备文件系统中实际出现的地方。 -##### Function Parameters +##### 函数参数 ```c static int @@ -8131,15 +7959,15 @@ tun_create_device(struct tuntap_driver *drv, int unit, struct ucred *cr, struct cdev **dev, const char *name) ``` -The function accepts: +该函数接受: -- `drv` - pointer to the appropriate entry in `tuntap_drivers[]` -- `unit` - the allocated device unit number (0, 1, 2, etc.) -- `cr` - credential context (NULL for kernel-initiated creation, non-NULL for user-initiated) -- `dev` - output parameter receiving the created `struct cdev` pointer -- `name` - the complete device name string ("tun0", "tap3", etc.) +- `drv` - 指向 `tuntap_drivers[]` 中相应条目的指针 +- `unit` - 已分配的设备单元号(0, 1, 2 等) +- `cr` - 凭证上下文(内核发起的创建为 NULL,用户发起的为非 NULL) +- `dev` - 接收创建的 `struct cdev` 指针的输出参数 +- `name` - 完整的设备名称字符串("tun0", "tap3" 等) -##### Allocating the Softc Structure +##### 分配 Softc 结构 ```c tp = malloc(sizeof(*tp), M_TUN, M_WAITOK | M_ZERO); @@ -8149,20 +7977,20 @@ tp->tun_flags = drv->ident_flags; tp->tun_drv = drv; ``` -Every tun/tap/vmnet device instance requires a `tuntap_softc` structure to maintain its state. This structure contains everything needed to operate the device: flags, the associated network interface pointer, I/O synchronization primitives, and references back to the driver. +每个 tun/tap/vmnet 设备实例都需要一个 `tuntap_softc` 结构来维护其状态。这个结构包含操作设备所需的一切:标志、关联的网络接口指针、I/O 同步原语以及对驱动程序的引用。 -The allocation uses `M_WAITOK`, allowing the function to sleep if memory is temporarily unavailable. The `M_ZERO` flag ensures all fields initialize to zero, providing safe defaults for pointers and counters. +分配使用 `M_WAITOK`,允许函数在内存暂时不可用时休眠。`M_ZERO` 标志确保所有字段初始化为零,为指针和计数器提供安全的默认值。 -Two synchronization primitives are initialized: +两个同步原语被初始化: -- `tun_mtx` - a mutex protecting the softc's mutable fields -- `tun_cv` - a condition variable used during device destruction to wait for all operations to complete +- `tun_mtx` - 保护 softc 可变字段的互斥锁 +- `tun_cv` - 用于在设备销毁期间等待所有操作完成的条件变量 -The `tun_flags` field receives the driver's identity flags (0, TUN_L2, or TUN_L2|TUN_VMNET), establishing whether this instance behaves as a tun, tap, or vmnet device. The `tun_drv` backpointer allows the softc to access its parent driver's resources like the unit number allocator. +`tun_flags` 字段接收驱动程序的标识标志(0, TUN_L2 或 TUN_L2|TUN_VMNET),确定该实例是作为 tun、tap 还是 vmnet 设备运行。`tun_drv` 反向指针允许 softc 访问其父驱动程序的资源,如单元号分配器。 -##### Preparing Device Creation Arguments +##### 准备设备创建参数 -FreeBSD's modern device creation API uses a structure to pass parameters rather than a long argument list: +FreeBSD 的现代设备创建 API 使用结构体传递参数,而非长参数列表: ```c make_dev_args_init(&args); @@ -8177,24 +8005,24 @@ args.mda_unit = unit; args.mda_si_drv1 = tp; ``` -The `make_dev_args` structure configures every aspect of the device node: +`make_dev_args` 结构配置设备节点的各个方面: -**Flags**: When `cr` is non-NULL (user-initiated creation), two flags are set: +**标志**:当 `cr` 为非 NULL(用户发起创建)时,设置两个标志: -- `MAKEDEV_REF` - automatically add a reference to prevent immediate destruction -- `MAKEDEV_CHECKNAME` - validate the name doesn't conflict with existing devices +- `MAKEDEV_REF` - 自动添加引用以防止立即销毁 +- `MAKEDEV_CHECKNAME` - 验证名称不与现有设备冲突 -**Dispatch table**: `mda_devsw` points to the `cdevsw` containing function pointers for `open`, `read`, `write`, `ioctl`, etc. This is how the kernel knows which functions to call when userspace performs operations on this device. +**分发表**:`mda_devsw` 指向包含 `open`、`read`、`write`、`ioctl` 等函数指针的 `cdevsw`。这就是内核知道当用户空间对该设备执行操作时应调用哪些函数的方式。 -**Credentials**: `mda_cr` associates the creating user's credentials with the device, used for permission checks. +**凭证**:`mda_cr` 将创建用户的凭证与设备关联,用于权限检查。 -**Ownership and permissions**: The device node will be owned by the `uucp` user and `dialer` group with mode `0600` (read/write for owner only). These historical Unix conventions reflect the original use of serial devices for dial-up networking. In practice, administrators often adjust these permissions via `devfs.rules` or by having privileged daemons open the devices. +**所有权和权限**:设备节点将由 `uucp` 用户和 `dialer` 组拥有,权限为 `0600`(仅所有者可读/写)。这些传统的 Unix 约定反映了串行设备在拨号网络中的原始用途。实践中,管理员通常通过 `devfs.rules` 或让特权守护进程打开设备来调整这些权限。 -**Unit number**: `mda_unit` embeds the unit number into the device's minor number, allowing the kernel to distinguish `/dev/tun0` from `/dev/tun1`. +**单元编号**:`mda_unit` 将单元编号嵌入到设备的次设备号中,使内核能够区分 `/dev/tun0` 和 `/dev/tun1`。 -**Private data**: `mda_si_drv1` matters here: this field will become the `si_drv1` member of the created `struct cdev`, establishing the link from character device to driver state. Every subsequent operation on the device will retrieve the softc via this field. +**私有数据**:这里 `mda_si_drv1` 很重要:该字段将成为创建的 `struct cdev` 的 `si_drv1` 成员,建立从字符设备到驱动程序状态的链接。后续对设备的每次操作都将通过此字段获取 softc。 -##### Creating the Device Node +##### 创建设备节点 ```c error = make_dev_s(&args, dev, "%s", name); @@ -8204,17 +8032,17 @@ if (error != 0) { } ``` -The `make_dev_s` call creates the `struct cdev` and registers it with devfs. If successful, `*dev` receives a pointer to the new device structure. The `"%s"` format string and `name` argument specify the device node path within `/dev`. +`make_dev_s` 调用创建 `struct cdev` 并将其注册到 devfs。如果成功,`*dev` 将接收指向新设备结构的指针。`"%s"` 格式字符串和 `name` 参数指定了 `/dev` 下的设备节点路径。 -Common failure modes include: +常见的失败模式包括: -- Name conflicts (a device with that name already exists) -- Resource exhaustion (out of kernel memory) -- Devfs subsystem errors +- 名称冲突(已存在同名设备) +- 资源耗尽(内核内存不足) +- Devfs 子系统错误 -On failure, the function immediately deallocates the softc and returns the error to the caller. This prevents resource leaks. +失败时,函数立即释放 softc 并将错误返回给调用方。这防止了资源泄漏。 -##### Finalizing Device State +##### 完成设备状态 ```c KASSERT((*dev)->si_drv1 != NULL, @@ -8223,13 +8051,13 @@ tp->tun_dev = *dev; knlist_init_mtx(&tp->tun_rsel.si_note, &tp->tun_mtx); ``` -The `KASSERT` is a development-time sanity check verifying that `make_dev_s` correctly populated `si_drv1` from `mda_si_drv1`. This assertion would fire during kernel development if the device creation logic broke, but it compiles away in release builds. +`KASSERT` 是一个开发时健全性检查,用于验证 `make_dev_s` 是否正确地从 `mda_si_drv1` 填充了 `si_drv1`。如果设备创建逻辑出现问题,此断言会在内核开发期间触发,但在发布版本中会被编译掉。 -The `tp->tun_dev` assignment creates the reverse link: while `si_drv1` points from cdev to softc, `tun_dev` points from softc to cdev. This bidirectional linkage allows code to traverse in either direction. +`tp->tun_dev` 赋值创建了反向链接:当 `si_drv1` 从 cdev 指向 softc 时,`tun_dev` 从 softc 指向 cdev。这种双向链接允许代码向任一方向遍历。 -The `knlist_init_mtx` call initializes the kqueue notification list protected by the softc's mutex. This infrastructure supports `kqueue(2)` event monitoring, allowing userspace applications to efficiently wait for readable/writable conditions on the device. +调用 `knlist_init_mtx` 初始化由 softc 的互斥锁保护的 kqueue 通知列表。此基础设施支持 `kqueue(2)` 事件监控,允许用户空间应用程序高效等待设备上的可读/可写状态。 -##### Global Registration +##### 全局注册 ```c mtx_lock(&tunmtx); @@ -8238,13 +8066,13 @@ mtx_unlock(&tunmtx); return (0); ``` -Finally, the new device registers itself in the global `tunhead` list. This list allows the driver to enumerate all active tun/tap/vmnet instances, which is necessary during module unload or system-wide operations. +最后,新设备在全局 `tunhead` 列表中注册自己。此列表允许驱动程序枚举所有活动的 tun/tap/vmnet 实例,这在模块卸载或系统范围操作中是必要的。 -The `tunmtx` mutex protects the list from concurrent modification. Multiple threads might simultaneously create devices, so this lock ensures list consistency. +`tunmtx` 互斥锁保护列表免受并发修改的影响。多个线程可能同时创建设备,因此此锁确保列表的一致性。 -##### The Created Device State +##### 创建的设备状态 -At function completion, several kernel objects exist and are properly linked: +函数完成时,存在多个内核对象并且它们已正确链接: ```html /dev/tun0 (struct cdev) @@ -8256,11 +8084,11 @@ tuntap_softc tuntap_drivers[0] ``` -The softc is registered in the global device list, ready for both character device operations and network interface attachment. However, the network interface (`ifnet`) does not yet exist, that will be created by the `tuncreate` function. +softc 已注册到全局设备列表中,准备好进行字符设备操作和网络接口连接。然而,网络接口(`ifnet`)尚不存在,它将由 `tuncreate` 函数创建。 -This separation of concerns, character device creation versus network interface creation, allows the two subsystems to initialize independently and in flexible order. +这种关注点分离(字符设备创建与网络接口创建)允许两个子系统独立初始化并以灵活的次序进行。 -#### 2.3 Build & attach the `ifnet` (`tuncreate`): L2 (tap) vs L3 (tun) +#### 2.3 构建并连接 `ifnet`(`tuncreate`):L2(tap)与 L3(tun) ```c 950: static void @@ -8327,9 +8155,9 @@ This separation of concerns, character device creation versus network interface 1011: } ``` -The `tuncreate` function constructs and registers the network interface (`ifnet`) corresponding to a character device. After this function completes, the device appears in `ifconfig` output and can participate in network operations. This is where the character device world and the network stack converge. +`tuncreate` 函数构建并注册与字符设备对应的网络接口(`ifnet`)。此函数完成后,设备会出现在 `ifconfig` 输出中,并能参与网络操作。这是字符设备世界与网络栈交汇之处。 -##### Retrieving Driver Context +##### 检索驱动程序上下文 ```c tp = dev->si_drv1; @@ -8339,9 +8167,9 @@ KASSERT(tp != NULL, drv = tp->tun_drv; ``` -The function begins by traversing the link from `struct cdev` to `tuntap_softc` established during device creation. The assertion verifies this fundamental invariant, every device must have an associated softc. The `tun_drv` field provides access to the driver-level resources and configuration. +函数首先遍历在设备创建过程中建立的从 `struct cdev` 到 `tuntap_softc` 的链接。断言验证了这一基本不变性:每个设备必须有一个关联的 softc。`tun_drv` 字段提供了对驱动程序级资源和配置的访问。 -##### Determining Interface Type and Flags +##### 确定接口类型和标志 ```c iflags = IFF_MULTICAST; @@ -8354,24 +8182,24 @@ if ((tp->tun_flags & TUN_L2) != 0) { } ``` -The interface type and behavior flags depend on whether this is a layer 2 (Ethernet) or layer 3 (IP) tunnel: +接口类型和行为标志取决于这是二层(以太网)还是三层(IP)隧道: -**Layer 2 devices** (tap/vmnet with `TUN_L2` set): +**二层设备**(tap/vmnet,设置了 `TUN_L2`): -- `IFT_ETHER` - declares this as an Ethernet interface -- `IFF_BROADCAST` - supports broadcast transmission -- `IFF_SIMPLEX` - cannot receive its own transmissions (standard for Ethernet) -- `IFF_MULTICAST` - supports multicast groups +- `IFT_ETHER` - 将其声明为以太网接口 +- `IFF_BROADCAST` - 支持广播传输 +- `IFF_SIMPLEX` - 无法接收自己的传输(以太网标准) +- `IFF_MULTICAST` - 支持多播组 -**Layer 3 devices** (tun without `TUN_L2`): +**三层设备**(tun,未设置 `TUN_L2`): -- `IFT_PPP` - declares this as a point-to-point protocol interface -- `IFF_POINTOPOINT` - has exactly one peer (no broadcast domain) -- `IFF_MULTICAST` - supports multicast (though less meaningful for point-to-point) +- `IFT_PPP` - 将其声明为点对点协议接口 +- `IFF_POINTOPOINT` - 恰好有一个对等点(无广播域) +- `IFF_MULTICAST` - 支持多播(虽然对点对点意义不大) -These flags control how the network stack treats the interface. For example, routing code uses `IFF_POINTOPOINT` to determine whether a route needs a gateway address or just a destination. +这些标志控制网络栈如何处理该接口。例如,路由代码使用 `IFF_POINTOPOINT` 来判断路由是否需要网关地址还是仅需目的地址。 -##### Allocating and Initializing the Interface +##### 分配并初始化接口 ```c ifp = tp->tun_ifp = if_alloc(type); @@ -8379,17 +8207,17 @@ ifp->if_softc = tp; if_initname(ifp, drv->cdevsw.d_name, dev2unit(dev)); ``` -The `if_alloc` function allocates a `struct ifnet` of the specified type. This structure is the network stack's representation of the interface, containing packet queues, statistics counters, capability flags, and function pointers. +`if_alloc` 函数分配一个指定类型的 `struct ifnet`。这个结构体是网络栈对接口的表示,包含数据包队列、统计计数器、能力标志和函数指针。 -Three critical linkages are established: +建立了三个关键的链接关系: -1. `tp->tun_ifp = if_alloc(type)` - softc points to ifnet -2. `ifp->if_softc = tp` - ifnet points back to softc -3. `if_initname(ifp, drv->cdevsw.d_name, dev2unit(dev))` - associates the interface name ("tun0") with the ifnet +1. `tp->tun_ifp = if_alloc(type)` - softc 指向 ifnet +2. `ifp->if_softc = tp` - ifnet 指回 softc +3. `if_initname(ifp, drv->cdevsw.d_name, dev2unit(dev))` - 将接口名称("tun0")与 ifnet 关联起来 -The bidirectional linkage allows code working with either representation to access the other. Network code receiving a packet can find the character device state; character device operations can access network statistics. +双向链接允许处理其中任一表示的代码访问另一个。网络代码接收到数据包时可以找到字符设备状态;字符设备操作可以访问网络统计信息。 -##### Configuring Interface Operations +##### 配置接口操作 ```c ifp->if_ioctl = tunifioctl; @@ -8397,11 +8225,11 @@ ifp->if_flags = iflags; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ``` -The `if_ioctl` function pointer handles interface configuration requests like `SIOCSIFADDR` (set address), `SIOCSIFMTU` (set MTU), and `SIOCSIFFLAGS` (set flags). This is distinct from the character device's `ioctl` handler, which processes device-specific commands. +`if_ioctl` 函数指针处理接口配置请求,如 `SIOCSIFADDR`(设置地址)、`SIOCSIFMTU`(设置 MTU)和 `SIOCSIFFLAGS`(设置标志)。这与字符设备的 `ioctl` 处理程序不同,后者处理设备特定的命令。 -The interface flags are copied from the previously determined `iflags` value. The send queue's maximum length is set to `ifqmaxlen` (typically 50), limiting how many packets can await transmission to userspace. +接口标志从先前确定的 `iflags` 值复制而来。发送队列的最大长度设置为 `ifqmaxlen`(通常为 50),限制了等待传输到用户空间的数据包数量。 -##### Setting Interface Capabilities +##### 设置接口能力 ```c ifp->if_capabilities |= IFCAP_LINKSTATE | IFCAP_MEXTPG; @@ -8411,25 +8239,25 @@ if ((tp->tun_flags & TUN_L2) != 0) ifp->if_capenable |= IFCAP_LINKSTATE | IFCAP_MEXTPG; ``` -Interface capabilities declare what hardware offload features the device supports. Two sets of flags exist: +接口能力声明设备支持的硬件卸载功能。存在两组标志: -- `if_capabilities` - features the interface can support -- `if_capenable` - features currently enabled +- `if_capabilities` - 接口可以支持的功能 +- `if_capenable` - 当前启用的功能 -All interfaces support: +所有接口都支持: -- `IFCAP_LINKSTATE` - can report link up/down state changes -- `IFCAP_MEXTPG` - supports multi-page external mbufs (zero-copy optimization) +- `IFCAP_LINKSTATE` - 可以报告链路向上/向下状态变化 +- `IFCAP_MEXTPG` - 支持多页外部 mbuf(零拷贝优化) -Layer 2 interfaces additionally support: +二层接口额外支持: -- `IFCAP_RXCSUM` - receive checksum offload for IPv4 -- `IFCAP_RXCSUM_IPV6` - receive checksum offload for IPv6 -- `IFCAP_LRO` - Large Receive Offload (TCP segment coalescing) +- `IFCAP_RXCSUM` - IPv4 接收校验和卸载 +- `IFCAP_RXCSUM_IPV6` - IPv6 接收校验和卸载 +- `IFCAP_LRO` - 大接收卸载(TCP 段合并) -These capabilities are initially disabled for tap/vmnet devices. When userspace enables virtio-net header mode via the `TAPSVNETHDR` ioctl, additional transmit capabilities become available, and the code updates these flags accordingly. +这些能力最初对于 tap/vmnet 设备是禁用的。当用户空间通过 `TAPSVNETHDR` ioctl 启用 virtio-net 头部模式时,额外的传输能力变得可用,代码会相应地更新这些标志。 -##### Layer 2 Interface Registration +##### 二层接口注册 ```c if ((tp->tun_flags & TUN_L2) != 0) { @@ -8442,25 +8270,25 @@ if ((tp->tun_flags & TUN_L2) != 0) { ether_ifattach(ifp, eaddr.octet); ``` -For Ethernet interfaces, four function pointers configure packet processing: +对于以太网接口,四个函数指针配置数据包处理: -- `if_init` - called when the interface transitions to the up state -- `if_start` - legacy packet transmission (called by the send queue) -- `if_transmit` - modern packet transmission (bypasses send queue when possible) -- `if_qflush` - discards queued packets +- `if_init` - 当接口转换为向上状态时调用 +- `if_start` - 传统的数据包传输(由发送队列调用) +- `if_transmit` - 现代的数据包传输(尽可能绕过发送队列) +- `if_qflush` - 丢弃排队的数据包 -The `ether_gen_addr` function generates a random MAC address for the local side of the tunnel. The address uses the locally-administered bit pattern, ensuring it doesn't conflict with real hardware addresses. +`ether_gen_addr` 函数为隧道的本地端生成一个随机的 MAC 地址。该地址使用本地管理的位模式,确保不与真实硬件地址冲突。 -`ether_ifattach` performs Ethernet-specific registration: +`ether_ifattach` 执行以太网特定的注册: -- Registers the interface with the network stack -- Attaches BPF (Berkeley Packet Filter) with `DLT_EN10MB` (Ethernet) link type -- Initializes the interface's link-layer address structure -- Sets up multicast filter management +- 将接口注册到网络栈 +- 使用 `DLT_EN10MB`(以太网)链接类型附加 BPF(伯克利数据包过滤器) +- 初始化接口的链路层地址结构 +- 设置多播过滤器管理 -After `ether_ifattach`, the interface is fully operational and visible to userspace tools. +在 `ether_ifattach` 之后,接口完全可操作,并且对用户空间工具可见。 -##### Layer 3 Interface Registration +##### 三层接口注册 ```c } else { @@ -8476,20 +8304,20 @@ After `ether_ifattach`, the interface is fully operational and visible to usersp } ``` -Point-to-point interfaces follow a simpler path: +点对点接口遵循更简单的路径: -The MTU is set to `TUNMTU` (typically 1500), and two packet transmission functions are installed: +MTU 设置为 `TUNMTU`(通常为 1500),并且安装了两个数据包传输函数: -- `if_start` - handles packets from the send queue -- `if_output` - called directly by the routing code +- `if_start` - 处理发送队列中的数据包 +- `if_output` - 由路由代码直接调用 -The `if_snd.ifq_drv_maxlen = 0` setting is significant, it prevents the legacy send queue from holding packets, as the modern path uses `if_transmit` semantics even though the function pointer isn't set. `IFQ_SET_READY` marks the queue as operational. +`if_snd.ifq_drv_maxlen = 0` 设置很重要,它可以阻止旧式发送队列保存数据包,因为现代路径使用 `if_transmit` 语义,即使函数指针未设置。`IFQ_SET_READY` 将队列标记为可操作。 -`if_attach` registers the interface with the network stack, making it visible to routing and configuration tools. +`if_attach` 将接口注册到网络栈中,使其对路由和配置工具可见。 -`bpfattach` enables packet capture with `DLT_NULL` link type. This link type prepends a 4-byte address family field (AF_INET or AF_INET6) to each packet, allowing tools like `tcpdump` to distinguish IPv4 from IPv6 traffic without examining packet contents. +`bpfattach` 启用具有 `DLT_NULL` 链路类型的数据包捕获。此链路类型在每个数据包前添加一个 4 字节的地址族字段(AF_INET 或 AF_INET6),使 `tcpdump` 等工具无需检查数据包内容即可区分 IPv4 和 IPv6 流量。 -##### Marking Initialization Complete +##### 标记初始化完成 ```c TUN_LOCK(tp); @@ -8497,13 +8325,13 @@ tp->tun_flags |= TUN_INITED; TUN_UNLOCK(tp); ``` -The `TUN_INITED` flag signals that the interface is fully constructed. Other code paths check this flag before performing operations. For example, the device `open` function verifies that both `TUN_INITED` and `TUN_OPEN` are set before allowing I/O. +`TUN_INITED` 标志表示接口已完全构建。其他代码路径在执行操作前会检查此标志。例如,设备的 `open` 函数会验证 `TUN_INITED` 和 `TUN_OPEN` 是否都已设置,然后才允许 I/O。 -The mutex protects this flag from races where one thread checks the state while another is still initializing. +互斥锁保护此标志,防止一个线程检查状态而另一个线程仍在初始化时出现竞态条件。 -##### The Completed Interface +##### 完成的接口 -After `tuncreate` returns, both the character device and network interface exist and are cross-linked: +在 `tuncreate` 返回后,字符设备和网络接口都已存在并相互关联: ```html /dev/tun0 (struct cdev) @@ -8513,9 +8341,9 @@ tuntap_softc tun0 (struct ifnet) ``` -Opening `/dev/tun0` with `open(2)` allows userspace to read and write packets. Transmitting packets to the `tun0` interface via `sendto(2)` or routing queues them for userspace to read. This bidirectional connection enables userspace VPN and virtualization software to implement custom network protocols while plugging into the kernel's network stack. +通过 `open(2)` 打开 `/dev/tun0` 允许用户空间读写数据包。通过 `sendto(2)` 或路由向 `tun0` 接口发送数据包会将其排队,等待用户空间读取。这种双向连接使得用户空间 VPN 和虚拟化软件能够实现自定义网络协议,同时接入内核的网络栈。 -#### 3) `open(2)`: vnet context, mark open, link up +#### 3) `open(2)`: vnet 上下文,标记已打开,链路激活 ```c 1064: static int @@ -8577,9 +8405,9 @@ Opening `/dev/tun0` with `open(2)` allows userspace to read and write packets. T 1120: } ``` -The `tunopen` function handles the `open(2)` system call on tun/tap/vmnet character devices. This is the entry point where userspace applications like VPN daemons or virtual machine monitors gain control over a network interface. Opening the device transitions it from an initialized but inactive state to an operational state ready for packet I/O. +`tunopen` 函数处理对 tun/tap/vmnet 字符设备的 `open(2)` 系统调用。这是用户空间应用程序(如 VPN 守护进程或虚拟机监视器)获得网络接口控制权的入口点。打开设备会将其从已初始化但非活动状态转变为可进行数据包 I/O 的操作状态。 -##### Function Signature and Virtual Network Context +##### 函数签名与虚拟网络上下文 ```c static int @@ -8588,11 +8416,11 @@ tunopen(struct cdev *dev, int flag, int mode, struct thread *td) CURVNET_SET(TD_TO_VNET(td)); ``` -The function receives the standard character device `open` parameters: the device being opened, flags from the `open(2)` call, mode bits, and the thread performing the operation. +该函数接收标准字符设备 `open` 参数:正在打开的设备、来自 `open(2)` 调用的标志、模式位以及执行操作的线程。 -The `CURVNET_SET` macro is critical for FreeBSD's VNET (virtual network stack) support. In systems using jails or virtualization, multiple independent network stacks may exist. This macro switches to the network context associated with the opening thread's jail or vnet, ensuring all subsequent network operations affect the correct stack. Every function that touches network interfaces or routing tables must bracket its work between `CURVNET_SET` and `CURVNET_RESTORE`. +`CURVNET_SET` 宏对于 FreeBSD 的 VNET(虚拟网络栈)支持至关重要。在使用 jail 或虚拟化的系统中,可能存在多个独立的网络栈。此宏切换到与打开线程的 jail 或 vnet 关联的网络上下文,确保所有后续网络操作影响正确的栈。每个涉及网络接口或路由表的函数都必须将其工作包裹在 `CURVNET_SET` 和 `CURVNET_RESTORE` 之间。 -##### Device Type Validation +##### 设备类型验证 ```c tunflags = 0; @@ -8603,9 +8431,9 @@ if (error != 0) { } ``` -Although the device should already exist and be properly typed, this code validates that the device name still corresponds to a known tun/tap/vmnet variant. The check should always succeed, as indicated by the comment "Shouldn't happen". The validation guards against corrupted kernel state or race conditions during device destruction. +尽管设备应该已经存在且类型正确,此代码会验证设备名称是否仍然对应于已知的 tun/tap/vmnet 变体。如注释“不应发生”所示,该检查应始终成功。该验证用于防范设备销毁期间内核状态损坏或竞态条件。 -##### Retrieving and Validating Device State +##### 检索并验证设备状态 ```c tp = dev->si_drv1; @@ -8620,11 +8448,11 @@ if ((tp->tun_flags & TUN_INITED) == 0) { } ``` -The softc is retrieved via the `si_drv1` link established during device creation. The assertion verifies this fundamental invariant. +通过设备创建时建立的 `si_drv1` 链接获取 softc。断言验证了这一基本不变性。 -The softc mutex is acquired before checking state flags, preventing race conditions. The `TUN_INITED` flag check ensures the network interface was successfully created. If initialization failed or hasn't completed yet, the open fails with `ENXIO` (device not configured). +在检查状态标志之前获取 softc 互斥锁,以防止竞态条件。`TUN_INITED` 标志检查确保网络接口已成功创建。如果初始化失败或尚未完成,则打开操作失败并返回 `ENXIO`(设备未配置)。 -##### Enforcing Exclusive Access +##### 强制排他访问 ```c if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) { @@ -8634,16 +8462,16 @@ if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) { } ``` -Tun/tap devices enforce exclusive access, only one process may have a device open at a time. This design simplifies packet routing: there's always exactly one userspace consumer for packets arriving at the interface. +Tun/tap 设备强制独占访问,一次只能有一个进程打开设备。这种设计简化了数据包路由:对于到达接口的数据包,始终恰好有一个用户空间消费者。 -The check examines two flags: +检查两个标志: -- `TUN_OPEN` - device is already open by another process -- `TUN_DYING` - device is being destroyed +- `TUN_OPEN` - 设备已被另一个进程打开 +- `TUN_DYING` - 设备正在被销毁 -Either condition returns `EBUSY`, informing userspace that the device is unavailable. This prevents scenarios where multiple VPN daemons fight over the same tunnel or where a process opens a device mid-destruction. +任一条件都会返回 `EBUSY`,向用户空间通知设备不可用。这避免了多个 VPN 守护进程争夺同一隧道,或进程在设备销毁过程中打开设备的情况。 -##### Marking the Device Busy +##### 标记设备忙碌 ```c error = tun_busy_locked(tp); @@ -8651,13 +8479,13 @@ KASSERT(error == 0, ("Must be able to busy an unopen tunnel")); ifp = TUN2IFP(tp); ``` -The busy mechanism prevents device destruction while operations are in progress. The `tun_busy_locked` function increments the `tun_busy` counter and fails if `TUN_DYING` is set. +忙碌机制防止在操作进行中销毁设备。`tun_busy_locked` 函数递增 `tun_busy` 计数器,并在设置了 `TUN_DYING` 时失败。 -The assertion verifies that marking the device busy must succeed, since we hold the lock and already checked that neither `TUN_OPEN` nor `TUN_DYING` is set, no concurrent destruction can be occurring. +断言验证标记设备忙碌必须成功,因为我们持有锁并且已经检查过既没有设置 `TUN_OPEN` 也没有设置 `TUN_DYING`,因此不可能存在并发的销毁操作。 -The `TUN2IFP` macro extracts the `ifnet` pointer from the softc, providing access to the network interface for subsequent configuration. +`TUN2IFP` 宏从 softc 中提取 `ifnet` 指针,为后续配置提供对网络接口的访问。 -##### Layer 2 Interface Activation +##### 二层接口激活 ```c if ((tp->tun_flags & TUN_L2) != 0) { @@ -8672,31 +8500,31 @@ if ((tp->tun_flags & TUN_L2) != 0) { } ``` -For Ethernet interfaces (tap/vmnet), opening the device activates several features: +对于以太网接口(tap/vmnet),打开设备会激活多项功能: -The MAC address is copied from the interface to `tp->tun_ether`. This snapshot preserves the "remote" MAC address that userspace might need. While the interface itself knows its local MAC address, the softc stores this copy for symmetric access patterns. +MAC 地址从接口复制到 `tp->tun_ether`。此快照保留了用户空间可能需要的“远程”MAC 地址。虽然接口本身知道其本地 MAC 地址,但 softc 存储此副本以实现对称访问模式。 -Two driver flags are updated: +更新了两个驱动程序标志: -- `IFF_DRV_RUNNING` - signals that the driver is ready to transmit and receive -- `IFF_DRV_OACTIVE` - cleared to indicate output is not blocked +- `IFF_DRV_RUNNING` - 表示驱动程序已准备好发送和接收 +- `IFF_DRV_OACTIVE` - 清除以表示输出未被阻塞 -These "driver flags" (`if_drv_flags`) are distinct from interface flags (`if_flags`). Driver flags reflect the device driver's internal state, while interface flags reflect administratively configured properties. +这些“驱动程序标志”(`if_drv_flags`)与接口标志(`if_flags`)不同。驱动程序标志反映设备驱动程序的内部状态,而接口标志反映管理配置的属性。 -The `tapuponopen` sysctl controls whether opening the device automatically marks the interface administratively up. When enabled, `ifp->if_flags |= IFF_UP` brings the interface up without requiring a separate `ifconfig tap0 up` command. This convenience feature is disabled by default to maintain traditional Unix semantics where device availability and interface state are orthogonal. +`tapuponopen` sysctl 控制打开设备时是否自动将接口标记为管理性启用。当启用时,`ifp->if_flags |= IFF_UP` 使接口启用,无需单独执行 `ifconfig tap0 up` 命令。此便利功能默认禁用,以保持传统的 Unix 语义,即设备可用性与接口状态相互独立。 -##### Recording Ownership +##### 记录所有权 ```c tp->tun_pid = td->td_proc->p_pid; tp->tun_flags |= TUN_OPEN; ``` -The controlling process's PID is recorded in `tun_pid`. This information appears in `ifconfig` output and helps administrators identify which process owns each tunnel. While not used for access control (the file descriptor provides that), it's valuable for debugging and monitoring. +控制进程的 PID 记录在 `tun_pid` 中。此信息出现在 `ifconfig` 输出中,帮助管理员识别哪个进程拥有每个隧道。虽然不用于访问控制(文件描述符提供了这一功能),但它在调试和监控中很有价值。 -The `TUN_OPEN` flag is set, transitioning the device into the open state. Subsequent open attempts will now fail with `EBUSY` until this process closes the device. +设置 `TUN_OPEN` 标志,将设备转换到打开状态。后续的打开尝试将失败并返回 `EBUSY`,直到此进程关闭设备。 -##### Signaling Link State +##### 发出链路状态信号 ```c if_link_state_change(ifp, LINK_STATE_UP); @@ -8704,13 +8532,13 @@ TUNDEBUG(ifp, "open\n"); TUN_UNLOCK(tp); ``` -The `if_link_state_change` call notifies the network stack that the interface's link is now up. This generates routing socket messages that daemons like `devd` can monitor, and it updates the interface's link state visible in `ifconfig` output. +`if_link_state_change` 调用通知网络栈接口的链路现已启用。这会生成路由套接字消息,供 `devd` 等守护进程监控,并更新 `ifconfig` 输出中可见的接口链路状态。 -For physical Ethernet interfaces, link state reflects cable connection status. For tun/tap devices, link state reflects whether userspace has the device open. This semantic mapping allows routing protocols and management tools to treat virtual interfaces consistently with physical ones. +对于物理以太网接口,链路状态反映电缆连接状态。对于 tun/tap 设备,链路状态反映用户空间是否打开了设备。这种语义映射允许路由协议和管理工具将虚拟接口与物理接口一致对待。 -The debug message logs the open event, and the mutex is released before the final setup step. +调试消息记录打开事件,并在最终设置步骤之前释放互斥锁。 -##### Establishing Close Notification +##### 建立关闭通知 ```c (void)devfs_set_cdevpriv(tp, tundtor); @@ -8718,15 +8546,15 @@ CURVNET_RESTORE(); return (0); ``` -The `devfs_set_cdevpriv` call associates the softc with this file descriptor and registers `tundtor` (tunnel destructor) as the cleanup function. When the file descriptor is closed, whether explicitly via `close(2)` or implicitly via process termination, the kernel automatically invokes `tundtor` to tear down the device state. +`devfs_set_cdevpriv` 调用将 softc 与此文件描述符关联,并注册 `tundtor`(隧道析构函数)作为清理函数。当文件描述符被关闭时,无论是通过 `close(2)` 显式关闭还是通过进程终止隐式关闭,内核都会自动调用 `tundtor` 来拆除设备状态。 -This mechanism provides robust cleanup semantics. Even if a process crashes or is killed, the kernel ensures proper device shutdown. The function pointer and data association are per-file-descriptor, allowing the same device to be opened multiple times in succession (though not concurrently) with correct cleanup for each instance. +此机制提供了健壮的清理语义。即使进程崩溃或被杀死,内核也能确保设备正确关闭。函数指针和数据关联是每个文件描述符独立的,允许同一设备连续多次打开(尽管不能并发),并为每个实例进行正确的清理。 -The return value 0 signals successful open. At this point, userspace can begin reading packets transmitted to the interface and writing packets to inject into the network stack. +返回值 0 表示成功打开。此时,用户空间可以开始读取发送到接口的数据包,并写入数据包以注入网络栈。 -##### State Transitions +##### 状态转换 -The open operation transitions the device through several states: +打开操作使设备经历多个状态: ```html Device created -> TUN_INITED set -> @@ -8749,15 +8577,15 @@ Register close handler Device ready for I/O ``` -After successful open, the device exists in three interlinked representations: +成功打开后,设备会以三种相互关联的形式存在: -- Character device node (`/dev/tun0`) with an open file descriptor -- Network interface (`tun0`) with link state UP -- Softc structure binding them with `TUN_OPEN` set +- 字符设备节点(`/dev/tun0`),带有打开的文件描述符 +- 网络接口(`tun0`),链路状态为 UP +- 绑定它们的软结构(softc),并设置了 `TUN_OPEN` 标志 -Packets can now flow bidirectionally: the network stack queues outbound packets for userspace to read, and userspace writes inbound packets for the network stack to process. +现在数据包可以双向流动:网络栈将出站数据包排队供用户空间读取,而用户空间写入入站数据包供网络栈处理。 -#### 4) `read(2)`: userspace **receives** a whole packet (or EWOULDBLOCK) +#### 4) `read(2)`: 用户空间**接收**一个完整数据包(或 EWOULDBLOCK) ```c 1706: /* @@ -8824,9 +8652,9 @@ Packets can now flow bidirectionally: the network stack queues outbound packets 1767: } ``` -The `tunread` function implements the `read(2)` system call for tun/tap devices, transferring packets from the kernel's network stack to userspace. This is the critical path where packets destined for transmission on the virtual network interface become available to VPN daemons, virtual machine monitors, or other userspace networking applications. +`tunread` 函数实现了 tun/tap 设备的 `read(2)` 系统调用,将数据包从内核的网络栈传输到用户空间。这是关键路径:原本要发送到虚拟网络接口上的数据包,在这里变得可供 VPN 守护进程、虚拟机监视器或其他用户空间网络应用程序使用。 -##### Function Overview and Context Retrieval +##### 函数概览与上下文检索 ```c static int @@ -8839,11 +8667,11 @@ tunread(struct cdev *dev, struct uio *uio, int flag) int error = 0; ``` -The function receives the standard `read(2)` parameters: the device being read, a `uio` (user I/O) structure describing the userspace buffer, and flags from the `open(2)` call (particularly `O_NONBLOCK`). +该函数接收标准的 `read(2)` 参数:被读取的设备、描述用户空间缓冲区的 `uio`(用户 I/O)结构,以及来自 `open(2)` 调用的标志(特别是 `O_NONBLOCK`)。 -The softc and interface pointers are retrieved via the established linkages. The `mbuf` pointer `m` will hold the packet being transferred, while `len` tracks how much data to copy. +通过已建立的链接获取软结构(softc)和接口指针。`mbuf` 指针 `m` 将持有正在传输的数据包,而 `len` 跟踪要复制的数据量。 -##### Device Readiness Check +##### 设备就绪检查 ```c TUNDEBUG(ifp, "read\n"); @@ -8855,22 +8683,22 @@ if ((tp->tun_flags & TUN_READY) != TUN_READY) { } ``` -The `TUN_READY` macro combines two flags: `TUN_OPEN | TUN_INITED`. Both must be set for I/O to proceed: +`TUN_READY` 宏组合了两个标志:`TUN_OPEN | TUN_INITED`。这两个标志都必须设置,I/O 才能继续进行: -- `TUN_INITED` - the network interface was successfully created -- `TUN_OPEN` - a process has opened the device +- `TUN_INITED` —— 网络接口已成功创建 +- `TUN_OPEN` —— 某个进程已打开该设备 -If either condition fails, the read returns `EHOSTDOWN`, signaling that the network path is unavailable. This error code is semantically appropriate, from the kernel's perspective, packets are being sent to a "host" (userspace), but that host is down. +如果任一条件失败,读取操作会返回 `EHOSTDOWN`,表示网络路径不可用。从内核的角度来看,这个错误码在语义上是恰当的:数据包正在被发送到一个“主机”(用户空间),但该主机已宕机。 -##### Preparing for Packet Retrieval +##### 准备数据包检索 ```c tp->tun_flags &= ~TUN_RWAIT; ``` -The `TUN_RWAIT` flag tracks whether a reader is blocked waiting for packets. Clearing it before entering the loop ensures correct state regardless of how the previous read completed, whether it retrieved a packet, timed out, or was interrupted. +`TUN_RWAIT` 标志跟踪是否有读取者正在阻塞等待数据包。在进入循环前清除该标志,可以确保无论之前的读取是如何完成的(取到了数据包、超时或被中断),状态都是正确的。 -##### The Packet Dequeue Loop +##### 数据包出队循环 ```c for (;;) { @@ -8892,34 +8720,34 @@ for (;;) { TUN_UNLOCK(tp); ``` -This loop implements the standard kernel pattern for blocking I/O with non-blocking mode support. +这个循环实现了支持非阻塞模式的标准内核阻塞 I/O 模式。 -**Packet retrieval**: `IFQ_DEQUEUE` atomically removes the head packet from the interface's send queue. This macro handles queue locking internally and returns NULL if the queue is empty. +**数据包获取**:`IFQ_DEQUEUE` 原子地从接口的发送队列中移除头部数据包。该宏在内部处理队列锁定,如果队列为空则返回 NULL。 -**Success path**: When `m != NULL`, a packet was successfully dequeued, and the loop exits. +**成功路径**:当 `m != NULL` 时,成功取出一个数据包,循环退出。 -**Non-blocking path**: If the queue is empty and `O_NONBLOCK` was specified during `open(2)`, the read immediately returns `EWOULDBLOCK` (also known as `EAGAIN`). This allows userspace to use `poll(2)`, `select(2)`, or `kqueue(2)` to wait efficiently for readable conditions without blocking the thread. +**非阻塞路径**:如果队列为空且在 `open(2)` 时指定了 `O_NONBLOCK`,则读取立即返回 `EWOULDBLOCK`(也称为 `EAGAIN`)。这允许用户空间使用 `poll(2)`、`select(2)` 或 `kqueue(2)` 高效地等待可读条件,而无需阻塞线程。 -**Blocking path**: For blocking reads, the code: +**阻塞路径**:对于阻塞读取,代码执行: -1. Sets `TUN_RWAIT` to indicate a reader is waiting -2. Calls `mtx_sleep` to block the thread atomically +1. 设置 `TUN_RWAIT` 以表示有读取者正在等待 +2. 调用 `mtx_sleep` 原子地阻塞该线程 -The `mtx_sleep` function atomically releases `tp->tun_mtx` and puts the thread to sleep. When woken (by `tunstart` or `tunstart_l2` when packets arrive), it reacquires the mutex before returning. +`mtx_sleep` 函数原子地释放 `tp->tun_mtx` 并使线程进入睡眠状态。当被唤醒时(当数据包到达时由 `tunstart` 或 `tunstart_l2` 唤醒),在返回前重新获取该互斥锁。 -The sleep parameters specify: +睡眠参数指定: -- `tp` - the wait channel (arbitrary unique pointer, using the softc) -- `&tp->tun_mtx` - mutex to release/reacquire atomically -- `PCATCH | (PZERO + 1)` - allow signal interruption, priority just above normal -- `"tunread"` - name for debugging (shows in `ps` or `top`) -- `0` - no timeout (sleep indefinitely) +- `tp` —— 等待通道(任意唯一指针,使用软结构) +- `&tp->tun_mtx` - 自动释放/重新获取的互斥锁 +- `PCATCH | (PZERO + 1)` - 允许信号中断,优先级略高于正常 +- `"tunread"` - 调试名称(显示在 `ps` 或 `top` 中) +- `0` - 无超时(无限期睡眠) -**Signal handling**: If interrupted by a signal (like `SIGINT`), `mtx_sleep` returns an error (typically `EINTR` or `ERESTART`), and the function propagates this to userspace. This allows `Ctrl+C` to interrupt a blocked read. +**信号处理**:如果被信号(如 `SIGINT`)中断,`mtx_sleep` 返回一个错误(通常是 `EINTR` 或 `ERESTART`),并且函数将该错误传播到用户空间。这允许 `Ctrl+C` 中断阻塞的读取操作。 -After successfully dequeuing a packet, the mutex is released. The remainder of the function operates on the mbuf without holding locks, avoiding contention with packet transmission threads. +成功从队列中取出数据包后,释放互斥锁。函数的其余部分在不持有锁的情况下操作 mbuf,避免与数据包传输线程发生竞争。 -##### Virtio-Net Header Processing +##### Virtio-Net 头部处理 ```c len = min(tp->tun_vhdrlen, uio->uio_resid); @@ -8935,19 +8763,19 @@ if (len > 0) { } ``` -For tap devices configured with virtio-net header mode (via the `TAPSVNETHDR` ioctl), packets are prefixed with a metadata header describing offload features. This optimization allows userspace (particularly QEMU/KVM) to use hardware offload capabilities: +对于配置了 virtio-net 头部模式(通过 `TAPSVNETHDR` ioctl)的 tap 设备,数据包前会附加一个描述卸载功能的元数据头部。此优化允许用户空间(尤其是 QEMU/KVM)使用硬件卸载能力: -The `tun_vhdrlen` field is zero for standard mode and non-zero (typically 10 or 12 bytes) when virtio headers are enabled. The code only processes headers if both the header is enabled (`len > 0`) and the userspace buffer has room (`uio->uio_resid`). +标准模式下 `tun_vhdrlen` 字段为零,启用 virtio 头部时非零(通常为 10 或 12 字节)。代码仅在头部已启用(`len > 0`)且用户空间缓冲区有空间(`uio->uio_resid`)时才处理头部。 -The `vhdr` structure is zero-initialized to provide safe defaults. If the mbuf has offload flags set (`TAP_ALL_OFFLOAD` includes TCP/UDP checksum offload and TSO), `virtio_net_tx_offload` populates the header with: +`vhdr` 结构被零初始化以提供安全的默认值。如果 mbuf 设置了卸载标志(`TAP_ALL_OFFLOAD` 包括 TCP/UDP 校验和卸载和 TSO),则 `virtio_net_tx_offload` 会用以下内容填充头部: -- Checksum computation parameters (where to start, where to insert) -- Segmentation parameters (MSS, header length) -- Generic flags (whether header is valid) +- 校验和计算参数(起点和插入位置) +- 分段参数(MSS、头部长度) +- 通用标志(头部是否有效) -The `uiomove(&vhdr, len, uio)` call copies the header to userspace. This function handles the kernel-to-user memory transfer, updating `uio` to reflect consumed buffer space. If this copy fails (typically due to invalid userspace pointer), the error is recorded but processing continues to free the mbuf. +`uiomove(&vhdr, len, uio)` 调用将头部复制到用户空间。此函数处理内核到用户的内存传输,更新 `uio` 以反映已消耗的缓冲区空间。如果此复制失败(通常由于无效的用户空间指针),则记录错误,但处理继续以释放 mbuf。 -##### Packet Data Transfer +##### 数据包数据传输 ```c if (error == 0) @@ -8956,17 +8784,17 @@ m_freem(m); return (error); ``` -Assuming the header transfer succeeded (or no header was required), `m_mbuftouio` copies the packet data from the mbuf chain to the userspace buffer. This function: -- Walks the mbuf chain (packets may be fragmented across multiple mbufs) -- Copies each segment to userspace via `uiomove` -- Updates `uio->uio_resid` to reflect remaining buffer space -- Returns an error if the buffer is too small or pointers are invalid +假设头部传输成功(或不需要头部),`m_mbuftouio` 将数据包数据从 mbuf 链复制到用户空间缓冲区。此函数: +- 遍历 mbuf 链(数据包可能分散在多个 mbuf 中) +- 通过 `uiomove` 将每个段复制到用户空间 +- 更新 `uio->uio_resid` 以反映剩余缓冲区空间 +- 如果缓冲区太小或指针无效,则返回错误 -The `m_freem` call releases the mbuf back to the kernel's memory pool. This must always execute, even if earlier operations failed, to prevent memory leaks. The mbuf is freed regardless of whether the copy succeeded, once dequeued from the send queue, the packet's fate is sealed. +`m_freem` 调用将 mbuf 释放回内核的内存池。即使早期操作失败,也必须始终执行此操作,以防止内存泄漏。一旦从发送队列中取出,无论复制是否成功,mbuf 都会被释放,数据包的命运已定。 -##### Data Flow Summary +##### 数据流总结 -The complete path from network transmission to userspace read: +从网络传输到用户空间读取的完整路径: ```text Application calls send()/sendto() -> @@ -8989,32 +8817,32 @@ Free mbuf Userspace receives packet data ``` -##### Error Handling Semantics +##### 错误处理语义 -The function returns several distinct error codes with specific meanings: +该函数返回多个不同的错误代码,具有特定含义: -- `EHOSTDOWN` - device not ready (not open or not initialized) -- `EWOULDBLOCK` - non-blocking read, no packets available -- `EINTR`/`ERESTART` - interrupted by signal while waiting -- `EFAULT` - userspace buffer pointer invalid -- `0` - success, packet transferred +- `EHOSTDOWN` - 设备未就绪(未打开或未初始化) +- `EWOULDBLOCK` - 非阻塞读取,无可用数据包 +- `EINTR`/`ERESTART` - 等待时被信号中断 +- `EFAULT` - 用户空间缓冲区指针无效 +- `0` - 成功,已传输数据包 -These error codes allow userspace to distinguish between transient conditions (like `EWOULDBLOCK` requiring retry) and permanent failures (like `EHOSTDOWN` requiring device reopen). +这些错误代码允许用户空间区分瞬态条件(如 `EWOULDBLOCK` 需要重试)和永久性故障(如 `EHOSTDOWN` 需要重新打开设备)。 -##### Blocking and Wakeup Coordination +##### 阻塞与唤醒协调 -The `TUN_RWAIT` flag and `mtx_sleep` coordination ensure efficient resource usage. When no packets are available: +`TUN_RWAIT` 标志和 `mtx_sleep` 协调确保了高效的资源使用。当没有数据包可用时: -1. Reader blocks in `mtx_sleep`, consuming no CPU -2. When the network stack transmits a packet, `tunstart` or `tunstart_l2` executes -3. Those functions check `TUN_RWAIT` and call `wakeup(tp)` if set -4. The sleeping thread wakes, loops, and dequeues the packet +1. 读取者在 `mtx_sleep` 中阻塞,不消耗 CPU +2. 当网络栈传输数据包时,执行 `tunstart` 或 `tunstart_l2` +3. 这些函数检查 `TUN_RWAIT`,如果设置了则调用 `wakeup(tp)` +4. 睡眠线程唤醒,循环并取出数据包 -This pattern avoids polling loops while ensuring prompt packet delivery. The mutex protects against races where packets arrive between the empty queue check and the sleep call. +这种模式避免了轮询循环,同时确保了数据包的及时交付。互斥锁防止了在空队列检查与睡眠调用之间数据包到达的竞争情况。 -#### 5) `write(2)`: userspace **injects** a packet (L2 vs L3 path) +#### 5) `write(2)`: 用户空间**注入**数据包(L2 与 L3 路径) -#### 5.1 Main write dispatcher (`tunwrite`) +#### 5.1 主写入分发器(`tunwrite`) ```c 1896: /* @@ -9083,9 +8911,9 @@ This pattern avoids polling loops while ensuring prompt packet delivery. The mut 1959: } ``` -The `tunwrite` function implements the `write(2)` system call for tun/tap devices, injecting packets from userspace into the kernel's network stack. This is the complementary operation to `tunread`, where `tunread` delivers kernel-originated packets to userspace, `tunwrite` accepts userspace packets for kernel processing. The comment "an atomic write is a packet - or else!" emphasizes a critical design principle: each `write(2)` call must contain exactly one complete packet. +`tunwrite` 函数实现了 tun/tap 设备的 `write(2)` 系统调用,将用户空间的数据包注入内核的网络栈。这是 `tunread` 的互补操作:`tunread` 将内核生成的数据包传递给用户空间,而 `tunwrite` 则接收用户空间的数据包供内核处理。注释“一次原子写入就是一个数据包——否则!”强调了一个关键的设计原则:每个 `write(2)` 调用必须包含恰好一个完整的数据包。 -##### Function Initialization and Context +##### 函数初始化与上下文 ```c static int @@ -9103,9 +8931,9 @@ tunwrite(struct cdev *dev, struct uio *uio, int flag) ifp = TUN2IFP(tp); ``` -The function retrieves the device context through the standard `si_drv1` linkage. Local variables track the maximum receive unit, alignment requirements, virtio header length, and whether this is a layer 2 interface. +该函数通过标准的 `si_drv1` 关联检索设备上下文。局部变量跟踪最大接收单元、对齐要求、virtio 头部长度以及是否为二层接口。 -##### Interface State Validation +##### 接口状态验证 ```c TUNDEBUG(ifp, "tunwrite\n"); @@ -9117,13 +8945,13 @@ if (uio->uio_resid == 0) return (0); ``` -Two early checks filter out invalid operations: +两个早期检查过滤掉无效操作: -**Interface down check**: If the interface is administratively down (not marked `IFF_UP`), the write succeeds immediately without processing the packet. This silent discard behavior differs from the read path, which returns `EHOSTDOWN` when not ready. The asymmetry makes sense: applications writing packets shouldn't fail when the interface is temporarily down, packets are simply dropped, mimicking what would happen on a real network interface with no carrier. +**接口关闭检查**:如果接口处于管理性关闭状态(未标记 `IFF_UP`),写入操作会立即成功返回而不处理该数据包。这种静默丢弃行为与读取路径不同,后者在未就绪时会返回 `EHOSTDOWN`。这种不对称设计是合理的:当接口暂时关闭时,写入数据包的应用程序不应失败,数据包只是被丢弃,模拟了真实网络接口在无载波时的行为。 -**Zero-length write**: Writing zero bytes is treated as a no-op success. This handles edge cases like `write(fd, buf, 0)` without error. +**零长度写入**:写入零字节被视为无操作成功。这会处理诸如 `write(fd, buf, 0)` 之类的边界情况而不报错。 -##### Determining Packet Size Limits +##### 确定数据包大小限制 ```c l2tun = (tp->tun_flags & TUN_L2) != 0; @@ -9137,21 +8965,21 @@ if (l2tun) { mru += sizeof(uint32_t); ``` -The Maximum Receive Unit (MRU) depends on the interface type: +最大接收单元(MRU)取决于接口类型: -- Layer 3 (tun): `TUNMRU` (typically 1500 bytes, standard IPv4 MTU) -- Layer 2 (tap/vmnet): `TAPMRU` (typically 1518 bytes, Ethernet frame size) +- 三层(tun):`TUNMRU`(通常为 1500 字节,标准 IPv4 MTU) +- 二层(tap/vmnet):`TAPMRU`(通常为 1518 字节,以太网帧大小) -**Alignment requirements**: Layer 2 devices set `align = ETHER_ALIGN` (usually 2 bytes). This ensures the IP header following the 14-byte Ethernet header lands on a 4-byte boundary, which improves performance on architectures with alignment restrictions or cache line efficiency concerns. +**对齐要求**:二层设备设置 `align = ETHER_ALIGN`(通常为2字节)。这确保14字节以太网头部后的IP头部落在4字节边界上,从而在具有对齐限制或关注缓存行效率的架构上提升性能。 -**Header adjustments**: The MRU increases to accommodate: +**头部调整**:MRU 会增加以容纳: -- Virtio-net headers for tap devices (`vhdrlen` bytes) -- Address family indicator for tun devices in IFHEAD mode (4 bytes) +- tap 设备的 Virtio-net 头部(`vhdrlen` 字节) +- IFHEAD 模式下 tun 设备的地址族指示符(4 字节) -These headers precede the actual packet data in the userspace buffer but are not part of the on-wire packet format. +这些头部位于用户空间缓冲区中实际数据包数据之前,但不属于线路上的数据包格式。 -##### Validating Write Size +##### 验证写入大小 ```c if (uio->uio_resid < 0 || uio->uio_resid > mru) { @@ -9160,15 +8988,15 @@ if (uio->uio_resid < 0 || uio->uio_resid > mru) { } ``` -The write size (`uio->uio_resid`) must fall within valid bounds. Negative sizes are impossible in correct operation but checked for safety. Oversized writes indicate either: +写入大小(`uio->uio_resid`)必须在有效范围内。在正确操作中负大小不可能出现,但为安全起见会进行检查。过大的写入表示: -- Application bugs (trying to write jumbo frames without configuration) -- Protocol violations (incorrect packet framing) -- Malicious behavior +- 应用程序错误(尝试写入未配置的巨型帧) +- 协议违规(不正确的数据包帧格式) +- 恶意行为 -The `EIO` return signals a generic I/O error, appropriate for data that cannot be processed. +`EIO` 返回值指示通用 I/O 错误,适用于无法处理的数据。 -##### Processing Virtio-Net Headers +##### 处理 Virtio-Net 头部 ```c if (vhdrlen > 0) { @@ -9183,17 +9011,17 @@ if (vhdrlen > 0) { } ``` -When virtio-net header mode is enabled (common for VM networking), userspace prepends a small header to each packet describing offload operations: +当启用virtio-net头部模式(常见于虚拟机网络)时,用户空间在每个数据包前添加一个小头部,描述卸载操作: -- **Checksum offload**: Instructs the kernel where to compute and insert checksums -- **Segmentation offload**: For large packets (TSO/GSO), describes how to segment into MTU-sized chunks -- **Receive offload hints**: Indicates checksums already validated by VM guest +- **校验和卸载**:指示内核在何处计算并插入校验和 +- **分段卸载**:对于大数据包(TSO/GSO),描述如何分段为MTU大小的块 +- **接收卸载提示**:指示 VM 客户机已验证的校验和 -The `uiomove` call copies the header from userspace, consuming `vhdrlen` bytes from the user buffer and advancing `uio`. If the copy fails (invalid pointer), the error propagates immediately, a corrupted header cannot be safely processed. +`uiomove` 调用从用户空间复制头部,消耗 `vhdrlen` 字节的用户缓冲区并推进 `uio`。如果复制失败(无效指针),错误会立即传播,因为受损的头部不能被安全处理。 -The debug output logs header fields for troubleshooting offload issues. In production builds with `tundebug = 0`, these statements compile away. +调试输出记录头部字段,用于排查卸载问题。在生产构建中,当 `tundebug = 0` 时,这些语句会被编译掉。 -##### Constructing the Mbuf +##### 构建 Mbuf ```c if ((m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR)) == NULL) { @@ -9202,19 +9030,19 @@ if ((m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR)) == NULL) { } ``` -The `m_uiotombuf` function is the kernel's utility for converting userspace data into the network stack's native packet format (mbuf chains). Its parameters specify: +`m_uiotombuf` 函数是内核将用户空间数据转换为网络栈本地数据包格式(mbuf 链)的实用工具。其参数指定: -- `uio` - source data from userspace -- `M_NOWAIT` - don't sleep for memory (return NULL immediately if allocation fails) -- `0` - no maximum length (use all remaining `uio_resid` bytes) -- `align` - start packet data this many bytes into the first mbuf -- `M_PKTHDR` - allocate an mbuf with packet header (required for network packets) +- `uio` - 来自用户空间的源数据 +- `M_NOWAIT` - 不为内存而睡眠(分配失败时立即返回 NULL) +- `0` - 无最大长度(使用所有剩余的 `uio_resid` 字节) +- `align` - 将数据包数据从第一个 mbuf 起始处偏移此字节数 +- `M_PKTHDR` - 分配带有数据包头部的 mbuf(网络数据包必需) -**Memory allocation failure**: If `m_uiotombuf` returns NULL, the system is out of mbuf memory. The `IFCOUNTER_IERRORS` counter increments (visible in `netstat -i`), and `ENOBUFS` informs userspace of temporary resource exhaustion. Applications should generally retry after a brief delay. +**内存分配失败**:如果 `m_uiotombuf` 返回 NULL,则系统 mbuf 内存耗尽。`IFCOUNTER_IERRORS` 计数器递增(在 `netstat -i` 中可见),`ENOBUFS` 告知用户空间临时资源耗尽。应用程序通常应在短暂延迟后重试。 -**The M_NOWAIT policy**: Using `M_NOWAIT` rather than `M_WAITOK` prevents userspace writes from blocking indefinitely when memory is low. This is appropriate for the write path, if memory isn't available now, failing quickly allows the application to handle backpressure. +**M_NOWAIT 策略**:使用 `M_NOWAIT` 而非 `M_WAITOK` 可防止用户在内存不足时无限期阻塞。这适用于写入路径:如果当前内存不可用,快速失败让应用程序处理背压。 -##### Setting Packet Metadata +##### 设置数据包元数据 ```c m->m_pkthdr.rcvif = ifp; @@ -9223,17 +9051,17 @@ mac_ifnet_create_mbuf(ifp, m); #endif ``` -Two pieces of metadata are attached to the packet: +两个元数据片段会附加到数据包上: -**Receive interface**: `m_pkthdr.rcvif` records which interface received the packet. This seems counterintuitive; we're injecting a packet, not receiving one, but from the kernel's perspective, packets written to `/dev/tun0` are "received" on the `tun0` interface. This field is used for: +**接收接口**:`m_pkthdr.rcvif` 记录了接收该数据包的接口。这看起来有悖直觉——我们是在注入数据包,而非接收——但从内核视角看,写入 `/dev/tun0` 的数据包相当于在 `tun0` 接口上“被接收”。该字段用于: -- Firewall rules (ipfw, pf) that filter based on incoming interface -- Routing decisions that consider packet source -- Accounting that attributes traffic to specific interfaces +- 基于入接口过滤的防火墙规则(ipfw、pf) +- 考虑数据包源的路由决策 +- 将流量归属到特定接口的计费统计 -**MAC Framework labeling**: If the Mandatory Access Control framework is enabled, `mac_ifnet_create_mbuf` applies security labels to the packet based on the interface's policy. This supports systems using TrustedBSD MAC for fine-grained network security. +**MAC 框架标记**:如果启用了强制访问控制框架,`mac_ifnet_create_mbuf` 会根据接口策略为数据包应用安全标签。这支持使用 TrustedBSD MAC 实现细粒度网络安全的系统。 -##### Dispatching by Layer +##### 按层分发 ```c if (l2tun) @@ -9242,24 +9070,24 @@ if (l2tun) return (tunwrite_l3(tp, m)); ``` -The final step delegates to layer-specific processing functions: +最后一步将控制权转交给特定层的处理函数: -**Layer 2 path** (`tunwrite_l2`): For tap/vmnet devices, the mbuf contains a complete Ethernet frame. The function: -- Validates the Ethernet header -- Applies virtio-net offload hints if present -- Injects the frame into the Ethernet processing path -- Potentially processes through LRO (Large Receive Offload) +**第二层路径**(`tunwrite_l2`):对于 tap/vmnet 设备,mbuf 包含完整的以太网帧。该函数: +- 验证以太网头部 +- 如果存在则应用 virtio-net 卸载提示 +- 将帧注入以太网处理路径 +- 可能通过 LRO(大型接收卸载)进行处理 -**Layer 3 path** (`tunwrite_l3`): For tun devices, the mbuf contains a raw IP packet (possibly preceded by an address family indicator in IFHEAD mode). The function: -- Extracts the protocol family (IPv4 vs IPv6) -- Dispatches to the appropriate network layer protocol handler -- Bypasses link-layer processing entirely +**第三层路径**(`tunwrite_l3`):对于 tun 设备,mbuf 包含原始 IP 数据包(在 IFHEAD 模式下可能前面带有地址族指示符)。该函数: +- 提取协议族(IPv4 或 IPv6) +- 分派到相应的网络层协议处理程序 +- 完全绕过链路层处理 -Both functions assume ownership of the mbuf, they will either successfully inject it into the network stack or free it on error. The caller should not access the mbuf after these calls return. +两个函数都获取了 mbuf 的所有权——它们要么成功将其注入网络栈,要么在出错时释放它。调用者在这些函数返回后不应再访问该 mbuf。 -##### Data Flow Summary +##### 数据流总结 -The complete path from userspace write to kernel network processing: +从用户空间写入到内核网络处理的完整路径如下: ```html Application calls write(fd, packet, len) -> @@ -9284,26 +9112,26 @@ Network stack processes packet Routing, firewall, socket delivery ``` -##### Atomic Write Semantics +##### 原子写入语义 -The opening comment, "an atomic write is a packet - or else!", highlights a critical contract: userspace must write complete packets in single `write(2)` calls. The driver provides no buffering or packet assembly: +开头的注释“一次原子写入就是一个数据包——否则!”强调了关键约定:用户空间必须通过单次 `write(2)` 调用写入完整的数据包。驱动程序不提供缓冲或数据包组装: -- Writing 1000 bytes, then 500 bytes creates **two** packets (1000-byte and 500-byte) -- Not "one 1500-byte packet assembled from two writes" +- 写入 1000 字节,然后写入 500 字节会创建**两个**数据包(1000 字节和 500 字节) +- 不能“由两次写入组装成一个 1500 字节的数据包” -This design simplifies the driver and matches the semantics of real network interfaces, which receive complete frames. Applications that need to construct packets piece-by-piece must buffer in userspace before writing. +这种设计简化了驱动程序,并与实际网络接口的语义相匹配(接收完整帧)。需要逐段构建数据包的应用程序必须在用户空间缓冲后再写入。 -##### Error Handling and Resource Management +##### 错误处理与资源管理 -The function's error handling demonstrates defensive programming patterns: +该函数的错误处理体现了防御性编程模式: -- **Early validation** prevents resource allocation for invalid requests -- **Immediate cleanup** on `m_uiotombuf` failure (increment error counter, return ENOBUFS) -- **Ownership transfer** to layer-specific functions eliminates double-free risks +- **早期验证**防止对无效请求进行资源分配 +- `m_uiotombuf` 失败时**立即清理**(递增错误计数器,返回 ENOBUFS) +- 将**所有权转移**到特定层函数消除了双重释放风险 -The only resource allocated (the mbuf) has clear ownership transfer semantics. After calling `tunwrite_l2` or `tunwrite_l3`, the write function never touches it again. +唯一分配的资源(mbuf)具有清晰的所有权转移语义。在调用 `tunwrite_l2` 或 `tunwrite_l3` 之后,写入函数就不再接触它。 -#### 5.2 L3 (`tun`) dispatch to the network stack (netisr) +#### 5.2 L3(`tun`)分派到网络栈(netisr) ```c 1845: static int @@ -9358,9 +9186,9 @@ The only resource allocated (the mbuf) has clear ownership transfer semantics. A 1894: } ``` -The `tunwrite_l3` function handles packets written to layer 3 (tun) devices, injecting raw IP packets directly into the kernel's network protocol handlers. Unlike layer 2 (tap) devices that process complete Ethernet frames, tun devices work with IP packets that have no link-layer headers, making them ideal for VPN implementations and IP tunneling protocols. +`tunwrite_l3` 函数处理写入第三层(tun)设备的数据包,将原始 IP 数据包直接注入内核的网络协议处理程序。与处理完整以太网帧的第二层(tap)设备不同,tun 设备处理的是没有链路层头部的 IP 数据包,因此非常适合 VPN 实现和 IP 隧道协议。 -##### Function Context and Protocol Family Extraction +##### 函数上下文与协议族提取 ```c static int @@ -9373,9 +9201,9 @@ tunwrite_l3(struct tuntap_softc *tp, struct mbuf *m) ifp = TUN2IFP(tp); ``` -The function receives the softc and an mbuf containing the packet. The `epoch_tracker` will be used later to ensure safe concurrent access to routing structures. The `family` variable will hold the protocol family (AF_INET or AF_INET6), and `isr` will identify the appropriate network interrupt service routine. +该函数接收 softc 和一个包含数据包的 mbuf。`epoch_tracker` 将在后续用于确保对路由结构的安全并发访问。`family` 变量将保存协议族(AF_INET 或 AF_INET6),`isr` 则标识合适的网络中断服务例程。 -##### Determining Protocol Family +##### 确定协议族 ```c TUN_LOCK(tp); @@ -9392,38 +9220,38 @@ if (tp->tun_flags & TUN_IFHEAD) { } ``` -Tun devices support two modes for indicating packet protocol: +Tun 设备支持两种指示数据包协议的模式: -**IFHEAD mode** (`TUN_IFHEAD` flag set): Each packet begins with a 4-byte address family indicator in network byte order. This mode, enabled via the `TUNSIFHEAD` ioctl, allows a single tun device to carry both IPv4 and IPv6 traffic. The code: +**IFHEAD 模式**(设置了 `TUN_IFHEAD` 标志):每个数据包以网络字节序的 4 字节地址族指示符开头。此模式通过 `TUNSIFHEAD` ioctl 启用,允许单个 tun 设备同时承载 IPv4 和 IPv6 流量。代码: -1. Checks if the first mbuf contains at least 4 bytes using `m->m_len` -2. If not, calls `m_pullup` to consolidate the header into the first mbuf -3. Extracts the family using `mtod` (mbuf-to-data pointer) and converts from network to host byte order with `ntohl` -4. Strips the family indicator with `m_adj`, which advances the data pointer by 4 bytes +1. 使用 `m->m_len` 检查第一个 mbuf 是否包含至少 4 个字节 +2. 若不满足,调用 `m_pullup` 将头部合并到第一个 mbuf 中 +3. 使用 `mtod`(mbuf 到数据指针)提取地址族,并用 `ntohl` 从网络字节序转换为主机字节序 +4. 使用 `m_adj` 剥离地址族指示符(将数据指针前进 4 个字节) -The `m_pullup` call can fail if memory is exhausted, returning NULL. In this case, the original mbuf has already been freed by `m_pullup`, so the function simply returns `ENOBUFS` without calling `m_freem`. +如果内存耗尽,`m_pullup` 调用可能失败并返回 NULL。此时,原始的 mbuf 已被 `m_pullup` 释放,因此函数直接返回 `ENOBUFS`,无需调用 `m_freem`。 -**Non-IFHEAD mode** (default): All packets are assumed to be IPv4. This legacy mode simplifies applications that only handle IPv4, but prevents multiplexing protocols over one device. +**非IFHEAD模式**(默认):所有包都假定为IPv4。这种传统模式简化了仅处理IPv4的应用程序,但阻止了通过一个设备复用多种协议。 -The mutex is held only while reading `tun_flags`, minimizing lock contention. The comment "Could be unlocked read?" questions whether the lock is even necessary, since flags rarely change after initialization, an unlocked read would likely be safe. However, the conservative approach prevents theoretical races. +互斥锁仅在读取`tun_flags`时持有,以最小化锁竞争。注释"Could be unlocked read?"质疑锁是否必要,因为标志在初始化后很少改变,非锁定读取很可能安全。然而,保守的方法避免了理论上的竞争条件。 -##### Berkeley Packet Filter Tap +##### Berkeley 数据包过滤器 Tap ```c BPF_MTAP2(ifp, &family, sizeof(family), m); ``` -The `BPF_MTAP2` macro passes the packet to any attached BPF (Berkeley Packet Filter) listeners, typically packet capture tools like `tcpdump`. The macro name breaks down as: +`BPF_MTAP2`宏将包传递给任何已连接的BPF(伯克利包过滤器)监听者,通常是像`tcpdump`这样的包捕获工具。宏名称分解如下: -- **BPF** - Berkeley Packet Filter subsystem -- **MTAP** - tap into the packet stream from an mbuf -- **2** - two-argument variant that prepends metadata +- **BPF** - Berkeley 数据包过滤器子系统 +- **MTAP** - 从mbuf中接入报文流 +- **2** - 双参数变体,用于前置元数据 -The call prepends the 4-byte `family` value before the packet data, allowing capture tools to distinguish IPv4 from IPv6 without packet inspection. This matches the link-layer type `DLT_NULL` configured during interface creation; captured packets have a 4-byte address family header even if the wire format doesn't. +该调用在包数据之前前置4字节的`family`值,使捕获工具无需检查包内容即可区分IPv4和IPv6。这与接口创建期间配置的链路层类型`DLT_NULL`匹配;捕获的包会有一个4字节的地址族头部,即使线路格式中没有。 -BPF operates efficiently: if no listeners are attached, the macro expands to a simple conditional check that costs only a few instructions. This design allows pervasive instrumentation points throughout the network stack without performance impact when not actively debugging. +BPF高效运行:如果没有监听者,该宏扩展为一个简单的条件检查,仅消耗几条指令。这种设计允许在整个网络栈中散布检测点,而在未主动调试时不会影响性能。 -##### Protocol Validation and Dispatch Setup +##### 协议验证与分发设置 ```c switch (family) { @@ -9443,57 +9271,57 @@ default: } ``` -The protocol family determines which network layer interrupt service routine (netisr) will process the packet: +协议族决定了哪个网络层中断服务例程(netisr)将处理该包: -- **AF_INET** -> `NETISR_IP` - IPv4 processing -- **AF_INET6** -> `NETISR_IPV6` - IPv6 processing +- **AF_INET** -> `NETISR_IP` - IPv4 处理 +- **AF_INET6** -> `NETISR_IPV6` - IPv6 处理 -The `#ifdef` guards are required: if the kernel was compiled without IPv4 or IPv6 support, those cases don't exist, and attempting to inject such packets results in `EAFNOSUPPORT` (address family not supported). +`#ifdef`保护是必需的:如果内核在没有IPv4或IPv6支持的情况下编译,这些情况不存在,尝试注入此类包将导致`EAFNOSUPPORT`(地址族不支持)。 -Unsupported protocol families trigger immediate mbuf deallocation via `m_freem` and return an error. This prevents packets from leaking into the network stack with incorrect metadata that could cause crashes or security issues. +不支持的协议族会通过`m_freem`立即释放mbuf并返回错误。这防止了带有错误元数据的包泄漏到网络栈中,从而可能导致崩溃或安全问题。 -##### Entropy Collection +##### 熵收集 ```c random_harvest_queue(m, sizeof(*m), RANDOM_NET_TUN); ``` -This call contributes entropy to the kernel's random number generator. Network packet arrival timing is unpredictable and difficult for attackers to manipulate, making it a valuable entropy source. The function samples metadata about the mbuf structure (not packet contents) to seed the random pool. +此调用为内核的随机数生成器贡献熵。网络包到达的时机不可预测且难以被攻击者操控,使其成为宝贵的熵源。该函数采样mbuf结构的元数据(而非包内容)来为随机池提供种子。 -The `RANDOM_NET_TUN` flag tags the entropy source, allowing the random subsystem to track entropy diversity. Systems relying on `/dev/random` for cryptographic operations benefit from accumulating entropy from multiple independent sources. +`RANDOM_NET_TUN`标志标记了熵源,允许随机子系统跟踪熵的多样性。依赖`/dev/random`进行加密操作的系统受益于从多个独立源积累熵。 -##### Interface Statistics +##### 接口统计 ```c if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len); if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); ``` -These calls update interface statistics visible via `netstat -i` or `ifconfig`: +这些调用更新可通过`netstat -i`或`ifconfig`查看的接口统计信息: -- `IFCOUNTER_IBYTES` - total bytes received -- `IFCOUNTER_IPACKETS` - total packets received +- `IFCOUNTER_IBYTES` - 接收的总字节数 +- `IFCOUNTER_IPACKETS` - 接收的总数据包数 -From the kernel's perspective, packets written by userspace are "input" to the interface, hence the use of input counters rather than output counters. This matches the semantic established by setting `m_pkthdr.rcvif` earlier, the packet is being received from userspace. +从内核角度看,用户空间写入的包是接口的"输入",因此使用输入计数器而非输出计数器。这与之前设置`m_pkthdr.rcvif`所建立的语义一致:包是从用户空间接收的。 -The `if_inc_counter` function handles atomic updates, ensuring accurate counts even with concurrent packet processing on multiprocessor systems. +`if_inc_counter`函数处理原子更新,确保在多处理器系统上并发处理包时计数仍然准确。 -##### Network Stack Context Setup +##### 网络栈上下文设置 ```c CURVNET_SET(ifp->if_vnet); M_SETFIB(m, ifp->if_fib); ``` -Two pieces of context are established before injecting the packet: +在注入包之前,需要建立两个上下文: -**Virtual network stack**: `CURVNET_SET` switches to the network context (vnet) associated with the interface. In systems using jails or network stack virtualization, multiple independent network stacks coexist. This macro ensures routing tables, firewall rules, and socket lookups operate in the correct namespace. +**虚拟网络栈**:`CURVNET_SET`切换到与接口关联的网络上下文(vnet)。在使用jail或网络栈虚拟化的系统中,多个独立的网络栈共存。此宏确保路由表、防火墙规则和套接字查找在正确的命名空间中操作。 -**Forwarding Information Base (FIB)**: `M_SETFIB` tags the packet with the interface's FIB number. FreeBSD supports multiple routing tables (FIBs), allowing policy-based routing where different applications or interfaces use distinct routing policies. The packet inherits the interface's FIB, ensuring routes are looked up in the appropriate table. +**转发信息库(FIB)**:`M_SETFIB`用接口的FIB编号标记该包。FreeBSD支持多个路由表(FIB),允许基于策略的路由,其中不同的应用或接口使用不同的路由策略。该包继承接口的FIB,确保在适当的表中查找路由。 -These settings affect all subsequent packet processing: firewall rules, routing decisions, and socket delivery. +这些设置会影响所有后续的包处理:防火墙规则、路由决策和套接字交付。 -##### Epoch-Protected Dispatch +##### Epoch 保护的分发 ```c NET_EPOCH_ENTER(et); @@ -9503,38 +9331,38 @@ CURVNET_RESTORE(); return (0); ``` -The critical packet injection occurs within an epoch section: +关键的包注入发生在epoch段内: -**Network epoch**: FreeBSD's network stack uses epoch-based reclamation (a form of read-copy-update) to protect data structures from concurrent access without heavy locking. `NET_EPOCH_ENTER` registers this thread as active in the network epoch, preventing routing entries, interface structures, and other network objects from being deallocated until `NET_EPOCH_EXIT`. +**网络epoch**:FreeBSD的网络栈使用基于epoch的回收(一种读-复制-更新形式)来保护数据结构免受并发访问的影响,而无需繁重的锁定。`NET_EPOCH_ENTER`将此线程注册为网络epoch中的活跃线程,防止路由条目、接口结构和其他网络对象在`NET_EPOCH_EXIT`之前被释放。 -This mechanism enables lock-free reads of routing tables and interface lists, dramatically improving multicore scalability. The epoch tracker `et` maintains the context needed to exit cleanly. +此机制支持对路由表和接口列表的无锁读取,显著提高多核可扩展性。epoch 跟踪器 `et` 维护了干净退出所需的上下文。 -**Netisr dispatch**: `netisr_dispatch(isr, m)` hands the packet to the network interrupt service routine subsystem. This asynchronous dispatch model decouples packet injection from protocol processing: +**Netisr 分发**:`netisr_dispatch(isr, m)` 将数据包传递给网络中断服务例程子系统。这种异步分发模型将数据包注入与协议处理解耦: -1. The packet is queued to the appropriate netisr thread (typically one per CPU core) -2. The calling thread (handling the `write(2)`) returns immediately -3. The netisr thread dequeues and processes the packet asynchronously +1. 数据包被排队到适当的 netisr 线程(通常每个 CPU 核心一个) +2. 调用线程(处理 `write(2)`)立即返回 +3. netisr 线程从队列中取出数据包并异步处理 -This design prevents userspace writes from blocking in complex protocol processing (IP forwarding, firewall evaluation, TCP reassembly). The netisr thread will: -- Validate IP headers (checksum, length, version) -- Process IP options -- Consult routing tables -- Apply firewall rules -- Deliver to local sockets or forward to other interfaces +这种设计防止用户态写操作在复杂的协议处理(IP 转发、防火墙评估、TCP 重组)中被阻塞。netisr 线程将: +- 验证 IP 头部(校验和、长度、版本) +- 处理 IP 选项 +- 查询路由表 +- 应用防火墙规则 +- 投递到本地套接字或转发到其他接口 -**Context restoration**: `CURVNET_RESTORE` switches back to the calling thread's original network context. This is essential for correctness, without restoration, subsequent operations in the thread would execute in the wrong network namespace. +**上下文恢复**:`CURVNET_RESTORE` 切换回调用线程的原始网络上下文。这对于正确性至关重要;如果不恢复,线程中的后续操作将在错误的网络命名空间中执行。 -##### Ownership and Lifecycle +##### 所有权与生命周期 -After `netisr_dispatch`, the function returns success but no longer owns the mbuf. The netisr subsystem assumes responsibility for either: -- Delivering the packet to its destination and freeing the mbuf -- Dropping the packet (for policy, routing, or validation reasons) and freeing the mbuf +在 `netisr_dispatch` 之后,函数返回成功,但不再拥有 mbuf。netisr 子系统负责以下任一操作: +- 将数据包投递到其目的地并释放 mbuf +- 丢弃数据包(由于策略、路由或验证原因)并释放 mbuf -The function never needs to call `m_freem` in the success path, ownership has transferred to the network stack. +函数在成功路径上永远不需要调用 `m_freem`,所有权已转移到网络栈。 -##### Data Flow Through the Network Stack +##### 通过网络栈的数据流 -The complete path after dispatch: +分发后的完整路径: ```html tunwrite_l3() injects packet -> @@ -9553,17 +9381,17 @@ Firewall evaluation (ipfw, pf) | -> Drop: m_freem() ``` -##### Error Paths and Resource Management +##### 错误路径与资源管理 -The function has three possible outcomes: +函数有三种可能的结果: -1. **Success** (return 0): Packet dispatched to network stack, mbuf ownership transferred -2. **Pullup failure** (return ENOBUFS): `m_pullup` freed the mbuf, no further cleanup needed -3. **Unsupported protocol** (return EAFNOSUPPORT): Mbuf explicitly freed with `m_freem` +1. **成功**(返回 0):数据包已分派到网络栈,mbuf 所有权已转移 +2. **pullup 失败**(返回 ENOBUFS):`m_pullup` 释放了 mbuf,无需进一步清理 +3. **不支持的协议**(返回 EAFNOSUPPORT):使用 `m_freem` 显式释放 mbuf -All paths correctly manage mbuf ownership, preventing both leaks and double-frees. This careful resource management is characteristic of well-designed kernel code. +所有路径都能正确管理 mbuf 所有权,防止泄漏和双重释放。这种谨慎的资源管理是设计良好的内核代码的特征。 -#### 6) Readiness: `poll(2)` and kqueue +#### 6) 就绪状态:`poll(2)` 和 kqueue ```c 1965: */ @@ -9625,7 +9453,7 @@ All paths correctly manage mbuf ownership, preventing both leaks and double-free 2021: } ``` -The `tunpoll` function implements support for `poll(2)` and `select(2)`, which allow applications to monitor multiple file descriptors for I/O readiness: +`tunpoll` 函数实现了对 `poll(2)` 和 `select(2)` 的支持,允许应用程序监控多个文件描述符的 I/O 就绪状态: ```c static int @@ -9636,19 +9464,19 @@ tunpoll(struct cdev *dev, int events, struct thread *td) int revents = 0; ``` -The function receives: +该函数接收: -- `dev` - the character device being polled -- `events` - bitmask of events the application wants to monitor -- `td` - the calling thread context +- `dev` - 被轮询的字符设备 +- `events` - 应用程序希望监控的事件的位掩码 +- `td` - 调用线程上下文 -The return value `revents` indicates which requested events are currently ready. The function builds this bitmask by checking actual device conditions. +返回值 `revents` 指示当前哪些请求的事件已就绪。函数通过检查设备实际条件来构建此位掩码。 -##### Event Notification Mechanisms: `tunpoll` and `tunkqfilter` +##### 事件通知机制:`tunpoll` 和 `tunkqfilter` -Efficient I/O multiplexing is essential for applications managing multiple tun/tap devices or integrating tunnel I/O with other event sources. FreeBSD provides two interfaces for this: the traditional `poll(2)`/`select(2)` system calls and the more scalable `kqueue(2)` mechanism. The `tunpoll` and `tunkqfilter` functions implement these interfaces, allowing applications to wait efficiently for readable or writable conditions without busy-polling. +高效的 I/O 多路复用对于管理多个 tun/tap 设备或将隧道 I/O 与其他事件源集成的应用程序至关重要。FreeBSD 提供两种接口:传统的 `poll(2)`/`select(2)` 系统调用,以及更具可扩展性的 `kqueue(2)` 机制。`tunpoll` 和 `tunkqfilter` 函数实现了这些接口,允许应用程序高效地等待可读或可写条件,而无需忙轮询。 -##### Read Readiness +##### 读取就绪 ```c if (events & (POLLIN | POLLRDNORM)) { @@ -9664,41 +9492,41 @@ if (events & (POLLIN | POLLRDNORM)) { } ``` -When the application requests read events (`POLLIN` or `POLLRDNORM`, which are synonymous for devices): +当应用程序请求读事件(`POLLIN` 或 `POLLRDNORM`,对于设备来说是同义的): -**Queue check**: The send queue lock is acquired, and `IFQ_IS_EMPTY` tests whether packets await reading. If packets are present: +**队列检查**:获取发送队列锁,并使用 `IFQ_IS_EMPTY` 测试是否有数据包等待读取。如果有数据包存在: -- The requested read events are added to `revents` -- The application will be notified that `read(2)` can proceed without blocking +- 请求的读事件被添加到 `revents` +- 应用程序将收到通知,`read(2)` 可以无阻塞地进行 -**Registration for notification**: If the queue is empty: +**注册通知**:如果队列为空: -- `selrecord` registers this thread's interest in the device becoming readable -- The thread's context is added to `tp->tun_rsel`, a per-device selection list -- When packets arrive later (in `tunstart` or `tunstart_l2`), the code calls `selwakeup(&tp->tun_rsel)` to notify all registered threads +- `selrecord` 注册此线程对设备可读的兴趣 +- 线程的上下文被添加到 `tp->tun_rsel`,这是一个每设备的选择列表 +- 当数据包随后到达时(在 `tunstart` 或 `tunstart_l2` 中),代码调用 `selwakeup(&tp->tun_rsel)` 通知所有已注册的线程 -The `selrecord` mechanism is the key to efficient waiting. Instead of the application repeatedly polling, the kernel maintains a list of interested threads and wakes them when conditions change. This pattern appears throughout the FreeBSD kernel for any device supporting `poll(2)`. +`selrecord` 机制是高效等待的关键。内核维护一个感兴趣线程的列表,并在条件变化时唤醒它们,而不是让应用程序反复轮询。这种模式在 FreeBSD 内核中广泛出现,适用于任何支持 `poll(2)` 的设备。 -The send queue lock protects against races where packets arrive between checking the queue and registering interest. The lock ensures atomicity: if the queue is empty during the check, registration completes before any packet arrival can call `selwakeup`. +发送队列锁保护了在检查队列和注册兴趣之间可能发生的数据包到达竞争。该锁确保了原子性:如果在检查期间队列为空,则在任何数据包到达调用 `selwakeup` 之前完成注册。 -##### Write Readiness +##### 写入就绪 ```c revents |= events & (POLLOUT | POLLWRNORM); ``` -Writes are always ready for tun/tap devices. The device has no internal buffering that could fill, `write(2)` either succeeds immediately (allocating an mbuf and dispatching to the network stack) or fails immediately (if mbuf allocation fails). There's no condition where writing would block waiting for buffer space to become available. +tun/tap 设备的写操作始终就绪。该设备没有可能填满的内部缓冲,`write(2)` 要么立即成功(分配 mbuf 并分派到网络栈),要么立即失败(如果 mbuf 分配失败)。没有写入会因等待缓冲区空间可用而阻塞的情况。 -This unconditional write readiness is common for network devices. Unlike pipes or sockets with limited buffer space, tun/tap devices accept writes as fast as the application can generate them, relying on the mbuf allocator's dynamic memory management. +这种无条件的写就绪性在网络设备中很常见。与具有有限缓冲区空间的管道或套接字不同,tun/tap 设备接受写入的速度与应用程序生成它们的速度一样快,依赖于 mbuf 分配器的动态内存管理。 -##### Kqueue Interface: `tunkqfilter` +##### Kqueue 接口:`tunkqfilter` -The `tunkqfilter` function implements support for `kqueue(2)`, FreeBSD's scalable event notification mechanism. Kqueue offers several advantages over `poll(2)`: +`tunkqfilter` 函数实现了对 `kqueue(2)` 的支持,这是 FreeBSD 的可扩展事件通知机制。Kqueue 相比 `poll(2)` 具有多个优势: -- Edge-triggered semantics (notifications only on state changes) -- Better performance with thousands of file descriptors -- User data can be attached to events -- More flexible event types (not just read/write) +- 边沿触发语义(仅在状态变化时通知) +- 在数千个文件描述符时性能更好 +- 用户数据可以附加到事件上 +- 更灵活的事件类型(不仅仅是读/写) ```c static int @@ -9708,9 +9536,9 @@ tunkqfilter(struct cdev *dev, struct knote *kn) struct ifnet *ifp = TUN2IFP(tp); ``` -The function receives a `knote` (kernel note) structure representing the event registration. The `knote` persists across multiple event deliveries, unlike `poll(2)` which requires re-registration on every call. +该函数接收一个代表事件注册的 `knote`(内核通知)结构。与每次调用都需要重新注册的 `poll(2)` 不同,`knote` 在多次事件传递之间持久存在。 -##### Filter Type Validation +##### 过滤器类型验证 ```c switch(kn->kn_filter) { @@ -9731,12 +9559,12 @@ default: } ``` -The application specifies which event type to monitor via `kn->kn_filter`: +应用程序通过 `kn->kn_filter` 指定要监视的事件类型: -- `EVFILT_READ` - monitor for readable condition -- `EVFILT_WRITE` - monitor for writable condition +- `EVFILT_READ` - 监视可读条件 +- `EVFILT_WRITE` - 监视可写条件 -For each filter type, the code assigns a function table (`kn_fop`) that implements the filter's semantics. These tables were defined earlier in the source: +对于每种过滤器类型,代码分配一个实现该过滤器语义的函数表(`kn_fop`)。这些表在源代码的较早部分定义: ```c static const struct filterops tun_read_filterops = { @@ -9754,16 +9582,16 @@ static const struct filterops tun_write_filterops = { }; ``` -The `filterops` structure defines callbacks: +`filterops` 结构定义了回调: -- `f_isfd` - flag indicating this filter operates on file descriptors -- `f_attach` - called when the filter is registered (NULL here, no special setup needed) -- `f_detach` - called when the filter is removed (`tunkqdetach` cleanup) -- `f_event` - called to test event condition (`tunkqread` or `tunkqwrite`) +- `f_isfd` - 指示此过滤器操作于文件描述符的标志 +- `f_attach` - 当过滤器被注册时调用(此处为 NULL,无需特殊设置) +- `f_detach` - 当过滤器被移除时调用(`tunkqdetach` 清理) +- `f_event` - 调用以测试事件条件(`tunkqread` 或 `tunkqwrite`) -Unsupported filter types (like `EVFILT_SIGNAL` or `EVFILT_TIMER`) return `EINVAL`, as they don't make sense for tun/tap devices. +不支持的过滤器类型(如 `EVFILT_SIGNAL` 或 `EVFILT_TIMER`)返回 `EINVAL`,因为它们对 tun/tap 设备无意义。 -##### Registering the Event +##### 注册事件 ```c kn->kn_hook = tp; @@ -9773,21 +9601,21 @@ return (0); } ``` -Two steps complete registration: +两个步骤完成注册: -**Attach context**: `kn->kn_hook` stores the softc pointer. This allows the filter operation functions (`tunkqread`, `tunkqwrite`) to access device state without global lookups. When the event fires, the callback receives the `knote`, extracts `kn_hook`, and casts it back to `tuntap_softc *`. +**附加上下文**:`kn->kn_hook` 存储了 softc 指针。这允许过滤器操作函数(`tunkqread`、`tunkqwrite`)在没有全局查找的情况下访问设备状态。当事件触发时,回调接收 `knote`,提取 `kn_hook`,并将其转换回 `tuntap_softc *`。 -**Add to notification list**: `knlist_add` inserts the `knote` into the device's kernel note list (`tp->tun_rsel.si_note`). This list is shared between `poll(2)` and `kqueue(2)` infrastructure, the `si_note` field within `tun_rsel` handles kqueue events, while other `tun_rsel` fields handle poll/select events. +**添加到通知列表**:`knlist_add` 将 `knote` 插入到设备的内核通知列表(`tp->tun_rsel.si_note`)中。该列表在 `poll(2)` 和 `kqueue(2)` 基础设施之间共享,`tun_rsel` 中的 `si_note` 字段处理 kqueue 事件,而 `tun_rsel` 的其他字段处理 poll/select 事件。 -When packets arrive (in `tunstart` or `tunstart_l2`), the code calls `KNOTE_LOCKED(&tp->tun_rsel.si_note, 0)`, which iterates the knote list and invokes each filter's `f_event` callback. If the callback returns true (readable/writable condition met), the kqueue subsystem delivers the event to userspace. +当数据包到达时(在 `tunstart` 或 `tunstart_l2` 中),代码调用 `KNOTE_LOCKED(&tp->tun_rsel.si_note, 0)`,该函数遍历 knote 列表并调用每个过滤器的 `f_event` 回调。如果回调返回 true(满足可读/可写条件),则 kqueue 子系统将事件传递到用户空间。 -The third argument to `knlist_add` (0) indicates no special flags, the knote is added unconditionally without requiring specific locking state. +`knlist_add` 的第三个参数 (0) 表示没有特殊标志,knote 无条件添加,无需特定的锁定状态。 -##### Filter Operation Callbacks +##### 过滤器操作回调 -Though not shown in this fragment, the filter operations are worth understanding: +尽管此片段未显示,但过滤器操作值得理解: -**`tunkqread`**: Called to test read readiness +**`tunkqread`**:调用以测试读取就绪状态 ```c static int @@ -9803,9 +9631,9 @@ tunkqread(struct knote *kn, long hint) } ``` -The callback checks the send queue length and stores it in `kn->kn_data`, making the count available to userspace via the `kevent` structure. Returning 1 signals the event should fire; returning 0 means the condition is not yet met. +回调函数检查发送队列长度并将其存储在 `kn->kn_data` 中,使应用程序通过 `kevent` 结构能获取该计数值。返回 1 表示事件应触发;返回 0 表示条件尚未满足。 -**`tunkqwrite`**: Called to test write readiness +**`tunkqwrite`**:调用以测试写入就绪状态 ```c static int @@ -9819,9 +9647,9 @@ tunkqwrite(struct knote *kn, long hint) } ``` -Since writes are always possible, this always returns 1. The `kn_data` field is set to the interface MTU, giving userspace information about maximum write size. +由于写入始终是可能的,因此该函数总是返回 1。`kn_data` 字段被设置为接口的 MTU,向用户空间提供关于最大写入大小的信息。 -**`tunkqdetach`**: Called when removing the event +**`tunkqdetach`**:在移除事件时调用 ```c static void @@ -9833,29 +9661,29 @@ tunkqdetach(struct knote *kn) } ``` -This removes the knote from the device's notification list, ensuring no further events are delivered for this registration. +此函数从设备的通知列表中移除该 knote,确保不再为此次注册传递后续事件。 -##### Comparison: Poll vs. Kqueue +##### 比较:Poll 与 Kqueue -The two mechanisms serve similar purposes but with different characteristics: +这两种机制具有类似目的,但特性不同: -**Poll/Select**: -- Level-triggered: reports readiness state on every call -- Requires kernel scanning of all file descriptors on each call -- Simple API, widely portable -- O(n) complexity in number of file descriptors +**Poll/Select**: +- 水平触发:每次调用时报告就绪状态 +- 需要在每次调用时由内核扫描所有文件描述符 +- API 简单,广泛可移植 +- 复杂度为 O(n),n 为文件描述符数量 -**Kqueue**: -- Edge-triggered: reports changes in readiness state -- Kernel maintains active event list, only reports changes -- More complex API, FreeBSD/macOS specific -- O(1) complexity for event delivery +**Kqueue**: +- 边沿触发:报告就绪状态的变化 +- 内核维护活动事件列表,仅报告变化 +- 更复杂的 API,FreeBSD/macOS 特有 +- 事件传递复杂度为 O(1) -For applications monitoring a single tun/tap device, the difference is negligible. For VPN concentrators or network simulators managing hundreds of virtual interfaces, kqueue's scalability advantages become significant. +对于监控单个 tun/tap 设备的应用程序,差异可以忽略不计。对于管理数百个虚拟接口的 VPN 集中器或网络模拟器,kqueue 的可扩展性优势变得显著。 -##### Notification Flow +##### 通知流程 -When a packet arrives for transmission, the complete notification sequence: +当有数据包到达等待传输时,完整的通知序列如下: ```html Network stack routes packet to tun0 -> @@ -9871,56 +9699,56 @@ Application receives notification Application calls read() to retrieve packet ``` -This multi-mechanism notification ensures applications using any waiting strategy, blocking reads, poll/select loops, or kqueue event loops, receive prompt packet delivery notification. +这种多机制通知确保无论应用程序采用哪种等待策略(阻塞读取、poll/select 循环或 kqueue 事件循环),都能及时收到数据包送达通知。 -#### Interactive Exercises for `tun(4)/tap(4)` +#### `tun(4)/tap(4)` 的交互练习 -**Goal:** Trace both directions of data flow and map user-space operations to the exact kernel lines. +**目标:** 追踪数据流的双向路径,并将用户空间操作映射到精确的内核代码行。 -##### A) Device personalities and cloning (warm-up) +##### A) 设备特性与克隆(热身) -1. In the `tuntap_drivers[]` array, list the three `.d_name` values and identify which function pointers (`.d_open`, `.d_read`, `.d_write`, etc.) are assigned for each. Note: are they the same or different functions? Quote the initializer lines you used. (Tip: examine lines around 280-291 and the subsequent entries for tap/vmnet.) +1. 在 `tuntap_drivers[]` 数组中,列出三个 `.d_name` 值,并确定每个值分配了哪些函数指针(`.d_open`、`.d_read`、`.d_write` 等)。注意:它们是相同的函数还是不同的函数?引用你使用的初始化行。(提示:检查第 280-291 行附近以及后续 tap/vmnet 的条目。) -2. In `tun_clone_create()`, find where the driver: +2. 在 `tun_clone_create()` 中,找到驱动程序执行以下操作的位置: - - computes the final name with unit, - - calls `clone_create()`, - - falls back to `tun_create_device()`, and - - calls `tuncreate()` to attach the ifnet. +- 计算包含单元号的最终名称, + - 调用 `clone_create()`, + - 回退到 `tun_create_device()`,以及 +- 调用 `tuncreate()` 以附加 ifnet。 - Quote those lines and explain the sequence. +引用这些行并解释顺序。 -3. In `tun_create_device()`, record the mode used for the `cdev` and which field points `si_drv1` to the softc. Quote the lines. (Hint: look for `mda_mode` and `mda_si_drv1`.) +3. 在 `tun_create_device()` 中,记录用于 `cdev` 的模式以及哪个字段将 `si_drv1` 指向 softc。引用这些行。(提示:查找 `mda_mode` 和 `mda_si_drv1`。) -##### B) Interface bring-up path +##### B) 接口启动路径 -1. In `tuncreate()`, point to the `if_alloc()`, `if_initname()`, and `if_attach()` calls. Why is `bpfattach()` called for L3 mode **with `DLT_NULL`** instead of `DLT_EN10MB`? Quote the lines you used. +1. 在 `tuncreate()` 中,指向 `if_alloc()`、`if_initname()` 和 `if_attach()` 的调用。为什么在 L3 模式下调用 `bpfattach()` 时使用 **`DLT_NULL`** 而不是 `DLT_EN10MB`?引用你使用的行。 -2. In `tunopen()`, identify where link state is marked UP on open. Quote the line(s). +2. 在 `tunopen()` 中,标识在打开时链路状态被标记为 UP 的位置。引用该行(或这些行)。 -3. In `tunopen()`, what prevents two processes from opening the same device simultaneously? Quote the check and explain the flags involved. (Hint: look for `TUN_OPEN` and `EBUSY`.) +3. 在 `tunopen()` 中,是什么阻止了两个进程同时打开同一个设备?请引用检查代码并解释涉及的标志。(提示:查找 `TUN_OPEN` 和 `EBUSY`。) -##### C) Read a packet from user space (kernel -> user) +##### C) 从用户空间读取数据包(内核 -> 用户) -1. In `tunread()`, explain the blocking and non-blocking behaviors. Which flag forces `EWOULDBLOCK`? Where is the sleep done? Quote the lines. +1. 在 `tunread()` 中,解释阻塞和非阻塞行为。哪个标志强制返回 `EWOULDBLOCK`?睡眠在哪里发生?请引用相关代码行。 -2. Where is the optional virtio header copied to user space, and how is the payload then delivered? Quote those lines. +2. 可选的 virtio 头部在哪里被复制到用户空间,载荷随后如何传递?请引用相关代码行。 -3. Where are readers woken when output arrives from the stack? Trace the wakeups in `tunstart_l2()` (or the L3 start path): `wakeup`, `selwakeuppri`, and `KNOTE`. Quote the lines. +3. 当来自协议栈的输出到达时,读取进程在哪里被唤醒?追踪 `tunstart_l2()`(或 L3 启动路径)中的唤醒机制:`wakeup`、`selwakeuppri` 和 `KNOTE`。请引用相关代码行。 -##### D) Write a packet from user space (user -> kernel) +##### D) 从用户空间写入数据包(用户 -> 内核) -1. In `tunwrite()`, find the guard that silently ignores writes if the interface is down, and the check that bounds the maximum write size (MRU + headers). Quote the lines. +1. 在 `tunwrite()` 中,找到当接口关闭时静默忽略写入的保护检查,以及限制最大写入大小(MRU + 头部)的检查。请引用相关代码行。 -2. Still in `tunwrite()`, where is the user buffer turned into an mbuf? Quote the call and explain the `align` parameter for L2. +2. 同样在 `tunwrite()` 中,用户缓冲区在哪里被转换为 mbuf?请引用调用并解释 L2 的 `align` 参数。 -3. Follow the L3 path into `tunwrite_l3()`: where is the address family read (when `TUN_IFHEAD` is set), where is BPF tapped, and where is the netisr dispatch called? Quote those lines. +3. 追踪 L3 路径进入 `tunwrite_l3()`:当设置了 `TUN_IFHEAD` 时,地址族在哪里被读取?BPF 在哪里被钩入?netisr 调度在哪里被调用?请引用相关代码行。 -4. Follow the L2 path into `tunwrite_l2()`: where does it drop frames whose destination MAC address doesn't match the interface's MAC (unless promiscuous mode is set)? This simulates what real Ethernet hardware wouldn't deliver. Quote those lines. +4. 追踪 L2 路径进入 `tunwrite_l2()`:在何处丢弃那些目的 MAC 地址与接口 MAC 不匹配的帧(除非设置了混杂模式)?这模拟了真实以太网硬件不会传递的行为。请引用相关代码行。 -##### E) Quick user-space validations (safe experiments) +##### E) 快速用户空间验证(安全实验) -These checks assume you created a `tun0` (L3) or `tap0` (L2) and brought it up in a private VM. +这些检查假设你已创建了 `tun0`(L3)或 `tap0`(L2)并在私有虚拟机中启动它。 ```bash # L3: read a packet the kernel queued for us @@ -9934,32 +9762,32 @@ These checks assume you created a `tun0` (L3) or `tap0` (L2) and brought it up i # (later in the book we'll show a tiny C sender using write()) ``` -For each command you run, point to the exact lines in `tunread()` or `tunwrite_l3()` that explain the behavior you observe. +对于你运行的每个命令,指出 `tunread()` 或 `tunwrite_l3()` 中解释你观察到的行为的确切代码行。 -#### Stretch (thought experiments) +#### 延伸(思想实验) -1. If `tunwrite()` returned `EIO` when the interface is down, instead of ignoring writes, how would tools that rely on blind writes behave? Point to the current "ignore if down" line and explain the design choice. +1. 如果 `tunwrite()` 在接口关闭时返回 `EIO` 而不是忽略写入,那么依赖盲目写入的工具会如何表现?请指向当前的"忽略关闭"行并解释设计选择。 -2. Suppose `tunstart_l2()` called `wakeup(tp)` but **not** `selwakeuppri(&tp->tun_rsel, ...)`. What would happen to an application using `poll(2)` to wait for packets? Would blocking `read(2)` still work? Point to both notification mechanisms and explain why each is necessary. +2. 假设 `tunstart_l2()` 调用了 `wakeup(tp)` 但**没有**调用 `selwakeuppri(&tp->tun_rsel, ...)`。那么使用 `poll(2)` 等待数据包的应用程序会发生什么?阻塞式 `read(2)` 还能工作吗?请指出两种通知机制并解释为什么各自都是必要的。 -#### Bridging to the next tour +#### 前往下一个导览的过渡 -The `if_tuntap` driver demonstrates how character devices and network interfaces integrate, with userspace acting as the "hardware" endpoint. Our next driver explores fundamentally different territory: **uart_bus_pci** shows how real hardware devices are discovered and bound to kernel drivers through FreeBSD's layered bus architecture. +`if_tuntap` 驱动程序演示了字符设备和网络接口如何集成,用户空间充当"硬件"端点。我们的下一个驱动程序探索了一个根本不同的领域:**uart_bus_pci** 展示了真实硬件设备如何通过 FreeBSD 的分层总线架构被发现并绑定到内核驱动程序。 -This shift from character device operations to bus attachment represents a critical architectural pattern: the separation between **bus-specific glue code** and **device-agnostic core functionality**. The uart_bus_pci driver is intentionally minimal, with under 300 lines of code, focusing solely on device identification (matching PCI vendor/device IDs), resource negotiation (claiming I/O ports and interrupts), and handoff to the generic UART subsystem via `uart_bus_probe()` and `uart_bus_attach()`. +从字符设备操作到总线挂载的转变代表了一个关键架构模式:**总线特定的粘合代码**与**设备无关的核心功能**之间的分离。uart_bus_pci 驱动程序故意保持最小,仅有不到 300 行代码,专注于设备识别(匹配 PCI 厂商/设备 ID)、资源协商(声明 I/O 端口和中断),以及通过 `uart_bus_probe()` 和 `uart_bus_attach()` 移交给通用 UART 子系统。 -### Tour 4 - The PCI glue: `uart(4)` +### 导览 4 - PCI 粘合层:`uart(4)` -Open the file: +打开文件: ```console % cd /usr/src/sys/dev/uart % less uart_bus_pci.c ``` -This file is the **PCI "bus glue"** for the generic UART core. It matches hardware via a PCI ID table, picks a UART **class**, calls the **shared uart bus probe/attach**, and adds a tiny bit of bus-specific logic (MSI preference, unique console matching). The actual UART register shuffling lives in the common UART code; this file is about **matching and wiring**. +该文件是通用 UART 核心的 **PCI "总线粘合层"**。它通过 PCI ID 表匹配硬件,选择 UART **类别**,调用**共享的 uart 总线 probe/attach**,并添加少量总线特定的逻辑(MSI 偏好、唯一控制台匹配)。实际的 UART 寄存器操作位于通用 UART 代码中;此文件关于**匹配和连接**。 -#### 1) Method table + driver object (what Newbus calls) +#### 1) 方法表 + 驱动对象(Newbus 调用的内容) ```c 52: static device_method_t uart_pci_methods[] = { @@ -9977,13 +9805,13 @@ This file is the **PCI "bus glue"** for the generic UART core. It matches hardwa 65: }; ``` -*Map this mentally to the Newbus lifecycle: `probe` -> `attach` -> `detach` (+ `resume`).* +*在脑海中将此映射到 Newbus 生命周期:`probe` -> `attach` -> `detach` (+ `resume`)。* -##### Device Methods and Driver Structure +##### 设备方法与驱动程序结构 -FreeBSD's device driver framework uses an object-oriented approach where drivers declare which operations they support through method tables. The `uart_pci_methods` array and `uart_pci_driver` structure establish this driver's interface to the kernel's device management subsystem. +FreeBSD的设备驱动程序框架采用面向对象的方式,驱动程序通过方法表声明其支持的操作。`uart_pci_methods` 数组和 `uart_pci_driver` 结构建立了该驱动程序与内核设备管理子系统的接口。 -##### The Device Method Table +##### 设备方法表 ```c static device_method_t uart_pci_methods[] = { @@ -9996,19 +9824,19 @@ static device_method_t uart_pci_methods[] = { }; ``` -The `device_method_t` array maps generic device operations to driver-specific implementations. Each `DEVMETHOD` entry binds a method identifier to a function pointer: +`device_method_t` 数组将通用设备操作映射到驱动程序特定的实现。每个 `DEVMETHOD` 条目将方法标识符绑定到一个函数指针: -**`device_probe`** -> `uart_pci_probe`: Called by the PCI bus driver during device enumeration to ask "can you drive this device?" The function examines the device's PCI vendor and device IDs, returning a priority value indicating how well it matches. Lower values mean better matches; returning `ENXIO` means "not my device." +**`device_probe`** -> `uart_pci_probe`:在设备枚举期间由PCI总线驱动程序调用,用于询问“你能驱动这个设备吗?”该函数检查设备的PCI供应商和设备ID,返回一个优先级值,表示匹配程度。值越低表示匹配越好;返回 `ENXIO` 表示“非我的设备”。 -**`device_attach`** -> `uart_pci_attach`: Called after a successful probe to initialize the device. This function allocates resources (I/O ports, interrupts), configures the hardware, and makes the device operational. If attachment fails, the driver should release any allocated resources. +**`device_attach`** -> `uart_pci_attach`:在成功探测后调用,用于初始化设备。该函数分配资源(I/O端口、中断),配置硬件并使设备可操作。如果挂载失败,驱动程序应释放所有已分配的资源。 -**`device_detach`** -> `uart_pci_detach`: Called when the device is being removed from the system (hot-unplug, driver unload, or system shutdown). Must release all resources claimed during attach and ensure the hardware is left in a safe state. +**`device_detach`** -> `uart_pci_detach`:当设备从系统中移除(热插拔、驱动程序卸载或系统关闭)时调用。必须释放挂载期间声明的所有资源,并确保硬件处于安全状态。 -**`device_resume`** -> `uart_bus_resume`: Called when the system resumes from a suspend state. Note this points to `uart_bus_resume`, not a PCI-specific function, the generic UART layer handles power management uniformly across all bus types. +**`device_resume`** -> `uart_bus_resume`:当系统从挂起状态恢复时调用。注意,这里指向的是 `uart_bus_resume`,而非PCI特定的函数;通用UART层统一处理所有总线类型的电源管理。 -**`DEVMETHOD_END`**: A sentinel marking the array's end. The kernel iterates this table until reaching this terminator. +**`DEVMETHOD_END`**:标记数组结束的哨兵。内核遍历此表直到遇到此终止符。 -##### The Driver Declaration +##### 驱动程序声明 ```c static driver_t uart_pci_driver = { @@ -10018,28 +9846,28 @@ static driver_t uart_pci_driver = { }; ``` -The `driver_t` structure packages the method table with metadata: +`driver_t` 结构将方法表与元数据打包在一起: -**`uart_driver_name`**: A string identifying this driver, typically "uart". This name appears in kernel messages, device tree output, and administrative tools. The name is defined in the generic uart code and shared across all bus attachments (PCI, ISA, ACPI), ensuring consistent device naming regardless of how the UART was discovered. +**`uart_driver_name`**:标识此驱动程序的字符串,通常为 "uart"。此名称出现在内核消息、设备树输出和管理工具中。该名称在通用UART代码中定义,并在所有总线挂载(PCI、ISA、ACPI)间共享,确保无论UART如何被发现,设备命名都保持一致。 -**`uart_pci_methods`**: Pointer to the method table defined above. When the kernel needs to perform an operation on a uart_pci device, it looks up the appropriate method in this table and calls the corresponding function. +**`uart_pci_methods`**:指向上面定义的方法表的指针。当内核需要对 `uart_pci` 设备执行操作时,它会在该表中查找相应的方法并调用对应的函数。 -**`sizeof(struct uart_softc)`**: The size of the driver's per-device state structure. The kernel allocates this much memory when creating a device instance, accessible via `device_get_softc()`. Importantly, this uses `uart_softc` from the generic UART layer, not a PCI-specific structure, the core UART state is bus-agnostic. +**`sizeof(struct uart_softc)`**:驱动程序每设备状态结构的大小。创建设备实例时,内核分配此大小的内存,可通过 `device_get_softc()` 访问。重要的是,这里使用的是通用UART层的 `uart_softc`,而非PCI特定的结构;核心UART状态与总线无关。 -##### Architectural Significance +##### 架构意义 -This simple structure embodies FreeBSD's layered driver model. The method table contains four functions: +这个简单的结构体现了FreeBSD的分层驱动程序模型。方法表包含四个功能: -- Two are PCI-specific (`uart_pci_probe`, `uart_pci_attach`, `uart_pci_detach`) -- One is bus-agnostic (`uart_bus_resume`) +- 两个是PCI特定的(`uart_pci_probe`、`uart_pci_attach`、`uart_pci_detach`) +- 一个与总线无关(`uart_bus_resume`) -The PCI-specific functions handle only bus-related concerns: matching device IDs, claiming PCI resources, and managing MSI interrupts. All UART-specific logic, baud rate configuration, FIFO management, character I/O, lives in the generic `uart_bus.c` code that these functions call. +PCI特定的功能仅处理与总线相关的事务:匹配设备ID、声明PCI资源和管理MSI中断。所有UART特定的逻辑(波特率配置、FIFO管理、字符I/O)都位于这些函数调用的通用 `uart_bus.c` 代码中。 -This separation means the same UART hardware logic works whether the device appears on the PCI bus, the ISA bus, or as an ACPI-enumerated device. Only the probe/attach glue changes. This pattern, thin bus-specific wrappers around substantial generic cores, reduces code duplication and simplifies porting to new bus types or architectures. +这种分离意味着无论设备出现在PCI总线、ISA总线还是作为ACPI枚举的设备,相同的UART硬件逻辑都能工作。只有探测/挂载的胶水代码会变化。这种模式(在通用核心外层包裹薄薄的总线特定封装)减少了代码重复,并简化了移植到新型总线或架构的过程。 -The method table mechanism also enables runtime polymorphism. If a UART appears on different buses (a 16550 on both PCI and ISA, for example), the kernel loads different driver modules (`uart_pci`, `uart_isa`), each with its own method table, but both share the underlying `uart_softc` structure and call the same generic functions for actual device operation. +方法表机制还实现了运行时多态性。如果UART出现在不同的总线上(例如,一个16550同时存在于PCI和ISA),内核会加载不同的驱动程序模块(`uart_pci`、`uart_isa`),每个模块都有自己的方法表,但共享底层的 `uart_softc` 结构,并调用相同的通用函数进行实际的设备操作。 -#### 2) Local structs + flags we'll use +#### 2) 我们将使用的本地结构体和标志 ```c 67: struct pci_id { @@ -10060,13 +9888,13 @@ The method table mechanism also enables runtime polymorphism. If a UART appears 84: #define PCI_RID_MASK 0x0000ffff ``` -*What matters later:* `rid` (which BAR/IRQ to use), optional `rclk` and `regshft`, and the `PCI_NO_MSI` hint. +*后续关注点:* `rid`(要使用的BAR/IRQ)、可选的 `rclk` 和 `regshft`,以及 `PCI_NO_MSI` 提示。 -##### Device Identification Structures +##### 设备标识结构 -Hardware drivers must identify which specific devices they can manage. For PCI devices, this identification relies on vendor and device ID codes burned into the hardware's configuration space. The `pci_id` and `pci_unique_id` structures encode this matching logic along with device-specific configuration parameters. +硬件驱动程序必须识别它们可以管理的特定设备。对于PCI设备,此识别依赖于硬件配置空间中固化写入的供应商和设备ID代码。`pci_id` 和 `pci_unique_id` 结构将这种匹配逻辑与设备特定的配置参数一起编码。 -##### The Primary Identification Structure +##### 主要标识结构 ```c struct pci_id { @@ -10081,27 +9909,27 @@ struct pci_id { }; ``` -Each `pci_id` entry describes one UART variant and how to configure it: +每个 `pci_id` 条目描述一种 UART 变体及其配置方式: -**`vendor` and `device`**: The primary identification pair. Every PCI device has a 16-bit vendor ID (assigned by the PCI Special Interest Group) and a 16-bit device ID (assigned by the vendor). For example, Intel is vendor `0x8086`, and their AMT Serial-over-LAN controller is device `0x108f`. These IDs are read from the device's configuration space at bus enumeration time. +**`vendor` 和 `device`**:主要标识对。每个 PCI 设备都有一个 16 位的厂商 ID(由 PCI 特别兴趣小组分配)和一个 16 位的设备 ID(由厂商分配)。例如,Intel 的厂商 ID 是 `0x8086`,其 AMT Serial-over-LAN 控制器的设备 ID 是 `0x108f`。这些 ID 在总线枚举时从设备的配置空间读取。 -**`subven` and `subdev`**: Secondary identification for OEM customization. Many manufacturers build cards using reference designs from chipset vendors, then assign their own subsystem vendor and device IDs. A value of `0xffff` in these fields acts as a wildcard, meaning "match any subsystem IDs." This allows matching either specific OEM variants or entire chipset families. +**`subven` 和 `subdev`**:OEM 定制化的次要标识。许多制造商使用芯片组厂商的参考设计制造板卡,然后分配自己的子系统厂商和设备 ID。这些字段中的 `0xffff` 值充当通配符,表示“匹配任何子系统 ID”。这允许匹配特定的 OEM 变体或整个芯片组系列。 -The four-level matching hierarchy enables precise identification: +四级匹配层次结构实现了精确标识: -1. Match only specific OEM cards: all four IDs must match exactly -2. Match all cards using a chipset: `vendor`/`device` match, `subven`/`subdev` are `0xffff` -3. Match specific OEM customization: `vendor`/`device` plus exact `subven`/`subdev` +1. 仅匹配特定的 OEM 卡:所有四个 ID 必须完全匹配 +2. 匹配使用某芯片组的所有卡:`vendor`/`device` 匹配,`subven`/`subdev` 为 `0xffff` +3. 匹配特定的 OEM 定制:`vendor`/`device` 加上确切的 `subven`/`subdev` -**`desc`**: Human-readable device description displayed in boot messages and `dmesg` output. Examples: "Intel AMT - SOL" or "Oxford Semiconductor OXCB950 Cardbus 16950 UART". This string helps administrators identify which physical device corresponds to which `/dev/cuaU*` entry. +**`desc`**:人类可读的设备描述,显示在启动信息和 `dmesg` 输出中。例如:"Intel AMT - SOL" 或 "Oxford Semiconductor OXCB950 Cardbus 16950 UART"。该字符串帮助管理员识别哪个物理设备对应哪个 `/dev/cuaU*` 条目。 -**`rid`**: Resource ID specifying which PCI Base Address Register (BAR) contains the UART's registers. PCI devices can have up to six BARs (numbered 0x10, 0x14, 0x18, 0x1c, 0x20, 0x24). Most UARTs use BAR 0 (`0x10`), but some multi-function cards place the UART at alternate BARs. This field may also encode flags via the high bits. +**`rid`**:资源 ID,指定哪个 PCI 基地址寄存器(BAR)包含 UART 的寄存器。PCI 设备最多可有六个 BAR(编号为 0x10、0x14、0x18、0x1c、0x20、0x24)。大多数 UART 使用 BAR 0(`0x10`),但一些多功能卡将 UART 放在其他 BAR 上。该字段可能还通过高位编码标志。 -**`rclk`**: Reference clock frequency in Hz. The UART's baud rate generator divides this clock to produce serial bit timing. Standard PC UARTs use 1843200 Hz (1.8432 MHz), but embedded UARTs and specialized cards often use different frequencies. Some Intel devices use 24x the standard clock for high-speed operation. An incorrect `rclk` causes garbled serial communication due to baud rate mismatch. +**`rclk`**:参考时钟频率,单位为 Hz。UART 的波特率发生器分频此时钟以产生串行位时序。标准 PC UART 使用 1843200 Hz(1.8432 MHz),但嵌入式 UART 和专用卡常使用不同频率。某些 Intel 设备使用标准时钟的 24 倍以实现高速操作。错误的 `rclk` 会因波特率不匹配导致串行通信乱码。 -**`regshft`**: Register address shift value. Most UARTs place consecutive registers at consecutive byte addresses (shift = 0), but some embed the UART in larger register spaces with registers at every 4th byte (shift = 2) or other intervals. The driver shifts register offsets by this amount when accessing hardware. This accommodates SoC designs where the UART shares address space with other peripherals. +**`regshft`**:寄存器地址位移值。大多数 UART 将连续寄存器放在连续的字节地址上(位移=0),但有些将 UART 嵌入更大的寄存器空间,寄存器每隔 4 个字节(位移=2)或其他间隔放置。驱动程序在访问硬件时按此量移位寄存器偏移。这适应了 UART 与其他外设共享地址空间的 SoC 设计。 -##### The Simplified Identification Structure +##### 简化标识结构 ```c struct pci_unique_id { @@ -10110,34 +9938,34 @@ struct pci_unique_id { }; ``` -This smaller structure identifies devices guaranteed to exist only once per system. Certain hardware, particularly server management controllers and embedded SoC UARTs, is designed as singleton devices. For these, vendor and device IDs alone suffice for matching against system consoles, without needing subsystem IDs or configuration parameters. +这个较小的结构标识保证每个系统只存在一次的设备。某些硬件,特别是服务器管理控制器和嵌入式 SoC UART,被设计为单实例设备。对于这些设备,仅靠厂商和设备 ID 就足以匹配系统控制台,无需子系统 ID 或配置参数。 -The distinction matters for console matching: if a UART serves as the system console (configured in firmware or boot loader), the kernel must identify which enumerated device corresponds to the pre-configured console. For unique devices, a simple vendor/device match provides certainty. +这种区别对控制台匹配很重要:如果 UART 作为系统控制台(在固件或引导加载程序中配置),内核必须识别哪个枚举设备对应于预配置的控制台。对于唯一设备,简单的厂商/设备匹配提供了确定性。 -##### Resource ID Encoding +##### 资源 ID 编码 ```c #define PCI_NO_MSI 0x40000000 #define PCI_RID_MASK 0x0000ffff ``` -The `rid` field serves double duty through bit packing: +`rid` 字段通过位打包承担双重职责: -**`PCI_RID_MASK` (0x0000ffff)**: The lower 16 bits contain the actual BAR number (0x10, 0x14, etc.). Masking with this value extracts the resource ID for bus allocation functions. +**`PCI_RID_MASK`(0x0000ffff)**:低 16 位包含实际的 BAR 编号(0x10、0x14 等)。与此值掩码可提取用于总线分配函数的资源 ID。 -**`PCI_NO_MSI` (0x40000000)**: The high bit flags devices with broken or unreliable Message Signaled Interrupt (MSI) support. Some UART implementations don't correctly implement MSI, causing interrupt delivery failures or system hangs. This flag tells the attach function to use traditional line-based interrupts instead of attempting MSI allocation. +**`PCI_NO_MSI`(0x40000000)**:高位标记支持损坏或不可靠的消息信号中断(MSI)的设备。某些 UART 实现未正确实现 MSI,导致中断传递失败或系统挂起。此标志通知附加函数使用传统的基于线路的中断,而不是尝试 MSI 分配。 -This encoding scheme avoids enlarging the `pci_id` structure with an additional boolean field. Since BAR numbers only use the low byte, the high bits are available for flags. The driver extracts the actual RID with `id->rid & PCI_RID_MASK` and checks MSI capability with `(id->rid & PCI_NO_MSI) == 0`. +这种编码方案避免了用额外的布尔字段扩大 `pci_id` 结构。由于 BAR 编号只使用低字节,高位可用于标志。驱动程序通过 `id->rid & PCI_RID_MASK` 提取实际 RID,并通过 `(id->rid & PCI_NO_MSI) == 0` 检查 MSI 能力。 -##### Purpose in Device Matching +##### 在设备匹配中的目的 -These structures populate a large static array (examined in the next fragment) that the probe function searches during device enumeration. When the PCI bus driver discovers a device with class "Simple Communications" (modems and UARTs), it calls this driver's probe function. The probe function walks the array comparing the device's IDs against each entry, looking for a match. Upon finding one, it uses the associated `desc`, `rid`, `rclk`, and `regshft` values to configure the device correctly. +这些结构填充了一个大型静态数组(在下一片段中查看),探测函数在设备枚举期间搜索该数组。当 PCI 总线驱动程序发现类别为 "Simple Communications"(调制解调器和 UART)的设备时,它会调用此驱动程序的探测函数。探测函数遍历该数组,将设备的 ID 与每个条目进行比较,寻找匹配项。找到后,它使用关联的 `desc`、`rid`、`rclk` 和 `regshft` 值来正确配置设备。 -This table-driven approach simplifies adding new hardware support: most new UART variants require only adding a table entry with the correct IDs and clock frequency, without modifying code. +这种表驱动方法简化了添加新硬件支持:大多数新 UART 变体只需添加一个包含正确 ID 和时钟频率的表条目,无需修改代码。 -#### 3) The PCI **ID table** (ns8250-ish parts) +#### 3) PCI **ID 表**(ns8250 系列部件) -Below is the **contiguous** table used to match vendor/device(/subvendor/subdevice), plus per-device hints (RID, reference clock, register shift). The `0xffff` row terminates the list. +下面是用于匹配供应商/设备(/子供应商/子设备)的**连续**表,以及每个设备提示(RID、参考时钟、寄存器移位)。`0xffff`行终止该列表。 ```c 86: static const struct pci_id pci_ns8250_ids[] = { @@ -10272,92 +10100,92 @@ Below is the **contiguous** table used to match vendor/device(/subvendor/subdevi 215: }; ``` -*Notice per-device **RID** (which BAR/IRQ), frequency hints (`rclk` like `24 \* DEFAULT_RCLK`), and optional `regshft`.* +*注意每个设备的 **RID**(哪个BAR/IRQ)、频率提示(如`24 \* DEFAULT_RCLK`的`rclk`)和可选的`regshft`。* -##### The Device Identification Table +##### 设备识别表 -The `pci_ns8250_ids` array is the heart of the driver's device recognition logic. This table lists every known PCI UART variant compatible with the NS8250/16550 register interface, along with the configuration parameters needed to operate each correctly. During system boot, the PCI bus driver walks all discovered devices and calls this driver's probe function for potential matches; the probe function searches this table to determine compatibility. +`pci_ns8250_ids`数组是驱动程序设备识别逻辑的核心。该表列出了所有已知的、与NS8250/16550寄存器接口兼容的PCI UART变体,以及正确操作每个变体所需的配置参数。在系统启动期间,PCI总线驱动程序遍历所有发现的设备,并调用此驱动程序的探测函数进行潜在匹配;探测函数搜索此表以确定兼容性。 -##### Table Structure and Purpose +##### 表结构与目的 ```c static const struct pci_id pci_ns8250_ids[] = { ``` -The array name, `pci_ns8250_ids`, reflects that all listed devices implement the National Semiconductor 8250 (or compatible 16450/16550/16650/16750/16850/16950) register interface. Despite coming from dozens of manufacturers, these UARTs share a common programming model dating back to the original IBM PC's serial port design. This compatibility allows a single driver to support disparate hardware through a unified register abstraction. +数组名称`pci_ns8250_ids`反映了所有列出的设备都实现了National Semiconductor 8250(或兼容的16450/16550/16650/16750/16850/16950)寄存器接口。尽管来自数十家制造商,这些UART共享一个通用的编程模型,其起源可追溯到原始IBM PC的串口设计。这种兼容性允许单个驱动程序通过统一的寄存器抽象支持不同的硬件。 -The `static const` qualifiers indicate this data is read-only and internal to this compilation unit. The table resides in read-only memory, preventing accidental modification and allowing the kernel to share one copy across all CPU cores. +`static const`限定符表明该数据是只读的,并且仅在此编译单元内部使用。该表驻留在只读内存中,防止意外修改,并允许内核在所有CPU核心之间共享一个副本。 -##### Entry Analysis: Understanding the Patterns +##### 条目分析:理解模式 -Examining representative entries reveals the matching hierarchy and configuration diversity: +检查代表性条目揭示了匹配层次结构和配置多样性: -**Simple wildcard match** (Intel AMT SOL entry in `pci_ns8250_ids`): +**简单通配符匹配**(`pci_ns8250_ids` 中的 Intel AMT SOL 条目): ```c { 0x8086, 0x108f, 0xffff, 0, "Intel AMT - SOL", 0x10 }, ``` -- Vendor 0x8086 (Intel), device 0x108f (AMT Serial-over-LAN) -- Subsystem IDs 0xffff (wildcard) match all OEM variants -- Description for boot messages and device listings -- RID 0x10 (BAR0), standard clock rate (implied DEFAULT_RCLK), no register shift +- 供应商0x8086(Intel),设备0x108f(AMT Serial-over-LAN) +- 子系统 ID 0xffff(通配符)匹配所有 OEM 变体 +- 用于启动消息和设备列表的描述 +- RID 0x10(BAR0),标准时钟频率(隐含 DEFAULT_RCLK),无寄存器偏移 -This pattern matches Intel's AMT SOL controller regardless of which motherboard manufacturer integrated it. +此模式匹配Intel的AMT SOL控制器,无论哪个主板制造商集成了它。 -**OEM-specific match** (adjacent HP Diva entries in `pci_ns8250_ids`): +**OEM 特定匹配**(`pci_ns8250_ids` 中相邻的 HP Diva 条目): ```c { 0x103c, 0x1048, 0x103c, 0x1227, "HP Diva Serial [GSP] UART - Powerbar SP2", 0x10 }, { 0x103c, 0x1048, 0x103c, 0x1301, "HP Diva RMP3", 0x14 }, ``` -- Same chipset (HP vendor 0x103c, device 0x1048) used in multiple products -- Different subsystem device IDs (0x1227, 0x1301) distinguish variants -- Different BARs (0x10 vs 0x14) indicate the UART appears at different addresses in each card's configuration space +- 相同的芯片组(HP 厂商 0x103c,设备 0x1048)用于多个产品 +- 不同的子系统设备 ID(0x1227, 0x1301)区分变体 +- 不同的BAR(0x10 vs 0x14)表明UART在每个卡的配置空间中出现不同的地址 -This illustrates how one chipset spawns multiple table entries when OEMs configure it differently across product lines. +这说明了当OEM在不同产品线上以不同方式配置同一芯片组时,如何产生多个表条目。 -**Non-standard clock frequency** (Dell Remote Access Card III entry in `pci_ns8250_ids`): +**非标准时钟频率**(`pci_ns8250_ids` 中的 Dell Remote Access Card III 条目): ```c { 0x1028, 0x0008, 0xffff, 0, "Dell Remote Access Card III", 0x14, 128 * DEFAULT_RCLK }, ``` -- Dell (0x1028) RAC III uses 128x the standard 1.8432 MHz clock = 235.9296 MHz -- This extremely high frequency supports baud rates far beyond standard serial ports -- Without the correct `rclk` value, all baud rate calculations would be wrong by 128x, producing gibberish +- Dell(0x1028)RAC III使用128倍标准1.8432 MHz时钟= 235.9296 MHz +- 这种极高的频率支持远超标准串口的波特率 +- 如果没有正确的`rclk`值,所有波特率计算都会错误128倍,产生乱码 -Server management cards often use high clocks to support fast console redirection over network links. +服务器管理卡通常使用高时钟来支持通过网络链路进行快速控制台重定向。 -**Register address shifting** (Intel ValleyView LPIO1 HSUART entry in `pci_ns8250_ids`): +**寄存器地址移位**(`pci_ns8250_ids` 中的 Intel ValleyView LPIO1 HSUART 条目): ```c { 0x8086, 0x0f0a, 0xffff, 0, "Intel ValleyView LPIO1 HSUART#1", 0x10, 24 * DEFAULT_RCLK, 2 }, ``` -- Intel SoC UART with 24x standard clock for high-speed operation -- `regshft = 2` means registers appear at 4-byte intervals (addresses 0, 4, 8, 12, ...) -- The generic UART code shifts all register offsets left by 2 bits: `address << 2` +- Intel SoC UART使用24倍标准时钟以实现高速操作 +- `regshft = 2` 表示寄存器以 4 字节间隔出现(地址 0, 4, 8, 12, ...) +- 通用UART代码将所有寄存器偏移左移2位:`address << 2` -This accommodates SoC designs where the UART shares a large memory-mapped region with other peripherals, often with registers aligned to 32-bit boundaries for bus efficiency. +这适应了SoC设计,其中UART与其他外设共享一个大型内存映射区域,通常寄存器对齐到32位边界以提高总线效率。 -**MSI incompatibility** (Atom Processor S1200 entry in `pci_ns8250_ids`, combined with the `PCI_NO_MSI` handling in `uart_pci_attach`): +**MSI不兼容性**(`pci_ns8250_ids`中的Atom Processor S1200条目,结合`uart_pci_attach`中的`PCI_NO_MSI`处理): ```c { 0x8086, 0x0c5f, 0xffff, 0, "Atom Processor S1200 UART", 0x10 | PCI_NO_MSI }, ``` -- The `PCI_NO_MSI` flag in the RID field indicates broken MSI support -- The attach function will detect this flag and use legacy line-based interrupts instead -- These devices claim MSI capability in their PCI configuration space but don't deliver interrupts correctly +- RID字段中的`PCI_NO_MSI`标志表示MSI支持异常 +- attach函数将检测此标志并使用传统基于行的中断 +- 这些设备在其PCI配置空间中声明MSI能力,但无法正确传递中断 -Such quirks typically arise from silicon errata or incomplete MSI implementation in integrated peripherals. +此类异常通常源于硅片勘误或集成外设中MSI实现不完整。 -**Multiple subsystem variants** (Timedia Technology entries in `pci_ns8250_ids`): +**多子系统变体**(`pci_ns8250_ids` 中的 Timedia Technology 条目): ```c { 0x1409, 0x7168, 0x1409, 0x4025, "Timedia Technology Serial Port", 0x10, @@ -10366,39 +10194,39 @@ Such quirks typically arise from silicon errata or incomplete MSI implementation 8 * DEFAULT_RCLK }, ``` -- Same base chipset (vendor 0x1409, device 0x7168) used across a product family -- Each subsystem device ID represents a different card model or port count variant -- All share the same clock (8x standard) and BAR configuration -- The probe function matches the first entry with compatible subsystem IDs +- 相同的基础芯片组(厂商 0x1409,设备 0x7168)用于整个产品系列 +- 每个子系统设备ID对应不同的卡型号或端口数量变体 +- 所有设备共享相同的时钟(8倍标准时钟)和BAR配置 +- probe函数匹配第一个兼容子系统ID的条目 -This repetition is unavoidable when a manufacturer uses one chipset across many SKUs, each with unique subsystem identification. +当一家制造商在多个SKU中使用同一芯片组,且每个SKU具有独特的子系统标识时,这种重复是不可避免的。 -##### The Sentinel Entry +##### 哨兵条目 ```c { 0xffff, 0, 0xffff, 0, NULL, 0, 0} ``` -The final entry marks the table's end. The matching function walks entries until finding `vendor == 0xffff`, indicating no more devices to check. Using 0xffff (an invalid vendor ID; no such vendor exists) ensures the sentinel can't accidentally match real hardware. +最后一个条目标记了表的结束。匹配函数会遍历条目,直到找到`vendor == 0xffff`,这表示没有更多设备需要检查。使用0xffff(一个无效的厂商ID;不存在这样的厂商)确保哨兵不会意外匹配到真实的硬件。 -##### Table Maintenance and Evolution +##### 表维护与演进 -This table grows continuously as new UART hardware appears. Adding support for a new device typically requires: +随着新的UART硬件的出现,这张表会不断增长。添加对新设备的支持通常需要: -1. Determining the vendor/device/subsystem IDs (via `pciconf -lv` on FreeBSD) -2. Finding the correct BAR where the UART registers reside (often documented, sometimes discovered via trial) -3. Identifying the clock frequency (from datasheets or experimentation) -4. Testing that standard NS8250 register access works +1. 确定厂商/设备/子系统ID(在FreeBSD上通过`pciconf -lv`命令获取) +2. 找到UART寄存器所在的正确BAR(通常有文档说明,有时通过试错发现) +3. 识别时钟频率(来自数据手册或实验) +4. 测试标准的NS8250寄存器访问是否正常 -Most entries use default values (standard clock, no shift, BAR0), requiring only IDs and a description. Complex entries like those with unusual clocks or MSI quirks often emerge from bug reports or hardware donations to developers. +大多数条目使用默认值(标准时钟、无移位、BAR0),只需要ID和描述。复杂的条目(如具有不寻常时钟或MSI特殊处理的条目)通常来自bug报告或开发者收到的硬件捐赠。 -The table-driven approach keeps the code maintainable: adding a new UART rarely requires code changes, just a new table entry. This is critical for a subsystem supporting dozens of manufacturers and hundreds of product variants accumulated over decades of PC hardware evolution. +这种表驱动方法使代码易于维护:添加新的UART通常不需要修改代码,只需添加一个新表条目。这对于一个支持数十家制造商和数百个产品变体的子系统至关重要,这些变体是数十年PC硬件演变的积累。 -##### Architectural Note +##### 架构说明 -This table documents only NS8250-compatible UARTs. Non-compatible serial controllers (like USB serial adapters, IEEE 1394 serial, or proprietary designs) use different drivers. The probe function verifies NS8250 compatibility before accepting a device, ensuring this table's assumptions hold for all matched hardware. +此表仅记录与NS8250兼容的UART。不兼容的串行控制器(如USB串行适配器、IEEE 1394串行或专有设计)使用不同的驱动程序。probe函数在接受设备之前会验证NS8250兼容性,确保此表的假设对所有匹配的硬件都成立。 -#### 4) Matching function: from PCI IDs to a hit +#### 4) 匹配函数:从PCI ID到命中 ```c 218: const static struct pci_id * @@ -10423,13 +10251,13 @@ This table documents only NS8250-compatible UARTs. Non-compatible serial control 237: return ((id->vendor == vendor && id->device == device) ? id : NULL); ``` -*First match vendor/device; if the entry has specific sub-IDs, check those too; otherwise accept the wildcard.* +*首先匹配厂商/设备;如果条目有特定的子ID,则也检查这些子ID;否则接受通配符。* -##### Device Matching Logic: `uart_pci_match` +##### 设备匹配逻辑:`uart_pci_match` -The `uart_pci_match` function implements a two-phase search algorithm that efficiently matches PCI devices against the identification table while respecting the vendor/device/subsystem hierarchy. This function is the core of device recognition, called during probe to determine if a discovered PCI device is a supported UART. +`uart_pci_match`函数实现了一种两阶段搜索算法,该算法能高效地将PCI设备与识别表进行匹配,同时遵循厂商/设备/子系统的层次结构。该函数是设备识别的核心,在probe期间被调用,用于判断发现的PCI设备是否为受支持的UART。 -##### Function Signature and Context +##### 函数签名与上下文 ```c const static struct pci_id * @@ -10438,11 +10266,11 @@ uart_pci_match(device_t dev, const struct pci_id *id) uint16_t device, subdev, subven, vendor; ``` -The function accepts a `device_t` representing the PCI device being probed and a pointer to the start of the identification table. It returns either a pointer to the matching `pci_id` entry (containing configuration parameters) or NULL if no match exists. +该函数接受一个`device_t`参数(表示正在被probe的PCI设备)和一个指向识别表起始位置的指针。它返回一个指向匹配的`pci_id`条目(包含配置参数)的指针,如果没有匹配则返回NULL。 -The return type is `const struct pci_id *` because the function returns a pointer into the read-only table, the caller must not modify the returned entry. +返回类型是`const struct pci_id *`,因为该函数返回一个指向只读表的指针,调用者不得修改返回的条目。 -##### Phase One: Primary ID Matching +##### 阶段一:主 ID 匹配 ```c vendor = pci_get_vendor(dev); @@ -10454,33 +10282,33 @@ if (id->vendor == 0xffff) return (NULL); ``` -The function begins by reading the device's primary identification from PCI configuration space. The `pci_get_vendor()` and `pci_get_device()` functions access configuration space registers 0x00 and 0x02, which every PCI device must implement. +函数首先从PCI配置空间中读取设备的主要标识。`pci_get_vendor()`和`pci_get_device()`函数访问配置空间寄存器0x00和0x02,这是每个PCI设备必须实现的。 -**The search loop**: The `while` condition has two termination criteria: +**搜索循环**:`while`条件有两个终止条件: -1. `id->vendor != 0xffff` - haven't reached the sentinel entry -2. `(id->vendor != vendor || id->device != device)` - current entry doesn't match +1. `id->vendor != 0xffff` —— 尚未到达哨兵条目 +2. `(id->vendor != vendor || id->device != device)` - 当前条目不匹配 -The loop advances through the table until finding either a matching vendor/device pair or the sentinel. This linear search is acceptable because: +循环在表中前进,直到找到匹配的厂商/设备对或哨兵。这种线性搜索是可接受的,因为: -- The table has fewer than 100 entries (fast even with linear search) -- Probe happens once per device at boot (not performance-critical) -- The table is in cache-friendly sequential memory +- 表中的条目少于100个(即使线性搜索也很快) +- 探测在启动时每设备发生一次(非性能关键) +- 表位于缓存友好的顺序内存中 -**Sentinel detection**: If the loop exits with `id->vendor == 0xffff`, no entry matched the device's primary IDs. Returning NULL signals "not my device" to the probe function, which will return `ENXIO` to allow other drivers a chance. +**哨兵检测**:如果循环以 `id->vendor == 0xffff` 退出,则没有条目匹配设备的主ID。返回 NULL 向探测函数表示“不是我的设备”,探测函数将返回 `ENXIO`,从而允许其他驱动程序有机会。 -##### Wildcard Subsystem Handling +##### 通配符子系统处理 ```c if (id->subven == 0xffff) return (id); ``` -This is the fast-path exit for entries with wildcard subsystem IDs. When `subven == 0xffff`, the entry matches all variants of this chipset regardless of OEM customization. The function returns immediately without reading subsystem IDs from configuration space. +这是具有通配符子系统ID的条目的快速路径退出。当 `subven == 0xffff` 时,该条目匹配此芯片组的所有变体,无论OEM自定义如何。函数立即返回,无需从配置空间读取子系统ID。 -This optimization avoids unnecessary PCI configuration reads for the common case where the driver accepts all OEM variants of a chipset (e.g., "Intel AMT - SOL" matches Intel's chipset in any motherboard). +此优化避免了在驱动程序接受芯片组的所有OEM变体(例如,“Intel AMT - SOL” 匹配任何主板中的Intel芯片组)的常见情况下不必要的PCI配置读取。 -##### Phase Two: Subsystem ID Matching +##### 阶段二:子系统 ID 匹配 ```c subven = pci_get_subvendor(dev); @@ -10490,14 +10318,14 @@ while (id->vendor == vendor && id->device == device && id++; ``` -For entries requiring specific subsystem matches, the function reads the subsystem vendor and device IDs from PCI configuration space registers 0x2C and 0x2E. +对于需要特定子系统匹配的条目,函数从PCI配置空间寄存器0x2C和0x2E读取子系统供应商和设备ID。 -**The refinement loop**: This second search advances through consecutive table entries with the same primary IDs, looking for a subsystem match. The loop continues while: +**精炼循环**:此第二次搜索前进到具有相同主ID的连续表条目中,寻找子系统匹配。循环在以下条件下继续: -1. `id->vendor == vendor && id->device == device` - still examining entries for this chipset -2. `(id->subven != subven || id->subdev != subdev)` - subsystem IDs don't match +1. `id->vendor == vendor && id->device == device` —— 仍在该芯片组的条目中检查 +2. `(id->subven != subven || id->subdev != subdev)` - 子系统 ID 不匹配 -This handles tables with multiple entries for one chipset, each specifying different OEM variants: +这处理了一个芯片组有多个条目,每个指定不同OEM变体的表: c @@ -10506,73 +10334,73 @@ c { 0x103c, 0x1048, 0x103c, 0x1301, "HP Diva RMP3", 0x14 }, ``` -Both entries have vendor 0x103c and device 0x1048, but different subsystem device IDs. The loop examines each until finding the correct variant. +两个条目的供应商都是0x103c,设备都是0x1048,但子系统设备ID不同。循环检查每个条目,直到找到正确的变体。 -##### Final Validation +##### 最终验证 ```c return ((id->vendor == vendor && id->device == device) ? id : NULL); ``` -After the refinement loop exits, one of two conditions holds: +精炼循环退出后,满足以下两个条件之一: -1. The loop found a matching entry (all four IDs match) -> return it -2. The loop exhausted entries for this chipset without matching subsystems -> return NULL +1. 循环找到一个匹配的条目(所有四个ID都匹配)→ 返回该条目 +2. 循环用完了此芯片组的条目但没有匹配的子系统 → 返回NULL -The ternary expression performs a final sanity check: even though the loop condition guarantees `id` points to an entry with matching primary IDs (or past the last such entry), explicitly verifying ensures correct behavior if the loop walked past all entries for this device without finding a subsystem match. +三元表达式执行最终的健全性检查:即使循环条件保证 `id` 指向一个具有匹配主ID的条目(或超过最后一个这样的条目),显式验证可确保如果循环遍历完此设备的所有条目而未找到子系统匹配时行为正确。 -This covers the case where: +这覆盖了以下情况: -- Primary IDs match (phase one succeeded) -- Table has entries with specific subsystem requirements -- None of those subsystem entries match the device -- The loop advanced until finding a different primary ID or the sentinel +- 主 ID 匹配(阶段一成功) +- 表中有指定子系统要求的条目 +- 这些子系统条目中没有匹配设备的 +- 循环前进直到找到一个不同的主ID或哨兵 -##### Matching Examples +##### 匹配示例 -**Example 1: Simple wildcard match** +**示例 1:简单通配符匹配** -- Device: Intel AMT SOL (vendor 0x8086, device 0x108f) -- Phase one: finds `{ 0x8086, 0x108f, 0xffff, 0, ... }` -- Wildcard check: `subven == 0xffff`, return immediately -- Result: match without reading subsystem IDs +- 设备:Intel AMT SOL(厂商 0x8086,设备 0x108f) +- 阶段一:找到 `{ 0x8086, 0x108f, 0xffff, 0, ... }` +- 通配符检查:`subven == 0xffff`,立即返回 +- 结果:匹配而不读取子系统ID -**Example 2: OEM-specific match** +**示例 2:OEM 特定匹配** -- Device: HP Diva RMP3 (vendor 0x103c, device 0x1048, subven 0x103c, subdev 0x1301) -- Phase one: finds first entry with vendor 0x103c, device 0x1048 -- Wildcard check: `subven != 0xffff`, read subsystem IDs -- Phase two: first entry has subdev 0x1227 (no match), advance -- Phase two: second entry has subdev 0x1301 (match!), return -- Result: returns second entry with BAR 0x14 and correct description +- 设备:HP Diva RMP3(厂商 0x103c,设备 0x1048,subven 0x103c,subdev 0x1301) +- 阶段一:找到供应商0x103c、设备0x1048的第一个条目 +- 通配符检查:`subven != 0xffff`,读取子系统 ID +- 阶段二:第一个条目的 subdev 为 0x1227(不匹配),前进 +- 阶段二:第二个条目的 subdev 为 0x1301(匹配!),返回 +- 结果:返回第二个条目,BAR 0x14 和正确的描述 -**Example 3: No match** +**示例 3:无匹配** -- Device: Unknown UART (vendor 0x1234, device 0x5678) -- Phase one: walks entire table without finding matching primary IDs -- Sentinel detection: returns NULL -- Result: probe function returns `ENXIO` +- 设备:未知 UART(厂商 0x1234,设备 0x5678) +- 阶段一:遍历整个表但未找到匹配的主ID +- 哨兵检测:返回 NULL +- 结果:探测函数返回 `ENXIO` -##### Efficiency Considerations +##### 效率考量 -The two-phase approach optimizes the common case: +两阶段方法优化了常见情况: -- Most table entries use wildcard subsystems (require only primary ID match) -- Reading PCI configuration space is slower than memory access -- Deferring subsystem ID reads until necessary reduces probe latency +- 大多数表条目使用通配符子系统(仅需主 ID 匹配) +- 读取PCI配置空间比内存访问慢 +- 将子系统 ID 读取推迟到必要时减少探测延迟 -For devices with wildcard entries, the function performs two configuration space reads (vendor, device) and returns. Only devices requiring subsystem matching incur four reads. +对于带有通配符条目的设备,函数执行两次配置空间读取(供应商、设备)并返回。只有需要子系统匹配的设备会进行四次读取。 -The linear search is justified because: +采用线性查找是合理的,因为: -- Table size is bounded and small (< 100 entries) -- Modern CPUs prefetch sequential memory efficiently -- Probe happens once per device lifetime, not in I/O paths -- Code simplicity outweighs marginal speedup from binary search or hash tables +- 表的大小有限且较小(< 100 个条目) +- 现代 CPU 高效预取顺序内存 +- 探测在设备生命周期中发生一次,不在 I/O 路径中 +- 代码的简洁性胜过二分查找或哈希表带来的边际速度提升 -##### Integration with Probe Function +##### 与探测函数的集成 -The probe function calls `uart_pci_match` with the table base pointer: +探测函数使用表基指针调用 `uart_pci_match`: ```c id = uart_pci_match(dev, pci_ns8250_ids); @@ -10582,9 +10410,9 @@ if (id != NULL) { } ``` -A non-NULL return provides both confirmation that the device is supported and access to its configuration parameters (`id->rid`, `id->rclk`, `id->regshft`). The probe function uses these values to initialize the generic UART layer correctly for this hardware variant. +非 NULL 的返回值既确认了设备受支持,也提供了对其配置参数的访问权限(`id->rid`、`id->rclk`、`id->regshft`)。探测函数利用这些值正确初始化适用于该硬件变体的通用 UART 层。 -#### 5) Console uniqueness helper (rare but educational) +#### 5) 控制台唯一性辅助函数(罕见但有教育意义) ```c 239: extern SLIST_HEAD(uart_devinfo_list, uart_devinfo) uart_sysdevs; @@ -10621,19 +10449,19 @@ A non-NULL return provides both confirmation that the device is supported and ac 275: } ``` -*If a PCI UART is known to be **unique** in a system, tie it to the console instance automatically.* +*若 PCI UART 在系统中已知是**唯一的**,则自动将其绑定到控制台实例。* -##### Console Device Matching: `uart_pci_unique_console_match` +##### 控制台设备匹配:`uart_pci_unique_console_match` -FreeBSD must identify which UART serves as the system console, the device where boot messages appear and where single-user mode login occurs. For most systems, firmware or the boot loader configures the console before the kernel starts, but the kernel must later match this pre-configured console to the correct driver instance during PCI enumeration. The `uart_pci_unique_console_match` function solves this matching problem for devices guaranteed to exist only once per system. +FreeBSD 必须识别哪个 UART 作为系统控制台,即显示启动信息及单用户模式登录的设备。对于大多数系统,固件或引导加载程序在内核启动前配置了控制台,但内核后续必须在 PCI 枚举期间将这个预配置的控制台匹配到正确的驱动程序实例。`uart_pci_unique_console_match` 函数解决了对于每个系统保证只存在一次的设备的匹配问题。 -##### The Console Matching Problem +##### 控制台匹配问题 -When the kernel boots, early console output may use a UART initialized by firmware (BIOS/UEFI) or the boot loader. This "system device" (`sysdev`) has register addresses and basic configuration but no association with a PCI device tree entry. Later, during normal device enumeration, the PCI bus driver discovers UARTs and attaches driver instances. The kernel must determine which enumerated device corresponds to the pre-configured console. +当内核引导时,早期控制台输出可能使用由固件(BIOS/UEFI)或引导加载程序初始化的 UART。这个“系统设备”(`sysdev`)拥有寄存器地址和基本配置,但与 PCI 设备树条目没有关联。后续,在正常的设备枚举期间,PCI 总线驱动程序发现 UART 并附加驱动程序实例。内核必须确定哪个被枚举的设备对应于预配置的控制台。 -The challenge: PCI enumeration order is not guaranteed. The device at PCI address `0:1f:3` (bus 0, device 31, function 3) might enumerate as `uart0` on one boot and `uart1` after adding a card. Matching by device tree position would be unreliable. +挑战:PCI 枚举顺序无法保证。位于 PCI 地址 `0:1f:3`(总线 0,设备 31,功能 3)的设备在一次启动中可能枚举为 `uart0`,而在添加一块卡后可能枚举为 `uart1`。按设备树位置匹配是不可靠的。 -##### The Unique Device Approach +##### 唯一设备方法 ```c extern SLIST_HEAD(uart_devinfo_list, uart_devinfo) uart_sysdevs; @@ -10643,13 +10471,13 @@ static const struct pci_unique_id pci_unique_devices[] = { }; ``` -The solution for certain hardware: some devices are architecturally guaranteed to exist only once. Server management controllers, SoC-integrated UARTs, and cloud instance serial ports fall into this category. For these devices, vendor and device IDs alone suffice for matching. +针对某些硬件的解决方案:某些设备在架构上保证只存在一次。服务器管理控制器、SoC 集成的 UART 以及云实例串行端口属于此类。对于这些设备,仅凭供应商 ID 和设备 ID 就足以实现匹配。 -The `uart_sysdevs` list contains pre-configured console devices recorded during early boot. Each `uart_devinfo` structure captures the console's register base address, baud rate, and (if known) PCI identification. +`uart_sysdevs` 列表包含早期启动期间记录的预配置控制台设备。每个 `uart_devinfo` 结构捕获控制台的寄存器基地址、波特率以及(如果已知)PCI 标识。 -The `pci_unique_devices` array lists devices meeting the uniqueness criterion. Currently it contains only Amazon's EC2 serial device (vendor 0x1d0f, device 0x8250), which exists exactly once in EC2 instances and serves as the console for serial console access. +`pci_unique_devices` 数组列出了满足唯一性准则的设备。目前仅包含 Amazon 的 EC2 串行设备(供应商 0x1d0f,设备 0x8250),该设备在 EC2 实例中恰好存在一个,并作为串行控制台访问的终端。 -##### Function Entry and Device Identification +##### 函数入口与设备标识 ```c static void @@ -10665,14 +10493,14 @@ uart_pci_unique_console_match(device_t dev) device = pci_get_device(dev); ``` -The function is called from `uart_pci_probe` after successful device identification but before final probe completion. It receives the device being probed and retrieves: +该函数在设备成功识别之后、最终探测完成之前从 `uart_pci_probe` 中调用。它接收正在探测的设备并获取以下内容: -- The softc (driver instance state) via `device_get_softc()` -- The device's vendor and device IDs from PCI configuration space +- 通过 `device_get_softc()` 获取的 softc(驱动程序实例状态) +- 来自 PCI 配置空间的设备供应商 ID 和设备 ID -The softc at this point has been partially initialized by `uart_bus_probe()` with register access methods and clock rates, but `sc->sc_sysdev` is NULL unless console matching succeeds. +此时,softc 已由 `uart_bus_probe()` 使用寄存器访问方法和时钟速率部分初始化,但除非控制台匹配成功,否则 `sc->sc_sysdev` 为 NULL。 -##### Uniqueness Verification +##### 唯一性验证 ```c /* Is this a device known to exist only once in a system? */ @@ -10684,21 +10512,21 @@ for (id = pci_unique_devices; ; id++) { } ``` -The loop searches the unique device table for a match. Two exit conditions: +循环在唯一设备表中搜索匹配项。存在两种退出条件: -**Not unique**: If the loop walks past the last entry without matching, this device isn't guaranteed unique. The function returns immediately; console matching requires stricter identification (likely including subsystem IDs or base address comparison), which this function doesn't attempt. +**非唯一**:如果循环遍历完所有条目仍未匹配,则此设备不能保证唯一。函数立即返回;控制台匹配需要更严格的识别(可能包括子系统 ID 或基地址比较),而此函数不尝试这些方法。 -**Is unique**: If vendor and device IDs match an entry, the device is guaranteed unique in the system. The loop breaks, and matching proceeds. +**保证唯一性**:如果厂商ID和设备ID与某个条目匹配,则该设备在系统中保证是唯一的。循环随即终止,匹配继续。 -The array bounds check uses `nitems(pci_unique_devices)`, a macro computing array element count. This pointer comparison detects when `id` has advanced past the array's end: +数组边界检查使用了 `nitems(pci_unique_devices)`,这是一个计算数组元素个数的宏。该指针比较用于检测 `id` 是否已越过数组末尾: ```c if (id == &pci_unique_devices[nitems(pci_unique_devices)]) ``` -This is equivalent to `id == pci_unique_devices + array_length`, checking if the pointer equals the address just beyond the last valid element. +这等价于 `id == pci_unique_devices + array_length`,检查指针是否等于最后一个有效元素之后的地址。 -##### Console Device Matching +##### 控制台设备匹配 ```c /* If it matches a console, it must be the same device. */ @@ -10711,40 +10539,40 @@ SLIST_FOREACH(sysdev, &uart_sysdevs, next) { } ``` -The `SLIST_FOREACH` macro iterates the system device list, checking each pre-configured console for matching PCI IDs. The list typically contains zero or one entry (systems without serial consoles or with one console), but the code correctly handles multiple consoles. +`SLIST_FOREACH` 宏遍历系统设备列表,检查每个预配置的控制台是否与PCI ID匹配。该列表通常包含零个或一个条目(没有串行控制台或只有一个控制台的系统),但代码正确处理了多个控制台的情况。 -**Match confirmation**: When `sysdev->pci_info` matches the device's vendor and device IDs, the uniqueness guarantee ensures this enumerated device is the same physical hardware the firmware configured as a console. No ambiguity exists; there's only one device with these IDs in the system. +**匹配确认**:当 `sysdev->pci_info` 与设备的厂商ID和设备ID匹配时,唯一性保证确保该枚举出的设备与固件配置为控制台的物理硬件是同一个。不存在歧义;系统中只有一个具有这些ID的设备。 -**Linking the instances**: `sc->sc_sysdev = sysdev` creates a bidirectional association: +**实例关联**:`sc->sc_sysdev = sysdev` 建立了双向关联: -- The driver instance (`sc`) now knows it's managing a console device -- Console-specific behaviors activate: special character handling, kernel message output, debugger entry +- 驱动程序实例(`sc`)现在知道它正在管理一个控制台设备 +- 控制台特定行为激活:特殊字符处理、内核消息输出、调试器入口 -**Clock synchronization**: `sysdev->bas.rclk = sc->sc_bas.rclk` updates the system device's clock rate to match the value from the identification table. Early boot initialization might not know the precise clock frequency, using a default or probe-detected value. The PCI driver, having matched the device against the table, knows the correct frequency and updates the system device record. +**时钟同步**:`sysdev->bas.rclk = sc->sc_bas.rclk` 将系统设备的时钟频率更新为与识别表中的值匹配。早期引导初始化可能不知道精确的时钟频率,使用的是默认值或探测到的值。PCI驱动程序在将设备与表匹配后,知道正确的频率,并更新系统设备记录。 -This clock update is critical: if early boot used an incorrect clock, baud rate calculations would be wrong. The console might have worked by luck (if firmware configured the UART's divisor latch directly) but would fail when the driver reconfigures it. Synchronizing `rclk` ensures subsequent operations use correct values. +这种时钟更新至关重要:如果早期引导使用了错误的时钟,波特率计算就会出错。控制台可能碰巧能工作(如果固件直接配置了UART的分频锁存器),但当驱动程序重新配置它时就会失败。同步 `rclk` 可确保后续操作使用正确的值。 -##### Why This Function Exists +##### 为什么存在此函数 -Traditional console matching compares base addresses: the system device's physical register address matches the PCI BAR of one enumerated device. This works reliably but requires reading BARs for all UARTs and handling complications like I/O port vs. memory-mapped registers. +传统的控制台匹配比较基地址:系统设备的物理寄存器地址与某个枚举设备的PCI BAR匹配。这种方法可靠,但需要读取所有UART的BAR,并处理I/O端口与内存映射寄存器等复杂情况。 -For unique devices, vendor/device ID matching is simpler and equally reliable. The uniqueness guarantee eliminates ambiguity: if a unique device exists as a console and that device is enumerated, they must be the same. +对于唯一设备,厂商/设备ID匹配更简单且同样可靠。唯一性保证消除了歧义:如果某个唯一设备作为控制台存在,且该设备被枚举出来,则它们必须是同一个。 -##### Limitations and Scope +##### 局限性与范围 -This function only handles devices in `pci_unique_devices`. Most UARTs don't qualify: +此函数仅处理 `pci_unique_devices` 中的设备。大多数UART不满足条件: -- Multi-port cards have identical vendor/device IDs for all ports -- Generic chipsets appear in multiple products -- Motherboard UARTs from one vendor may use the same chipset across product lines +- 多端口卡的所有端口具有相同的厂商ID和设备ID +- 通用芯片组出现在多个产品中 +- 同一厂商的主板UART可能在多个产品线中使用相同的芯片组 -For non-unique devices, the probe function falls back to other matching methods (typically base address comparison in `uart_bus_probe`), or the console association might be established through hints or device tree properties. +对于非唯一设备,探测函数会回退到其他匹配方法(通常在 `uart_bus_probe` 中进行基地址比较),或者通过hints或设备树属性建立控制台关联。 -The function is called opportunistically: it attempts to match for all probed devices but only succeeds for unique devices that also happen to be consoles. Failure is not an error; it simply means this device is either not unique or not a console. +该函数机会性地被调用:它尝试对所有探测到的设备进行匹配,但仅对恰好也是控制台的唯一设备成功。失败不是错误;仅意味着该设备要么不是唯一的,要么不是控制台。 -##### Integration Context +##### 集成上下文 -The probe function calls this after initial device identification: +探测函数在完成初始设备识别后调用此函数: ```c result = uart_bus_probe(dev, ...); @@ -10752,11 +10580,11 @@ if (sc->sc_sysdev == NULL) uart_pci_unique_console_match(dev); ``` -The check `sc->sc_sysdev == NULL` ensures this function runs only if `uart_bus_probe` didn't already establish a console association through other means. This ordering provides a fallback: try precise matching first (base address comparison), then try unique device matching. +检查 `sc->sc_sysdev == NULL` 确保该函数仅在 `uart_bus_probe` 未通过其他方式建立控制台关联时运行。这种顺序提供了一种回退机制:先尝试精确匹配(基地址比较),再尝试唯一设备匹配。 -If matching succeeds, subsequent driver operations recognize the console status and enable special handling: synchronous output for panic messages, debugger break character detection, and kernel message routing. +如果匹配成功,后续驱动程序操作会识别控制台状态,并启用特殊处理:恐慌消息的同步输出、调试器断点字符检测以及内核消息路由。 -#### 6) `probe`: choose the class and call the **shared** bus probe +#### 6) `probe`:选择类并调用**共享的**总线探测 ```c 277: static int @@ -10810,13 +10638,13 @@ If matching succeeds, subsequent driver operations recognize the console status 325: } ``` -*Two routes to a match: explicit table hit or class/subclass fallback. Then call the **UART bus probe** with `regshft`, `rclk`, and `rid`.* +*两种匹配路径:显式表命中或类/子类回退。然后使用 `regshft`、`rclk` 和 `rid` 调用 **UART 总线探测**。* -##### Device Probe Function: `uart_pci_probe` +##### 设备探测函数:`uart_pci_probe` -The probe function is the kernel's first interaction with a potential device during enumeration. When the PCI bus driver discovers a device, it calls the probe function of every registered driver, asking "can you manage this device?" The probe function examines the hardware's identification and configuration, returning a priority value indicating match quality or an error signaling "not my device." +探测函数是内核在枚举期间与潜在设备进行首次交互。当 PCI 总线驱动程序发现一个设备时,它会调用每个已注册驱动程序的探测函数,询问“你能管理这个设备吗?”探测函数检查硬件的标识和配置,返回一个表示匹配质量的优先级值,或者返回一个表示“不是我的设备”的错误。 -##### Function Purpose and Contract +##### 函数目的与契约 ```c static int @@ -10829,17 +10657,17 @@ uart_pci_probe(device_t dev) sc = device_get_softc(dev); ``` -The probe function receives a `device_t` representing the hardware being examined. It must determine compatibility without modifying device state or allocating resources; those operations belong in the attach function. +探测函数接收一个 `device_t` 参数,代表正在检查的硬件。它必须在不修改设备状态或分配资源的情况下确定兼容性;这些操作属于挂接函数。 -The return value encodes probe results: +返回值编码了探测结果: -- Negative values or zero indicate success, with lower values representing better matches -- Positive values (particularly `ENXIO`) indicate "this driver cannot manage this device" -- The kernel selects the driver returning the lowest (best) value +- 负值或零表示成功,数值越低表示匹配越好 +- 正值(特别是 `ENXIO`)表示“此驱动程序无法管理此设备” +- 内核选择返回最低(最佳)值的驱动程序 -The softc is retrieved via `device_get_softc()`, which returns a zeroed structure of the size specified in the driver declaration (`sizeof(struct uart_softc)`). The probe function initializes critical fields like `sc_class` before delegating to generic code. +通过 `device_get_softc()` 获取软上下文(softc),它返回一个已清零的结构,大小由驱动程序声明中指定(`sizeof(struct uart_softc)`)。探测函数在委派给通用代码之前初始化关键字段,例如 `sc_class`。 -##### Explicit Device Table Matching +##### 显式设备表匹配 ```c id = uart_pci_match(dev, pci_ns8250_ids); @@ -10849,20 +10677,20 @@ if (id != NULL) { } ``` -The primary matching path searches the explicit device table. If `uart_pci_match` returns non-NULL, the device is explicitly supported with known configuration parameters. +主要的匹配路径搜索显式的设备表。如果 `uart_pci_match` 返回非 NULL,则该设备被显式支持,并具有已知的配置参数。 -**Setting the UART class**: `sc->sc_class = &uart_ns8250_class` assigns the function table for NS8250-compatible register access. The `uart_class` structure (defined in the generic UART layer) contains function pointers for operations like: +**设置 UART 类**:`sc->sc_class = &uart_ns8250_class` 为 NS8250 兼容的寄存器访问分配函数表。`uart_class` 结构(在通用 UART 层中定义)包含用于操作(例如)的函数指针: -- Reading/writing registers -- Configuring baud rates -- Managing FIFOs and flow control -- Handling interrupts +- 读/写寄存器 +- 配置波特率 +- 管理 FIFO 和流控制 +- 处理中断 -Different UART families (NS8250/16550, SAB82532, Z8530) would assign different class pointers. This driver only handles NS8250 variants, so the class assignment is unconditional. +不同的 UART 系列(NS8250/16550、SAB82532、Z8530)会分配不同的类指针。此驱动程序仅处理 NS8250 变体,因此类分配是无条件的。 -The `goto match` bypasses subsequent checks, once explicitly identified, no further heuristics are needed. +`goto match` 会绕过后续检查,一旦被显式识别,就不需要进一步的启发式方法。 -##### Generic SimpleComm Device Fallback +##### 通用 SimpleComm 设备回退 ```c if (pci_get_class(dev) == PCIC_SIMPLECOMM && @@ -10875,17 +10703,17 @@ if (pci_get_class(dev) == PCIC_SIMPLECOMM && } ``` -This fallback handles devices not in the explicit table but advertising themselves as generic UARTs through PCI class codes. The PCI specification defines a class/subclass/programming interface hierarchy for device categorization: +此回退处理那些不在显式表中但通过 PCI 类代码自我声明为通用 UART 的设备。PCI 规范定义了一个类/子类/编程接口层次结构用于设备分类: -**Class check**: `PCIC_SIMPLECOMM` (0x07) identifies "Simple Communication Controllers," which includes serial ports, parallel ports, and modems. +**类检查**:`PCIC_SIMPLECOMM` (0x07) 标识“简单通信控制器”,包括串口、并口和调制解调器。 -**Subclass check**: `PCIS_SIMPLECOMM_UART` (0x00) narrows this to serial controllers specifically. +**子类检查**:`PCIS_SIMPLECOMM_UART` (0x00) 将其进一步缩小为串行控制器。 **Programming interface check**: `pci_get_progif(dev) < PCIP_SIMPLECOMM_UART_16550A` accepts devices claiming 8250-compatible (ProgIF 0x00) or 16450-compatible (ProgIF 0x01) programming interfaces, but rejects devices claiming 16550A compatibility (ProgIF 0x02) or higher. -This seemingly backwards logic exists because early 16550A implementations had broken FIFOs. The PCI specification allowed devices to claim "16550-compatible" without specifying whether FIFOs worked. Rejecting 16550A+ ProgIF values forces these devices through explicit table matching, where quirks can be documented. Only conservative 8250/16450 claims are trusted. +这个看似反向的逻辑存在是因为早期的 16550A 实现存在故障的 FIFO。PCI 规范允许设备声明“16550 兼容”,而不说明 FIFO 是否工作。拒绝 16550A+ 的 ProgIF 值迫使这些设备通过显式表匹配,在那里可以记录 quirks。只有保守的 8250/16450 声明才被信任。 -**Fallback configuration**: The `cid` structure (declared at function entry) provides default parameters: +**回退配置**:`cid` 结构(在函数入口声明)提供默认参数: ```c struct pci_id cid = { @@ -10896,24 +10724,24 @@ struct pci_id cid = { }; ``` -The comment `/* XXX rclk what to do */` highlights uncertainty: without explicit table entry, the correct clock frequency is unknown. The generic code defaults to 1.8432 MHz (standard PC UART clock), which works for most hardware but fails for devices with non-standard clocks. +注释 `/* XXX rclk what to do */` 突出了不确定性:没有显式的表条目,正确的时钟频率未知。通用代码默认使用 1.8432 MHz(标准 PC UART 时钟),这对大多数硬件有效,但对于非标准时钟的设备会失败。 -The `PCI_NO_MSI` flag in the default RID disables MSI for generic devices. Since quirks aren't known, conservative interrupt handling prevents potential MSI-related hangs or interrupt storms. +默认 RID 中的 `PCI_NO_MSI` 标志禁用了通用设备的 MSI。由于未知 quirks,保守的中断处理可以防止潜在的 MSI 相关挂起或中断风暴。 -Setting `id = &cid` makes this local structure visible to the match path below, treating the generic configuration as if it came from the table. +设置 `id = &cid` 使此本地结构对下面的匹配路径可见,将通用配置视为来自表。 -##### Non-Match Exit +##### 未匹配退出 ```c /* Add checks for non-ns8250 IDs here. */ return (ENXIO); ``` -If neither explicit matching nor generic class matching succeeds, the device isn't a supported UART. Returning `ENXIO` ("Device not configured") tells the kernel to try other drivers. +如果显式匹配和通用类匹配都失败,则设备不是受支持的 UART。返回 `ENXIO`(“设备未配置”)告诉内核尝试其他驱动程序。 -The comment indicates an extension point: drivers for other UART families (Exar, Oxford, Sunix with proprietary registers) would add their checks here before the final `ENXIO`. +该注释指示了一个扩展点:其他UART系列的驱动程序(如Exar、Oxford、Sunix等使用私有寄存器的设备)可以在最终的`ENXIO`之前在此添加自己的检查逻辑。 -##### Delegating to Generic Probe Logic +##### 委托给通用探测逻辑 ```c match: @@ -10924,42 +10752,42 @@ if (result > 0) return (result); ``` -The `match` label unifies both identification paths (explicit table and generic class). All subsequent code operates on `id`, which points either to a table entry or the `cid` structure. +`match`标签统一了两个识别路径(显式表识别和通用类别识别)。后续所有代码都基于`id`工作,它要么指向一个表条目,要么指向`cid`结构体。 -**Calling the generic layer**: `uart_bus_probe()` lives in `uart_bus.c` and handles bus-agnostic initialization: +**调用通用层**:`uart_bus_probe()`位于`uart_bus.c`中,负责处理与总线无关的初始化: -- Allocates and maps the I/O resource (BAR indicated by `id->rid`) -- Configures register access using `id->regshft` -- Sets the reference clock to `id->rclk` (or default if zero) -- Probes the hardware to verify UART presence and identify the FIFO depth -- Establishes register base address +- 分配并映射I/O资源(由`id->rid`指示的BAR) +- 使用 `id->regshft` 配置寄存器访问 +- 将参考时钟设置为`id->rclk`(若该值为零则使用默认值) +- 探测硬件以验证UART存在性并识别FIFO深度 +- 建立寄存器基地址 -The additional parameters (three zeros) specify: +附加参数(三个零)指定: -- Flags controlling probe behavior -- Device unit number hint (0 = auto-assign) -- Reserved for future use +- 控制探测行为的标志 +- 设备单元号提示(0 = 自动分配) +- 保留供将来使用 -**Error handling**: If `uart_bus_probe` returns a positive value (error), that value propagates to the caller. Typical errors include: +**错误处理**:如果`uart_bus_probe`返回正值(错误),则该值会传播给调用者。典型错误包括: -- `ENOMEM` - couldn't allocate resources -- `ENXIO` - registers don't respond correctly (not a UART or disabled) -- `EIO` - hardware access failures +- `ENOMEM` - 无法分配资源 +- `ENXIO` - 寄存器未正确响应(不是 UART 或已禁用) +- `EIO` - 硬件访问失败 -Successful probe returns zero or a negative priority value. +成功探测返回零或负优先级值。 -##### Console Device Association +##### 控制台设备关联 ```c if (sc->sc_sysdev == NULL) uart_pci_unique_console_match(dev); ``` -After successful generic probe, the driver attempts console matching. The check `sc->sc_sysdev == NULL` ensures this runs only if `uart_bus_probe` didn't already identify the device as a console (which it might have done via base address comparison). +在通用探测成功后,驱动程序会尝试进行控制台匹配。检查`sc->sc_sysdev == NULL`确保仅在`uart_bus_probe`尚未将该设备识别为控制台时执行此操作(该函数可能已通过基地址比较完成了识别)。 -Console association is opportunistic; failure doesn't prevent device attachment, it just means this UART won't receive kernel messages or serve as a login prompt. +控制台关联是机会性的;失败不会阻止设备挂载,只是意味着该UART不会接收内核消息或作为登录提示符使用。 -##### Setting Device Description +##### 设置设备描述 ```c /* Set/override the device description. */ @@ -10968,23 +10796,23 @@ if (id->desc) return (result); ``` -The device description appears in boot messages, `dmesg`, and `pciconf -lv` output. It helps administrators identify hardware: "Intel AMT - SOL" is more meaningful than "PCI device 8086:108f." +设备描述会出现在启动消息、`dmesg`和`pciconf -lv`输出中。它帮助管理员识别硬件:"Intel AMT - SOL"比"PCI device 8086:108f"更具意义。 -For explicitly matched devices, `id->desc` contains the table-specified string. For generic devices, it's "Generic SimpleComm PCI device." The description is set unconditionally if present; even if a generic probe set one, the PCI-specific driver overrides it with more accurate information. +对于显式匹配的设备,`id->desc`包含表中指定的字符串。对于通用设备,则为"Generic SimpleComm PCI device"。若有描述信息,则无条件设置;即使通用探测已设置过描述,PCI专用驱动程序也会用更精确的信息覆盖它。 -Finally, the function returns the result from `uart_bus_probe`, which the kernel uses to select among competing drivers. For UARTs, this is typically `BUS_PROBE_DEFAULT` (-20), the standard priority for base-OS drivers, since NS8250 drivers are the only ones claiming these devices. +最后,函数返回`uart_bus_probe`的结果,内核使用该结果在多个竞争驱动程序中进行选择。对于UART,这通常是`BUS_PROBE_DEFAULT`(-20),即基础系统驱动程序的优先级标准,因为NS8250驱动是唯一认领这些设备的驱动程序。 -##### Probe Priority and Driver Selection +##### 探测优先级与驱动程序选择 -The probe priority mechanism handles hardware claimed by multiple drivers. Consider a multi-function card with serial ports and network interfaces: -- `uart_pci` might probe it (matches PCI class, returning `BUS_PROBE_DEFAULT` = -20) -- A vendor-specific driver might also probe it (matching vendor/device ID exactly) +探测优先级机制处理多个驱动程序认领同一硬件的情况。考虑一个包含串口和网络接口的多功能卡: +- `uart_pci` 可能会探测它(匹配 PCI 类,返回 `BUS_PROBE_DEFAULT` = -20) +- 某个厂商专用驱动程序也可能探测它(精确匹配厂商/设备ID) -The vendor driver should return a higher value (closer to zero), such as `BUS_PROBE_VENDOR` (-10) or `BUS_PROBE_SPECIFIC` (0), and Newbus will select it because its priority is **greater** than `BUS_PROBE_DEFAULT`. Remember: closer to zero wins. +厂商驱动应返回一个更大的值(更接近零),例如`BUS_PROBE_VENDOR`(-10)或`BUS_PROBE_SPECIFIC`(0),Newbus将选择它,因为其优先级**大于**`BUS_PROBE_DEFAULT`。记住:越接近零的优先级越高。 -For most serial hardware, only `uart_pci` probes successfully, making priority moot. But the mechanism allows graceful coexistence with specialised drivers. +对于大多数串行硬件,只有`uart_pci`能够成功探测,因此优先级问题无关紧要。但该机制允许与专用驱动程序优雅共存。 -##### The Complete Probe Flow +##### 完整的探测流程 ```html PCI bus discovers device @@ -11014,9 +10842,9 @@ Set device description Return success (0 or priority) ``` -After successful probe, the kernel records this driver as the handler for this device and will later call `uart_pci_attach` to complete initialization. +探测成功后,内核将该驱动程序记录为此设备的处理程序,稍后会调用`uart_pci_attach`完成初始化。 -#### 7) `attach`: prefer **single-vector MSI**, then defer to the core +#### 7) `attach`:优先使用**单向量MSI**,然后交由核心处理 ```c 327: static int @@ -11046,13 +10874,13 @@ After successful probe, the kernel records this driver as the handler for this d 351: } ``` -*Small bus-specific policy (prefer 1-vector MSI) and then **delegate** to `uart_bus_attach()`.* +*小型总线特定策略(优先使用 1 向量 MSI),然后**委托**给 `uart_bus_attach()`。* -##### Device Attach Function: `uart_pci_attach` +##### 设备连接函数:`uart_pci_attach` -The attach function is called after successful probe to make the device operational. While probe merely identifies the device and verifies compatibility, attach allocates resources, configures hardware, and integrates the device into the system. For uart_pci, attach focuses on one PCI-specific concern, interrupt configuration, before delegating to the generic UART initialization code. +attach函数在探测成功后调用,用于使设备进入可操作状态。探测仅负责识别设备和验证兼容性,而attach负责分配资源、配置硬件并将设备集成到系统中。对于uart_pci,attach专注于一个PCI特有的关注点——中断配置,然后才将工作委托给通用的UART初始化代码。 -##### Function Entry and Context +##### 函数入口与上下文 ```c static int @@ -11065,27 +10893,27 @@ uart_pci_attach(device_t dev) sc = device_get_softc(dev); ``` -The attach function receives the same `device_t` passed to probe. The softc retrieved here contains initialization performed during probe: the UART class assignment, base address configuration, and any console association. +attach 函数接收与 probe 相同的 `device_t` 参数。此处获取的 softc 包含 probe 期间执行的初始化:UART 类分配、基地址配置以及任何控制台关联。 -Unlike probe (which must be idempotent and non-destructive), attach may modify device state, allocate resources, and fail destructively. If attach fails, the device becomes unavailable and typically requires reboot or manual intervention to recover. +与 probe(必须是幂等且无破坏性的)不同,attach 可以修改设备状态、分配资源,并且可能以破坏性的方式失败。如果 attach 失败,设备将不可用,通常需要重启或手动干预才能恢复。 -##### Message Signaled Interrupts: Background +##### 消息信号中断:背景 -Traditional PCI interrupts use dedicated physical signal lines (INTx: INTA#, INTB#, INTC#, INTD#) shared among multiple devices. This sharing causes several problems: +传统的 PCI 中断使用专用的物理信号线(INTx:INTA#、INTB#、INTC#、INTD#),这些信号线在多个设备之间共享。这种共享会导致以下几个问题: -- Interrupt storms when devices don't properly acknowledge interrupts -- Latency from iterating handlers until finding the interrupting device -- Limited routing flexibility in complex systems +- 当设备未正确确认中断时,中断风暴会发生。 +- 遍历处理程序直到找到中断设备会导致延迟。 +- 复杂系统中路由灵活性有限 -Message Signaled Interrupts (MSI) replace physical signals with memory writes to special addresses. When a device needs service, it writes to a CPU-specific address, triggering an interrupt on that CPU. MSI advantages: +消息信号中断(MSI)用对特殊地址的内存写入替代物理信号。当设备需要服务时,它会向 CPU 特定的地址写入,从而在相应 CPU 上触发中断。MSI 的优势: -- No sharing, each device gets dedicated interrupt vectors -- Lower latency, direct CPU targeting -- Better scalability, thousands of vectors available vs. four INTx lines +- 无共享,每个设备获得专用的中断向量。 +- 更低延迟,直接 CPU 目标定位 +- 更好的可扩展性,数千个向量可用,而 INTx 只有四条线 -However, MSI implementation quality varies, particularly in UARTs (simple devices often getting minimal validation). Some UART MSI implementations suffer from lost interrupts, spurious interrupts, or system hangs. +然而,MSI 实现质量参差不齐,尤其是在 UART 中(简单设备通常只进行最低限度的验证)。某些 UART 的 MSI 实现存在丢失中断、虚假中断或系统挂起的问题。 -##### MSI Eligibility Check +##### MSI 资格检查 ```c /* @@ -11097,20 +10925,20 @@ if ((id == NULL || (id->rid & PCI_NO_MSI) == 0) && pci_msi_count(dev) == 1) { ``` -The driver attempts MSI allocation only when three conditions hold: +驱动程序仅在满足以下三个条件时才尝试分配 MSI: -**Device not in table OR MSI not explicitly disabled**: The condition `(id == NULL || (id->rid & PCI_NO_MSI) == 0)` evaluates true in two cases: +**设备不在表中或 MSI 未被显式禁用**:条件 `(id == NULL || (id->rid & PCI_NO_MSI) == 0)` 在两种情况下评估为真: -1. `id == NULL` - device matched via generic class codes, not explicit table entry (no known quirks) -2. `(id->rid & PCI_NO_MSI) == 0` - device in table, but MSI flag is clear (MSI known working) +1. `id == NULL` - 设备通过通用类代码匹配,非显式表条目(无双亲行为) +2. `(id->rid & PCI_NO_MSI) == 0` —— 设备在表中,但 MSI 标志已清除(MSI 已知工作正常)。 -If the device has `PCI_NO_MSI` set in its table entry, this condition fails and MSI allocation is skipped entirely. Legacy line-based interrupts will be used instead. +如果设备在其表项中设置了 `PCI_NO_MSI`,则该条件失败,完全跳过 MSI 分配。将改用传统的基于线的中断。 -**Single MSI vector advertised**: `pci_msi_count(dev) == 1` queries the device's MSI capability structure to determine how many interrupt vectors it supports. UARTs only need one interrupt (serial events: received character, transmit buffer empty, modem status change), so multi-vector support is unnecessary. +**单个 MSI 向量通告**:`pci_msi_count(dev) == 1` 查询设备的 MSI 能力结构,以确定其支持的中断向量数量。UART 只需要一个中断(串行事件:接收到字符、发送缓冲器空、调制解调器状态变化),因此多向量支持是不必要的。 -The comment captures hard-won experience: devices advertising multiple MSI vectors (even though they only use one) often have buggy implementations. Restricting allocation to single-vector devices avoids these problems. A device advertising eight vectors for a simple UART likely received minimal MSI testing. +注释记录了来之不易的经验:通告多个 MSI 向量(尽管它们只使用一个)的设备通常存在有问题的实现。将分配限制为单向量设备可以避免这些问题。一个简单的 UART 通告八个向量很可能只经过了最低限度的 MSI 测试。 -##### MSI Allocation +##### MSI 分配 ```c count = 1; @@ -11120,72 +10948,72 @@ if (pci_alloc_msi(dev, &count) == 0) { } ``` -**Requesting allocation**: `pci_alloc_msi(dev, &count)` asks the PCI subsystem to allocate MSI vectors for this device. The `count` parameter is both input and output: -- Input: requested number of vectors (1) -- Output: actual allocated count (might be less if resources exhausted) +**请求分配**:`pci_alloc_msi(dev, &count)` 要求 PCI 子系统为此设备分配 MSI 向量。`count` 参数既作为输入又作为输出: +- 输入:请求的向量数(1) +- 输出:实际分配的数量(如果资源耗尽可能更少) -The function returns zero on success, non-zero on failure. Failure reasons include: -- System doesn't support MSI (old chipsets, disabled in BIOS) -- MSI resources exhausted (too many devices already using MSI) -- Device MSI capability structure is malformed +函数成功时返回零,失败时返回非零。失败原因包括: +- 系统不支持 MSI(旧芯片组,BIOS 中禁用) +- MSI 资源耗尽(已有太多设备在使用 MSI) +- 设备 MSI 能力结构格式错误。 -**Recording interrupt resource ID**: On successful allocation, `sc->sc_irid = 1` records that interrupt resource ID 1 will be used. The significance: -- RID 0 typically represents the legacy INTx interrupt -- RID 1+ represent MSI vectors -- The generic UART attach code will allocate the interrupt resource using this RID +**记录中断资源 ID**:成功分配后,`sc->sc_irid = 1` 记录将使用中断资源 ID 1。其意义: +- RID 0 通常表示传统的 INTx 中断。 +- RID 1+ 表示 MSI 向量 +- 通用的 UART attach 代码将使用此 RID 分配中断资源。 -Without this assignment, the default RID (0) would be used, causing the driver to allocate the legacy interrupt instead of the newly-allocated MSI vector. +如果没有这个赋值,将使用默认的 RID (0),导致驱动程序分配传统的中断而不是新分配的 MSI 向量。 -**User notification**: `device_printf` logs the MSI allocation to the console and system message buffer. This information helps administrators debug interrupt-related issues. Output appears as: +**用户通知**:`device_printf` 将 MSI 分配记录到控制台和系统消息缓冲区。此信息有助于管理员调试与中断相关的问题。输出显示为: ```yaml uart0: port 0xf0e0-0xf0e7 mem 0xfebff000-0xfebff0ff irq 16 at device 22.0 on pci0 uart0: Using 1 MSI message ``` -**Silent fallback**: If `pci_alloc_msi` fails, the conditional body doesn't execute. The `sc->sc_irid` field remains at its default value (0), and no message is printed. The attach function proceeds to generic initialization, which will allocate the legacy interrupt. This silent fallback ensures device functionality even when MSI is unavailable, legacy interrupts work universally. +**静默回退**:如果 `pci_alloc_msi` 失败,条件体不会执行。`sc->sc_irid` 字段保持其默认值(0),且不打印任何消息。attach 函数继续进行通用初始化,该初始化将分配传统中断。这种静默回退确保即使 MSI 不可用时设备仍能运行,传统中断具有通用兼容性。 -##### Delegating to Generic Attach +##### 委托给通用连接 ```c return (uart_bus_attach(dev)); ``` -After PCI-specific interrupt configuration, the function calls `uart_bus_attach()` to complete initialization. This generic function (shared across all bus types: PCI, ISA, ACPI, USB) performs: +在 PCI 特定的中断配置之后,该函数调用 `uart_bus_attach()` 来完成初始化。这个通用函数(在所有总线类型中共享:PCI、ISA、ACPI、USB)执行以下操作: -**Resource allocation**: -- I/O ports or memory-mapped registers (already mapped during probe) -- Interrupt resource (using `sc->sc_irid` to select MSI or legacy) -- Possibly DMA resources (not used by most UARTs) +**资源分配**: +- I/O 端口或内存映射寄存器(已在探测阶段映射) +- 中断资源(使用 `sc->sc_irid` 选择 MSI 或传统方式) +- 可能的 DMA 资源(大多数 UART 不使用) -**Hardware initialization**: -- Reset the UART -- Configure default parameters (8 data bits, no parity, 1 stop bit) -- Enable and size the FIFO -- Set up modem control signals +**硬件初始化**: +- 复位 UART +- 配置默认参数(8 数据位,无校验,1 停止位) +- 启用并设置 FIFO 大小 +- 设置调制解调器控制信号 -**Character device creation**: -- Allocate TTY structures -- Create device nodes (`/dev/cuaU0`, `/dev/ttyU0`) -- Register with the TTY layer for line discipline support +**字符设备创建**: +- 分配 TTY 结构 +- 创建设备节点(`/dev/cuaU0`、`/dev/ttyU0`) +- 注册到 TTY 层以支持行规程 -**Console integration**: -- If `sc->sc_sysdev` is set, configure as system console -- Enable console output through this UART -- Handle kernel debugger entry via break signals +**控制台集成**: +- 如果设置了 `sc->sc_sysdev`,则配置为系统控制台 +- 通过此 UART 启用控制台输出 +- 通过中断信号处理内核调试器入口 -**Return value propagation**: The return value from `uart_bus_attach()` passes directly to the kernel. Success (0) indicates the device is operational; errors (positive errno values) indicate failure. +**返回值传递**:`uart_bus_attach()` 的返回值直接传递给内核。成功(0)表示设备可操作;错误(正的 errno 值)表示失败。 -##### Attach Failure Handling +##### 连接失败处理 -If `uart_bus_attach()` fails, the device remains unusable. The PCI subsystem notes the failure and won't call device methods (read, write, ioctl) on this instance. However, resources already allocated by attach (like MSI vectors) may leak unless the driver's detach function is called. +如果 `uart_bus_attach()` 失败,设备将保持不可用状态。PCI 子系统会记录该失败,并且不会对此实例调用设备方法(读、写、ioctl)。然而,attach 已分配的资源(如 MSI 向量)可能会泄漏,除非调用了驱动程序的 detach 函数。 -Proper error handling in the generic attach code ensures: -- Failed interrupt allocation triggers resource cleanup -- Partial initialization is rolled back -- The device remains in a safe state for retry or removal +通用 attach 代码中的正确处理错误确保了: +- 中断分配失败触发资源清理 +- 部分初始化会被回滚 +- 设备保持在安全状态,以便重试或移除 -##### The Complete Attach Flow +##### 完整的 Attach 流程 ```html Kernel calls uart_pci_attach(dev) @@ -11212,21 +11040,21 @@ Create device nodes (/dev/cuaU*, /dev/ttyU*) Return success/failure ``` -After successful attach, the UART is fully operational. Applications can open `/dev/cuaU0` for serial communication, kernel messages flow to the console (if configured), and interrupt-driven I/O handles character transmission and reception. +成功 attach 后,UART 完全可操作。应用程序可以打开 `/dev/cuaU0` 进行串行通信,内核消息会流向控制台(如果已配置),中断驱动的 I/O 处理字符的发送和接收。 -##### Architectural Simplicity +##### 架构简洁性 -The attached function's brevity, twenty-three lines including comments, demonstrates the layered architecture's power. PCI-specific concerns (MSI allocation) are handled here in minimal code, while complex UART initialization lives in the generic layer where it's shared across all bus types. +attach 函数非常简洁,包括注释在内共二十三行,展示了分层架构的强大之处。PCI 特定关注点(MSI 分配)在这里以最少的代码处理,而复杂的 UART 初始化位于通用层,该层在所有总线类型中共享。 -This separation means: +这种分离意味着: -- ISA-attached UARTs skip MSI logic but reuse all UART initialization -- ACPI-attached UARTs might handle power management differently but share character device creation -- USB serial adapters use completely different interrupt delivery but share TTY integration +- ISA 连接的 UART 跳过 MSI 逻辑但重用所有 UART 初始化 +- ACPI 连接的 UART 可能以不同方式处理电源管理但共享字符设备创建 +- USB 串行适配器使用完全不同的中断传递但共享 TTY 集成 -The uart_pci driver is thin glue connecting PCI resource management to generic UART functionality, exactly as intended. +uart_pci 驱动程序是一个薄薄的粘合层,将 PCI 资源管理与通用 UART 功能连接起来,完全符合设计初衷。 -#### 8) `detach` and module registration +#### 8) `detach` 与模块注册 ```c 353: static int @@ -11244,13 +11072,13 @@ The uart_pci driver is thin glue connecting PCI resource management to generic U 366: DRIVER_MODULE(uart, pci, uart_pci_driver, NULL, NULL); ``` -*Release MSI if we took it, then let the UART core unwind. Finally, register this driver on the **`pci`** bus.* +*如果分配了 MSI 则释放它,然后让 UART 核心进行回退。最后,将此驱动程序注册到 **`pci`** 总线上。* -##### Device Detach Function and Driver Registration +##### 设备分离函数与驱动程序注册 -The detach function is called when a device must be removed from the system, either due to hot-unplug, driver unload, or system shutdown. It must reverse all operations performed during attach, releasing resources and ensuring the hardware is left in a safe state. The final `DRIVER_MODULE` macro registers the driver with the kernel's device framework. +detach 函数在必须从系统中移除设备时被调用,可能是由于热插拔、驱动程序卸载或系统关机。它必须反转 attach 期间执行的所有操作,释放资源并确保硬件处于安全状态。最后的 `DRIVER_MODULE` 宏将驱动程序注册到内核的设备框架中。 -##### Device Detach Function: `uart_pci_detach` +##### 设备分离函数:`uart_pci_detach` ```c static int @@ -11261,106 +11089,106 @@ uart_pci_detach(device_t dev) sc = device_get_softc(dev); ``` -Detach receives the device being removed and retrieves its softc containing the current configuration. The function must be prepared to handle partial initialization states, if attach failed midway, detach might be called to clean up whatever succeeded. +Detach 接收正在移除的设备,并检索包含当前配置的 softc。该函数必须准备好处理部分初始化的状态:如果 attach 中途失败,detach 可能被调用来清理已成功的部分。 -##### MSI Resource Release +##### MSI 资源释放 ```c if (sc->sc_irid != 0) pci_release_msi(dev); ``` -The conditional checks whether MSI was allocated during attach. Recall that `sc->sc_irid = 1` signals successful MSI allocation; the default value (0) indicates legacy interrupts were used. +条件判断检查是否在 attach 期间分配了 MSI。回顾一下,`sc->sc_irid = 1` 表示成功分配了 MSI;默认值(0)表示使用了传统中断。 -**Releasing MSI vectors**: `pci_release_msi(dev)` returns the MSI interrupt vector to the system pool, making it available for other devices. This call must be made before the generic detach, which will deallocate the interrupt resource itself. The sequence matters: +**释放 MSI 向量**:`pci_release_msi(dev)` 将 MSI 中断向量归还给系统池,使其可供其他设备使用。此调用必须在通用 detach(拆卸)之前进行,因为通用 detach 会自行释放中断资源。顺序很重要: -1. Release MSI allocation (returns vector to system) -2. Generic detach deallocates the interrupt resource (frees kernel structures) +1. 释放 MSI 分配(将向量返回给系统) +2. 通用 detach 释放中断资源(释放内核结构) -Reversing this order would leak MSI vectors, the kernel would consider them allocated even after the device is gone. +颠倒此顺序会导致 MSI 向量泄漏,内核会认为它们仍处于已分配状态,即使设备已经不存在。 -**Why check `sc_irid`?**: Calling `pci_release_msi` when MSI wasn't allocated is harmless but wastes cycles. More importantly, it documents the code's intent: "if we allocated MSI during attach, release it during detach." This symmetry aids understanding. +**为什么要检查 `sc_irid`?**:在未分配 MSI 的情况下调用 `pci_release_msi` 是无害的,但会浪费 CPU 周期。更重要的是,它记录了代码的意图:“如果在 attach(挂载)期间分配了 MSI,则在 detach 期间释放它。”这种对称性有助于理解。 -The lack of error handling is intentional, `pci_release_msi` cannot meaningfully fail during detach. The device is being removed regardless; if MSI release fails (due to corrupted kernel state), proceeding with detach is still correct. +错误处理的缺失是有意为之。在 detach 期间,`pci_release_msi` 不可能有意义地失败。设备无论如何都会被移除;即使 MSI 释放失败(由于内核状态损坏),继续进行 detach 仍然是正确的。 -##### Delegating to Generic Detach +##### 委托给通用分离 ```c return (uart_bus_detach(dev)); ``` -After PCI-specific resource cleanup, the function calls `uart_bus_attach()` to handle generic UART teardown. This mirrors the attach sequence: PCI-specific code wraps generic code. +在完成 PCI 特定的资源清理后,函数调用 `uart_bus_attach()` 来处理通用的 UART 拆卸。这与 attach 序列对应:PCI 特定代码包裹通用代码。 -**Generic detach operations**: +**通用分离操作**: -**Character device removal**: Close any open file descriptors, destroy `/dev/cuaU*` and `/dev/ttyU*` nodes, and deregister from the TTY layer. +**字符设备移除**:关闭所有打开的文件描述符,销毁 `/dev/cuaU*` 和 `/dev/ttyU*` 节点,并从 TTY 层取消注册。 -**Hardware shutdown**: Disable interrupts at the UART, flush FIFOs, and deassert modem control signals. This prevents the hardware from generating spurious interrupts or asserting control lines after the driver is gone. +**硬件关闭**:在 UART 处禁用中断、刷新 FIFO、并撤销调制解调器控制信号。这可以防止驱动程序移除后硬件产生虚假中断或断言控制线。 -**Resource deallocation**: Free the interrupt resource (the kernel structure, not the MSI vector, that was already released above), unmap I/O ports or memory regions, and release any allocated kernel memory. +**资源释放**:释放中断资源(内核结构,而非 MSI 向量,后者已在上文中释放)、取消映射 I/O 端口或内存区域,并释放任何已分配的内核内存。 -**Console disconnection**: If this device was the system console, redirect console output to an alternative device or disable console output entirely. The system must remain bootable even if the console UART is removed. +**控制台断开**:如果该设备曾是系统控制台,则将控制台输出重定向到替代设备,或完全禁用控制台输出。即使控制台 UART 被移除,系统也必须保持可启动状态。 -**Return value**: `uart_bus_detach()` returns zero on success or an error code on failure. In practice, detach rarely fails, the device is being removed whether or not software cleanup succeeds gracefully. +**返回值**:`uart_bus_detach()` 成功时返回零,失败时返回错误代码。实际上,detach 很少失败,无论软件清理是否优雅完成,设备都会被移除。 -##### Detach Failure Consequences +##### 分离失败的后果 -If detach returns an error, the kernel's response depends on context: +如果 detach 返回错误,内核的响应取决于上下文: -**Driver unload**: If attempting to unload the driver module (`kldunload uart_pci`), the operation fails and the module remains loaded. The device stays attached, preventing resource leaks. +**驱动程序卸载**:如果尝试卸载驱动程序模块(`kldunload uart_pci`),操作将失败,模块保持加载状态。设备保持挂载,防止资源泄漏。 -**Device hot-removal**: If physical removal triggered detach (PCIe hot-unplug), the hardware is already gone. Detach failure is logged but the device tree entry is removed anyway. Resource leaks may occur, but system stability is preserved. +**设备热移除**:如果物理移除触发了 detach(PCIe 热拔出),硬件已不存在。detach 失败会被记录,但设备树条目仍会被移除。可能会发生资源泄漏,但系统稳定性得以保持。 -**System shutdown**: During shutdown, detach failures are ignored. The system is halting regardless, so resource leaks are irrelevant. +**系统关机**:在关机期间,detach 失败会被忽略。系统无论如何都会停机,因此资源泄漏无关紧要。 -Well-designed detach functions should never fail. The uart_pci implementation achieves this by: +设计良好的 detach 函数永远不应失败。`uart_pci` 实现通过以下方式实现这一点: -- Performing only infallible operations (resource release) -- Delegating complex logic to generic code that handles edge cases -- Not requiring hardware responses (hardware might already be disconnected) +- 仅执行不会失败的操作(资源释放) +- 将复杂逻辑委托给处理边缘情况的通用代码 +- 不需要硬件响应(硬件可能已经断开连接) -##### Driver Registration: `DRIVER_MODULE` +##### 驱动程序注册:`DRIVER_MODULE` ```c DRIVER_MODULE(uart, pci, uart_pci_driver, NULL, NULL); ``` -This macro registers the driver with FreeBSD's device framework, making it available for device matching during boot and module load. The macro expands to considerable infrastructure code, but its parameters are straightforward: +该宏将驱动程序注册到 FreeBSD 的设备框架中,使其在启动和模块加载时可用于设备匹配。该宏会扩展为大量基础结构代码,但其参数非常直观: -**`uart`**: The driver name, matching the string in `uart_driver_name`. This name appears in kernel messages, device tree paths, and administrative commands. Multiple drivers can share the same name if they attach to different buses, `uart_pci`, `uart_isa`, and `uart_acpi` all use "uart", distinguishing themselves by the bus they attach to. +**`uart`**:驱动程序名称,与 `uart_driver_name` 中的字符串匹配。此名称出现在内核消息、设备树路径和管理命令中。多个驱动程序可以共享同一名称,只要它们挂载到不同的总线上即可,例如 `uart_pci`、`uart_isa` 和 `uart_acpi` 都使用 "uart",通过它们挂载的总线来区分。 -**`pci`**: The parent bus name. This driver attaches to the PCI bus, so it specifies "pci". The kernel's bus framework uses this to determine when to call the driver's probe function, only PCI devices are offered to `uart_pci`. +**`pci`**:父总线名称。此驱动程序挂载到 PCI 总线,因此指定 "pci"。内核的总线框架使用此信息来决定何时调用驱动程序的 probe(探测)函数,只有 PCI 设备才会被提供给 `uart_pci`。 -**`uart_pci_driver`**: Pointer to the `driver_t` structure defined earlier, containing the method table and softc size. The kernel uses this to invoke driver methods and allocate per-device state. +**`uart_pci_driver`**:指向前面定义的 `driver_t` 结构的指针,包含方法表和 softc 大小。内核使用它来调用驱动程序方法并为每个设备分配状态。 -**`NULL, NULL`**: Two reserved parameters for module initialization hooks. Most drivers don't need these, passing NULL for both. The hooks allow running code when the module loads (before any device attach) or unloads (after all devices detach). Uses include: +**`NULL, NULL`**:模块初始化钩子的两个保留参数。大多数驱动程序不需要它们,都传入 NULL。这些钩子允许在模块加载时(在任何设备附接之前)或卸载时(在所有设备分离之后)运行代码。用途包括: -- Allocating global resources (memory pools, worker threads) -- Registering with subsystems (like the network stack) -- Performing one-time hardware initialization +- 分配全局资源(内存池、工作线程) +- 向子系统(如网络协议栈)注册 +- 执行一次性硬件初始化 -For uart_pci, no module-level initialization is needed, all work happens in probe/attach on a per-device basis. +对于 uart_pci,无需模块级初始化,所有工作都在每个设备的探测/附接中完成。 -##### The Module Lifecycle +##### 模块生命周期 -The `DRIVER_MODULE` macro makes the driver participates in FreeBSD's modular kernel architecture: +`DRIVER_MODULE` 宏使驱动程序参与 FreeBSD 的模块化内核架构: -**Static compilation**: If compiled into the kernel (`options UART` in kernel config), the driver is available at boot. The linker includes `uart_pci_driver` in the kernel's driver table, and PCI enumeration during boot calls its probe function. +**静态编译**:如果编译进内核(在内核配置中使用 `options UART`),驱动程序在启动时可用。链接器将 `uart_pci_driver` 包含在内核的驱动表中,启动时的 PCI 枚举会调用其探测函数。 -**Dynamic loading**: If compiled as a module (`kldload uart_pci.ko`), the module loader processes the `DRIVER_MODULE` registration, adding the driver to the active table. Existing devices are reprobed; new matches trigger attach. +**动态加载**:如果编译为模块(`kldload uart_pci.ko`),模块加载器处理 `DRIVER_MODULE` 注册,将驱动程序添加到活动表中。已存在的设备会被重新探测;新的匹配项会触发附接。 -**Dynamic unloading**: `kldunload uart_pci` attempts to detach all devices managed by this driver. If any detach fails or devices are in use (open file descriptors), unload fails and the module remains. Successful unload removes the driver from the active table. +**动态卸载**:`kldunload uart_pci` 尝试分离此驱动程序管理的所有设备。如果任何分离失败或设备正在使用(打开的文件描述符),卸载失败且模块保留。成功卸载会将驱动程序从活动表中移除。 -##### Relationship to Other UART Drivers +##### 与其他 UART 驱动程序的关系 -The FreeBSD UART subsystem includes multiple bus-specific drivers all sharing generic code: +FreeBSD UART 子系统包含多个特定于总线的驱动程序,它们都共享通用代码: -- `uart_pci.c` - PCI-attached UARTs (this driver) -- `uart_isa.c` - ISA bus UARTs (legacy COM ports) -- `uart_acpi.c` - ACPI-enumerated UARTs (modern laptops/servers) -- `uart_fdt.c` - Flattened Device Tree UARTs (embedded systems, ARM) +- `uart_pci.c` - PCI 附接的 UART(此驱动程序) +- `uart_isa.c` - ISA 总线 UART(传统 COM 端口) +- `uart_acpi.c` - ACPI 枚举的 UART(现代笔记本/服务器) +- `uart_fdt.c` - 扁平设备树 UART(嵌入式系统、ARM) -Each uses `DRIVER_MODULE` to register with its respective bus: +每个都使用 `DRIVER_MODULE` 向各自的总线注册: ```c DRIVER_MODULE(uart, pci, uart_pci_driver, NULL, NULL); // PCI bus @@ -11368,16 +11196,16 @@ DRIVER_MODULE(uart, isa, uart_isa_driver, NULL, NULL); // ISA bus DRIVER_MODULE(uart, acpi, uart_acpi_driver, NULL, NULL); // ACPI bus ``` -All share the name "uart" but attach to different buses. A system might load all four modules simultaneously, with each handling UARTs discovered on its bus. A desktop might have: -- Two ISA COM ports (COM1/COM2 via uart_isa) -- One PCI management controller (IPMI via uart_pci) -- Zero ACPI UARTs (not present) +它们都共享名称 "uart",但附接到不同的总线。系统可能同时加载所有四个模块,每个模块处理其总线上发现的 UART。台式机可能有: +- 两个 ISA COM 端口(通过 uart_isa 的 COM1/COM2) +- 一个 PCI 管理控制器(通过 uart_pci 的 IPMI) +- 零个 ACPI UART(不存在) -Each device gets an independent driver instance, all sharing the generic UART code in `uart_bus.c` and `uart_core.c`. +每个设备获得一个独立的驱动程序实例,所有实例共享 `uart_bus.c` 和 `uart_core.c` 中的通用 UART 代码。 -##### Complete Driver Structure +##### 完整的驱动程序结构 -With all pieces explained, the complete driver structure is: +在解释了所有部分之后,完整的驱动程序结构如下: ```text uart_pci_methods[] -> Method table (probe/attach/detach/resume) @@ -11387,426 +11215,426 @@ uart_pci_driver -> Driver declaration (name, methods, softc size) DRIVER_MODULE() -> Registration (uart, pci, uart_pci_driver) ``` -At runtime, the PCI bus driver discovers devices and consults the registered driver table. For each device, it calls probe functions of matching drivers. The uart_pci probe function examines device IDs against its table, returning success for matches. The kernel then calls attach to initialize the device. Later, detach cleans up when the device is removed. +在运行时,PCI 总线驱动程序发现设备并查询已注册的驱动表。对于每个设备,它调用匹配驱动程序的探测函数。uart_pci 探测函数根据其表检查设备 ID,对匹配返回成功。然后内核调用附接来初始化设备。之后,当设备被移除时,分离进行清理。 -This architecture, method tables, layered initialization, bus-independent core logic, repeats throughout FreeBSD's device driver framework. Understanding it in the uart_pci context prepares you for more complex drivers: network cards, storage controllers, and graphics adapters all follow similar patterns at larger scale. +这种架构——方法表、分层初始化、与总线无关的核心逻辑——在 FreeBSD 的设备驱动框架中反复出现。在 uart_pci 上下文中理解它,为你处理更复杂的驱动程序做好准备:网卡、存储控制器和图形适配器都以更大的规模遵循类似的模式。 -#### Interactive Exercises for `uart(4)` +#### `uart(4)` 的交互练习 -**Goal:** Cement the PCI driver pattern: device identification tables -> probe -> attach -> generic core, with MSI as a bus-specific variation. +**目标:** 巩固 PCI 驱动程序模式:设备标识表 -> 探测 -> 附接 -> 通用核心,其中 MSI 作为特定于总线的变体。 -##### A) Driver Skeleton & Registration +##### A) 驱动程序骨架与注册 -1. Point to the `device_method_t` array and the `driver_t` structure. For each, identify what it declares and how they connect to each other. Quote the relevant lines. Which field in `driver_t` points to the method table? *Hint:* look for `uart_pci_methods[]` and the `uart_pci_driver` definition near the top of the file. +1. 指向 `device_method_t` 数组和 `driver_t` 结构。对于每个,说明它们声明了什么以及如何相互连接。引用相关行。`driver_t` 中的哪个字段指向方法表?*提示:* 在文件头部附近查找 `uart_pci_methods[]` 和 `uart_pci_driver` 的定义。 -2. Where is the `DRIVER_MODULE` macro and which bus does it target? What are the five parameters it receives? Quote it and explain each parameter. *Hint:* `DRIVER_MODULE(uart, pci, ...)` sits at the bottom of the file. +2. `DRIVER_MODULE` 宏位于何处,它针对哪个总线?它接收哪五个参数?请引用该宏并解释每个参数。*提示:* `DRIVER_MODULE(uart, pci, ...)` 位于文件底部。 -##### B) Device Identification and Matching +##### B) 设备标识与匹配 -1. In the `pci_ns8250_ids[]` table, find at least two Intel entries (vendor 0x8086) that demonstrate special handling: one with the `PCI_NO_MSI` flag and one with a non-standard clock frequency (`rclk`). Quote both complete entries and explain what each special parameter means for the hardware. *Hint:* grep the table for `0x8086` and look near the Atom and ValleyView HSUART rows. +1. 在 `pci_ns8250_ids[]` 表中,找到至少两个 Intel 条目(供应商 0x8086),它们展示了特殊处理:一个带有 `PCI_NO_MSI` 标志,另一个带有非标准时钟频率(`rclk`)。引用这两个完整条目并解释每个特殊参数对硬件意味着什么。*提示:* 使用 grep 搜索 `0x8086` 并查看 Atom 和 ValleyView HSUART 行附近。 -2. In `uart_pci_match()`, trace the two-phase matching logic. Where does the first loop match primary IDs (vendor/device)? Where does the second loop match subsystem IDs? What happens if an entry has `subven == 0xffff`? Quote the relevant lines (3-5 lines total). *Hint:* work through the two `for` loops in `uart_pci_match` and note the `subven == 0xffff` wildcard check. +2. 在 `uart_pci_match()` 中,追踪两阶段匹配逻辑。第一个循环在哪里匹配主 ID(供应商/设备)?第二个循环在哪里匹配子系统 ID?如果条目具有 `subven == 0xffff`,会发生什么?引用相关行(总共 3-5 行)。*提示:* 遍历 `uart_pci_match` 中的两个 `for` 循环,注意 `subven == 0xffff` 通配符检查。 -3. Find an example in `pci_ns8250_ids[]` where the same vendor/device pair appears multiple times with different subsystem IDs. Quote 2-3 consecutive entries and explain why this duplication exists. *Hint:* the HP Diva block (vendor 0x103c, device 0x1048) and the Timedia 0x1409/0x7168 block in `pci_ns8250_ids`. +3. 在 `pci_ns8250_ids[]` 中找到一个示例,其中相同的供应商/设备对多次出现,但具有不同的子系统 ID。引用 2-3 个连续条目并解释为什么存在这种重复。*提示:* HP Diva 块(供应商 0x103c,设备 0x1048)以及 Timedia 0x1409/0x7168 块位于 `pci_ns8250_ids` 中。 -##### C) Probe Flow +##### C) 探测流程 -1. In `uart_pci_probe()`, show where the code sets `sc->sc_class` to `&uart_ns8250_class` after successful table matching, and where it then calls `uart_bus_probe()`. Quote both spots (2-3 lines each). *Hint:* the class assignment sits on the success path after `uart_pci_match`, and the `uart_bus_probe` call is the final step before `uart_pci_probe` returns. +1. 在 `uart_pci_probe()` 中,展示代码在成功表匹配后设置 `sc->sc_class` 为 `&uart_ns8250_class` 的位置,以及随后调用 `uart_bus_probe()` 的位置。引用这两处(每处 2-3 行)。*提示:* 类赋值位于 `uart_pci_match` 之后的成功路径上,而 `uart_bus_probe` 调用是 `uart_pci_probe` 返回前的最后一步。 -2. What does `uart_pci_unique_console_match()` do when it finds a unique device that matches a console? Quote the assignment to `sc->sc_sysdev` and the `rclk` synchronization line. Why is clock synchronization necessary? *Hint:* focus on the tail of `uart_pci_unique_console_match`, where `sc->sc_sysdev` is set and `sc->sc_sysdev->bas.rclk` is copied into `sc->sc_bas.rclk`. +2. 当 `uart_pci_unique_console_match()` 找到与控制台匹配的唯一设备时,它做了什么?引用对 `sc->sc_sysdev` 的赋值以及 `rclk` 同步行。为什么时钟同步是必要的?*提示:* 关注 `uart_pci_unique_console_match` 的尾部,其中设置了 `sc->sc_sysdev` 并将 `sc->sc_sysdev->bas.rclk` 复制到 `sc->sc_bas.rclk`。 -3. In `uart_pci_probe()`, explain the fallback path for "Generic SimpleComm" devices. What PCI class, subclass, and progif values trigger this path? Why does the comment say "XXX rclk what to do"? Quote the conditional check and note what configuration is used. *Hint:* look for the local `cid` structure at the top of `uart_pci_probe` and the `pci_get_class/subclass/progif` check further down. +3. 在 `uart_pci_probe()` 中,解释“Generic SimpleComm”设备的回退路径。哪些 PCI 类、子类和 progif 值触发此路径?为什么注释说“XXX rclk what to do”?引用条件检查并指出使用了什么配置。*提示:* 查看 `uart_pci_probe` 顶部的局部 `cid` 结构以及后面更远的 `pci_get_class/subclass/progif` 检查。 -##### D) Attach and Detach +##### D) 连接与分离 -1. In `uart_pci_attach()`, why does the function re-match the device against the ID table when probe already did matching? Quote the line. *Hint:* look for the `uart_pci_match` call near the top of `uart_pci_attach`. +1. 在 `uart_pci_attach()` 中,为什么该函数会重新将设备与 ID 表匹配,而 probe 已经进行了匹配?引用该行。*提示:* 查找 `uart_pci_attach` 顶部附近的 `uart_pci_match` 调用。 -2. Quote the exact conditional that checks MSI eligibility (must prefer single-vector MSI) and the call that allocates it. What happens if MSI allocation fails? Quote 5-7 lines. *Hint:* the `pci_msi_count`/`pci_alloc_msi` block sits just after the `uart_pci_match` call in `uart_pci_attach`. +2. 引用检查 MSI 资格的精确条件(必须优先使用单向量 MSI)以及分配它的调用。如果 MSI 分配失败会发生什么?引用 5-7 行。*提示:* `pci_msi_count`/`pci_alloc_msi` 块位于 `uart_pci_attach` 中 `uart_pci_match` 调用之后。 -3. In `uart_pci_detach()`, quote the two critical operations: MSI release and delegation to generic detach. Why must MSI be released before calling `uart_bus_detach()`? Explain the order dependency. *Hint:* both the `pci_release_msi` call and the `uart_bus_detach` call appear in sequence inside `uart_pci_detach`. +3. 在 `uart_pci_detach()` 中,引用两个关键操作:MSI 释放和委托给通用 detach。为什么必须在调用 `uart_bus_detach()` 之前释放 MSI?解释顺序依赖关系。*提示:* `pci_release_msi` 调用和 `uart_bus_detach` 调用在 `uart_pci_detach` 中顺序出现。 -##### E) Integration: Tracing Complete Flow +##### E) 集成:追踪完整流程 -1. Starting from boot, trace how a Dell RAC 4 (vendor 0x1028, device 0x0012) becomes `/dev/cuaU0`. For each step, quote the relevant line: +1. 从启动开始,追踪 Dell RAC 4(供应商 0x1028,设备 0x0012)如何成为 `/dev/cuaU0`。对于每一步,引用相关行: -- Which table entry matches? -- What clock frequency does it specify? -- What happens in probe? (which class is set? which function is called?) -- What happens in attach? (will it use MSI?) -- Which generic function creates the device node? +- 哪个表条目匹配? +- 它指定了什么时钟频率? +- 在 probe 中发生了什么?(设置了哪个类?调用了哪个函数?) +- 在 attach 中发生了什么?(它会使用 MSI 吗?) +- 哪个通用函数创建了设备节点? -2. A device has vendor 0x8086, device 0xa13d (100 Series Chipset KT). Will it use MSI? Trace through the logic: +2. 某个设备的供应商为 0x8086,设备为 0xa13d(100 系列芯片组 KT)。它会使用 MSI 吗?追踪逻辑: -- Find and quote the table entry -- Check the `rid` field, what flag is present? -- Quote the conditional in `uart_pci_attach()` that checks this flag -- What interrupt mechanism will be used instead? +- 查找并引用表条目 +- 检查 `rid` 字段,存在什么标志? +- 引用 `uart_pci_attach()` 中检查该标志的条件 +- 将使用什么中断机制代替? -##### F) Architecture and Design Patterns +##### F) 架构与设计模式 -1. Compare `if_tuntap.c` (from the previous section) with `uart_bus_pci.c`: +1. 比较 `if_tuntap.c`(来自上一节)与 `uart_bus_pci.c`: -- if_tuntap had ~2200 lines; uart_bus_pci has ~370. Why such a difference in size? -- if_tuntap contained complete device logic; uart_bus_pci is mostly glue code. Where does the actual UART register access, baud rate configuration, and TTY integration happen? (Hint: what function does attach call?) -- Which design approach, monolithic like if_tuntap or layered like uart_bus_pci, makes it easier to support the same hardware on multiple buses (PCI, ISA, USB)? +- `if_tuntap` 大约有 2200 行;`uart_bus_pci` 大约有 370 行。为什么大小差异如此之大? +- `if_tuntap` 包含完整的设备逻辑;`uart_bus_pci` 主要是粘合代码。实际的 UART 寄存器访问、波特率配置和 TTY 集成在哪里发生?(提示:attach 调用了哪个函数?) +- 哪种设计方法(如 `if_tuntap` 的单一式或 `uart_bus_pci` 的分层式)更容易在同一硬件支持多个总线(PCI、ISA、USB)时使用? -2. Imagine you need to add support for: +2. 想象你需要添加对以下设备的支持: -- A new PCI UART: vendor 0xABCD, device 0x1234, standard clock, BAR 0x10 -- An ISA-attached version of the same UART chipset +- 一个新的 PCI UART:厂商 0xABCD,设备 0x1234,标准时钟,BAR 0x10 +- 一个挂接在 ISA 总线上的相同 UART 芯片组版本 - For the PCI variant, what would you modify in `uart_bus_pci.c`? (Quote the structure and location) - For the ISA variant, would you modify `uart_bus_pci.c` at all, or work in a different file? - How many lines of UART register access code would you need to write/duplicate? +对于 PCI 变体,你会修改 `uart_bus_pci.c` 中的什么?(引用结构和位置) +对于 ISA 变体,你会修改 `uart_bus_pci.c` 吗,还是在一个不同的文件中工作? +你需要编写/复制多少行 UART 寄存器访问代码? -#### Stretch (thought experiments) +#### 延伸(思想实验) -Examine the MSI allocation logic in `uart_pci_attach()`. +检查 `uart_pci_attach()` 中的 MSI 分配逻辑。 -The comment says "experience suggests this is only reliable when one MSI vector is advertised." +注释说“经验表明,仅当只通告一个 MSI 向量时,这才可靠。” -1. Why would a simple UART (which only needs one interrupt) ever advertise multiple MSI vectors? -2. What problems might occur with multi-vector MSI that the driver avoids by checking `pci_msi_count(dev) == 1`? -3. If MSI allocation fails silently (the `if` condition is false), the driver continues. Where in the generic attach code will the interrupt resource be allocated instead? What type of interrupt will be used +1. 为什么一个简单的UART(只需要一个中断)会声明多个MSI向量? +2. 驱动程序通过检查 `pci_msi_count(dev) == 1` 来避免的多向量MSI可能引发哪些问题? +3. 如果MSI分配静默失败(`if`条件为false),驱动程序将继续执行。在通用的attach代码中,中断资源将在哪里被分配?将使用哪种类型的中断? -#### Why this matters in your "anatomy" chapter +#### 为什么这在你的“解剖”章节中很重要 -You've just walked a **tiny PCI glue** driver end-to-end. It **matches** devices, chooses a UART **class**, calls a **shared probe/attach** in the subsystem core, and sprinkles light PCI policy (MSI/console). This is the same shape you'll reuse for other buses: **match -> probe -> attach -> core**, plus **resources/IRQs** and **clean detach**. Keep this pattern in mind when you move from pseudo-devices to **real hardware** in later chapters. +你刚刚完整地走了一遍**小型PCI粘合**驱动程序。它**匹配**设备,选择一个UART**类**,调用子系统核心中的**共享probe/attach**,并辅以轻量级PCI策略(MSI/控制台)。这是你将在其他总线上重复使用的相同结构:**match -> probe -> attach -> core**,再加上**资源/IRQ**和**干净的detach**。当你从伪设备转向后续章节的**真实硬件**时,请牢记此模式。 ## 从四个驱动程序到一个心智模型 -You've now walked through four complete drivers, each demonstrating different aspects of FreeBSD's device driver architecture. These weren't arbitrary examples; they form a deliberate progression that reveals the patterns underlying all kernel drivers. +你现在已经完整地学习了四个驱动程序,每个都展示了FreeBSD设备驱动程序架构的不同方面。这些并非随意的示例;它们构成了一个经过设计的递进过程,揭示了所有内核驱动程序背后的模式。 -### The Progression You've Completed +### 你已完成的学习递进 -**Tour 1: `/dev/null`, `/dev/zero`, `/dev/full`** (null.c) +**导览 1:`/dev/null`、`/dev/zero`、`/dev/full`**(null.c) -- Simplest possible character devices -- Static device creation during module load -- Trivial operations: discard writes, return zeros, simulate errors -- No per-device state, no timers, no complexity -- **Key lesson**: The `cdevsw` function dispatch table and basic I/O with `uiomove()` +- 最简单的字符设备 +- 在模块加载期间静态创建设备 +- 简单操作:丢弃写入、返回零、模拟错误 +- 无每设备状态,无定时器,无复杂性 +- **关键教训**:`cdevsw`函数分发表和通过`uiomove()`进行的基本I/O -**Tour 2: LED Subsystem** (led.c) +**导览 2:LED 子系统**(led.c) -- Dynamic device creation on demand -- Subsystem providing both userspace interface and kernel API -- Timer-driven state machine for pattern execution -- Pattern parsing DSL converting user commands to internal codes -- **Key lesson**: Stateful devices, infrastructure drivers, lock separation (mtx vs. sx) +- 按需动态创建设备 +- 提供用户空间接口和内核 API 的子系统 +- 用于模式执行的定时器驱动状态机 +- 将用户命令转换为内部编码的模式解析 DSL +- **关键要点**:有状态设备、基础设施驱动程序、锁分离(mtx vs. sx) -**Tour 3: TUN/TAP Network Tunnels** (if_tuntap.c) +**导览 3:TUN/TAP 网络隧道**(if_tuntap.c) -- Dual character device + network interface -- Bidirectional data flow: kernel <-> userspace packet exchange -- Network stack integration (ifnet, BPF, routing) -- Blocking I/O with proper wakeups (poll/select/kqueue support) -- **Key lesson**: Complex integration bridging two kernel subsystems +- 双重字符设备 + 网络接口 +- 双向数据流:内核 <-> 用户空间数据包交换 +- 网络栈集成(ifnet、BPF、路由) +- 支持正确唤醒的阻塞I/O(poll/select/kqueue支持) +- **关键要点**:桥接两个内核子系统的复杂集成 -**Tour 4: PCI UART Driver** (uart_bus_pci.c) +**导览 4:PCI UART 驱动程序**(uart_bus_pci.c) -- Hardware bus attachment (PCI enumeration) -- Layered architecture: thin bus glue + thick generic core -- Device identification via vendor/device ID tables -- Resource management (BARs, interrupts, MSI) -- **Key lesson**: The probe-attach-detach lifecycle, code reuse through layering +- 硬件总线连接(PCI 枚举) +- 分层架构:薄总线粘合层 + 厚通用核心 +- 通过厂商/设备 ID 表的设备标识 +- 资源管理(BAR、中断、MSI) +- **关键教训**:probe-attach-detach生命周期,通过分层实现的代码复用 -### Patterns That Emerged +### 呈现出的模式 -As you progressed through these drivers, certain patterns appeared repeatedly: +随着你逐步学习这些驱动程序,某些模式反复出现: -#### 1. The Character Device Pattern +#### 1. 字符设备模式 -Every character device follows the same structure, whether it's `/dev/null` or `/dev/tun0`: +无论是`/dev/null`还是`/dev/tun0`,每个字符设备都遵循相同的结构: -- A `cdevsw` structure mapping system calls to functions -- `make_dev()` creating the `/dev` entry -- `si_drv1` linking the device node to per-device state -- `destroy_dev()` cleaning up on removal +- 将系统调用映射到函数的 `cdevsw` 结构 +- 使用`make_dev()`创建`/dev`条目 +- 通过`si_drv1`将设备节点链接到每个设备的状态 +- `destroy_dev()` 在移除时清理 -The complexity varies, null.c has no state, led.c tracks patterns, tuntap tracks network interface, but the skeleton is identical. +复杂度各不相同,null.c没有状态,led.c跟踪模式,tuntap跟踪网络接口,但框架是相同的。 -#### 2. The Dynamic vs. Static Device Pattern +#### 2. 动态设备与静态设备模式 -null.c creates three fixed devices at module load. led.c and tuntap create devices on demand as hardware registers or users open device nodes. This flexibility comes with complexity: +null.c在模块加载时创建三个固定设备。led.c和tuntap则按需创建设备,例如当硬件注册或用户打开设备节点时。这种灵活性伴随着复杂度: -- Unit number allocation (unrhdr) -- Global registries (linked lists) -- More sophisticated locking +- 单元号分配(unrhdr) +- 全局注册表(链表) +- 更复杂的锁定机制 -#### 3. The Subsystem API Pattern +#### 3. 子系统API模式 -led.c demonstrates infrastructure design: it's both a device driver (exposing `/dev/led/*`) and a service provider (exporting `led_create()` for other drivers). This dual role appears throughout FreeBSD drivers that are libraries for other drivers. +led.c演示了基础设施设计:它既是设备驱动程序(暴露`/dev/led/*`),又是服务提供者(为其他驱动程序导出`led_create()`)。这种双重角色在FreeBSD中作为其他驱动程序的库的驱动程序中普遍存在。 -#### 4. The Layered Architecture Pattern +#### 4. 分层架构模式 -uart_bus_pci.c is minimal because most logic lives in uart_bus.c. The pattern: +uart_bus_pci.c 的代码量很少,因为大部分逻辑都位于 uart_bus.c 中。其模式如下: -- Bus-specific code handles: device identification, resource claiming, interrupt setup -- Generic code handles: device initialization, protocol implementation, user interface +- 总线特定代码处理:设备标识、资源声明、中断设置 +- 通用代码处理:设备初始化、协议实现、用户接口 -This separation means the same UART logic works on PCI, ISA, USB, and device-tree platforms. +这种分离意味着同一套 UART 逻辑可以在 PCI、ISA、USB 以及设备树平台上工作。 -#### 5. The Data Movement Patterns +#### 5. 数据移动模式 -You've seen three approaches to transferring data: +你已经看到了三种数据传输方式: -- **Simple**: null_write sets `uio_resid = 0` and returns (discard data) -- **Buffered**: zero_read loops calling `uiomove()` from a kernel buffer -- **Zero-copy**: tuntap uses mbufs for efficient packet handling +- **简单**:null_write 设置 `uio_resid = 0` 并返回(丢弃数据) +- **缓冲型**:zero_read 通过循环调用 `uiomove()` 从内核缓冲区中读取数据 +- **零拷贝**:tuntap 使用 mbuf 实现高效数据包处理 -#### 6. The Synchronization Patterns +#### 6. 同步模式 -Each driver's locking reflects its needs: +每个驱动程序的锁定方式反映了自身的需求: -- null.c: none (stateless devices) -- led.c: two locks (mtx for fast state, sx for slow structure changes) -- tuntap: per-device mutex protecting queues and ifnet state -- uart_pci: minimal (most locking in generic uart_bus layer) +- null.c:无(无状态设备) +- led.c:两个锁(mtx 用于快速状态,sx 用于慢速结构变化) +- tuntap:每设备互斥锁保护队列和 ifnet 状态 +- uart_pci:最小化(大多数锁在通用 uart_bus 层) -#### 7. The Lifecycle Patterns +#### 7. 生命周期模式 -All drivers follow create-operate-destroy, but with variations: +所有驱动程序都遵循“创建-操作-销毁”的流程,但各有差异: -- **Module lifecycle**: null.c's `MOD_LOAD`/`MOD_UNLOAD` events -- **Dynamic lifecycle**: led.c's `led_create()`/`led_destroy()` API -- **Clone lifecycle**: tuntap's on-demand device creation -- **Hardware lifecycle**: uart_pci's probe-attach-detach sequence +- **模块生命周期**:null.c 的 `MOD_LOAD`/`MOD_UNLOAD` 事件 +- **动态生命周期**:led.c 的 `led_create()`/`led_destroy()` API +- **克隆生命周期**:tuntap 的按需设备创建 +- **硬件生命周期**:uart_pci 的探测-连接-分离序列 -### What You Can Now Recognize +### 现在你能识别什么 -After these four tours, when you encounter any FreeBSD driver, you should immediately identify: +经过这四次“巡览”后,当你遇到任意一个 FreeBSD 驱动程序时,你应该能立即识别出: -**What kind of driver is this?** +**这是哪种类型的驱动程序?** -- Character device only? (like null.c) -- Infrastructure/subsystem? (like led.c) -- Dual device/network? (like tuntap) -- Hardware bus attachment? (like uart_pci) +- 仅字符设备?(如 null.c) +- 基础设施/子系统?(如 led.c) +- 双设备/网络?(如 tuntap) +- 硬件总线挂载?(如 uart_pci) -**Where's the state?** +**状态存储在哪里?** -- Global only? (led.c's global list and timer) -- Per-device? (tuntap's softc with queues and ifnet) -- Split? (uart_pci's minimal state + uart_bus's rich state) +- 仅全局?(led.c 的全局列表和定时器) +- 每个设备单独存储?(tuntap 的 softc 包含队列和 ifnet) +- 分离的?(uart_pci 的最小状态 + uart_bus 的丰富状态) -**How's it locked?** +**它是如何加锁的?** -- One mutex for everything? -- Multiple locks for different data/access patterns? -- Handed off to generic code? +- 一个互斥锁处理所有事情? +- 多个锁用于不同的数据/访问模式? +- 交给通用代码处理? -**What's the data path?** +**数据路径是什么?** -- Copying with `uiomove()`? -- Using mbufs? -- Zero-copy techniques? +- 通过 `uiomove()` 进行拷贝? +- 使用 mbuf? +- 零拷贝技术? -**What's the lifecycle?** +**生命周期是怎样的?** -- Fixed (created once at load)? -- Dynamic (created on demand)? -- Hardware-driven (appears/disappears with physical devices)? +- 固定(加载时创建一次)? +- 动态(按需创建)? +- 由硬件驱动(随物理设备出现/消失)? -### The Blueprint Ahead +### 前瞻蓝图 -The document that follows distills these patterns into a quick-reference guide, a checklist and template collection you can use when writing or analyzing drivers. It's organized by integration point (character device, network interface, bus attachment) and captures the critical decisions and invariants you must maintain. +以下文档将这些模式提炼为快速参考指南、检查表和模板集合,可用于编写或分析驱动程序时使用。它按照集成点(字符设备、网络接口、总线连接)组织,并记录了必须维护的关键决策和不变条件。 -Think of the four drivers you've studied as worked examples, and the blueprint as the extracted principles. Together, they form your foundation for understanding FreeBSD's driver architecture. The drivers showed you *how* things work in context; the blueprint reminds you *what* you must do to make your own drivers work correctly. +将您研究的四个驱动程序视为工作示例,而蓝图则是提炼出的原则。它们共同构成了您理解FreeBSD驱动程序架构的基础。驱动程序向您展示了事物在上下文中*如何*工作;蓝图则提醒您需要*做什么*才能让自己的驱动程序正确运行。 -When you're ready to write your own driver or modify an existing one, start with the blueprint's self-check questions. Then refer back to the appropriate tour (null.c for basic devices, led.c for timers and APIs, tuntap for networking, uart_pci for hardware) to see those patterns in complete implementations. +当您准备好编写自己的驱动程序或修改现有驱动程序时,从蓝图的自检问题开始。然后参考相应的导览(基本设备参考null.c,定时器和API参考led.c,网络参考tuntap,硬件参考uart_pci),查看这些模式在完整实现中的体现。 -You're now equipped to navigate the kernel's device drivers, not as intimidating black boxes, but as variations on patterns you've internalized through hands-on study. +现在您已经具备导航内核设备驱动程序的能力,不再将它们视为令人生畏的黑盒,而是通过实践学习内化了的模式变体。 ## 驱动程序解剖蓝图(FreeBSD 14.3) -This is your quick-reference map for FreeBSD drivers. It captures the shape (the moving parts and where they live), the contract (what the kernel expects from you), and the pitfalls (what breaks under load). Use it as the checklist before and after you code. +这是FreeBSD驱动程序的快速参考地图。它捕捉了形状(活动部件及其位置)、契约(内核期望您做什么)以及陷阱(负载下会出什么问题)。在编写代码前后将其用作检查清单。 -### Core Skeleton: What Every Driver Needs +### 核心骨架:每个驱动程序需要什么 -**Identify your integration point:** +**确定您的集成点:** -**Character device (devfs)** -> `struct cdevsw` + `make_dev*()`/`destroy_dev()` +**字符设备(devfs)** -> `struct cdevsw` + `make_dev*()`/`destroy_dev()` -- Entry points: open/read/write/ioctl/poll/kqfilter -- Example: null.c, led.c +- 入口点:open/read/write/ioctl/poll/kqfilter +- 示例:null.c, led.c -**Network interface (ifnet)** -> `if_alloc()`/`if_attach()`/`if_free()` + optional cdev +**网络接口(ifnet)** -> `if_alloc()`/`if_attach()`/`if_free()` + 可选 cdev -- Callbacks: `if_transmit` or `if_start`, input via `netisr_dispatch()` -- Example: if_tuntap.c +- 回调:`if_transmit` 或 `if_start`,通过 `netisr_dispatch()` 输入 +- 示例:if_tuntap.c -**Bus-attached (e.g., PCI)** -> `device_method_t[]` + `driver_t` + `DRIVER_MODULE()` +**总线连接(例如 PCI)** -> `device_method_t[]` + `driver_t` + `DRIVER_MODULE()` -- Lifecycle: probe/attach/detach (+ suspend/resume if needed) -- Example: uart_bus_pci.c +- 生命周期:probe/attach/detach(+ 需要时 suspend/resume) +- 示例:uart_bus_pci.c -**Minimal invariants (commit these to memory):** +**最小不变条件(请牢记):** -- Every object you create (cdev, ifnet, callout, taskqueue, resource) has a symmetric destroy/free on error paths and during detach/unload -- Concurrency is explicit: if you touch state from multiple contexts (syscall path, timeout, rx/tx, interrupt), you hold the right lock or design for lock-free with strict rules -- Resource cleanup must happen in reverse order of allocation +- 您创建的每个对象(cdev, ifnet, callout, taskqueue, resource)在错误路径和分离/卸载期间都有对称的销毁/释放 +- 并发是显式的:如果从多个上下文(系统调用路径、超时、rx/tx、中断)接触状态,则需持有正确的锁,或通过严格规则设计无锁方案 +- 资源清理必须按分配顺序的逆序进行 -### Character Device Blueprint +### 字符设备蓝图 -**Shape:** +**形态:** -- `static struct cdevsw` with only what you implement; leave others `nullop` or omit -- Module or init hook creates nodes: `make_dev_credf()`/`make_dev_s()` -- Keep a `struct cdev *` to tear down later +- `static struct cdevsw` 只包含您实现的内容;其他部分保留 `nullop` 或省略 +- 模块或初始化钩子创建节点:`make_dev_credf()`/`make_dev_s()` +- 保留一个 `struct cdev *` 供以后拆除 -**Entry points:** +**入口点:** -**read**: Loop while `uio->uio_resid > 0`; move bytes with `uiomove()`; return early on error +**read**: 当 `uio->uio_resid > 0` 时循环;使用 `uiomove()` 移动字节;出错时提前返回 -- Example: zero_read loops copying from pre-zeroed kernel buffer +- 示例:zero_read 循环从预置零的内核缓冲区复制 -**write**: Either consume (`uio_resid = 0; return 0;`) or fail (`return ENOSPC/EIO/...`) +**write(写入)**:要么消耗(`uio_resid = 0; return 0;`)要么失败(`return ENOSPC/EIO/...`) -- No partial writes unless you mean it -- Example: null_write consumes all; full_write always fails +- 除非你有意为之,否则不要部分写入 +- 示例:null_write 消耗所有数据;full_write 总是失败 -**ioctl**: Small `switch(cmd)`; return 0, specific errno, or `ENOIOCTL` +**ioctl**:小型的 `switch(cmd)`;返回 0、特定 errno 或 `ENOIOCTL` -- Handle standard terminal ioctls (`FIONBIO`, `FIOASYNC`) even if they're no-ops -- Example: null_ioctl handles kernel dump configuration +- 处理标准终端 ioctl(`FIONBIO`、`FIOASYNC`),即使它们是空操作 +- 示例:null_ioctl 处理内核转储配置 -**poll/kqueue (optional)**: Wire readiness + notifications if userspace blocks +**poll/kqueue(可选)**:如果用户空间阻塞,连接就绪状态 + 通知 -- Example: tuntap's poll checks queue and registers via `selrecord()` +- 示例:tuntap 的 poll 检查队列并通过 `selrecord()` 注册 -**Concurrency & timers:** +**并发与定时器:** -- If you have periodic work (e.g., LED blink), use a callout bound to the right mutex -- Arm/re-arm responsibly; stop it in teardown when the last user goes away -- Example: led.c's `callout_init_mtx(&led_ch, &led_mtx, 0)` +- 如果有周期性工作(例如LED闪烁),使用绑定到正确互斥锁的callout +- 负责任地启动/重新启动;在最后一个用户离开时的拆除阶段停止它 +- 示例:led.c 的 `callout_init_mtx(&led_ch, &led_mtx, 0)` -**Teardown:** +**拆除:** -- `destroy_dev()`, stop callouts/taskqueues, free buffers -- Clear pointers (e.g., `si_drv1 = NULL`) under lock before freeing -- Example: led_destroy's two-phase cleanup (mtx then sx) +- `destroy_dev()`,停止 callouts/taskqueues,释放缓冲区 +- 在释放之前,在锁下清除指针(例如 `si_drv1 = NULL`) +- 示例:led_destroy 的两阶段清理(先 mtx 后 sx) -**Check before lab:** +**实验前检查:** -- Can you match each user-visible behavior to the exact entry point? -- Are all allocations paired with frees on every error path? +- 您能否将每个用户可见的行为匹配到确切的入口点? +- 所有分配是否在每个错误路径上都与释放配对? -### Network Pseudo-Interface Blueprint +### 网络伪接口蓝图 -**Two faces:** +**两面性:** -- Character device side (`/dev/tunN`, `/dev/tapN`) with open/read/write/ioctl/poll -- ifnet side (`ifconfig tun0 ...`) with attach, flags, link state, and BPF hooks +- 字符设备侧(`/dev/tunN`,`/dev/tapN`)包含 open/read/write/ioctl/poll +- ifnet 侧(`ifconfig tun0 ...`)包含 attach、flags、link state 和 BPF 钩子 -**Data flow:** +**数据流:** -**Kernel -> user (read)**: +**内核 -> 用户(读取)**: -- Dequeue packet (mbuf) from your queue -- Block until available unless `O_NONBLOCK` (then `EWOULDBLOCK`) -- Copy optional headers first (virtio/ifhead), then payload via `m_mbuftouio()` -- Free mbuf with `m_freem()` -- Example: tunread's loop with `mtx_sleep()` for blocking +- 从您的队列中取出数据包(mbuf) +- 阻塞直到可用,除非设置了 `O_NONBLOCK`(然后返回 `EWOULDBLOCK`) +- 先复制可选的头部(virtio/ifhead),然后通过 `m_mbuftouio()` 复制有效载荷 +- 使用 `m_freem()` 释放 mbuf +- 示例:tunread 中使用 `mtx_sleep()` 实现阻塞的循环 -**User -> kernel (write)**: +**用户 -> 内核(写入)**: -- Build mbuf with `m_uiotombuf()` -- Decide L2 vs L3 path -- For L3: pick AF and `netisr_dispatch()` -- For L2: validate destination (drop frames real NIC wouldn't receive unless promisc) -- Example: tunwrite_l3 dispatches via NETISR_IP/NETISR_IPV6 +- 使用 `m_uiotombuf()` 构建 mbuf +- 决定 L2 还是 L3 路径 +- 对于 L3:选择 AF 并使用 `netisr_dispatch()` +- 对于 L2:验证目标(丢弃真实网卡不会接收的帧,除非混杂模式) +- 示例:tunwrite_l3 通过 NETISR_IP/NETISR_IPV6 分发 -**Lifecycle:** +**生命周期:** -- Clone or first open creates cdev and softc -- Then `if_alloc()`/`if_attach()` and `bpfattach()` -- Open can raise link up; close can drop it -- Example: tuncreate builds ifnet, tunopen marks link UP +- 克隆或首次打开创建 cdev 和 softc +- 然后 `if_alloc()`/`if_attach()` 和 `bpfattach()` +- 打开可以提升链路;关闭可以降低链路 +- 示例:tuncreate 构建 ifnet,tunopen 标记链路 UP -**Notify readers:** +**通知读取者:** -- `wakeup()`, `selwakeuppri()`, `KNOTE()` when packets arrive -- Example: tunstart's triple notification when packet enqueued +- 当数据包到达时调用 `wakeup()`、`selwakeuppri()`、`KNOTE()` +- 示例:tunstart 在数据包入队时的三重通知 -**Check before lab:** +**实验前检查:** -- Do you know which paths block and which return immediately? -- Is your maximum I/O size bounded (MRU + headers)? -- Are wakeups fired on every packet enqueue? +- 你是否知道哪些路径会阻塞、哪些会立即返回? +- 你的最大 I/O 大小是否有界限(MRU + 头部开销)? +- 是否每个数据包入队时都会触发唤醒? -### PCI Glue Blueprint +### PCI 粘合蓝图 -**Match -> Probe -> Attach -> Detach:** +**匹配 -> 探测 -> 连接 -> 分离:** -**Match**: Vendor/device(/subvendor/subdevice) table; fall back to class/subclass when needed +**匹配**:厂商/设备(/子厂商/子设备)表;必要时回退到类别/子类别 -- Example: uart_pci_match's two-phase search (primary IDs then subsystem) +- 示例:uart_pci_match 的两阶段搜索(先主 ID 后子系统) -**Probe**: Choose driver class, compute parameters (reg shift, rclk, BAR RID), then call shared bus probe +**探测**:选择驱动程序类别,计算参数(寄存器移位、rclk、BAR RID),然后调用共享总线探测 -- Example: uart_pci_probe sets `sc->sc_class = &uart_ns8250_class` +- 示例:uart_pci_probe 设置 `sc->sc_class = &uart_ns8250_class` -**Attach**: Allocate interrupts (prefer single-vector MSI if supported), then delegate to subsystem +**连接**:分配中断(如果支持则优先使用单向量 MSI),然后委托给子系统 -- Example: uart_pci_attach's conditional MSI allocation +- 示例:uart_pci_attach 的条件 MSI 分配 -**Detach**: Release MSI/IRQ, then delegate to subsystem detach +**分离**:释放 MSI/IRQ,然后委托给子系统分离 -- Example: uart_pci_detach checks `sc_irid` and releases MSI if allocated +- 示例:uart_pci_detach 检查 `sc_irid` 并在分配时释放 MSI -**Resources:** +**资源:** -- Map BARs, allocate IRQs, hand resources to core -- Track IDs so you can release them symmetrically -- Example: `id->rid & PCI_RID_MASK` extracts BAR number +- 映射 BAR,分配 IRQ,将资源交给核心 +- 跟踪 ID,以便对称地释放它们 +- 示例:`id->rid & PCI_RID_MASK` 提取 BAR 编号 -**Check before lab:** +**实验前检查:** -- Do you handle the "no match" path cleanly (`ENXIO`)? -- Are you leak-free across any mid-attach failure? -- Do you check for quirks (like `PCI_NO_MSI` flag)? +- 你是否干净地处理了“无匹配”路径(返回 `ENXIO`)? +- 在中间附着失败的任何过程中,是否没有内存泄漏? +- 你是否检查了特殊情形(如 `PCI_NO_MSI` 标志)? -### Locking & Concurrency Cheatsheet +### 加锁与并发速查表 -**Fast path data movement** (read/write, rx/tx): +**快速路径数据移动**(读/写、收/发): -- Protect queues and state with a mutex -- Minimize hold time; never sleep while holding if avoidable -- Example: tuntap's `tun_mtx` protecting send queue +- 使用互斥锁保护队列和状态 +- 最小化持有时间;如果可避免,不要在持有锁时睡眠 +- 示例:tuntap 的 `tun_mtx` 保护发送队列 -**Configuration / topology** (create/destroy, link up/down): +**配置/拓扑**(创建/销毁、链路激活/关闭): -- Typically an sx lock or higher-level serialization -- Example: led.c's `led_sx` for device creation/destruction +- 通常使用 sx 锁或更高级别的序列化 +- 示例:led.c 的 `led_sx` 用于设备创建/销毁 -**Timer/callout**: +**定时器/callout**: -- Use `callout_init_mtx(&callout, &mtx, flags)` so timeout runs with your mutex held -- Example: led.c's timer automatically holds `led_mtx` +- 使用 `callout_init_mtx(&callout, &mtx, flags)`,以便超时运行在持有互斥锁的状态下 +- 示例:led.c 的定时器自动持有 `led_mtx` -**User-space notifications**: +**用户空间通知**: -- After enqueuing: `wakeup(tp)`, `selwakeuppri(&sel, PRIO)`, `KNOTE(&klist, NOTE_*)` -- Example: tunstart's triple notification pattern +- 入队后:`wakeup(tp)`、`selwakeuppri(&sel, PRIO)`、`KNOTE(&klist, NOTE_*)` +- 示例:tunstart 的三重通知模式 -**Lock ordering rules:** +**锁顺序规则:** -- Never acquire locks in inconsistent order -- Document your lock hierarchy -- Example: led.c acquires `led_mtx` then releases before taking `led_sx` +- 绝不以不一致的顺序获取锁 +- 记录你的锁层次结构 +- 示例:led.c 先获取 `led_mtx`,然后在释放后获取 `led_sx` -### Data Movement Patterns +### 数据移动模式 -**`uiomove()` loop for cdev read/write:** +**用于 cdev 读/写的 `uiomove()` 循环:** -- Cap chunk size to a safe buffer (avoid giant copies) -- Check and handle errors on each iteration -- Example: zero_read limits to `ZERO_REGION_SIZE` per iteration +- 将块大小限制在安全缓冲区范围内(避免巨型拷贝) +- 在每次迭代时检查并处理错误 +- 示例:zero_read 每次迭代限制为 `ZERO_REGION_SIZE` -**mbuf path for networking:** +**用于网络的 mbuf 路径:** -**User -> kernel**: +**用户 -> 内核**: ```c m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR); @@ -11814,7 +11642,7 @@ m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR); netisr_dispatch(isr, m); ``` -**Kernel -> user**: +**内核 -> 用户**: ```c // optional header to user (uiomove()) @@ -11822,69 +11650,69 @@ m_mbuftouio(uio, m, 0); m_freem(m); ``` -Example: tunwrite builds mbuf; tunread extracts to userspace +示例:tunwrite 构建 mbuf;tunread 提取到用户空间 -### Common Patterns From the Tours +### 导览中的常见模式 -**Pattern: Shared `cdevsw`, per-device state via `si_drv1`** +**模式:共享 `cdevsw`,通过 `si_drv1` 实现每设备状态** -- One function table, many device instances -- Example: led.c shares `led_cdevsw` across all LEDs -- State accessed via `sc = dev->si_drv1` +- 一个函数表,多个设备实例 +- 示例:led.c 在所有 LED 间共享 `led_cdevsw` +- 通过 `sc = dev->si_drv1` 访问状态 -**Pattern: Subsystem providing both APIs** +**模式:提供两种 API 的子系统** -- Userspace interface (character device) -- Kernel API (function calls) -- Example: led.c's `led_write()` vs. `led_set()` +- 用户空间接口(字符设备) +- 内核 API(函数调用) +- 示例:led.c 的 `led_write()` 与 `led_set()` -**Pattern: Timer-driven state machine** +**模式:定时器驱动的状态机** -- Reference counter tracks active items -- Timer reschedules only when work remains -- Example: led.c's `blinkers` counter gates timer +- 引用计数器跟踪活动项 +- 只有当仍有工作待完成时,定时器才会重新调度 +- 示例:led.c 的 `blinkers` 计数器控制定时器 -**Pattern: Two-phase cleanup** +**模式:两阶段清理** -- Phase 1: Make invisible (clear pointers, remove from lists) -- Phase 2: Free resources -- Example: led_destroy clears `si_drv1` before destroying device +- 阶段1:使其不可见(清除指针、从链表中移除) +- 阶段 2:释放资源 +- 示例:led_destroy 在销毁设备前清除 `si_drv1` -**Pattern: Unit number allocation** +**模式:单元号分配** -- Use `unrhdr` for dynamic assignment -- Prevents conflicts in multi-instance devices -- Example: led.c's `led_unit` pool +- 使用 `unrhdr` 进行动态分配 +- 防止多实例设备中的冲突 +- 示例:led.c 的 `led_unit` 池 -### Errors, Edge Cases, and User Experience +### 错误、边界情况和用户体验 -**Error handling:** +**错误处理:** -- Prefer clear errno over silent behavior unless silence is part of the contract -- Example: tunwrite silently ignores writes when interface down (expected behavior) -- Example: led_write returns `EINVAL` for bad commands (error condition) +- 优先使用明确的 errno 而不是静默行为,除非静默行为是约定的一部分 +- 示例:tunwrite 在接口关闭时静默忽略写入(这是预期行为) +- 示例:led_write 对错误命令返回 `EINVAL`(错误条件) -**Bound inputs:** +**边界输入:** -- Always validate sizes, counts, indices -- Example: led_write rejects commands over 512 bytes -- Example: tuntap checks against MRU + headers +- 始终验证大小、计数、索引 +- 示例:led_write 拒绝超过512字节的命令 +- 示例:tuntap 针对 MRU + 头部进行检查 -**Default to fail fast:** +**默认为快速失败:** -- Unsupported ioctl -> `ENOIOCTL` -- Invalid flags -> `EINVAL` -- Malformed frames -> drop and increment error counter +- 不支持的 ioctl -> `ENOIOCTL` +- 无效标志 -> `EINVAL` +- 格式错误的帧 -> 丢弃并递增错误计数器 -**Module unload:** +**模块卸载:** -- Think about impact on active users -- Don't yank foundational devices from busy systems -- Example: null.c can be unloaded; led.c cannot (no unload handler) +- 考虑对活跃用户的影响 +- 不要从繁忙系统中强行移除基础设备 +- 示例:null.c 可以被卸载;led.c 不能(没有卸载处理程序) -### Minimal Templates +### 最小模板 -#### Character Device (Read/Write/Ioctl Only) +#### 字符设备(仅读/写/Ioctl) ```c static d_read_t foo_read; @@ -11933,7 +11761,7 @@ foo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, } ``` -#### Dynamic Device Registration +#### 动态设备注册 ```c static struct unrhdr *foo_units; @@ -11977,7 +11805,7 @@ foo_destroy(struct cdev *dev) } ``` -#### PCI Glue (Probe/Attach/Detach) +#### PCI 粘合(探测/连接/分离) ```c static int foo_probe(device_t dev) @@ -12028,50 +11856,50 @@ static driver_t foo_driver = { DRIVER_MODULE(foo, pci, foo_driver, NULL, NULL); ``` -### Pre-Lab Self-Check (2 Minutes) +### 实验前自检(2 分钟) -Ask yourself these questions before writing code: +在编写代码之前,问自己这些问题: -1. Which integration point am I targeting (devfs, ifnet, PCI)? -2. Do I know my entry points and what each must return on success/failure? -3. What are my locks and which contexts touch each field? -4. Can I list every resource I allocate and where I free it on: +1. 我的目标集成点是什么(devfs、ifnet、PCI)? +2. 我知道我的入口点以及每个入口点在成功/失败时必须返回什么吗? +3. 我的锁是什么,哪些上下文访问每个字段? +4. 我能列出我分配的每个资源以及在以下情况下在哪里释放它: - - Success path - - Mid-attach failure - - Detach/unload + - 成功路径 + - attach 中途失败 + - 分离/卸载 -5. Have I studied a similar driver from the tours? +5. 我是否研究过导览中类似的驱动程序? - - null.c for simple character devices - - led.c for dynamic devices and timers - - tuntap for network integration - - uart_pci for hardware attachment + - null.c 用于简单字符设备 + - led.c 用于动态设备和定时器 + - tuntap 用于网络集成 + - uart_pci 用于硬件连接 -### After-Lab Reflection (5 minutes) +### 实验后反思(5 分钟) -After writing or modifying code, verify: +编写或修改代码后,验证: -1. Did I leak anything on an early return? -2. Did I block in a context that shouldn't sleep? -3. Did I notify userspace/kernel peers after enqueuing work? -4. Can I point from a user-visible behavior back to the specific source lines? -5. Does my locking follow a consistent hierarchy? -6. Are my error messages helpful for debugging? +1. 我在提前返回时是否泄漏了什么? +2. 我是否在不应该睡眠的上下文中阻塞了? +3. 我在入队工作后是否通知了用户空间/内核同伴? +4. 我能否从用户可见的行为指向特定的源代码行? +5. 我的锁定是否遵循一致的层次结构? +6. 我的错误消息对调试有帮助吗? -### Common Pitfalls and How to Avoid Them +### 常见陷阱及如何避免 -This section catalogs the mistakes that cause the most pain in driver development, silent corruption, deadlocks, panics, and resource leaks. Each pitfall includes the symptom, the root cause, and the correct pattern to follow. +本节列出了驱动程序开发中造成最大痛苦的错误——静默损坏、死锁、panic 和资源泄漏。每个陷阱包括症状、根本原因和应遵循的正确模式。 -#### Data Movement Errors +#### 数据移动错误 -##### **Pitfall: Forgetting to update `uio_resid`** +##### **陷阱:忘记更新 `uio_resid`** -**Symptom**: Infinite loops in read/write handlers, or userspace receiving wrong byte counts. +**症状**:read/write 处理程序中的无限循环,或用户空间收到错误的字节数。 -**Root cause**: The kernel uses `uio_resid` to track remaining bytes. If you don't decrement it, the kernel thinks no progress was made. +**根本原因**:内核使用 `uio_resid` 跟踪剩余字节。如果你不递减它,内核认为没有进展。 -**Wrong**: +**错误做法**: ```c static int @@ -12082,7 +11910,7 @@ bad_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c static int @@ -12093,17 +11921,17 @@ good_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: Always ask "how many bytes did I actually process?" and update `uio_resid` accordingly. Even if you discard data (like `/dev/null`), you must mark it consumed. +**如何避免**:始终询问“我实际处理了多少字节?”并相应地更新 `uio_resid`。即使你丢弃了数据(如 `/dev/null`),也必须标记为已消费。 -**Related**: Partial transfers are dangerous. If you process some bytes but then fail, you must update `uio_resid` to reflect what was actually transferred before returning the error, or userspace will retry with the wrong offset. +**关联**:部分传输很危险。如果你处理了一些字节但随后失败,你必须在返回错误之前更新 `uio_resid` 以反映实际传输了多少,否则用户空间会使用错误的偏移量重试。 -##### **Pitfall: Not bounding chunk sizes in `uiomove()` loops** +##### **陷阱:未在 `uiomove()` 循环中限制块大小** -**Symptom**: Stack overflow if copying to stack buffer, kernel panic on huge allocations. +**症状**:如果拷贝到栈缓冲区则栈溢出,大分配时内核崩溃。 -**Root cause**: User requests can be arbitrarily large. Copying multi-megabyte transfers in one shot exhausts resources. +**根本原因**:用户请求可能任意大。一次性拷贝数兆字节的传输会耗尽资源。 -**Wrong**: +**错误**: ```c static int @@ -12115,7 +11943,7 @@ bad_read(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c #define CHUNK_SIZE 4096 @@ -12138,15 +11966,15 @@ good_read(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: Always loop with a reasonable chunk size (typically 4KB-64KB). Study `zero_read` in null.c, it limits transfers to `ZERO_REGION_SIZE` per iteration. +**如何避免**:始终使用合理块大小(通常4KB-64KB)进行循环。研究 null.c 中的 `zero_read`,它将每次迭代的传输限制为 `ZERO_REGION_SIZE`。 -##### **Pitfall: Accessing user memory directly from kernel** +##### **陷阱:从内核直接访问用户内存** -**Symptom**: Security vulnerabilities, kernel crashes on invalid pointers. +**症状**:安全漏洞、内核在无效指针时崩溃。 -**Root cause**: Kernel and user memory spaces are separate. Dereferencing user pointers directly bypasses protection. +**根本原因**:内核和用户内存空间是分离的。直接解引用用户指针会绕过保护。 -**Wrong**: +**错误**: ```c static int @@ -12157,7 +11985,7 @@ bad_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *t } ``` -**Correct**: +**正确**: ```c static int @@ -12174,17 +12002,17 @@ good_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread * } ``` -**How to avoid**: Never dereference pointers received from userspace. Use `copyin()`, `copyout()`, `copyinstr()`, or `uiomove()` for all user <-> kernel transfers. These functions validate addresses and handle page faults safely. +**如何避免**:永远不要解引用从用户空间接收的指针。对所有用户<->内核传输使用 `copyin()`、`copyout()`、`copyinstr()` 或 `uiomove()`。这些函数会验证地址并安全地处理缺页。 -#### Locking Disasters +#### 加锁灾难 -##### **Pitfall: Holding locks across `uiomove()`** +##### **陷阱:在 `uiomove()` 期间持有锁** -**Symptom**: System deadlock when user memory is paged out. +**症状**:当用户内存被换出时系统死锁。 -**Root cause**: `uiomove()` can page fault, which may need to acquire VM locks. If you hold another lock during the fault, and that lock is needed by the paging path, deadlock results. +**根本原因**:`uiomove()` 可能触发缺页,这可能需要获取VM锁。如果你在缺页期间持有另一个锁,并且该锁是换页路径所需的,则会导致死锁。 -**Wrong**: +**错误**: ```c static int @@ -12198,7 +12026,7 @@ bad_read(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c static int @@ -12221,17 +12049,17 @@ good_read(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: Always release locks before `uiomove()`, `copyin()`, `copyout()`. Snapshot the data you need while locked, then transfer it to userspace unlocked. +**如何避免**:始终在 `uiomove()`、`copyin()`、`copyout()` 之前释放锁。在锁定时快照所需数据,然后在解锁状态下将其传输到用户空间。 -**Exception**: Some sleep-capable locks (sx locks with `SX_DUPOK`) can be held across user memory access if carefully designed, but mutexes never can. +**例外**:一些可睡眠的锁(使用 `SX_DUPOK` 的 sx 锁)如果经过精心设计,可以在用户内存访问期间持有,但互斥锁永远不能。 -##### **Pitfall: Inconsistent lock ordering** +##### **陷阱:不一致的锁顺序** -**Symptom**: Deadlock when two threads acquire the same locks in opposite orders. +**症状**:当两个线程以相反顺序获取相同锁时发生死锁。 -**Root cause**: Lock ordering violations create circular wait conditions. +**根本原因**:锁顺序违规创建了循环等待条件。 -**Wrong**: +**错误**: ```c /* Thread A */ @@ -12243,7 +12071,7 @@ mtx_lock(&lock_b); mtx_lock(&lock_a); /* Order: B then A - DEADLOCK! */ ``` -**Correct**: +**正确**: ```c /* Establish hierarchy: always lock_a before lock_b */ @@ -12257,20 +12085,20 @@ mtx_lock(&lock_a); /* Same order everywhere */ mtx_lock(&lock_b); ``` -**How to avoid**: +**如何避免**: -1. Document your lock hierarchy in comments at the top of the file -2. Always acquire locks in the same order throughout the driver -3. Use `WITNESS` kernel option during development to detect violations -4. Study led.c: it acquires `led_mtx` first, releases it, then acquires `led_sx`, never holds both simultaneously +1. 在文件顶部的注释中记录你的锁层次结构 +2. 始终在整个驱动程序中以相同顺序获取锁 +3. 在开发期间使用 `WITNESS` 内核选项来检测违反情况 +4. 学习 led.c:它先获取 `led_mtx`,释放它,然后获取 `led_sx`,从不同时持有两者 -##### **Pitfall: Forgetting to initialize locks** +##### **陷阱:忘记初始化锁** -**Symptom**: Kernel panic with "lock not initialized" or immediate hang on first lock acquisition. +**症状**:内核恐慌,提示“锁未初始化”,或在首次获取锁时立即挂起。 -**Root cause**: Lock structures must be explicitly initialized before use. +**根本原因**:锁结构必须在使用前显式初始化。 -**Wrong**: +**错误**: ```c static struct mtx my_lock; /* Declared but not initialized */ @@ -12282,7 +12110,7 @@ foo_attach(device_t dev) } ``` -**Correct**: +**正确**: ```c static struct mtx my_lock; @@ -12296,20 +12124,20 @@ foo_init(void) SYSINIT(foo, SI_SUB_DRIVERS, SI_ORDER_FIRST, foo_init, NULL); ``` -**How to avoid**: +**如何避免**: -- Initialize locks in module load handler, `SYSINIT`, or attach function -- Use `mtx_init()`, `sx_init()`, `rw_init()` as appropriate -- For callouts: `callout_init_mtx()` associates timer with lock -- Study led.c's `led_drvinit()`: initializes all locks before any devices are created +- 在模块加载处理程序、`SYSINIT` 或连接函数中初始化锁 +- 适当使用 `mtx_init()`、`sx_init()`、`rw_init()` +- 对于 callout:`callout_init_mtx()` 将定时器与锁关联 +- 研究 led.c 中的 `led_drvinit()`:在创建设备之前初始化所有锁 -##### **Pitfall: Destroying locks while threads still hold them** +##### **陷阱:在线程仍然持有锁时销毁锁** -**Symptom**: Kernel panic during module unload or device detach. +**症状**:在模块卸载或设备分离时内核恐慌。 -**Root cause**: Lock structures must remain valid until all users are done. +**根本原因**:锁结构必须在所有使用者完成之前保持有效。 -**Wrong**: +**错误**: ```c static int @@ -12321,7 +12149,7 @@ bad_detach(device_t dev) } ``` -**Correct**: +**正确**: ```c static int @@ -12334,21 +12162,21 @@ good_detach(device_t dev) } ``` -**How to avoid**: +**如何避免**: -- `destroy_dev()` blocks until all open file descriptors close and in-progress operations complete -- Destroy locks only after devices/resources are gone -- For global locks: destroy in module unload or never (if module can't unload) +- `destroy_dev()` 会阻塞,直到所有打开的文件描述符关闭且正在进行的操作完成 +- 只有在设备/资源消失后才销毁锁 +- 对于全局锁:在模块卸载时销毁,或者永远不销毁(如果模块无法卸载) -#### Resource Management Failures +#### 资源管理失败 -##### **Pitfall: Leaking resources on error paths** +##### **陷阱:在错误路径上泄漏资源** -**Symptom**: Memory leaks, device node leaks, eventual resource exhaustion. +**症状**:内存泄漏、设备节点泄漏、最终资源耗尽。 -**Root cause**: Early returns skip cleanup code. +**根本原因**:提前返回跳过了清理代码。 -**Wrong**: +**错误**: ```c static int @@ -12368,7 +12196,7 @@ bad_attach(device_t dev) } ``` -**Correct**: +**正确**: ```c static int @@ -12396,20 +12224,20 @@ fail: } ``` -**How to avoid**: +**如何避免**: -- Use a single `fail:` label at the end of the function -- Check which resources were allocated and free only those -- Initialize pointers to NULL so you can check them -- Consider: every `malloc()` needs a `free()`, every `make_dev()` needs a `destroy_dev()` +- 在函数末尾使用单个 `fail:` 标签 +- 检查已分配了哪些资源,并仅释放这些资源 +- 将指针初始化为 NULL 以便检查 +- 考虑:每个 `malloc()` 都需要一个 `free()`,每个 `make_dev()` 都需要一个 `destroy_dev()` -##### **Pitfall: Use-after-free in concurrent cleanup** +##### **陷阱:并发清理中的释放后使用** -**Symptom**: Kernel panic with "page fault in kernel mode", often intermittent. +**症状**:内核崩溃,出现“内核模式下的页错误”,通常为间歇性。 -**Root cause**: One thread frees memory while another thread still accesses it. +**根本原因**:一个线程释放内存而另一个线程仍在访问它。 -**Wrong**: +**错误**: ```c void @@ -12422,7 +12250,7 @@ bad_destroy(struct cdev *dev) } ``` -**Correct**: +**正确**: ```c void @@ -12443,19 +12271,19 @@ good_destroy(struct cdev *dev) } ``` -**How to avoid**: +**如何避免**: -- Make objects invisible before freeing (clear pointers, remove from lists) -- Use `destroy_dev()` which waits for in-progress operations -- Study led_destroy: clears `si_drv1` first, removes from list, then frees +- 在释放对象前使其不可见(清除指针,从列表中移除) +- 使用 `destroy_dev()`,它等待正在进行的操作完成 +- 研究 led_destroy:先清除 `si_drv1`,从列表中移除,然后释放 -##### **Pitfall: Not checking for allocation failures with `M_NOWAIT`** +##### **陷阱:未检查 `M_NOWAIT` 分配失败** -**Symptom**: Kernel panic dereferencing NULL pointer. +**症状**:解引用 NULL 指针导致内核崩溃。 -**Root cause**: `M_NOWAIT` allocations can fail, but code assumes success. +**根本原因**:`M_NOWAIT` 分配可能失败,但代码假定成功。 -**Wrong**: +**错误**: ```c static int @@ -12468,7 +12296,7 @@ bad_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c static int @@ -12484,7 +12312,7 @@ good_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**Better**: Use `M_WAITOK` when safe: +**更佳做法**:在安全的情况下使用 `M_WAITOK`: ```c static int @@ -12498,21 +12326,21 @@ better_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: +**如何避免**: -- Use `M_WAITOK` unless in interrupt context or holding spin locks -- Always check `M_NOWAIT` allocations for NULL -- Study led_write: uses `M_WAITOK` since write operations can sleep +- 除非在中断上下文或持有自旋锁,否则使用 `M_WAITOK` +- 始终检查 `M_NOWAIT` 分配是否为 NULL +- 研究 led_write:使用 `M_WAITOK`,因为写操作可以休眠 -#### Timer and Asynchronous Operation Errors +#### 定时器和异步操作错误 -##### **Pitfall: Timer callback accessing freed memory** +##### **陷阱:定时器回调访问已释放的内存** -**Symptom**: Panic in timer callback, memory corruption. +**症状**:定时器回调中的崩溃、内存损坏。 -**Root cause**: Device destroyed but timer still scheduled. +**根本原因**:设备已销毁但定时器仍在调度中。 -**Wrong**: +**错误**: ```c void @@ -12526,7 +12354,7 @@ bad_destroy(struct cdev *dev) } ``` -**Correct**: +**正确**: ```c void @@ -12540,20 +12368,20 @@ good_destroy(struct cdev *dev) } ``` -**How to avoid**: +**如何避免**: -- Use `callout_drain()` before freeing structures accessed by callback -- Or use `callout_stop()` and ensure no callback is running -- Initialize callouts with `callout_init_mtx()` to automatically hold your lock -- Study led_destroy: stops timer when list becomes empty +- 在释放由回调访问的结构前使用 `callout_drain()` +- 或使用 `callout_stop()` 并确保没有回调正在运行 +- 使用 `callout_init_mtx()` 初始化 callout,以自动持有你的锁 +- 研究 led_destroy:当列表变空时停止定时器 -##### **Pitfall: Timer rescheduling unconditionally** +##### **陷阱:无条件地重新调度定时器** -**Symptom**: CPU waste, system slowdown, unnecessary wakeups. +**症状**:CPU 浪费、系统变慢、不必要的唤醒。 -**Root cause**: Timer fires even when there's no work to do. +**根本原因**:即使没有工作要做,定时器也会触发。 -**Wrong**: +**错误**: ```c static void @@ -12570,7 +12398,7 @@ bad_timeout(void *arg) } ``` -**Correct**: +**正确**: ```c static void @@ -12591,21 +12419,21 @@ good_timeout(void *arg) } ``` -**How to avoid**: +**如何避免**: -- Maintain a counter of items needing service -- Only schedule timer when counter > 0 -- Study led.c: `blinkers` counter gates timer rescheduling +- 维护一个需要服务的项目计数器 +- 仅在计数器大于 0 时安排定时器 +- 学习 led.c:`blinkers` 计数器控制定时器重新调度 -#### Network Driver Specific Issues +#### 网络驱动程序特定问题 -##### **Pitfall: Not freeing mbufs on error paths** +##### **陷阱:未在错误路径上释放 mbuf** -**Symptom**: mbuf exhaustion, "network buffers exhausted" messages. +**症状**:mbuf 耗尽、出现 "network buffers exhausted" 消息。 -**Root cause**: Mbufs are a limited resource that must be explicitly freed. +**根本原因**:Mbuf 是必须显式释放的有限资源。 -**Wrong**: +**错误**: ```c static int @@ -12622,7 +12450,7 @@ bad_transmit(struct ifnet *ifp, struct mbuf *m) } ``` -**Correct**: +**正确**: ```c static int @@ -12643,19 +12471,19 @@ good_transmit(struct ifnet *ifp, struct mbuf *m) } ``` -**How to avoid**: +**如何避免**: -- Whoever has the mbuf pointer is responsible for freeing it -- On error: `m_freem(m)` before returning -- On success: ensure someone else took ownership (queued, transmitted, etc.) +- 持有 mbuf 指针的人负责释放它 +- 在错误情况下:返回前调用 `m_freem(m)` +- 成功时:确保其他人取得了所有权(已排队、已发送等) -##### **Pitfall: Forgetting to notify blocked readers/writers** +##### **陷阱:忘记通知阻塞的读取者/写入者** -**Symptom**: Processes hang in read/write/poll even though data is available. +**症状**:即使数据可用,进程在 read/write/poll 中挂起。 -**Root cause**: Data arrives but waiters aren't woken. +**根本原因**:数据到达但等待者未被唤醒。 -**Wrong**: +**错误**: ```c static void @@ -12666,7 +12494,7 @@ bad_rx_handler(struct foo_softc *sc, struct mbuf *m) } ``` -**Correct**: +**正确**: ```c static void @@ -12681,21 +12509,21 @@ good_rx_handler(struct foo_softc *sc, struct mbuf *m) } ``` -**How to avoid**: +**如何避免**: -- After enqueueing data: call `wakeup()`, `selwakeuppri()`, `KNOTE()` -- Study tunstart in if_tuntap.c: triple notification pattern -- For write: notify after dequeueing (when space becomes available) +- 数据入队后:调用 `wakeup()`、`selwakeuppri()`、`KNOTE()` +- 学习 if_tuntap.c 中的 tunstart:三重通知模式 +- 对于写操作:在出队后(当空间可用时)通知 -#### Input Validation Failures +#### 输入验证失败 -##### **Pitfall: Not bounding input sizes** +##### **陷阱:未限制输入大小** -**Symptom**: Denial of service, kernel memory exhaustion. +**症状**:拒绝服务、内核内存耗尽。 -**Root cause**: Attacker can request huge allocations or cause huge copies. +**根本原因**:攻击者可以请求大量分配或导致大量复制。 -**Wrong**: +**错误**: ```c static int @@ -12709,7 +12537,7 @@ bad_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c #define MAX_CMD_SIZE 4096 @@ -12729,19 +12557,19 @@ good_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: +**如何避免**: -- Define maximum sizes for all inputs (commands, packets, buffers) -- Check limits before allocation -- Study led_write: rejects commands over 512 bytes +- 为所有输入(命令、数据包、缓冲区)定义最大大小 +- 在分配前检查限制 +- 研究 led_write:拒绝超过 512 字节的命令 -##### **Pitfall: Trusting user-provided lengths and offsets** +##### **陷阱:信任用户提供的长度和偏移量** -**Symptom**: Buffer overruns, reading uninitialized memory, information leaks. +**症状**:缓冲区溢出、读取未初始化的内存、信息泄漏。 -**Root cause**: User controls length fields in ioctl structures. +**根本原因**:用户在 ioctl 结构中控制长度字段。 -**Wrong**: +**错误**: ```c struct user_request { @@ -12760,7 +12588,7 @@ bad_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *t } ``` -**Correct**: +**正确**: ```c static int @@ -12776,21 +12604,21 @@ good_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread * } ``` -**How to avoid**: +**如何避免**: -- Validate all length fields against buffer sizes -- Validate offsets are within valid ranges -- Use `MIN()` to cap lengths: `len = MIN(user_len, MAX_LEN)` +- 对照缓冲区大小验证所有长度字段 +- 验证偏移量在有效范围内 +- 使用 `MIN()` 限制长度:`len = MIN(user_len, MAX_LEN)` -#### Race Conditions and Timing Issues +#### 竞态条件和时序问题 -##### **Pitfall: Check-then-use races** +##### **陷阱:检查后使用(TOCTOU)竞态** -**Symptom**: Intermittent crashes, security vulnerabilities (TOCTOU bugs). +**症状**:间歇性崩溃、安全漏洞(TOCTOU 错误)。 -**Root cause**: State changes between check and use. +**根本原因**:状态在检查和使用的间隙发生变化。 -**Wrong**: +**错误**: ```c static int @@ -12807,7 +12635,7 @@ bad_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**Correct**: +**正确**: ```c static int @@ -12830,19 +12658,19 @@ good_write(struct cdev *dev, struct uio *uio, int flags) } ``` -**How to avoid**: +**如何避免**: -- Hold appropriate lock from check through use -- Make checks and uses atomic with respect to each other -- Or use reference counting to keep objects alive +- 从检查到使用始终持有适当的锁 +- 使检查和使用相对于彼此是原子的 +- 或使用引用计数保持对象存活 -##### **Pitfall: Missing memory barriers on lock-free code** +##### **陷阱:无锁代码上缺少内存屏障** -**Symptom**: Rare corruption on multi-core systems, works fine in single-core. +**症状**:多核系统上罕见的损坏,单核系统正常工作。 -**Root cause**: CPU reordering of memory operations. +**根本原因**:CPU 对内存操作进行重排序。 -**Wrong**: +**错误**: ```c /* Producer */ @@ -12854,7 +12682,7 @@ if (sc->ready) /* Check flag */ use(sc->data); /* May see old data! */ ``` -**Correct with explicit barriers**: +**使用显式屏障的正确做法**: ```c /* Producer */ @@ -12866,7 +12694,7 @@ if (atomic_load_acq_int(&sc->ready)) /* Acquire barrier */ use(sc->data); ``` -**Better: Just use locks**: +**更好的做法:直接使用锁**: ```c /* Much simpler and correct */ @@ -12876,21 +12704,21 @@ sc->ready = 1; mtx_unlock(&sc->mtx); ``` -**How to avoid**: +**如何避免**: -- Avoid lock-free programming unless you're an expert -- Use locks for correctness, optimize only if profiling shows need -- If you must go lock-free: use atomic operations with explicit barriers +- 除非你是专家,否则避免无锁编程 +- 使用锁保证正确性,仅在性能分析显示需要时才优化 +- 如果必须采用无锁方式:使用带有显式屏障的原子操作 -#### Module Lifecycle Issues +#### 模块生命周期问题 -##### **Pitfall: Device operations racing with module unload** +##### **陷阱:设备操作与模块卸载竞态** -**Symptom**: Crash during `kldunload`, jumps to invalid memory. +**症状**:执行 `kldunload` 时崩溃,跳转到无效内存地址。 -**Root cause**: Functions unloaded while still in use. +**根本原因**:函数仍在使用时被卸载。 -**Wrong**: +**错误**: ```c static int @@ -12904,7 +12732,7 @@ bad_unload(module_t mod, int type, void *data) } ``` -**Correct**: +**正确**: ```c static int @@ -12920,19 +12748,19 @@ good_unload(module_t mod, int type, void *data) } ``` -**How to avoid**: +**如何避免**: -- `destroy_dev()` automatically prevents this by waiting -- For infrastructure modules (like led.c): don't provide unload handler -- Test unload under load: `while true; do cat /dev/foo; done & sleep 1; kldunload foo` +- `destroy_dev()` 通过等待机制自动避免此问题 +- 对于基础设施模块(如 led.c):不要提供卸载处理程序 +- 在负载下测试卸载:`while true; do cat /dev/foo; done & sleep 1; kldunload foo` -##### **Pitfall: Unload leaving dangling references** +##### **陷阱:卸载留下悬空引用** -**Symptom**: Crashes in seemingly unrelated code after module unload. +**症状**:模块卸载后在看似无关的代码中崩溃。 -**Root cause**: Other code holds pointers to unloaded module's data/functions. +**根本原因**:其他代码持有指向已卸载模块数据/函数的指针。 -**Wrong**: +**错误**: ```c /* Your module */ @@ -12952,7 +12780,7 @@ bad_unload(module_t mod, int type, void *data) } ``` -**Correct**: +**正确**: ```c static int @@ -12964,17 +12792,17 @@ good_unload(module_t mod, int type, void *data) } ``` -**How to avoid**: +**如何避免**: -- Every registration needs corresponding deregistration -- Every callback installation needs removal -- Every "register with subsystem" needs "unregister from subsystem" +- 每次注册都需要对应的注销操作 +- 每次回调安装都需要移除 +- 每次“向子系统注册”都需要“从子系统注销” -### Debugging Pitfall Patterns +### 调试陷阱模式 -#### **How to detect these bugs:** +#### **如何检测这些错误:** -**For locking issues**: +**对于加锁问题**: ```console # In kernel config or loader.conf @@ -12984,9 +12812,9 @@ options INVARIANTS options INVARIANT_SUPPORT ``` -WITNESS detects lock order violations and reports them in dmesg. +WITNESS 检测锁顺序违规并在 dmesg 中报告。 -**For memory issues**: +**对于内存问题**: ```console # Track allocations @@ -12996,131 +12824,131 @@ vmstat -m | grep M_YOURTYPE options MALLOC_DEBUG_MAXZONES=8 ``` -**For race conditions**: +**对于竞态条件**: -- Run stress tests on multi-core systems -- Use `stress2` test suite -- Concurrent operations: multiple threads opening/closing/reading/writing +- 在多核系统上运行压力测试 +- 使用 `stress2` 测试套件 +- 并发操作:多个线程同时打开/关闭/读/写 -**For leak detection**: +**对于泄漏检测**: -- Before load: note resource counts (`vmstat -m`, `devfs`, `ifconfig -a`) -- Load module, exercise it heavily -- Unload module -- Check resource counts - should return to baseline +- 加载前:记录资源计数(`vmstat -m`、`devfs`、`ifconfig -a`) +- 加载模块,充分测试 +- 卸载模块 +- 检查资源计数——应回到基准线 -### Prevention Checklist +### 预防清单 -Before committing code, verify: +在提交代码前,请验证: -**Data movement** +**数据移动** -- All `uiomove()` calls properly update `uio_resid` -- Chunk sizes bounded to reasonable limits -- No direct dereferencing of user pointers +- 所有 `uiomove()` 调用正确更新 `uio_resid` +- 块大小限制在合理范围内 +- 不直接解引用用户指针 -**Locking** +**加锁** -- No locks held across `uiomove()`/`copyin()`/`copyout()` -- Consistent lock ordering documented and followed -- All locks initialized before use -- Locks destroyed only after last user done +- 在 `uiomove()`/`copyin()`/`copyout()` 期间不持有锁 +- 一致的锁顺序已记录并遵循 +- 所有锁在使用前已初始化 +- 锁仅在最后一个使用者完成后才销毁 -**Resources** +**资源** -- Every allocation has matching free on all paths -- Error paths tested and leak-free -- Objects made invisible before freeing -- NULL checks after `M_NOWAIT` allocations +- 每个内存分配在所有路径上都有对应的释放 +- 错误路径经过测试且无泄漏 +- 对象在释放前已变得不可见 +- `M_NOWAIT` 分配后需检查是否为 NULL -**Timers** +**定时器** -- `callout_drain()` before freeing structures -- Timer rescheduling gated by work counter -- Callout initialized with associated mutex +- 在释放结构体前调用 `callout_drain()` +- 定时器重新调度受工作计数器控制 +- 定时器回调初始时需关联互斥锁 -**Network (if applicable)** +**网络(如果适用)** -- Mbufs freed on all error paths -- Triple notification after enqueue -- Input sizes validated against MRU +- 所有错误路径上释放 mbuf +- 入队后进行三次通知 +- 根据 MRU 验证输入大小 -**Input validation** +**输入验证** -- Maximum sizes defined and enforced -- User-provided lengths checked -- Offsets validated before use +- 定义并强制实施最大大小 +- 检查用户提供的长度 +- 偏移量在使用前需经过验证 -**Races** +**竞态** -- No check-then-use patterns without locks -- Critical sections properly protected -- Lock-free code avoided unless necessary +- 避免无锁情况下的“检查-然后使用”模式 +- 临界区得到正确保护 +- 除非必要,避免无锁代码 -**Lifecycle** +**生命周期** -- `destroy_dev()` before freeing softc -- All registrations have deregistrations -- Unload tested under concurrent use +- 在释放 `softc` 之前调用 `destroy_dev()` +- 所有注册都有对应的注销操作 +- 在并发使用下测试卸载 -### When Things Go Wrong +### 当问题出现时 -**If you see "sleeping with lock held"**: +**如果你看到 "sleeping with lock held"(持有锁时睡眠)**: -- Likely holding mutex across `uiomove()` or allocation with `M_WAITOK` -- Solution: Release lock before blocking operation +- 很可能是在 `uiomove()` 或使用 `M_WAITOK` 分配内存时持有了互斥锁 +- 解决方法:在阻塞操作前释放锁 -**If you see "lock order reversal"**: +**如果你看到 "lock order reversal"**: -- Two locks acquired in different orders in different code paths -- Solution: Establish and document hierarchy, fix violating code +- 两个锁在不同代码路径中以不同顺序获取 +- 解决方案:建立并记录层次结构,修复违规代码 -**If you see "page fault in kernel mode"**: +**如果你看到 "page fault in kernel mode"**: -- Usually use-after-free or NULL dereference -- Check: Are you accessing memory after freeing? Is `si_drv1` cleared first? +- 通常是释放后使用(use-after-free)或空指针解引用(NULL dereference) +- 检查:释放后是否仍在访问内存?`si_drv1` 是否先被清零? -**If processes hang forever**: +**如果进程永远挂起**: -- Missing `wakeup()` or notification -- Check: Does every enqueue call wakeup/selwakeup/KNOTE? +- 缺少 `wakeup()` 或通知 +- 检查:每次入队调用是否都触发了 `wakeup`/`selwakeup`/`KNOTE`? -**If resources leak**: +**如果资源泄漏**: -- Error path missing cleanup -- Check: Does every early return free what was allocated? +- 错误路径缺少清理 +- 检查:每个提前返回路径是否释放了已分配的资源? -### You're Ready: From Patterns to Practice +### 你已准备好:从模式到实践 -By studying these pitfalls and their solutions in the context of the four driver tours, you develop the instincts to avoid them. The patterns repeat: check before use, lock appropriately, free what you allocate, notify when you enqueue, validate user input. Master these, and your drivers will be robust. +通过在四个驱动程序示例的上下文中研究这些陷阱及其解决方案,你将培养出避免它们的直觉。模式会重复出现:使用前检查、正确加锁、释放已分配的资源、入队时通知、验证用户输入。掌握这些,你的驱动程序将变得健壮。 -You now have a compact mental model: the same few patterns repeat with different applications. Keep this blueprint open while you tackle hands-on labs, it's the shortest path from "I think I get it" to "I can ship a driver that behaves correctly." +现在,你已拥有一个简洁的心智模型:同样的几种模式在不同应用中重复出现。在进行动手实验时,请将此蓝图放在手边,这是从“我觉得我懂了”到“我能交付一个行为正确的驱动程序”的最短路径。 -When in doubt, return to the four driver tours. They're your worked examples showing these patterns in complete, working code. +如有疑问,请回顾四个驱动程序示例。它们是你的完整工作代码示例,展示了这些模式在完整、可运行的代码中的应用。 -**Next**, it's time to get hands-on with four practical labs. +**接下来**,是时候动手进行四个实践实验室了。 ## 动手实验:从阅读到构建(初学者安全) -You've read about driver structure; now **experience it**. These four carefully designed labs take you from reading code to building working kernel modules, each one validating your understanding before moving forward. +你已经阅读了关于驱动程序结构的内容;现在**亲自体验它**。这四个精心设计的实验室将带你从阅读代码到构建可工作的内核模块,每一步都验证你的理解,然后继续前进。 -### Lab Design Philosophy +### 实验设计理念 -These labs are: +这些实验室的特点: -- **Safe**: Run in your lab VM, isolated from your main system -- **Incremental**: Each builds on the last with clear checkpoints -- **Self-validating**: You'll know immediately if you've succeeded -- **Explanatory**: Code includes comments explaining the "why" behind the "what" -- **Complete**: All code is tested on FreeBSD 14.3 and ready to use +- **安全**:在你的实验室虚拟机中运行,与主系统隔离 +- **渐进**:每一步都建立在上一步的基础上,并有清晰的检查点 +- **自我验证**:你会立即知道是否成功 +- **可解释**:代码中包含注释,解释“做什么”背后的“为什么” +- **完整**:所有代码已在 FreeBSD 14.3 上测试,可直接使用 -### Prerequisites for All Labs +### 所有实验的先决条件 -Before starting, ensure you have: +开始前,请确保你已准备好: -1. **FreeBSD 14.3** running (VM or physical machine) +1. **运行中的 FreeBSD 14.3**(虚拟机或物理机) -2. **Source code installed**: `/usr/src` must exist +2. **已安装源代码**:`/usr/src` 必须存在 ```bash # If /usr/src is missing, install it: @@ -13128,56 +12956,56 @@ Before starting, ensure you have: % sudo git clone --branch releng/14.3 --depth 1 https://git.FreeBSD.org/src.git src /usr/src ``` -3. **Build tools installed**: +3. **已安装构建工具**: ```bash % sudo pkg install llvm ``` -4. **Root access** via `sudo` or `su` +4. **通过 `sudo` 或 `su` 的 root 访问权限** -5. **Your lab logbook** for notes and observations +5. **你的实验室日志**,用于记录笔记和观察 -### Time Commitment +### 时间投入 -- **Lab 1** (Scavenger Hunt): 30-40 minutes -- **Lab 2** (Hello Module): 40-50 minutes -- **Lab 3** (Device Node): 60-75 minutes -- **Lab 4** (Error Handling): 30-40 minutes +- **实验 1**(寻宝游戏):30-40 分钟 +- **实验 2**(Hello 模块):40-50 分钟 +- **实验 3**(设备节点):60-75 分钟 +- **实验 4**(错误处理):30-40 分钟 -**Total**: 2.5 - 3.5 hours for all labs +**总计**:所有实验 2.5 - 3.5 小时 -**Recommendation**: Complete Lab 1 and Lab 2 in one session, take a break, then tackle Lab 3 and 4 in a second session. +**建议**:在一个学习阶段完成实验 1 和实验 2,休息一下,然后在第二个阶段处理实验 3 和实验 4。 ## 实验1:探索驱动程序地图(只读寻宝游戏) -### Goal +### 目标 -Locate and identify key driver structures in real FreeBSD source code. Build navigation confidence and pattern recognition skills. +在实际的 FreeBSD 源代码中定位和识别关键驱动程序结构。建立导航信心和模式识别技能。 -### What You'll Learn +### 你将学到什么 -- How to find and read FreeBSD driver source files -- How to recognize common patterns (cdevsw, probe/attach, DRIVER_MODULE) -- Where different types of drivers live in the source tree -- How to use `less` and grep effectively for driver exploration +- 如何查找和阅读 FreeBSD 驱动程序源文件 +- 如何识别常见模式(cdevsw、probe/attach、DRIVER_MODULE) +- 不同类型的驱动程序在源码树中的位置 +- 如何有效使用 `less` 和 grep 进行驱动程序探索 -### Prerequisites +### 先决条件 -- FreeBSD 14.3 with /usr/src installed -- Text editor or `less` for viewing files -- Terminal with your favorite shell +- 已安装 /usr/src 的 FreeBSD 14.3 +- 文本编辑器或 `less` 用于查看文件 +- 带有所需 shell 的终端 -### Time Estimate +### 预计时间 -30-40 minutes (questions only) -+10 minutes if you want to explore beyond the questions +30-40 分钟(仅问题) ++10 分钟(如果你想在问题之外继续探索) -### Instructions +### 说明 -#### Part 1: Character Device Driver - The Null Driver +#### 第1部分:字符设备驱动程序 - 空设备驱动 -**Step 1**: Navigate to the null driver +**步骤 1**:导航到空设备驱动目录 ```bash % cd /usr/src/sys/dev/null @@ -13186,211 +13014,211 @@ total 8 -rw-r--r-- 1 root wheel 4127 Oct 14 10:15 null.c ``` -**Step 2**: Open the file with `less` +**步骤 2**:使用 `less` 打开文件 ```bash % less null.c ``` -**Navigation tips for `less`**: +**`less` 的导航技巧**: -- Press `/` to search (example: `/cdevsw` to find cdevsw structure) -- Press `n` to find next occurrence -- Press `q` to quit -- Press `g` to go to top, `G` to go to bottom +- 按 `/` 搜索(例如:`/cdevsw` 查找 cdevsw 结构) +- 按 `n` 查找下一个匹配 +- 按 `q` 退出 +- 按 `g` 跳转到顶部,按 `G` 跳转到底部 -**Step 3**: Answer these questions (write in your lab logbook): +**步骤 3**:回答以下问题(写入你的实验日志中): -**Q1**: What line number defines the `null_cdevsw` structure? -*Hint*: Search for `/cdevsw` in less +**Q1**:`null_cdevsw` 结构体在第几行定义? +*提示*:在 less 中搜索 `/cdevsw` -**Q2**: Which function handles writes to `/dev/null`? -*Hint*: Look at the `.d_write =` line in the cdevsw structure +**Q2**:哪个函数处理对 `/dev/null` 的写入? +*提示*:查看 cdevsw 结构体中的 `.d_write =` 行 -**Q3**: What does the write function return? -*Hint*: Look at the function implementation +**Q3**:写入函数返回什么? +*提示*:查看函数实现 -**Q4**: Where is the module event handler? What's its name? -*Hint*: Search for `modevent` +**Q4**:模块事件处理程序在哪里?它的名称是什么? +*提示*:搜索 `modevent` -**Q5**: What macro registers the module with the kernel? -*Hint*: Look near the end of the file, search for `DECLARE_MODULE` +**Q5**:哪个宏将模块注册到内核? +*提示*:在文件末尾附近查找 `DECLARE_MODULE` -**Q6**: How many device nodes does this module create in `/dev`? -*Hint*: Count the `make_dev_credf` calls in the load handler +**Q6**:该模块在 `/dev` 中创建了多少个设备节点? +*提示*:计算加载处理程序中 `make_dev_credf` 调用的次数 -**Q7**: What are the device node names? -*Hint*: Look at the last parameter in each `make_dev_credf` call +**Q7**:设备节点的名称是什么? +*提示*:查看每个 `make_dev_credf` 调用的最后一个参数 -#### Part 2: Infrastructure Driver - The LED Driver +#### 第2部分:基础设施驱动程序 - LED 驱动 -**Step 4**: Navigate to the LED driver +**步骤 4**:导航到 LED 驱动目录 ```bash % cd /usr/src/sys/dev/led % less led.c ``` -**Step 5**: Answer these questions: +**步骤 5**:回答以下问题: -**Q8**: Find the softc structure. What's it called? -*Hint*: Search for `_softc {` to find structure definitions +**Q8**:找到 softc 结构体。它的名称是什么? +*提示*:搜索 `_softc {` 查找结构定义 -**Q9**: Where is `led_create()` defined? -*Hint*: Search for `^led_create` (^ means start of line) +**Q9**:`led_create()` 定义在哪里? +*提示*:搜索 `^led_create`(^ 表示行首) -**Q10**: What subdirectory in `/dev` do LED device nodes appear under? -*Hint*: Look at the `make_dev` call in `led_create()`, check the path +**Q10**:LED 设备节点出现在 `/dev` 下的哪个子目录中? +*提示*:查看 `led_create()` 中的 `make_dev` 调用,检查路径 -**Q11**: Find the `led_write` function. What does it do with user input? -*Hint*: Look for the function definition, read the code +**问题11**:找到 `led_write` 函数。它对用户输入做了什么? +*提示*:查找函数定义,阅读代码 -**Q12**: Is there a probe/attach pair, or does this use a module event handler? -*Hint*: Search for `probe` and `attach` vs `modevent` +**问题12**:是否存在 probe/attach 配对,还是使用模块事件处理程序? +*提示*:搜索 `probe` 和 `attach` 对比 `modevent` -**Q13**: Can you find where the driver allocates memory for the softc? -*Hint*: Look in `led_create()` for `malloc` calls +**问题13**:你能找到驱动程序为 softc 分配内存的地方吗? +*提示*:在 `led_create()` 中查找 `malloc` 调用 -#### Part 3: Network Driver - The Tun/Tap Driver +#### 第3部分:网络驱动程序 - Tun/Tap 驱动程序 -**Step 6**: Navigate to the tun/tap driver +**第6步**:导航到 tun/tap 驱动程序 ```bash % cd /usr/src/sys/net % less if_tuntap.c ``` -**Note**: This is a larger, more complex driver. Don't try to understand everything, just find the specific patterns. +**注意**:这是一个较大、较复杂的驱动程序。不要试图理解所有内容,只需找到特定的模式。 -**Step 7**: Answer these questions: +**第7步**:回答以下问题: -**Q14**: Find the softc structure for tun. What's it called? -*Hint*: Search for `tun_softc {` +**问题14**:找到 tun 的 softc 结构。它叫什么? +*提示*:搜索 `tun_softc {` -**Q15**: Does the softc contain both a `struct cdev *` and network interface pointer? -*Hint*: Look at the members of the softc structure +**问题15**:softc 是否同时包含 `struct cdev *` 和网络接口指针? +*提示*:查看 softc 结构的成员 -**Q16**: Where is the `tun_cdevsw` structure defined? -*Hint*: Search for `tun_cdevsw =` +**问题16**:`tun_cdevsw` 结构在哪里定义? +*提示*:搜索 `tun_cdevsw =` -**Q17**: What function is called when you open `/dev/tun`? -*Hint*: Look at the `.d_open =` line in the cdevsw +**问题17**:当打开 `/dev/tun` 时调用哪个函数? +*提示*:查看 cdevsw 中的 `.d_open =` 行 -**Q18**: Where does the driver create the network interface? -*Hint*: Search for `if_alloc` in the source +**问题18**:驱动程序在哪里创建网络接口? +*提示*:在源代码中搜索 `if_alloc` -#### Part 4: Bus-Attached Driver - A PCI UART +#### 第 4 部分:总线连接驱动程序 - PCI UART -**Step 8**: Navigate to a PCI driver +**第 8 步**:导航到 PCI 驱动程序 ```bash % cd /usr/src/sys/dev/uart % less uart_bus_pci.c ``` -**Step 9**: Answer these questions: +**第9步**:回答以下问题: -**Q19**: Find the probe function. What's it called? -*Hint*: Look for a function ending in `_probe` +**问题19**:找到 probe 函数。它叫什么? +*提示*:查找以 `_probe` 结尾的函数 -**Q20**: What does the probe function check to identify compatible hardware? -*Hint*: Look inside the probe function for ID comparisons +**问题20**:probe 函数检查什么来识别兼容的硬件? +*提示*:在 probe 函数内部查找 ID 比较 -**Q21**: Where is `DRIVER_MODULE` declared? -*Hint*: Search for `DRIVER_MODULE` - should be near end of file +**问题21**:`DRIVER_MODULE` 在哪里声明? +*提示*:搜索 `DRIVER_MODULE` —— 应该在文件末尾附近 -**Q22**: What bus does this driver attach to? -*Hint*: Look at the second parameter to `DRIVER_MODULE` macro +**问题22**:这个驱动程序附加到哪个总线? +*提示*:查看 `DRIVER_MODULE` 宏的第二个参数 -**Q23**: Find the device method table. What's it called? -*Hint*: Search for `device_method_t` - should be an array +**问题23**:找到设备方法表。它叫什么? +*提示*:搜索 `device_method_t` —— 应该是一个数组 -**Q24**: How many methods are defined in the method table? -*Hint*: Count entries between the declaration and `DEVMETHOD_END` +**问题24**:方法表中定义了多少个方法? +*提示*:计算从声明到 `DEVMETHOD_END` 之间的条目数 -### Check Your Answers +### 检查你的答案 -After completing all questions, compare with the answer key below. Don't peek before attempting! +完成所有问题后,请对照下面的答案键。不要提前偷看! -#### Part 1: Null Driver +#### 第 1 部分:Null 驱动程序 -**A1**: The `null_cdevsw` definition (the character-device switch table for `/dev/null`) +**A1**: `null_cdevsw` 定义(用于 `/dev/null` 的字符设备开关表) -**A2**: `null_write` function +**A2**:`null_write` 函数 -**A3**: Sets `uio->uio_resid = 0` to mark all bytes consumed, then returns `0` (success). The data is discarded. +**A3**: 设置 `uio->uio_resid = 0` 以标记所有字节已消耗,然后返回 `0`(成功)。数据被丢弃。 -**A4**: `null_modevent()`, defined near the bottom of `null.c` just before the `DEV_MODULE` registration +**A4**: `null_modevent()`,定义在 `null.c` 底部,紧接在 `DEV_MODULE` 注册之前 -**A5**: `DEV_MODULE(null, null_modevent, NULL);` followed by `MODULE_VERSION(null, 1);` +**A5**:`DEV_MODULE(null, null_modevent, NULL);` 后跟 `MODULE_VERSION(null, 1);` -**A6**: Three device nodes: `/dev/null`, `/dev/zero` and `/dev/full` +**A6**:三个设备节点:`/dev/null`、`/dev/zero` 和 `/dev/full` -**A7**: "null", "zero", "full" +**A7**:"null"、"zero"、"full" -#### Part 2: LED Driver +#### 第 2 部分:LED 驱动程序 -**A8**: `struct ledsc` (note the compact "LED softc" name; not `led_softc`) +**A8**: `struct ledsc`(注意紧凑的 "LED softc" 名称;不是 `led_softc`) -**A9**: `led_create()` is a thin wrapper around `led_create_state()`; both live together in `led.c`, just after the `led_cdevsw` definition +**A9**: `led_create()` 是 `led_create_state()` 的薄包装;两者都位于 `led.c` 中,紧接在 `led_cdevsw` 定义之后 -**A10**: `/dev/led/` (LEDs appear as `/dev/led/name`, created with `make_dev(..., "led/%s", name)`) +**A10**: `/dev/led/`(LED 显示为 `/dev/led/name`,通过 `make_dev(..., "led/%s", name)` 创建) -**A11**: `led_write()` reads the user's buffer via `uiomove()`, passes it through `led_parse()` to turn a human-readable string like `"f3"` or `"m-.-"` into a compact pattern, then installs the pattern with `led_state()`. +**A11**: `led_write()` 通过 `uiomove()` 读取用户缓冲区,将其传递给 `led_parse()` 以将类似 `"f3"` 或 `"m-.-"` 的可读字符串转换为紧凑模式,然后通过 `led_state()` 安装该模式。 -**A12**: Neither. `led.c` is an infrastructure subsystem (no `probe`/`attach`, no module event handler). It initializes at boot via `SYSINIT(leddev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, led_drvinit, NULL)` near the end of the file and has no separate load/unload handler; hardware drivers call `led_create()`/`led_destroy()` to register their LEDs at runtime. +**A12**: 都不是。`led.c` 是一个基础设施子系统(没有 `probe`/`attach`,没有模块事件处理程序)。它在启动时通过文件末尾附近的 `SYSINIT(leddev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, led_drvinit, NULL)` 初始化,并且没有单独的加载/卸载处理程序;硬件驱动程序在运行时调用 `led_create()`/`led_destroy()` 来注册它们的 LED。 -**A13**: Yes, in `led_create_state()`: `sc = malloc(sizeof *sc, M_LED, M_WAITOK | M_ZERO);` +**A13**:是的,在 `led_create_state()` 中:`sc = malloc(sizeof *sc, M_LED, M_WAITOK | M_ZERO);` -#### Part 3: Tun/Tap Driver +#### 第 3 部分:Tun/Tap 驱动程序 -**A14**: `struct tuntap_softc` +**A14**:`struct tuntap_softc` -**A15**: Yes. The softc embeds an `ifnet` pointer (`tun_ifp`) and is linked to a `cdev` via `dev->si_drv1` and the softc's back-pointer. +**A15**: 是的。softc 嵌入了一个 `ifnet` 指针(`tun_ifp`),并通过 `dev->si_drv1` 和 softc 的反向指针链接到 `cdev`。 -**A16**: There's no single `tun_cdevsw` variable. Three `struct cdevsw` definitions live inside the `tuntap_drivers[]` array (one each for `tun`, `tap`, and `vmnet`). They share the same handlers (`tunopen`, `tunread`, `tunwrite`, `tunioctl`, `tunpoll`, `tunkqfilter`) and differ only in their `.d_name` and flags. +**A16**: 没有一个单独的 `tun_cdevsw` 变量。三个 `struct cdevsw` 定义位于 `tuntap_drivers[]` 数组内(分别对应 `tun`、`tap` 和 `vmnet`)。它们共享相同的处理程序(`tunopen`、`tunread`、`tunwrite`、`tunioctl`、`tunpoll`、`tunkqfilter`),仅在 `.d_name` 和标志上有所不同。 -**A17**: `tunopen()` is assigned to `.d_open` in each `cdevsw` inside `tuntap_drivers[]`. +**A17**: `tunopen()` 被分配给 `tuntap_drivers[]` 内每个 `cdevsw` 的 `.d_open`。 -**A18**: In `tuncreate()`, the interface is created with `if_alloc(type)` where `type` is `IFT_ETHER` for `tap` and `IFT_PPP` for `tun`. +**A18**: 在 `tuncreate()` 中,接口通过 `if_alloc(type)` 创建,其中 `type` 对于 `tap` 是 `IFT_ETHER`,对于 `tun` 是 `IFT_PPP`。 -#### Part 4: PCI UART Driver +#### 第 4 部分:PCI UART 驱动程序 **A19**: `uart_pci_probe()` -**A20**: It calls `uart_pci_match()` against the `pci_ns8250_ids` table to match known UART vendor/device IDs, and falls back to the PCI class code (`PCIC_SIMPLECOMM` with subclass `PCIS_SIMPLECOMM_UART`) for generic 16550-class parts. +**A20**: 它调用 `uart_pci_match()` 对照 `pci_ns8250_ids` 表来匹配已知的 UART 供应商/设备 ID,并回退到 PCI 类别代码(`PCIC_SIMPLECOMM` 和子类 `PCIS_SIMPLECOMM_UART`)以用于通用的 16550 类部件。 -**A21**: At the end of the file: `DRIVER_MODULE(uart, pci, uart_pci_driver, NULL, NULL);` +**A21**: 在文件末尾:`DRIVER_MODULE(uart, pci, uart_pci_driver, NULL, NULL);` -**A22**: `pci` (the second argument to `DRIVER_MODULE`). +**A22**: `pci`(`DRIVER_MODULE` 的第二个参数)。 **A23**: `uart_pci_methods[]` -**A24**: Four entries plus `DEVMETHOD_END`: `device_probe`, `device_attach`, `device_detach`, and `device_resume`. +**A24**:四个条目加上 `DEVMETHOD_END`:`device_probe`、`device_attach`、`device_detach` 和 `device_resume`。 -**If your answers differ significantly**: +**如果你的答案差异很大**: -1. Don't worry! FreeBSD code evolves between versions -2. The important part is **finding** the structures, not exact line numbers -3. If you found similar patterns in different locations, that's success +1. 别担心!FreeBSD 代码在不同版本间会演变 +2. 重要的是**找到**结构,而不是精确的行号 +3. 如果你在不同位置发现了类似模式,那就是成功 -### Success Criteria +### 成功标准 -- Found all major structures in each drive -- Understand the pattern: entry points (cdevsw/ifnet), lifecycle (probe/attach/detach), registration (DRIVER_MODULE/DECLARE_MODULE) -- Can navigate driver source confidently -- Recognize differences between driver types (character vs network vs bus-attached) +- 在每个驱动中找到了所有主要结构 +- 理解模式:入口点(cdevsw/ifnet)、生命周期(probe/attach/detach)、注册(DRIVER_MODULE/DECLARE_MODULE) +- 能够自信地导航驱动源代码 +- 识别不同驱动类型之间的差异(字符 vs 网络 vs 总线挂载) -### What You Learned +### 你学到了什么 -- **Character devices** use `cdevsw` structures with entry point functions -- **Network devices** combine character devices (`cdev`) with network interfaces (`ifnet`) -- **Bus-attached drivers** use newbus (probe/attach/detach) and method tables -- **Infrastructure modules** may skip probe/attach if they're not hardware drivers -- **softc structures** hold per-device state -- **Module registration** varies (DECLARE_MODULE vs DRIVER_MODULE) depending on driver type +- **字符设备**使用包含入口点函数的 `cdevsw` 结构 +- **网络设备**将字符设备(`cdev`)与网络接口(`ifnet`)结合 +- **总线连接驱动程序**使用 newbus(probe/attach/detach)和方法表 +- **基础设施模块**如果非硬件驱动程序,可以跳过 probe/attach +- **softc 结构**保存每设备状态 +- **模块注册**根据驱动程序类型而不同(DECLARE_MODULE vs DRIVER_MODULE) -### Lab Logbook Entry Template +### 实验日志条目模板 ```text Lab 1 Complete: [Date] @@ -13413,50 +13241,50 @@ Next steps: ## 实验2:仅带日志的最小模块 -### Goal +### 目标 -Build, load, and unload your first kernel module. Confirm your toolchain works and understand the module lifecycle through direct observation. +构建、加载和卸载你的第一个内核模块。确认你的工具链正常工作,并通过直接观察理解模块生命周期。 -### What You'll Learn +### 你将学到什么 -- How to write a minimal kernel module -- How to create a Makefile for kernel module builds -- How to load and unload modules safely -- How to observe kernel messages in dmesg -- The module event handler lifecycle (load/unload) -- How to troubleshoot common build errors +- 如何编写最小内核模块 +- 如何创建内核模块构建的 Makefile +- 如何安全地加载和卸载模块 +- 如何在 dmesg 中观察内核消息 +- 模块事件处理程序生命周期(加载/卸载) +- 如何排查常见构建错误 -### Prerequisites +### 先决条件 -- FreeBSD 14.3 with /usr/src installed -- Build tools installed (clang, make) -- sudo/root access -- Completed Lab 1 (recommended but not required) +- 已安装 /usr/src 的 FreeBSD 14.3 +- 已安装构建工具(clang、make) +- sudo/root 访问权限 +- 已完成实验 1(推荐但不是必需) -### Time Estimate +### 预计时间 -40-50 minutes (including build, test, and documentation) +40-50 分钟(包括构建、测试和文档记录) -### Instructions +### 说明 -#### Step 1: Create Working Directory +#### 第 1 步:创建工作目录 ```bash % mkdir -p ~/drivers/hello % cd ~/drivers/hello ``` -**Why this location?**: Your home directory keeps driver experiments separate from system files and survives reboots. +**为何选择此位置?**:你的主目录将驱动程序实验与系统文件隔离,并在重启后保持不变。 -#### Step 2: Create the Minimal Driver +#### 第2步:创建最小驱动程序 -Create a file named `hello.c`: +创建名为 `hello.c` 的文件: ```bash % vi hello.c # or nano, emacs, your choice ``` -Enter the following code (explanation follows): +输入以下代码(后续有解释): ```c /* @@ -13584,23 +13412,23 @@ DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(hello, 1); ``` -**Code explanation summary**: +**代码解释摘要**: -- **Includes**: Bring in kernel headers (unlike userspace, we can't use ``) -- **Event handler**: Function called when module loads/unloads -- **moduledata_t**: Connects the module name to its event handler -- **DECLARE_MODULE**: Registers everything with the kernel -- **MODULE_VERSION**: Declares version for dependency tracking +- **包含文件**:引入内核头文件(与用户空间不同,我们不能使用 ``) +- **事件处理程序**:模块加载/卸载时调用的函数 +- **moduledata_t**:将模块名称与事件处理程序连接起来 +- **DECLARE_MODULE**:向内核注册所有内容 +- **MODULE_VERSION**:声明版本以进行依赖跟踪 -#### Step 3: Create the Makefile +#### 第3步:创建 Makefile -Create a file named `Makefile` (exact name, capital M): +创建名为 `Makefile` 的文件(确切名称,大写 M): ```bash % vi Makefile ``` -Enter this content: +输入以下内容: ```makefile # Makefile for hello kernel module @@ -13624,14 +13452,14 @@ SRCS= hello.c .include ``` -**Makefile notes**: +**Makefile 说明**: -- **Must be named "Makefile"** (or "makefile", but "Makefile" is convention) -- **Tabs matter**: If you get errors, check that indentation uses TABS not spaces -- **KMOD** determines the output filename (`hello.ko`) -- **bsd.kmod.mk** is FreeBSD's kernel module build infrastructure (does the complex stuff) +- **必须命名为“Makefile”**(或“makefile”,但“Makefile”是惯例) +- **制表符很重要**:如果遇到错误,请检查缩进是否使用制表符而非空格 +- **KMOD** 决定输出文件名(`hello.ko`) +- **bsd.kmod.mk** 是 FreeBSD 的内核模块构建基础设施(处理复杂工作) -#### Step 4: Build the Module +#### 第4步:构建模块 ```bash % make clean @@ -13642,15 +13470,15 @@ cc -O2 -pipe -fno-strict-aliasing -Werror -D_KERNEL -DKLD_MODULE ... -c hello.c ld -d -warn-common -r -d -o hello.ko hello.o ``` -**What's happening**: +**发生了什么**: -1. **make clean**: Removes old build artifacts (always safe to run) -2. **make**: Compiles hello.c to hello.o, then links to create hello.ko -3. The compiler flags (`-D_KERNEL -DKLD_MODULE`) tell the code it's in kernel mode +1. **make clean**:移除旧的构建产物(运行始终安全) +2. **make**:将 hello.c 编译为 hello.o,然后链接以创建 hello.ko +3. 编译器标志(`-D_KERNEL -DKLD_MODULE`)告知代码处于内核模式 -**Expected output**: You should see compilation commands but **no errors**. +**预期输出**:你应该会看到编译命令,但**没有错误**。 -**Common error messages**: +**常见错误消息**: ```text Error: "implicit declaration of function 'printf'" @@ -13663,32 +13491,32 @@ Error: "undefined reference to __something" Fix: Usually means wrong includes or typo in function name ``` -#### Step 5: Verify Build Success +#### 第 5 步:验证构建成功 ```bash % ls -lh hello.ko -rwxr-xr-x 1 youruser youruser 14K Nov 14 15:30 hello.ko ``` -**What to look for**: +**注意查找**: -- **File exists**: `hello.ko` is present -- **Size is reasonable**: 10-20 KB is typical for minimal modules -- **Executable bit set**: `-rwxr-xr-x` (the 'x' means executable) +- **文件存在**:`hello.ko` 已生成 +- **大小合理**:最小模块通常为 10-20 KB +- **可执行位已设置**:`-rwxr-xr-x`('x' 表示可执行) -#### Step 6: Load the Module +#### 第6步:加载模块 ```bash % sudo kldload ./hello.ko ``` -**Important notes**: +**重要说明**: -- **Must use sudo** (or be root): Only root can load kernel modules -- **Use ./hello.ko**: The `./` tells kldload to use the local file, not search system paths -- **No output is normal**: If it loads successfully, kldload prints nothing +- **必须使用 sudo**(或 root):只有 root 可以加载内核模块 +- **使用 ./hello.ko**:`./` 告诉 kldload 使用本地文件,而非搜索系统路径 +- **无输出是正常的**:如果加载成功,kldload 不打印任何内容 -**If you get an error**: +**如果出现错误**: ```text kldload: can't load ./hello.ko: module already loaded or in kernel @@ -13701,22 +13529,22 @@ kldload: an error occurred. Please check dmesg(8) for more details. Solution: Run 'dmesg | tail' to see what went wrong ``` -#### Step 7: Verify Module Is Loaded +#### 步骤 7:验证模块已加载 ```bash % kldstat | grep hello 5 1 0xffffffff82500000 3000 hello.ko ``` -**Column meanings**: +**列含义**: -- **5**: Module ID (your number may differ) -- **1**: Reference count (how many things depend on it) -- **0xffffffff82500000**: Kernel memory address where module is loaded -- **3000**: Size in hex (0x3000 = 12288 bytes = 12 KB) -- **hello.ko**: Module filename +- **5**:模块ID(你的编号可能不同) +- **1**:引用计数(有多少东西依赖它) +- **0xffffffff82500000**:模块加载到的内核内存地址 +- **3000**:十六进制大小(0x3000 = 12288 字节 = 12 KB) +- **hello.ko**:模块文件名 -#### Step 8: View Kernel Messages +#### 第 8 步:查看内核消息 ```bash % dmesg | tail -5 @@ -13725,28 +13553,28 @@ Hello: This message appears in dmesg Hello: Module address: 0xffffffff82500000 ``` -**What's dmesg?**: The kernel message buffer. Everything printed with `printf()` in kernel code goes here. +**什么是 dmesg?**:内核消息缓冲区。内核代码中通过 `printf()` 打印的所有内容都会显示在这里。 -**Alternative ways to view**: +**其他查看方式**: ```bash % dmesg | grep Hello % tail -f /var/log/messages # Watch in real-time (Ctrl+C to stop) ``` -#### Step 9: Unload the Module +#### 步骤 9:卸载模块 ```bash % sudo kldunload hello ``` -**What happens**: +**会发生什么**: -1. Kernel calls your `hello_modevent()` with `MOD_UNLOAD` -2. Your handler prints "Goodbye!" and returns 0 (success) -3. Kernel removes the module from memory +1. 内核调用你的 `hello_modevent()`,并传入 `MOD_UNLOAD` +2. 你的处理程序打印 "Goodbye!" 并返回 0(成功) +3. 内核从内存中移除该模块 -#### Step 10: Verify Unload Messages +#### 第 10 步:验证卸载消息 ```bash % dmesg | tail -3 @@ -13755,7 +13583,7 @@ Hello: Module address: 0xffffffff82500000 Hello: Module unloaded. Goodbye! ``` -#### Step 11: Confirm Module Is Gone +#### 步骤 11:确认模块已消失 ```bash % kldstat | grep hello @@ -13765,60 +13593,60 @@ Hello: Module unloaded. Goodbye! [no output - this module doesn't create devices] ``` -### Behind the Scenes: What Just Happened? +### 幕后:刚才发生了什么? -Let's trace the **complete life cycle** of your module: +让我们追踪模块的**完整生命周期**: -#### When you ran `kldload ./hello.ko`: +#### 当你运行 `kldload ./hello.ko` 时: -1. **Kernel loads file**: Read hello.ko from disk into kernel memory -2. **Relocation**: Adjust memory addresses in the code to work at the loaded address -3. **Symbol resolution**: Connect function calls to their implementations -4. **Initialization**: Call your `hello_modevent()` with `MOD_LOAD` -5. **Registration**: Add "hello" to the kernel's module list -6. **Complete**: kldload returns success (exit code 0) +1. **内核加载文件**:将 hello.ko 从磁盘读入内核内存 +2. **重定位**:调整代码中的内存地址,使其在加载地址处正常工作 +3. **符号解析**:将函数调用连接到其实现 +4. **初始化**:调用你的 `hello_modevent()`,并传入 `MOD_LOAD` +5. **注册**:将 "hello" 添加到内核的模块列表中 +6. **完成**:kldload 返回成功(退出码 0) -Your `printf()` calls in `MOD_LOAD` happened during step 4. +你在 `MOD_LOAD` 中调用的 `printf()` 发生在步骤 4。 -#### When you ran `kldunload hello`: +#### 当你运行 `kldunload hello` 时: -1. **Lookup**: Find the "hello" module in kernel's module list -2. **Reference check**: Ensure nothing is using the module (ref count = 1) -3. **Shutdown**: Call your `hello_modevent()` with `MOD_UNLOAD` -4. **Cleanup**: Remove from module list -5. **Unmap**: Free the kernel memory that held the module code -6. **Complete**: kldunload returns success +1. **查找**:在内核的模块列表中找到 "hello" 模块 +2. **引用检查**:确保没有其他东西在使用该模块(引用计数 = 1) +3. **关闭**:调用你的 `hello_modevent()`,并传入 `MOD_UNLOAD` +4. **清理**:从模块列表中移除 +5. **取消映射**:释放存放模块代码的内核内存 +6. **完成**:kldunload 返回成功 -Your `printf()` in `MOD_UNLOAD` happened during step 3. +你在 `MOD_UNLOAD` 中调用的 `printf()` 发生在步骤 3。 -#### Why DECLARE_MODULE and MODULE_VERSION matter: +#### 为什么 DECLARE_MODULE 和 MODULE_VERSION 很重要: ```c DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); ``` -This macro expands to code that creates a special data structure in a special ELF section (`.set` section) of the hello.ko file. When the kernel loads the module, it scans for these structures and knows: +这个宏会展开为代码,在 hello.ko 文件的一个特殊 ELF 段(`.set` 段)中创建一个特殊数据结构。当内核加载模块时,它会扫描这些结构并知道: -- **Name**: "hello" -- **Handler**: `hello_modevent` -- **When to initialize**: SI_SUB_DRIVERS phase, SI_ORDER_MIDDLE position +- **名称**:"hello" +- **处理程序**:`hello_modevent` +- **何时初始化**:`SI_SUB_DRIVERS` 阶段,`SI_ORDER_MIDDLE` 位置 -Without this macro, the kernel wouldn't know your module exists! +没有这个宏,内核就不会知道你的模块存在! -### Troubleshooting Guide +### 故障排除指南 -#### Problem: Module won't compile +#### 问题:模块无法编译 -**Symptom**: `make` shows errors +**症状**:`make` 显示错误 -**Common causes**: +**常见原因**: -1. **Typo in code**: Carefully compare with example above -2. **Wrong includes**: Check that all four #include lines are present -3. **Tabs vs spaces in Makefile**: Makefiles require TABS for indentation -4. **Missing /usr/src**: Build needs kernel headers from /usr/src +1. **代码中有拼写错误**:仔细与上面的示例比较 +2. **包含头文件错误**:检查是否所有四行 `#include` 都存在 +3. **Makefile 中的制表符与空格**:Makefile 要求使用制表符缩进 +4. **缺少 /usr/src**:构建需要来自 /usr/src 的内核头文件 -**Debug steps**: +**调试步骤**: ```bash # Check if /usr/src exists @@ -13829,11 +13657,11 @@ Without this macro, the kernel wouldn't know your module exists! % cc -c -D_KERNEL -I/usr/src/sys hello.c ``` -#### Problem: "Operation not permitted" when loading +#### 问题:加载时出现 "Operation not permitted" -**Symptom**: `kldload: can't load ./hello.ko: Operation not permitted` +**症状**:`kldload: can't load ./hello.ko: Operation not permitted` -**Cause**: Not running as root +**原因**:未以 root 身份运行 **Fix**: @@ -13844,11 +13672,11 @@ Without this macro, the kernel wouldn't know your module exists! # kldload ./hello.ko ``` -#### Problem: "module already loaded" +#### 问题:"module already loaded" -**Symptom**: `kldload: can't load ./hello.ko: module already loaded` +**症状**:`kldload: can't load ./hello.ko: module already loaded` -**Cause**: Module is already in the kernel +**原因**:模块已存在于内核中 **Fix**: @@ -13857,61 +13685,61 @@ Without this macro, the kernel wouldn't know your module exists! % sudo kldload ./hello.ko ``` -#### Problem: No messages in dmesg +#### 问题:dmesg 中无消息 -**Symptom**: `kldload` succeeds but `dmesg` shows nothing +**症状**:`kldload` 成功但 `dmesg` 未显示任何内容 -**Possible causes**: +**可能的原因**: -1. **Messages scrolled away**: Use `dmesg | tail -20` to see recent messages -2. **Wrong module loaded**: Check `kldstat` to verify your module is there -3. **Event handler not called**: Check that DECLARE_MODULE matches moduledata_t name +1. **消息已滚动**:使用 `dmesg | tail -20` 查看最近消息 +2. **加载了错误的模块**:使用 `kldstat` 检查以确认你的模块已加载 +3. **事件处理程序未被调用**:检查 `DECLARE_MODULE` 是否与 `moduledata_t` 名称匹配 -#### Problem: Kernel panic +#### 问题:内核崩溃 -**Symptom**: System crashes, shows panic message +**症状**:系统崩溃,显示崩溃消息 -**Unlikely with this minimal module**, but if it happens: +**对于这个极简模块不太可能发生**,但如果出现: -1. **Don't panic** (no pun intended): Your VM can be rebooted -2. **Check the code**: Probably a typo in the DECLARE_MODULE macro -3. **Start fresh**: Reboot VM, compare your code character-by-character with example +1. **不要恐慌**(非双关语):你的虚拟机可以重启 +2. **检查代码**:很可能是 `DECLARE_MODULE` 宏中的拼写错误 +3. **重新开始**:重启虚拟机,逐个字符地将你的代码与示例进行比较 -### Success Criteria +### 成功标准 -- Module compiles without errors or warnings -- `hello.ko` file is created (10-20 KB) -- Module loads without errors -- Messages appear in dmesg showing load -- Module appears in `kldstat` output -- Module unloads successfully -- Unload message appears in dmesg -- No kernel panics or crashes +- 模块编译无错误或警告 +- 生成了 `hello.ko` 文件(10-20 KB) +- 模块加载无错误 +- dmesg 中出现显示加载的消息 +- 模块出现在 `kldstat` 输出中 +- 模块成功卸载 +- dmesg 中出现卸载消息 +- 无内核崩溃或故障 -### What You Learned +### 你学到了什么 -**Technical skills**: +**技术技能**: -- Writing a minimal kernel module structure -- Using FreeBSD's kernel module build system -- Loading and unloading kernel modules safely -- Observing kernel messages with dmesg +- 编写最小内核模块结构 +- 使用 FreeBSD 的内核模块构建系统 +- 安全地加载和卸载内核模块 +- 使用 dmesg 观察内核消息 -**Concepts**: +**概念**: -- Module event handlers (MOD_LOAD/MOD_UNLOAD lifecycle) -- DECLARE_MODULE and MODULE_VERSION macros -- Kernel printf vs userspace printf -- Why root access is required for module operations +- 模块事件处理程序(MOD_LOAD/MOD_UNLOAD 生命周期) +- DECLARE_MODULE 和 MODULE_VERSION 宏 +- 内核 printf 与用户空间 printf +- 为什么模块操作需要 root 权限 -**Confidence**: +**信心**: -- Your build environment works correctly -- You can compile and load kernel code -- You understand the basic module lifecycle -- You're ready to add actual functionality (Lab 3) +- 你的构建环境工作正常 +- 你可以编译和加载内核代码 +- 你理解了基本的模块生命周期 +- 你已经准备好添加实际功能(实验 3) -### Lab Logbook Entry Template +### 实验日志条目模板 ```text Lab 2 Complete: [Date] @@ -13938,18 +13766,18 @@ Next steps: [Ready for Lab 3: adding real functionality with device nodes] ``` -### Optional Experiment: Module Load Order +### 可选实验:模块加载顺序 -Want to see why SI_SUB and SI_ORDER matter? +想看看为什么 SI_SUB 和 SI_ORDER 很重要吗? -1. **Check current boot order**: +1. **检查当前启动顺序**: ```bash % kldstat -v | less ``` -2. **Try different subsystem orders**: - Edit hello.c and change: +2. **尝试不同的子系统顺序**: + 编辑 hello.c 并修改: ```c DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); @@ -13961,47 +13789,47 @@ to: DECLARE_MODULE(hello, hello_mod, SI_SUB_PSEUDO, SI_ORDER_FIRST); ``` -Rebuild and reload. Module still works! The order only matters when modules depend on each other. +重新构建并重新加载。模块仍然工作!顺序仅在模块相互依赖时才重要。 ## 实验3:创建和删除设备节点 -### Goal +### 目标 -Extend the minimal module to create a `/dev` entry that users can interact with. Implement basic read and write operations. +扩展这个极简模块,创建一个用户可交互的 `/dev` 条目。实现基本的读写操作。 -### What You'll Learn +### 你将学到什么 -- How to create a character device node in `/dev` -- How to implement cdevsw (character device switch) entry points -- How to safely copy data between user and kernel space with `uiomove()` -- How open/close/read/write syscalls connect to your driver functions -- The relationship between struct cdev, cdevsw, and device operations -- Proper resource cleanup and NULL pointer safety +- 如何在 `/dev` 中创建字符设备节点 +- 如何实现 cdevsw(字符设备开关)入口点 +- 如何使用 `uiomove()` 在用户空间和内核空间之间安全地复制数据 +- open/close/read/write 系统调用如何连接到你的驱动程序函数 +- struct cdev、cdevsw 和设备操作之间的关系 +- 正确的资源清理和 NULL 指针安全 -### Prerequisites +### 先决条件 -- Completed Lab 2 (Hello Module) -- Understanding of file operations (open, read, write, close) -- Basic C string handling knowledge +- 已完成实验 2(Hello 模块) +- 理解文件操作(打开、读、写、关闭) +- 基本的 C 字符串处理知识 -### Time Estimate +### 预计时间 -60-75 minutes (including code understanding, building, and thorough testing) +60-75 分钟(包括代码理解、构建和全面测试) -### Instructions +### 说明 -#### Step 1: Create New Working Directory +#### 第 1 步:创建新的工作目录 ```bash % mkdir -p ~/drivers/demo % cd ~/drivers/demo ``` -**Why a new directory?**: Keep each lab self-contained for easy reference later. +**为什么新建目录?**:保持每个实验独立,便于日后参考。 -#### Step 2: Create the Driver Source +#### 步骤 2:创建驱动程序源文件 -Create `demo.c` with the following complete code: +使用以下完整代码创建 `demo.c`: ```c /* @@ -14462,17 +14290,17 @@ DECLARE_MODULE(demo, demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(demo, 1); ``` -**Key concepts in this code**: +**此代码中的关键概念**: -1. **cdevsw structure**: The dispatch table connecting syscalls to your functions -2. **uiomove()**: Safe kernel <-> user data transfer (never use memcpy!) -3. **make_dev()**: Creates visible /dev entry -4. **destroy_dev()**: Removes device and waits for operations to complete -5. **NULL safety**: Always check pointers before use, set to NULL after free +1. **cdevsw 结构体**:连接系统调用与你的函数的分发表 +2. **uiomove()**:安全的内核 <-> 用户数据传输(绝不要使用 memcpy!) +3. **make_dev()**:创建可见的 /dev 条目 +4. **destroy_dev()**:移除设备并等待操作完成 +5. **NULL 安全性**:始终在使用前检查指针,释放后置为 NULL -#### Step 3: Create the Makefile +#### 步骤 3:创建 Makefile -Create `Makefile`: +创建 `Makefile`: ```makefile # Makefile for demo character device driver @@ -14483,7 +14311,7 @@ SRCS= demo.c .include ``` -#### Step 4: Build the Driver +#### 步骤 4:构建驱动程序 ```bash % make clean @@ -14494,11 +14322,11 @@ cc -O2 -pipe -fno-strict-aliasing -Werror -D_KERNEL ... -c demo.c ld -d -warn-common -r -d -o demo.ko demo.o ``` -**Expected**: Clean build with no errors. +**预期结果**:干净构建,无错误。 -**If you see warnings about unused parameters**: This is fine - we marked them `__unused` but some compiler versions still warn. +**如果看到关于未使用参数的警告**:这没问题——我们已将它们标记为 `__unused`,但某些编译器版本仍会警告。 -#### Step 5: Load the Driver +#### 步骤 5:加载驱动程序 ```bash % sudo kldload ./demo.ko @@ -14510,37 +14338,37 @@ demo: Try: cat /dev/demo demo: Try: echo "test" > /dev/demo ``` -#### Step 6: Verify Device Node Creation +#### 第 6 步:验证设备节点创建 ```bash % ls -l /dev/demo crw-rw-rw- 1 root wheel 0x5e Nov 14 16:00 /dev/demo ``` -**What you're seeing**: +**你所看到的内容**: -- **c**: Character device (not block device or regular file) -- **rw-rw-rw-**: Permissions 0666 (anyone can read/write) -- **root wheel**: Owned by root, group wheel -- **0x5e**: Device number (major/minor combined - your value may differ) -- **/dev/demo**: The device path +- **c**:字符设备(不是块设备或常规文件) +- **rw-rw-rw-**:权限 0666(任何人都可读/写) +- **root wheel**:由 root 拥有,组为 wheel +- **0x5e**:设备号(主/次设备号组合——你的值可能不同) +- **/dev/demo**:设备路径 -#### Step 7: Test Reading +#### 第 7 步:测试读取 ```bash % cat /dev/demo Hello from demo driver! ``` -**What happened**: +**发生了什么**: -1. `cat` opened /dev/demo -> `demo_open()` called -2. `cat` called `read()` -> `demo_read()` called -3. Driver copied "Hello from demo driver!\\n" to cat's buffer via `uiomove()` -4. `cat` printed the received data to stdout -5. `cat` closed the file -> `demo_close()` called +1. `cat` 打开 /dev/demo -> 调用 `demo_open()` +2. `cat` 调用 `read()` -> 调用 `demo_read()` +3. 驱动程序通过 `uiomove()` 将 "Hello from demo driver!\\n" 复制到 cat 的缓冲区 +4. `cat` 将接收到的数据打印到标准输出 +5. `cat` 关闭文件 -> 调用了 `demo_close()` -**Check kernel log**: +**检查内核日志**: ```bash % dmesg | tail -5 @@ -14550,9 +14378,9 @@ demo: Read completed, transferred 25 bytes demo: Device closed (pid=1234) ``` -**Note**: `uio_resid=65536` means cat requested 64 KB (its default buffer). We only sent 25 bytes, which is fine - read() returns how much was actually transferred. +**注意**:`uio_resid=65536` 表示 cat 请求了 64 KB(其默认缓冲区)。我们只发送了 25 字节,这没问题——read() 返回实际传输的数据量。 -#### Step 8: Test Writing +#### 第 8 步:测试写入 ```bash % echo "Test message" > /dev/demo @@ -14564,14 +14392,14 @@ demo: User wrote 13 bytes: "Test message demo: Device closed (pid=1235) ``` -**What happened**: +**发生了什么**: -1. Shell opened /dev/demo for writing +1. Shell 打开 /dev/demo 进行写入 2. `echo` wrote "Test message\\n" (13 bytes including newline) -3. Driver received it via `uiomove()` and logged it -4. Shell closed the device +3. 驱动程序通过 `uiomove()` 接收并记录 +4. Shell 关闭了设备 -#### Step 9: Test Multiple Operations +#### 第 9 步:测试多个操作 ```bash % (cat /dev/demo; echo "Another test" > /dev/demo; cat /dev/demo) @@ -14579,7 +14407,7 @@ Hello from demo driver! Hello from demo driver! ``` -**Watch dmesg in another terminal**: +**在另一个终端中查看 dmesg**: ```bash % dmesg -w # Watch mode - updates in real-time @@ -14598,7 +14426,7 @@ demo: Read completed, transferred 25 bytes demo: Device closed (pid=1238) ``` -#### Step 10: Test With dd (Controlled I/O) +#### 步骤 10:使用 dd 进行测试(受控 I/O) ```bash % dd if=/dev/demo bs=10 count=1 2>/dev/null @@ -14608,29 +14436,29 @@ Hello from Hello from demo driver! ``` -**What this shows**: +**这说明了什么**: -- First dd: Requested 10 bytes, got 10 bytes ("Hello from") -- Second dd: Requested 100 bytes, got 25 bytes (our full message) -- The driver respects the requested size via `uio_resid` +- 第一次 dd:请求 10 字节,得到 10 字节("Hello from") +- 第二次 dd:请求 100 字节,获得 25 字节(我们的完整消息) +- 驱动程序通过 `uio_resid` 尊重请求的大小 -#### Step 11: Verify Unload Protection +#### 第 11 步:验证卸载保护 -**Open the device and keep it open**: +**打开设备并保持打开状态**: ```bash % (sleep 30; echo "Done") > /dev/demo & [1] 1240 ``` -**Now try to unload** (in the same 30-second window): +**现在尝试卸载**(在同一30秒窗口内): ```bash % sudo kldunload demo [hangs... waiting...] ``` -**After 30 seconds**: +**30秒后**: ```text Done @@ -14639,9 +14467,9 @@ demo: Device /dev/demo destroyed [kldunload completes] ``` -**What happened**: `destroy_dev()` waited for the write operation to complete before allowing the unload. This is a CRITICAL safety feature - it prevents crashes from unloading code that's still executing. +**发生了什么**:`destroy_dev()` 等待写操作完成后再允许卸载。这是一个**关键的安全特性**——它防止因卸载仍在执行的代码而导致系统崩溃。 -#### Step 12: Final Cleanup +#### 第 12 步:最终清理 ```bash % sudo kldunload demo # If still loaded @@ -14649,18 +14477,18 @@ demo: Device /dev/demo destroyed ls: /dev/demo: No such file or directory # Good - it's gone ``` -### Behind the Scenes: The Complete Path +### 幕后:完整路径 -Let's trace `cat /dev/demo` from shell to driver and back: +让我们追踪 `cat /dev/demo` 从 shell 到驱动程序再返回的路径: -#### 1. Shell executes cat +#### 1. Shell 执行 cat ```text User space: Shell forks, execs /bin/cat with argument "/dev/demo" ``` -#### 2. cat opens the file +#### 2. cat 打开文件 ```text User space: @@ -14683,7 +14511,7 @@ User space: cat: fd = 3 (success) ``` -#### 3. cat reads data +#### 3. cat 读取数据 ```text User space: @@ -14716,7 +14544,7 @@ User space: cat: n = 24 (got 24 bytes) ``` -#### 4. cat processes data +#### 4. cat 处理数据 ```text User space: @@ -14724,7 +14552,7 @@ User space: [Your terminal shows: Hello from demo driver!] ``` -#### 5. cat tries to read more +#### 5. cat 尝试读取更多数据 ```text User space: @@ -14740,9 +14568,9 @@ User space: [Would print again, but cat knows this is a device not a file] ``` -Actually, `cat` will keep reading until it gets 0 bytes (EOF). Our driver never returns 0, so `cat` would hang! But typically cat times out or you hit Ctrl+C. +实际上,`cat` 会一直读取直到获得 0 字节(EOF)。我们的驱动程序从不返回 0,因此 `cat` 会挂起!但通常 `cat` 会超时,或者你可以按 Ctrl+C。 -**Better read() implementation** for file-like behavior: +**更好的 read() 实现**(模拟文件行为): ```c static size_t bytes_sent = 0; /* Track position */ @@ -14767,9 +14595,9 @@ demo_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) } ``` -But for our demo, the simple version is fine. +但对于我们的演示,简单版本就足够了。 -#### 6. cat closes file +#### 6. cat 关闭文件 ```text User space: @@ -14791,13 +14619,13 @@ User space: cat: exit(0) ``` -### Concept Deep-Dive: Why uiomove()? +### 概念深入:为什么要用 uiomove()? -**Question**: Why can't we just use `memcpy()` or direct pointer access? +**问题**:为什么我们不能直接使用 `memcpy()` 或直接指针访问? -**Answer**: User space and kernel space have **separate address spaces**. +**答案**:用户空间和内核空间具有**独立的地址空间**。 -#### Address space separation: +#### 地址空间分离: ```text User space (cat process): @@ -14810,7 +14638,7 @@ Kernel space: Address 0x1001: DIFFERENT memory ``` -A pointer that's valid in user space (like cat's buffer at `0x1000`) is **meaningless** in kernel space. If you try: +在用户空间有效的指针(如 cat 的缓冲区位于 `0x1000`)在内核空间是**无意义的**。如果你尝试: ```c /* WRONG - WILL CRASH */ @@ -14818,76 +14646,76 @@ char *user_buf = (char *)0x1000; /* User's buffer address */ strcpy(user_buf, "data"); /* KERNEL PANIC! */ ``` -The kernel will try to write to address `0x1000` in *kernel* address space, which is completely different memory. At best, you corrupt kernel data. At worst, immediate panic. +内核将尝试写入*内核*地址空间中的地址 `0x1000`,这完全是不同的内存。最坏情况下,你会损坏内核数据。更糟的情况是立即崩溃。 -#### What uiomove() does: +#### uiomove() 的作用: -1. **Validates**: Checks that user addresses are actually in user space -2. **Maps**: Temporarily maps user pages into kernel address space -3. **Copies**: Performs the copy using valid kernel addresses -4. **Unmaps**: Cleans up the temporary mapping -5. **Handles faults**: If user buffer is invalid, returns EFAULT +1. **验证**:检查用户地址是否确实在用户空间中 +2. **映射**:临时将用户页面映射到内核地址空间 +3. **复制**:使用有效内核地址执行复制 +4. **取消映射**:清理临时映射 +5. **处理错误**:如果用户缓冲区无效,返回 EFAULT -This is why **every driver must use uiomove(), copyin(), or copyout()** for user data transfer. Direct access is always wrong and dangerous. +这就是为什么**每个驱动程序必须使用 uiomove()、copyin() 或 copyout()** 进行用户数据传输。直接访问总是错误且危险的。 -### Success Criteria +### 成功标准 -- Driver compiles without errors -- Module loads successfully -- Device node `/dev/demo` appears with correct permissions -- Can read from device (get message) -- Can write to device (message logged in dmesg) -- Operations appear in dmesg with correct PIDs -- Module can be unloaded cleanly -- evice node disappears after unload -- Unload waits for operations to complete (tested with sleep experiment) -- No kernel panics or crashes +- 驱动程序编译无错误 +- 模块成功加载 +- 设备节点 `/dev/demo` 出现,权限正确 +- 可以从设备读取(获取消息) +- 可以向设备写入(消息记录在 dmesg 中) +- 操作出现在 dmesg 中,带有正确的 PID +- 模块可以干净地卸载 +- 卸载后设备节点消失 +- 卸载等待操作完成(通过睡眠实验测试) +- 无内核崩溃或故障 -### What You Learned +### 你学到了什么 -**Technical skills**: +**技术技能**: -- Creating character device nodes with `make_dev()` -- Implementing cdevsw method table -- Safe user-kernel data transfer with `uiomove()` -- Proper resource cleanup with `destroy_dev()` -- Debugging with `printf()` and dmesg +- 使用 `make_dev()` 创建字符设备节点 +- 实现 cdevsw 方法表 +- 使用 `uiomove()` 进行安全的用户-内核数据传输 +- 使用 `destroy_dev()` 进行正确的资源清理 +- 使用 `printf()` 和 dmesg 进行调试 -**Concepts**: +**概念**: -- How syscalls (open/read/write/close) map to driver functions -- The role of cdevsw as a dispatch table -- Why uiomove() is necessary (address space separation) -- How destroy_dev() provides synchronization -- The relationship between cdev, devfs, and /dev entries +- 系统调用(open/read/write/close)如何映射到驱动程序函数 +- cdevsw 作为分发表的作用 +- `uiomove()` 为什么是必要的(地址空间隔离) +- destroy_dev() 如何提供同步 +- cdev、devfs 和 /dev 条目之间的关系 -**Best practices**: +**最佳实践**: -- Always check make_dev() return value -- Always check for NULL before destroy_dev() -- Set pointers to NULL after freeing -- Use MIN() to prevent buffer overruns -- Log operations for debugging +- 始终检查 make_dev() 的返回值 +- 在调用 `destroy_dev()` 之前始终检查 NULL +- 释放后将指针设置为 NULL +- 使用 MIN() 防止缓冲区溢出 +- 记录操作以便调试 -### Common Mistakes and How to Avoid Them +### 常见错误及如何避免 -#### Mistake 1: Using memcpy() instead of uiomove() +#### 错误 1:使用 memcpy() 而非 uiomove() -**Wrong**: +**错误**: ```c memcpy(user_buffer, kernel_data, size); /* CRASH! */ ``` -**Right**: +**正确**: ```c uiomove(kernel_data, size, uio); /* Safe */ ``` -#### Mistake 2: Not consuming all write data +#### 错误 2:未消耗所有写入数据 -**Wrong**: +**错误**: ```c demo_write(...) { @@ -14897,9 +14725,9 @@ demo_write(...) { } ``` -**Result**: Kernel calls demo_write() again with remaining data -> infinite loop +**结果**:内核用剩余数据再次调用 demo_write() -> 无限循环 -**Right**: +**正确**: ```c demo_write(...) { @@ -14911,16 +14739,16 @@ demo_write(...) { } ``` -#### Mistake 3: Forgetting NULL check before destroy_dev() +#### 错误 3:在调用 destroy_dev() 之前忘记检查 NULL -**Wrong**: +**错误**: ```c MOD_UNLOAD: destroy_dev(demo_dev); /* What if make_dev failed? */ ``` -**Right**: +**正确**: ```c MOD_UNLOAD: @@ -14930,24 +14758,24 @@ MOD_UNLOAD: } ``` -#### Mistake 4: Wrong permissions on device node +#### 错误 4:设备节点权限错误 -If you use `0600` permissions: +如果使用 `0600` 权限: ```c make_dev(&demo_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "demo"); ``` -Regular users can't access it: +普通用户无法访问它: ```bash % cat /dev/demo cat: /dev/demo: Permission denied ``` -Use `0666` for world-accessible devices (appropriate for learning/testing). +对世界可访问的设备使用 `0666`(适合学习/测试)。 -### Lab Logbook Entry Template +### 实验日志条目模板 ```text Lab 3 Complete: [Date] @@ -14986,46 +14814,46 @@ Next steps: ## 实验4:错误处理和防御性编程 -### Goal +### 目标 Learn error handling by deliberately introducing bugs, observing symptoms, and fixing them properly. Develop defensive programming instincts for driver development. -### What You'll Learn +### 你将学到什么 -- What happens when cleanup is incomplete -- How to detect resource leaks -- The importance of cleanup order -- How to handle allocation failures -- Defensive programming techniques (NULL checks, pointer clearing) -- How to debug driver issues using kernel logs and system tools +- 当清理不完整时会发生什么 +- 如何检测资源泄漏 +- 清理顺序的重要性 +- 如何处理分配失败 +- 防御性编程技术(NULL 检查、指针清除) +- 如何使用内核日志和系统工具调试驱动程序问题 -### Prerequisites +### 先决条件 -- Completed Lab 3 (Demo Device) -- Understanding of demo.c code structure -- Ability to edit C code and rebuild +- 已完成实验 3(演示设备) +- 理解 demo.c 代码结构 +- 能够编辑 C 代码并重新构建 -### Time Estimate +### 预计时间 -30-40 minutes (deliberate breaking, observing, and fixing) +30-40 分钟(故意破坏、观察和修复) -### Important Safety Note +### 重要安全提示 -These experiments involve **deliberately crashing** your driver (not the kernel, just the driver). This is safe in your lab VM but demonstrates real bugs you must avoid in production code. +这些实验涉及**故意使你的驱动程序崩溃**(不是内核,只是驱动程序)。这在你的实验 VM 中是安全的,但演示了你必须避免在生产代码中出现的真实错误。 -**Always**: +**始终**: -- Use your lab VM, never your host system -- Take a VM snapshot before starting -- Be prepared to reboot if something hangs +- 使用你的实验 VM,绝不要用宿主机 +- 开始前先拍摄 VM 快照 +- 准备好在挂起时重启 -### Part 1: The Resource Leak Bug +### 第一部分:资源泄露错误 -#### Experiment 1A: Forget to destroy_dev() +#### 实验 1A:忘记调用 destroy_dev() -**Goal**: See what happens when you forget to clean up device nodes. +**目标**:看看当你忘记清理设备节点时会发生什么。 -**Step 1**: Edit demo.c, comment out destroy_dev(): +**第 1 步**:编辑 demo.c,注释掉 destroy_dev(): ```c case MOD_UNLOAD: @@ -15037,7 +14865,7 @@ case MOD_UNLOAD: break; ``` -**Step 2**: Rebuild and load: +**第 2 步**:重新构建并加载: ```bash % make clean && make @@ -15046,7 +14874,7 @@ case MOD_UNLOAD: crw-rw-rw- 1 root wheel 0x5e Nov 14 17:00 /dev/demo ``` -**Step 3**: Unload the module: +**步骤 3**:卸载模块: ```bash % sudo kldunload demo @@ -15054,50 +14882,50 @@ crw-rw-rw- 1 root wheel 0x5e Nov 14 17:00 /dev/demo demo: Device /dev/demo destroyed # Lied! ``` -**Step 4**: Check if device still exists: +**第 4 步**:检查设备是否仍然存在: ```bash % ls -l /dev/demo crw-rw-rw- 1 root wheel 0x5e Nov 14 17:00 /dev/demo # STILL THERE! ``` -**Step 5**: Try to use the orphaned device: +**步骤 5**:尝试使用孤儿设备: ```bash % cat /dev/demo ``` -**Symptoms you might see**: +**你可能看到的症状**: -- Hang (cat blocks forever) -- Kernel panic (jumps to unmapped memory) -- Error message about invalid device +- 挂起(cat 永久阻塞) +- 内核崩溃(跳转到未映射内存) +- 关于无效设备的错误消息 -**Step 6**: Check for leaks: +**第 6 步**:检查泄漏: ```bash % vmstat -m | grep cdev cdev 10 15K - 1442 16,32,64 ``` -The count may be higher than before you started. +计数可能比你开始前更高。 -**Step 7**: Reboot to clean up: +**第 7 步**:重启以清理: ```bash % sudo reboot ``` -**What you learned**: +**你学到的内容**: -- **Orphaned device nodes** persist in `/dev` even when driver unloads -- Trying to use orphaned devices causes **undefined behavior** (crash, hang, or errors) -- This is a **resource leak** - the cdev structure and device node are never freed -- **Always call destroy_dev()** in cleanup path +- **孤立设备节点**在驱动程序卸载后仍会存在于 `/dev` 中 +- 尝试使用孤立设备会导致**未定义行为**(崩溃、挂起或错误) +- 这是一种**资源泄漏**——`cdev` 结构和设备节点永远不会被释放 +- **始终在清理路径中调用 destroy_dev()** -#### Experiment 1B: Fix it properly +#### 实验 1B:正确修复 -**Step 1**: Restore the destroy_dev() call: +**第 1 步**:恢复 `destroy_dev()` 调用: ```c case MOD_UNLOAD: @@ -15109,7 +14937,7 @@ case MOD_UNLOAD: break; ``` -**Step 2**: Rebuild, load, test, unload: +**第 2 步**:重新构建、加载、测试、卸载: ```bash % make clean && make @@ -15120,23 +14948,23 @@ case MOD_UNLOAD: % ls -l /dev/demo # GONE - correct! ``` -**Success**: Device node properly cleaned up. +**成功**:设备节点已正确清理。 -### Part 2: The Wrong Order Bug +### 第二部分:顺序错误 Bug -#### Experiment 2A: Free before destroying +#### 实验 2A:先释放后销毁 -**Goal**: See why cleanup order matters. +**目标**:了解为什么清理顺序很重要。 -**Step 1**: Add a malloc'd buffer to demo.c: +**第 1 步**:向 demo.c 添加 malloc 的缓冲区: -After `static struct cdev *demo_dev = NULL;`, add: +在 `static struct cdev *demo_dev = NULL;` 之后,添加: ```c static char *demo_buffer = NULL; ``` -**Step 2**: Allocate in MOD_LOAD: +**第 2 步**:在 MOD_LOAD 中分配: ```c case MOD_LOAD: @@ -15149,7 +14977,7 @@ case MOD_LOAD: break; ``` -**Step 3**: **WRONG CLEANUP** - free before destroy: +**第 3 步**:**错误的清理顺序**——先释放后销毁: ```c case MOD_UNLOAD: @@ -15168,40 +14996,40 @@ case MOD_UNLOAD: break; ``` -**Step 4**: Rebuild and test: +**第 4 步**:重新构建并测试: ```bash % make clean && make % sudo kldload ./demo.ko ``` -**Step 5**: **While module is loaded**, in another terminal: +**第 5 步**:**当模块已加载时**,在另一个终端中: ```bash % ( sleep 2; cat /dev/demo ) & # Start delayed cat % sudo kldunload demo # Try to unload ``` -**Race condition**: +**竞态条件**: -1. kldunload starts -2. Your code frees demo_buffer -3. destroy_dev() called -4. Meanwhile, cat opened /dev/demo (device still existed!) -5. demo_read() tries to use freed demo_buffer -6. **Use-after-free crash** or corrupted data +1. kldunload 开始 +2. 你的代码释放了 `demo_buffer` +3. 调用 destroy_dev() +4. 同时,cat 打开 /dev/demo(设备仍然存在!) +5. demo_read() 尝试使用已释放的 demo_buffer +6. **释放后使用崩溃**或数据损坏 -**Symptoms**: +**症状**: -- Kernel panic: "page fault in kernel mode" -- Corrupted output -- Hang +- 内核崩溃:"page fault in kernel mode" +- 输出损坏 +- 挂起 -**Step 6**: Reboot to recover. +**第 6 步**:重启以恢复。 -#### Experiment 2B: Fix the ordering +#### 实验 2B:修复顺序 -**Correct order**: Make device invisible FIRST, then free resources. +**正确顺序**:先使设备不可见,然后释放资源。 ```c case MOD_UNLOAD: @@ -15220,14 +15048,14 @@ case MOD_UNLOAD: break; ``` -**Why this works**: +**为什么这样有效**: -1. `destroy_dev()` removes `/dev/demo` from filesystem -2. `destroy_dev()` **waits** for any in-progress operations (like active reads) -3. After `destroy_dev()` returns, **no new operations can start** -4. **Now** it's safe to free demo_buffer - nothing can access it +1. `destroy_dev()` 从文件系统中移除 `/dev/demo` +2. `destroy_dev()` **等待**任何正在进行的操作(如活跃的读取) +3. 在 `destroy_dev()` 返回后,**无法启动新操作** +4. **现在**可以安全地释放 `demo_buffer`——没有东西能访问它 -**Step 7**: Rebuild and test: +**第 7 步**:重新构建并测试: ```bash % make clean && make @@ -15237,21 +15065,21 @@ case MOD_UNLOAD: # Works safely - no crash ``` -**What you learned**: +**你学到的内容**: -- **Cleanup order is critical**: Device invisible -> wait for operations -> free resources -- `destroy_dev()` provides synchronization (waits for operations) -- **Reverse order** of initialization: Last allocated, first freed +- **清理顺序至关重要**:设备不可见 -> 等待操作 -> 释放资源 +- `destroy_dev()` 提供同步(等待操作完成) +- 初始化的**逆序**:最后分配,最先释放 -### Part 3: The NULL Pointer Bug +### 第三部分:空指针 Bug -#### Experiment 3A: Missing NULL check +#### 实验 3A:缺少 NULL 检查 -**Goal**: See why NULL checks matter. +**目标**:了解为什么 NULL 检查很重要。 -**Step 1**: Make make_dev() fail by using an existing name: +**第 1 步**:通过使用已存在的名称使 make_dev() 失败: -Load demo module, then try to load again in MOD_LOAD: +加载 demo 模块,然后尝试在 MOD_LOAD 中再次加载: ```c case MOD_LOAD: @@ -15263,7 +15091,7 @@ case MOD_LOAD: break; ``` -Or simulate failure: +或模拟失败: ```c case MOD_LOAD: @@ -15273,7 +15101,7 @@ case MOD_LOAD: break; ``` -**Step 2**: Try to unload without NULL check: +**第 2 步**:尝试在未进行 NULL 检查的情况下卸载: ```c case MOD_UNLOAD: @@ -15282,7 +15110,7 @@ case MOD_UNLOAD: break; ``` -**Step 3**: Test: +**第 3 步**:测试: ```bash % make clean && make @@ -15292,13 +15120,13 @@ case MOD_UNLOAD: # Might panic or crash ``` -**Symptoms**: +**症状**: -- Kernel panic in destroy_dev +- destroy_dev 中的内核崩溃 - "panic: bad address" -- System hang +- 系统挂起 -#### Experiment 3B: Proper NULL checking +#### 实验 3B:正确的 NULL 检查 ```c case MOD_LOAD: @@ -15322,19 +15150,19 @@ case MOD_UNLOAD: break; ``` -**Defensive programming rules**: +**防御性编程规则**: -1. **Check every allocation**: `if (ptr == NULL) handle_error();` -2. **Check before freeing**: `if (ptr != NULL) free(ptr);` -3. **Clear after freeing**: `ptr = NULL;` (defense against use-after-free) +1. **检查每次分配**:`if (ptr == NULL) handle_error();` +2. **释放前检查**:`if (ptr != NULL) free(ptr);` +3. **释放后清空**:`ptr = NULL;`(防止释放后使用) -### Part 4: The Allocation Failure Bug +### 第四部分:分配失败 Bug -#### Experiment 4: Handling malloc failures +#### 实验 4:处理 malloc 失败 -**Goal**: Learn to handle M_NOWAIT allocation failures. +**目标**:学习处理 M_NOWAIT 分配失败。 -**Step 1**: Add allocation to attach: +**第 1 步**:向 attach 添加分配: ```c case MOD_LOAD: @@ -15349,7 +15177,7 @@ case MOD_LOAD: break; ``` -**If malloc fails** (rare but possible): +**如果 malloc 失败**(罕见但可能): ```text panic: page fault while in kernel mode @@ -15359,7 +15187,7 @@ instruction pointer = 0x8:0xffffffff12345678 current process = 1234 (kldload) ``` -**Step 2**: Fix with proper error handling: +**第 2 步**:使用正确的错误处理进行修复: ```c case MOD_LOAD: @@ -15385,9 +15213,9 @@ case MOD_LOAD: break; ``` -**Wait, there's still a bug!** If `make_dev()` fails, we return without freeing `demo_buffer`. +**等等,还有一个 bug!** 如果 `make_dev()` 失败,我们返回时没有释放 `demo_buffer`。 -**Step 3**: Fix with complete error unwinding: +**第 3 步**:使用完整的错误回滚进行修复: ```c case MOD_LOAD: @@ -15422,16 +15250,16 @@ fail: return (error); ``` -**Error unwinding pattern**: +**错误展开模式**: -1. Each allocation step can fail -2. On failure, **undo everything done before** -3. Common pattern: use `goto fail` to centralize cleanup -4. Free in reverse order of allocation +1. 每个分配步骤都可能失败 +2. 失败时,**撤销之前所做的所有操作** +3. 常见模式:使用 `goto fail` 集中清理 +4. 按分配顺序的逆序释放 -### Part 5: Complete Example with Full Error Handling +### 第 5 部分:包含完整错误处理的完整示例 -Here's a template showing all best practices: +这是一个展示所有最佳实践的模板: ```c case MOD_LOAD: @@ -15468,18 +15296,18 @@ fail_0: return (error); ``` -**Why this pattern works**: +**为什么这种模式有效**: -- Each `fail_N` label knows exactly what was allocated up to that point -- Cleanup happens in reverse order (last allocated, first freed) -- Single return point for errors makes debugging easier -- All error paths properly clean up +- 每个 `fail_N` 标签明确知道到该点为止分配了什么 +- 清理按逆序进行(最后分配,最先释放) +- 单个错误返回点使调试更容易 +- 所有错误路径都正确清理 -### Debugging Checklist: Finding Driver Bugs +### 调试清单:查找驱动程序错误 -When your driver misbehaves, check these systematically: +当你的驱动程序行为异常时,按系统顺序检查以下内容: -#### 1. Check dmesg for kernel messages +#### 1. 检查 dmesg 中的内核消息 ```bash % dmesg | tail -20 @@ -15487,92 +15315,92 @@ When your driver misbehaves, check these systematically: % dmesg | grep -i "page fault" ``` -Look for: +查找: -- Panic messages -- "sleeping with lock held" +- 崩溃消息 +- "在持有锁时睡眠" - "lock order reversal" -- Your driver's printf messages +- 驱动程序的 printf 消息 -#### 2. Check for resource leaks +#### 2. 检查资源泄漏 -**Before loading module**: +**加载模块前**: ```bash % vmstat -m | grep cdev > before.txt ``` -**After load + unload**: +**加载并卸载后**: ```bash % vmstat -m | grep cdev > after.txt % diff before.txt after.txt ``` -If counts increased, you have a leak. +如果计数增加了,则存在泄漏。 -#### 3. Check for orphaned devices +#### 3. 检查孤立设备 ```bash % ls -l /dev/ | grep demo ``` -If `/dev/demo` exists after unload, you forgot `destroy_dev()`. +如果卸载后 `/dev/demo` 仍然存在,则你忘记了调用 `destroy_dev()`。 -#### 4. Test unload under load +#### 4. 在负载下测试卸载 ```bash % ( sleep 10; cat /dev/demo ) & % sudo kldunload demo ``` -Should wait for cat to finish. If it crashes, you have a race condition. +应等待 cat 完成。如果它崩溃了,则存在竞态条件。 -#### 5. Check module state +#### 5. 检查模块状态 ```bash % kldstat -v | grep demo ``` -Shows dependencies and references. +显示依赖关系和引用。 -### Success Criteria +### 成功标准 -- Observed orphaned device node (Experiment 1A) -- Fixed with proper destroy_dev() (Experiment 1B) -- Observed use-after-free crash (Experiment 2A) -- Fixed with correct cleanup order (Experiment 2B) -- Understood NULL pointer dangers (Experiment 3) -- Implemented proper NULL checking (Experiment 3B) -- Learned error unwinding pattern (Experiment 4) -- Can identify resource leaks with vmstat -- Can debug with dmesg +- 观察到孤立的设备节点(实验 1A) +- 通过正确的 destroy_dev() 修复(实验 1B) +- 观察到释放后使用崩溃(实验 2A) +- 通过正确的清理顺序修复(实验 2B) +- 理解 NULL 指针危险(实验 3) +- 实现了正确的 NULL 检查(实验 3B) +- 学习了错误展开模式(实验 4) +- 可以使用 vmstat 识别资源泄漏 +- 可以使用 dmesg 调试 -### What You Learned +### 你学到了什么 -**Bug types**: +**错误类型**: -- Resource leaks (forgotten destroy_dev) -- Use-after-free (wrong cleanup order) -- NULL pointer dereference (missing checks) -- Memory leaks (failed error unwinding) +- 资源泄漏(忘记 destroy_dev) +- 释放后使用(错误的清理顺序) +- NULL 指针解引用(缺少检查) +- 内存泄漏(错误展开失败) -**Defensive programming**: +**防御性编程**: -- Always check return values -- Always NULL-check before using pointers -- Clean up in reverse order of initialization -- Clear pointers after freeing (`ptr = NULL`) -- Use goto for error unwinding +- 始终检查返回值 +- 使用指针前始终检查 NULL +- 按初始化顺序的逆序清理 +- 释放后清除指针(`ptr = NULL`) +- 使用 goto 进行错误展开 -**Debugging techniques**: +**调试技术**: -- Using dmesg to track operations -- Using vmstat to detect leaks -- Testing unload under load -- Deliberately introducing bugs to understand symptoms +- 使用 dmesg 跟踪操作 +- 使用 vmstat 检测泄漏 +- 在负载下测试卸载 +- 故意引入错误以理解症状 -**Patterns to follow**: +**要遵循的模式**: ```c /* Allocation */ @@ -15600,7 +15428,7 @@ fail: return (error); ``` -### Lab Logbook Entry Template +### 实验日志条目模板 ```text Lab 4 Complete: [Date] @@ -15634,206 +15462,206 @@ Ready for Chapter 7: ## 实验总结和下一步 -Congratulations! You've completed all four labs. Here's what you've accomplished: +恭喜!你已完成所有四个实验。以下是你的收获: -### Lab Progression Summary +### 实验进度总结 -| Lab | What You Built | Key Skill | -| ----- | ----------------- | -------------------------------- | -| Lab 1 | Navigation skills | Read and understand driver code | -| Lab 2 | Minimal module | Build and load kernel modules | -| Lab 3 | Character device | Create /dev nodes, implement I/O | -| Lab 4 | Error handling | Defensive programming, debugging | +| 实验 | 你构建的内容 | 关键技能 | +| ------ | ------------------- | --------------------------- | +| 实验 1 | 导航技能 | 阅读和理解驱动程序代码 | +| 实验 2 | 最小模块 | 构建和加载内核模块 | +| 实验 3 | 字符设备 | 创建 /dev 节点,实现 I/O | +| 实验 4 | 错误处理 | 防御性编程,调试 | -### Key Concepts Mastered +### 掌握的关键概念 -**Module lifecycle**: +**模块生命周期**: -- MOD_LOAD -> initialize -- MOD_UNLOAD -> cleanup -- DECLARE_MODULE registration +- MOD_LOAD -> 初始化 +- MOD_UNLOAD -> 清理 +- DECLARE_MODULE 注册 -**Device framework**: +**设备框架**: -- cdevsw as method dispatch table -- make_dev() to create /dev entries -- destroy_dev() for cleanup + synchronization +- cdevsw 作为方法分发表 +- make_dev() 创建 /dev 条目 +- destroy_dev() 用于清理 + 同步 -**Data transfer**: +**数据传输**: -- uiomove() for safe user-kernel copying -- uio structure for I/O requests -- uio_resid tracking +- uiomove() 用于安全的用户-内核拷贝 +- uio 结构用于 I/O 请求 +- uio_resid 跟踪 -**Error handling**: +**错误处理**: -- NULL checking all allocations -- Reverse-order cleanup -- Error unwinding with goto -- Resource leak prevention +- NULL 检查所有分配 +- 逆序清理 +- 使用 goto 进行错误展开 +- 资源泄漏预防 -**Debugging**: +**调试**: -- Using dmesg for kernel logs -- vmstat for resource tracking -- Testing under load +- 使用 dmesg 查看内核日志 +- vmstat 用于资源跟踪 +- 在负载下测试 -### Your Driver Development Toolkit +### 你的驱动程序开发工具包 -You now have a solid foundation of: +你现在拥有了扎实的基础,包括: -1. **Pattern recognition**: You can look at any FreeBSD driver and identify its structure -2. **Practical skills**: You can build, load, test, and debug kernel modules -3. **Safety knowledge**: You understand common bugs and how to avoid them -4. **Debugging ability**: You can diagnose problems using system tools +1. **模式识别**:你能看懂任何 FreeBSD 驱动程序并识别其结构 +2. **实践技能**:你能构建、加载、测试和调试内核模块 +3. **安全知识**:你理解常见错误以及如何避免它们 +4. **调试能力**:你能使用系统工具诊断问题 -### Celebrate Your Achievement! +### 庆祝你的成就! -You've completed hands-on labs that many developers skip. You didn't just read about drivers, you **built** them, **broke** them, and **fixed** them. This experiential learning is invaluable. +你完成了许多开发者跳过的手动实验。你不仅阅读了驱动程序,还**构建**了它们、**破坏**了它们并**修复**了它们。这种体验式学习是无价的。 ## 总结 -Congratulations! You've completed a comprehensive tour of FreeBSD driver anatomy. Let's recap what you've learned and where we're heading next. +恭喜!你已经完成了 FreeBSD 驱动程序解剖的全面导览。让我们回顾一下你学到了什么以及接下来要去的方向。 -### What You Now Know +### 你现在知道了什么 -**Vocabulary** - You can speak the language of FreeBSD drivers: +**词汇** - 你可以说 FreeBSD 驱动程序的语言了: -- **newbus**: The device framework (probe/attach/detach) -- **devclass**: Grouping of related devices -- **softc**: Per-device private data structure -- **cdevsw**: Character device switch (entry point table) -- **ifnet**: Network interface structure -- **GEOM**: Storage layer architecture -- **devfs**: Dynamic device filesystem +- **newbus**:设备框架(probe/attach/detach) +- **devclass**:相关设备的分组 +- **softc**:每设备私有数据结构 +- **cdevsw**:字符设备开关(入口点表) +- **ifnet**:网络接口结构 +- **GEOM**:存储层架构 +- **devfs**:动态设备文件系统 -**Structure** - You recognize driver patterns instantly: +**结构** - 你能立即识别驱动程序模式: -- Probe functions check device IDs and return priority -- Attach functions initialize hardware and create device nodes -- Detach functions clean up in reverse order -- Method tables map kernel calls to your functions -- Module declarations register with the kernel +- Probe 函数检查设备 ID 并返回优先级 +- Attach 函数初始化硬件并创建设备节点 +- Detach 函数按相反顺序清理 +- 方法表将内核调用映射到你的函数 +- 模块声明向内核注册 -**Lifecycle** - You understand the flow: +**生命周期** - 你理解了流程: -1. Bus enumeration discovers hardware -2. Probe functions compete for devices -3. Attach functions initialize winners -4. Devices operate (read/write, transmit/receive) -5. Detach functions clean up on unload +1. 总线枚举发现硬件 +2. Probe 函数竞争设备 +3. Attach 函数初始化胜出者 +4. 设备运行(读/写、发送/接收) +5. Detach 函数在卸载时清理 -**Entry points** - You know how user programs reach your driver: +**入口点** - 你知道用户程序如何到达你的驱动程序: -- Character devices: open/close/read/write/ioctl via `/dev` -- Network interfaces: transmit/receive via network stack -- Storage devices: bio requests via GEOM/CAM +- 字符设备:通过 `/dev` 的 open/close/read/write/ioctl +- 网络接口:通过网络栈的发送/接收 +- 存储设备:通过 GEOM/CAM 的 bio 请求 -### What You Can Now Do +### 你现在能做什么 -- Navigate the FreeBSD kernel source tree confidently -- Recognize common driver patterns (probe/attach/detach, cdevsw) -- Understand probe/attach/detach lifecycle -- Build kernel modules with proper Makefiles -- Load and unload modules safely -- Create character device nodes with appropriate permissions -- Implement basic I/O operations (open/close/read/write) -- Use uiomove() correctly for user-kernel data transfer -- Handle errors and clean up resources properly -- Debug with dmesg and system tools -- Avoid common pitfalls (resource leaks, wrong cleanup order, NULL pointers) +- 自信地导航 FreeBSD 内核源代码树 +- 识别常见驱动程序模式(probe/attach/detach、cdevsw) +- 理解 probe/attach/detach 生命周期 +- 使用正确的 Makefile 构建内核模块 +- 安全地加载和卸载模块 +- 使用适当的权限创建字符设备节点 +- 实现基本 I/O 操作(open/close/read/write) +- 正确使用 uiomove() 进行用户-内核数据传输 +- 正确处理错误和清理资源 +- 使用 dmesg 和系统工具调试 +- 避免常见陷阱(资源泄漏、错误的清理顺序、NULL 指针) -### Mindset Shift +### 思维转变 -Notice the shift in this chapter: +注意本章的转变: -- **Chapter 1-5**: Foundations (UNIX, C, kernel C) -- **Chapter 6** (this one): Structure and patterns (recognition) -- **Chapter 7+**: Implementation (building) +- **第 1-5 章**:基础(UNIX、C、内核 C) +- **第 6 章**(本章):结构和模式(识别) +- **第 7 章+**:实现(构建) -You've crossed a threshold. You're no longer just learning concepts, you're ready to write real kernel code. This is exciting and a little intimidating, and that's exactly right. +你已经跨过了一个门槛。你不再只是学习概念——你准备好编写真正的内核代码了。这令人兴奋,也有一点令人生畏,而这正是应该有的感觉。 -### Final Thoughts +### 最后的想法 -Driver development is like learning a musical instrument. At first, the patterns feel foreign and complex. But with practice, they become second nature. You'll start to see probe/attach/detach everywhere you look. You'll recognize cdevsw instantly. You'll know what "allocate resources, check for errors, clean up on failure" means without thinking. +驱动程序开发就像学习乐器。起初,模式感觉很陌生和复杂。但随着练习,它们会变成第二本能。你会开始到处看到 probe/attach/detach。你会立即认出 cdevsw。你会不假思索地知道"分配资源、检查错误、失败时清理"意味着什么。 -**Trust the process**. The labs were just the beginning. In Chapter 7, you'll write more code, make mistakes, debug them, and build confidence. By Chapter 8, driver structure will feel natural. +**相信这个过程**。实验只是一个开始。在第 7 章中,你将编写更多代码、犯错误、调试它们并建立信心。到第 8 章时,驱动程序结构会感觉很自然。 -### Before You Move On +### 继续之前 -Take a moment to: +花一点时间: -- **Review your lab logbook** - What surprised you? What clicked? -- **Revisit any confusing sections** - Now that you've done the labs, re-reading makes more sense -- **Browse one more driver** - Pick any from `/usr/src/sys/dev` and see how much you recognize +- **回顾你的实验日志** - 什么让你惊讶?什么让你顿悟? +- **重读任何令人困惑的部分** - 现在你已经做了实验,重读会更有意义 +- **再浏览一个驱动程序** - 从 `/usr/src/sys/dev` 中任选一个,看看你能识别多少 -### Looking Ahead +### 展望未来 -Chapter 6 was the last foundational chapter of Part 1. You now have a complete mental model of how a FreeBSD driver is shaped, from the moment the bus enumerates a device, through probe, attach, operation, and detach, all the way out to `/dev` and `ifconfig`. +第 6 章是第 1 部分的最后一个基础章节。你现在有了一个关于 FreeBSD 驱动程序如何形成的完整心智模型——从总线枚举设备的那一刻起,经过 probe、attach、操作和 detach,一直到 `/dev` 和 `ifconfig`。 -The next chapter, **Chapter 7: Writing Your First Driver**, puts that model to work. You will build a pseudo-device called `myfirst`, attach it cleanly through Newbus, create a `/dev/myfirst0` node, expose a read-only sysctl, log lifecycle events, and detach without leaks. The goal is not a fancy driver, it is a disciplined one, the kind of skeleton every production driver grows from. +下一章,**第 7 章:编写你的第一个驱动程序**,将那个模型付诸实践。你将构建一个名为 `myfirst` 的伪设备,通过 Newbus 干净地连接它,创建一个 `/dev/myfirst0` 节点,暴露一个只读 sysctl,记录生命周期事件,并无泄漏地分离。目标不是一个花哨的驱动程序,而是一个有纪律的驱动程序——每个生产驱动程序都从这种骨架开始的那种。 -Everything you practised in this chapter, the cdevsw shape, the probe/attach/detach rhythm, the unwinding pattern, the rule to always release resources in reverse order, will show up again in Chapter 7 as code you type yourself. Keep your lab logbook close, keep `/usr/src/sys/dev/null/null.c` bookmarked as a reference skeleton, and when you turn the page, you will already know most of what you are about to build. +你在本章练习的一切——cdevsw 形状、probe/attach/detach 节奏、展开模式、始终按相反顺序释放资源的规则——都将在第 7 章中作为你自己编写的代码再次出现。保持你的实验日志在身边,保持 `/usr/src/sys/dev/null/null.c` 作为参考骨架的书签,当你翻页时,你已经知道了你即将构建的大部分内容。 ## 第1部分检查点 -Part 1 has carried you from "what even is UNIX" to "I can read a small driver and name its pieces." Before Chapter 7 asks you to type and load a real module, pause and confirm that the foundation feels steady under your feet. Part 2 builds directly on every skill that the first six chapters gathered. +第 1 部分带你从"UNIX 到底是什么"到"我能阅读一个小型驱动程序并说出它的组件名称"。在第 7 章要求你输入和加载真实模块之前,暂停一下,确认基础在你脚下是稳固的。第 2 部分直接建立在前六章收集的每一项技能之上。 -By the end of Part 1 you should be able to install, configure, and snapshot a FreeBSD working lab, track its source tree under version control, and keep a disciplined logbook of what you changed and why. You should be able to drive the FreeBSD command line for ordinary development work, which means moving around the filesystem, inspecting processes, reading and adjusting permissions, installing packages, following logs, and writing short shell scripts that survive unusual filenames. You should also be able to read and write kernel-style C without flinching at its dialect, including types and qualifiers, bit flags, the preprocessor, pointers and arrays, function pointers, bounded strings, and the kernel-side allocators and logging helpers that replace `malloc(3)` and `printf(3)`. And you should be able to look at any driver under `/usr/src/sys/dev` and name its pieces: which function is the probe, which is the attach, which is the detach, where the softc lives, which entry points the character switch provides, and what resources the attach path is acquiring. +到第 1 部分结束时,你应该能够安装、配置和快照一个 FreeBSD 工作实验环境,在版本控制下跟踪其源代码树,并保持关于你更改了什么以及为什么的纪律性日志。你应该能够驱动 FreeBSD 命令行进行普通开发工作,这意味着在文件系统中移动、检查进程、读取和调整权限、安装包、跟踪日志以及编写能处理异常文件名的短 shell 脚本。你还应该能够不畏惧其方言地阅读和编写内核风格的 C,包括类型和限定符、位标志、预处理器、指针和数组、函数指针、有界字符串,以及替代 `malloc(3)` 和 `printf(3)` 的内核侧分配器和日志助手。你应该能够查看 `/usr/src/sys/dev` 下的任何驱动程序并说出其组件名称:哪个函数是 probe、哪个是 attach、哪个是 detach、softc 在哪里、字符开关提供哪些入口点,以及 attach 路径获取了什么资源。 -If any of those still feels like a lookup rather than a habit, the labs that anchor them are worth a second pass: +如果其中任何一个仍然感觉像是查表而不是习惯,锚定它们的实验值得再做一遍: -- Lab discipline and source navigation: the hands-on labs across Chapter 2 (shell, files, processes, scripting) and the install-and-snapshot walk-through in Chapter 3. -- C for the kernel: Chapter 4 Lab 4 (Function Pointer Dispatch, a mini devsw) and Lab 5 (Fixed-Size Circular Buffer), both of which preview patterns you will meet again in every driver. -- Kernel C dialect: Chapter 5 Lab 1 (Safe Memory Allocation and Cleanup) and Lab 2 (User-Kernel Data Exchange), which teach the two boundaries every driver crosses. -- Driver anatomy: Chapter 6 Lab 1 (Explore the Driver Map), Lab 2 (Minimal Module with Logs Only), and Lab 3 (Create and Remove a Device Node). +- 实验纪律和源代码导航:第 2 章的动手实验(shell、文件、进程、脚本)和第 3 章的安装与快照演练。 +- 内核 C:第 4 章实验 4(函数指针分派,一个迷你 devsw)和实验 5(固定大小的循环缓冲区),两者都预览了你将在每个驱动程序中再次遇到的模式。 +- 内核 C 方言:第 5 章实验 1(安全内存分配和清理)和实验 2(用户-内核数据交换),它们教授每个驱动程序跨越的两个边界。 +- 驱动程序解剖:第 6 章实验 1(探索驱动程序地图)、实验 2(仅带日志的最小模块)和实验 3(创建和删除设备节点)。 -Part 2 will expect a working FreeBSD lab with `/usr/src` installed, a kernel you can build and boot, and the habit of reverting to a clean snapshot after each experiment. It will expect enough comfort with kernel C that a `struct cdevsw`, a `d_read` handler signature, or a labelled-goto cleanup pattern does not stop you. It will also expect the probe/attach/detach rhythm to be held firmly in mind, so that Chapter 7 can turn that rhythm into code you type yourself. If those three hold, you are ready to cross from recognition to authorship. If one wobbles, the quiet hour spent now saves a bewildering afternoon later. +第 2 部分将期望一个安装了 `/usr/src` 的可用 FreeBSD 实验环境、一个你可以构建和引导的内核,以及每次实验后恢复到干净快照的习惯。它将期望你对内核 C 有足够的舒适度,以至于 `struct cdevsw`、`d_read` 处理程序签名或标记 goto 清理模式不会阻止你。它还将期望 probe/attach/detach 节奏牢牢掌握在心中,以便第 7 章可以将那个节奏变成你自己编写的代码。如果这三点都站得住,你就准备好了从识别到创作的跨越。如果其中一点不稳定,现在花一个小时可以省去以后一个令人困惑的下午。 ## 挑战练习(可选) -These optional exercises deepen your understanding and build confidence. They're more open-ended than labs but still safe for beginners. Complete as many as you like before moving to Chapter 7. +这些可选练习加深你的理解并建立信心。它们比实验更开放,但对初学者仍然安全。在进入第 7 章之前完成你想做的即可。 -### Challenge 1: Trace a Lifecycle in dmesg +### 挑战 1:在 dmesg 中追踪生命周期 -**Goal**: Capture and annotate real driver lifecycle messages. +**目标**:捕获并注释真实的驱动程序生命周期消息。 -**Instructions**: +**说明**: -1. Choose a driver that's loadable as a module (e.g., `if_em`, `snd_hda`, `usb`) -2. Set up logging: +1. 选择一个可以作为模块加载的驱动程序(如 `if_em`、`snd_hda`、`usb`) +2. 设置日志: ```bash % tail -f /var/log/messages > ~/driver_lifecycle.log & ``` -3. Load the driver: +3. 加载驱动程序: ```bash % sudo kldload if_em ``` -4. Watch the attach sequence in real time -5. Unload the driver: +4. 实时观看连接序列 +5. 卸载驱动程序: ```bash % sudo kldunload if_em ``` -6. Stop logging (kill the tail process) -7. Annotate the log file: - - Mark where probe was called - - Mark where attach happened - - Mark resource allocations - - Mark where detach cleaned up -8. Write a one-page summary explaining the lifecycle you observed +6. 停止日志(终止 tail 进程) +7. 注释日志文件: + - 标记 probe 被调用的位置 + - 标记 attach 发生的位置 + - 标记资源分配 + - 标记 detach 清理的位置 +8. 写一页总结解释你观察到的生命周期 -**Success criteria**: Your annotated log shows clear understanding of when each lifecycle phase occurred. +**成功标准**:你注释的日志清楚展示了你对每个生命周期阶段何时发生的理解。 -### Challenge 2: Map the Entry Points +### 挑战 2:映射入口点 -**Goal**: Completely document a driver's cdevsw structure. +**目标**:完整记录一个驱动程序的 cdevsw 结构。 -**Instructions**: +**说明**: -1. Open `/usr/src/sys/dev/null/null.c` -2. Create a table: +1. 打开 `/usr/src/sys/dev/null/null.c` +2. 创建一个表格: -| Entry Point | Function Name | Present? | What It Does | +| 入口点 | 函数名 | 是否存在? | 做什么 | |-------------|---------------|----------|--------------| | d_open | ? | ? | ? | | d_close | ? | ? | ? | @@ -15843,173 +15671,173 @@ These optional exercises deepen your understanding and build confidence. They're | d_poll | ? | ? | ? | | d_mmap | ? | ? | ? | -3. Fill in the table -4. For missing entry points, explain why they're not needed -5. For present entry points, describe what they do in 1-2 sentences -6. Repeat for `/usr/src/sys/dev/led/led.c` -7. Compare the two tables: What's similar? What's different? Why? +3. 填写表格 +4. 对于缺失的入口点,解释为什么不需要它们 +5. 对于存在的入口点,用 1-2 句话描述它们做什么 +6. 对 `/usr/src/sys/dev/led/led.c` 重复此操作 +7. 比较两个表格:有什么相似?有什么不同?为什么? -**Success criteria**: Your tables are accurate and your explanations demonstrate understanding. +**成功标准**:你的表格准确,你的解释展示了理解。 -### Challenge 3: Classification Drill +### 挑战 3:分类练习 -**Goal**: Practice identifying driver families by examining source code. +**目标**:通过检查源代码练习识别驱动程序家族。 -**Instructions**: +**说明**: -1. Choose **five random drivers** from `/usr/src/sys/dev/` +1. 从 `/usr/src/sys/dev/` 中选择**五个随机驱动程序** ```bash % ls /usr/src/sys/dev | shuf | head -5 ``` -2. For each driver, create an entry in your logbook: - - Driver name - - Primary source file - - Classification (character, network, storage, bus, or mixed) - - Evidence (how did you determine the classification?) - - Purpose (what does this driver do?) +2. 对于每个驱动程序,在你的日志中创建一个条目: + - 驱动程序名称 + - 主要源文件 + - 分类(字符、网络、存储、总线或混合) + - 证据(你如何确定分类的?) + - 目的(这个驱动程序做什么?) -3. Verification: Use `man 4 ` to confirm your classification +3. 验证:使用 `man 4 ` 确认你的分类 -**Example entry**: +**示例条目**: ```text -Driver: led -File: sys/dev/led/led.c -Classification: Character device -Evidence: Has cdevsw structure, creates /dev/led/* nodes, no ifnet or GEOM -Purpose: Control system LEDs (keyboard lights, chassis indicators) -Man page: man 4 led (confirmed) +驱动程序:led +文件:sys/dev/led/led.c +分类:字符设备 +证据:有 cdevsw 结构,创建 /dev/led/* 节点,没有 ifnet 或 GEOM +目的:控制系统 LED(键盘灯、机箱指示灯) +手册页:man 4 led(已确认) ``` -**Success criteria**: Correctly classified all five, with clear evidence for each. +**成功标准**:正确分类所有五个,每个都有清晰的证据。 -### Challenge 4: Error Code Audit +### 挑战 4:错误码审计 -**Goal**: Understand error handling patterns in real drivers. +**目标**:理解真实驱动程序中的错误处理模式。 -**Instructions**: +**说明**: -1. Open `/usr/src/sys/dev/uart/uart_core.c` -2. Find the `uart_bus_attach()` function -3. List every error code returned (ENOMEM, ENXIO, EIO, etc.) -4. For each, note: - - What condition triggered it - - What resources were freed before returning - - Whether cleanup was complete +1. 打开 `/usr/src/sys/dev/uart/uart_core.c` +2. 找到 `uart_bus_attach()` 函数 +3. 列出每个返回的错误码(ENOMEM、ENXIO、EIO 等) +4. 对于每个错误码,记录: + - 什么条件触发了它 + - 返回前释放了什么资源 + - 清理是否完整 -5. Repeat for `/usr/src/sys/dev/ahci/ahci.c` (ahci_attach function) +5. 对 `/usr/src/sys/dev/ahci/ahci.c`(ahci_attach 函数)重复此操作 -6. Write a short essay (1-2 pages): - - Common error handling patterns you observed - - How drivers ensure no resource leaks - - Best practices you can apply to your own code +6. 写一篇短文(1-2 页): + - 你观察到的常见错误处理模式 + - 驱动程序如何确保没有资源泄漏 + - 你可以应用到自己的代码中的最佳实践 -**Success criteria**: Your essay demonstrates understanding of proper error unwinding. +**成功标准**:你的短文展示了对正确错误展开的理解。 -### Challenge 5: Dependency Detective +### 挑战 5:依赖侦探 -**Goal**: Understand module dependencies and load order. +**目标**:理解模块依赖和加载顺序。 -**Instructions**: +**说明**: -1. Find a driver that declares MODULE_DEPEND +1. 找到一个声明 MODULE_DEPEND 的驱动程序 ```bash % grep -r "MODULE_DEPEND" /usr/src/sys/dev/usb | head -5 ``` -2. Pick one example (e.g., a USB driver) -3. Open the source file and find all MODULE_DEPEND declarations -4. For each dependency: - - What module does it depend on? - - Why is this dependency needed? (What functions/types from that module are used?) - - What would happen if you tried to load without the dependency? -5. Test it: +2. 选择一个示例(如 USB 驱动程序) +3. 打开源文件并找到所有 MODULE_DEPEND 声明 +4. 对于每个依赖: + - 它依赖什么模块? + - 为什么需要这个依赖?(使用了该模块的哪些函数/类型?) + - 如果你在没有依赖的情况下尝试加载会发生什么? +5. 测试它: ```bash % sudo kldload % sudo kldload % kldstat ``` -6. Try to unload the dependency while your driver is loaded: +6. 尝试在你的驱动程序加载时卸载依赖: ```bash % sudo kldunload ``` - What happens? Why? + 发生了什么?为什么? -7. Document your findings: Draw a dependency graph showing the relationships. +7. 记录你的发现:绘制显示关系的依赖图。 -**Success criteria**: You can explain why each dependency exists and predict load order. +**成功标准**:你能解释为什么每个依赖存在并预测加载顺序。 -**Summary** +**小结** -These challenges develop: +这些挑战培养: -- **Challenge 1**: Real-world lifecycle observation -- **Challenge 2**: Entry point mastery -- **Challenge 3**: Pattern recognition across drivers -- **Challenge 4**: Error handling discipline -- **Challenge 5**: Dependency understanding +- **挑战 1**:真实世界的生命周期观察 +- **挑战 2**:入口点掌握 +- **挑战 3**:跨驱动程序的模式识别 +- **挑战 4**:错误处理纪律 +- **挑战 5**:依赖理解 -**Optional**: Share your challenge results in the FreeBSD forums or mailing lists. The community loves seeing newcomers take on harder problems. +**可选**:在 FreeBSD 论坛或邮件列表中分享你的挑战结果。社区喜欢看到新人挑战更难的问题。 ## 摘要参考表 - 驱动程序构建块一览 -This one-screen cheat sheet maps concepts to implementations. Bookmark this page for quick reference while working on Chapter 7 and beyond. +这个一屏速查表将概念映射到实现。为第 7 章及以后的工作收藏此页以便快速参考。 -| Concept | What It Is | Typical API/Structure | Where in Tree | When You'll Use It | +| 概念 | 是什么 | 典型 API/结构 | 在源代码树中的位置 | 何时使用 | |---------|------------|----------------------|---------------|-------------------| -| **device_t** | Opaque device handle | `device_t dev` | `` | Every driver function (probe/attach/detach) | -| **softc** | Per-device private data | `struct mydriver_softc` | You define it | Store state, resources, locks | -| **devclass** | Device class grouping | `devclass_t` | `` | Auto-managed by DRIVER_MODULE | -| **cdevsw** | Character device switch | `struct cdevsw` | `` | Character device entry points | -| **d_open** | Open handler | `d_open_t` | In your cdevsw | Initialize per-session state | -| **d_close** | Close handler | `d_close_t` | In your cdevsw | Clean up per-session state | -| **d_read** | Read handler | `d_read_t` | In your cdevsw | Transfer data to user | -| **d_write** | Write handler | `d_write_t` | In your cdevsw | Accept data from user | -| **d_ioctl** | Ioctl handler | `d_ioctl_t` | In your cdevsw | Configuration and control | -| **uiomove** | Copy to/from user | `int uiomove(...)` | `` | In read/write handlers | -| **make_dev** | Create device node | `struct cdev *make_dev(...)` | `` | In attach (character devices) | -| **destroy_dev** | Remove device node | `void destroy_dev(...)` | `` | In detach | -| **ifnet (if_t)** | Network interface | `if_t` | `` | Network drivers | -| **ether_ifattach** | Register Ethernet if | `void ether_ifattach(...)` | `` | Network driver attach | -| **ether_ifdetach** | Unregister Ethernet if | `void ether_ifdetach(...)` | `` | Network driver detach | -| **GEOM provider** | Storage provider | `struct g_provider` | `` | Storage drivers | -| **bio** | Block I/O request | `struct bio` | `` | Storage I/O handling | -| **bus_alloc_resource** | Allocate resource | `struct resource *` | `` | Attach (memory, IRQ, etc.) | -| **bus_release_resource** | Release resource | `void` | `` | Detach cleanup | -| **bus_space_read_N** | Read register | `uint32_t bus_space_read_4(...)` | `` | Hardware register access | -| **bus_space_write_N** | Write register | `void bus_space_write_4(...)` | `` | Hardware register access | -| **bus_setup_intr** | Register interrupt | `int bus_setup_intr(...)` | `` | Attach (interrupt setup) | -| **bus_teardown_intr** | Unregister interrupt | `int bus_teardown_intr(...)` | `` | Detach cleanup | -| **device_printf** | Device-specific log | `void device_printf(...)` | `` | All driver functions | -| **device_get_softc** | Retrieve softc | `void *device_get_softc(device_t)` | `` | First line of most functions | -| **device_set_desc** | Set device description | `void device_set_desc(...)` | `` | In probe function | -| **DRIVER_MODULE** | Register driver | Macro | `` | Once per driver (end of file) | -| **MODULE_VERSION** | Declare version | Macro | `` | Once per driver | -| **MODULE_DEPEND** | Declare dependency | Macro | `` | If you depend on other modules | -| **DEVMETHOD** | Map method to function | Macro | `` | In method table | -| **DEVMETHOD_END** | End method table | Macro | `` | Last entry in method table | -| **mtx** | Mutex lock | `struct mtx` | `` | Protect shared state | -| **mtx_init** | Initialize mutex | `void mtx_init(...)` | `` | In attach | -| **mtx_destroy** | Destroy mutex | `void mtx_destroy(...)` | `` | In detach | -| **mtx_lock** | Acquire lock | `void mtx_lock(...)` | `` | Before accessing shared data | -| **mtx_unlock** | Release lock | `void mtx_unlock(...)` | `` | After accessing shared data | -| **malloc** | Allocate memory | `void *malloc(...)` | `` | Dynamic allocation | -| **free** | Free memory | `void free(...)` | `` | Cleanup | -| **M_WAITOK** | Wait for memory | Flag | `` | malloc flag (can sleep) | -| **M_NOWAIT** | Don't wait | Flag | `` | malloc flag (returns NULL if unavailable) | +| **device_t** | 不透明设备句柄 | `device_t dev` | `` | 每个驱动程序函数(probe/attach/detach) | +| **softc** | 每设备私有数据 | `struct mydriver_softc` | 你定义它 | 存储状态、资源、锁 | +| **devclass** | 设备类分组 | `devclass_t` | `` | 由 DRIVER_MODULE 自动管理 | +| **cdevsw** | 字符设备开关 | `struct cdevsw` | `` | 字符设备入口点 | +| **d_open** | 打开处理程序 | `d_open_t` | 在你的 cdevsw 中 | 初始化每次会话的状态 | +| **d_close** | 关闭处理程序 | `d_close_t` | 在你的 cdevsw 中 | 清理每次会话的状态 | +| **d_read** | 读取处理程序 | `d_read_t` | 在你的 cdevsw 中 | 向用户传输数据 | +| **d_write** | 写入处理程序 | `d_write_t` | 在你的 cdevsw 中 | 从用户接收数据 | +| **d_ioctl** | Ioctl 处理程序 | `d_ioctl_t` | 在你的 cdevsw 中 | 配置和控制 | +| **uiomove** | 拷贝到/来自用户 | `int uiomove(...)` | `` | 在 read/write 处理程序中 | +| **make_dev** | 创建设备节点 | `struct cdev *make_dev(...)` | `` | 在 attach 中(字符设备) | +| **destroy_dev** | 移除设备节点 | `void destroy_dev(...)` | `` | 在 detach 中 | +| **ifnet (if_t)** | 网络接口 | `if_t` | `` | 网络驱动程序 | +| **ether_ifattach** | 注册以太网接口 | `void ether_ifattach(...)` | `` | 网络驱动程序 attach | +| **ether_ifdetach** | 注销以太网接口 | `void ether_ifdetach(...)` | `` | 网络驱动程序 detach | +| **GEOM provider** | 存储提供者 | `struct g_provider` | `` | 存储驱动程序 | +| **bio** | 块 I/O 请求 | `struct bio` | `` | 存储 I/O 处理 | +| **bus_alloc_resource** | 分配资源 | `struct resource *` | `` | Attach(内存、IRQ 等) | +| **bus_release_resource** | 释放资源 | `void` | `` | Detach 清理 | +| **bus_space_read_N** | 读取寄存器 | `uint32_t bus_space_read_4(...)` | `` | 硬件寄存器访问 | +| **bus_space_write_N** | 写入寄存器 | `void bus_space_write_4(...)` | `` | 硬件寄存器访问 | +| **bus_setup_intr** | 注册中断 | `int bus_setup_intr(...)` | `` | Attach(中断设置) | +| **bus_teardown_intr** | 注销中断 | `int bus_teardown_intr(...)` | `` | Detach 清理 | +| **device_printf** | 设备特定日志 | `void device_printf(...)` | `` | 所有驱动程序函数 | +| **device_get_softc** | 检索 softc | `void *device_get_softc(device_t)` | `` | 大多数函数的第一行 | +| **device_set_desc** | 设置设备描述 | `void device_set_desc(...)` | `` | 在 probe 函数中 | +| **DRIVER_MODULE** | 注册驱动程序 | 宏 | `` | 每个驱动程序一次(文件末尾) | +| **MODULE_VERSION** | 声明版本 | 宏 | `` | 每个驱动程序一次 | +| **MODULE_DEPEND** | 声明依赖 | 宏 | `` | 如果你依赖其他模块 | +| **DEVMETHOD** | 将方法映射到函数 | 宏 | `` | 在方法表中 | +| **DEVMETHOD_END** | 方法表结束 | 宏 | `` | 方法表的最后一个条目 | +| **mtx** | 互斥锁 | `struct mtx` | `` | 保护共享状态 | +| **mtx_init** | 初始化互斥锁 | `void mtx_init(...)` | `` | 在 attach 中 | +| **mtx_destroy** | 销毁互斥锁 | `void mtx_destroy(...)` | `` | 在 detach 中 | +| **mtx_lock** | 获取锁 | `void mtx_lock(...)` | `` | 访问共享数据之前 | +| **mtx_unlock** | 释放锁 | `void mtx_unlock(...)` | `` | 访问共享数据之后 | +| **malloc** | 分配内存 | `void *malloc(...)` | `` | 动态分配 | +| **free** | 释放内存 | `void free(...)` | `` | 清理 | +| **M_WAITOK** | 等待内存 | 标志 | `` | malloc 标志(可以睡眠) | +| **M_NOWAIT** | 不等待 | 标志 | `` | malloc 标志(不可用时返回 NULL) | -### Quick Lookup by Task +### 按任务快速查找 -**Need to...** | **Use This** | **Man Page** +**需要...** | **使用这个** | **手册页** ---|---|--- -Create a character device | `make_dev()` | `make_dev(9)` -Read/write hardware registers | `bus_space_read/write_N()` | `bus_space(9)` -Allocate hardware resources | `bus_alloc_resource()` | `bus_alloc_resource(9)` -Set up interrupts | `bus_setup_intr()` | `bus_setup_intr(9)` -Copy data to/from user | `uiomove()` | `uio(9)` -Log a message | `device_printf()` | `device(9)` -Protect shared data | `mtx_lock()` / `mtx_unlock()` | `mutex(9)` -Register a driver | `DRIVER_MODULE()` | `DRIVER_MODULE(9)` +创建字符设备 | `make_dev()` | `make_dev(9)` +读/写硬件寄存器 | `bus_space_read/write_N()` | `bus_space(9)` +分配硬件资源 | `bus_alloc_resource()` | `bus_alloc_resource(9)` +设置中断 | `bus_setup_intr()` | `bus_setup_intr(9)` +拷贝数据到/来自用户 | `uiomove()` | `uio(9)` +记录消息 | `device_printf()` | `device(9)` +保护共享数据 | `mtx_lock()` / `mtx_unlock()` | `mutex(9)` +注册驱动程序 | `DRIVER_MODULE()` | `DRIVER_MODULE(9)` -### Probe/Attach/Detach Quick Reference +### Probe/Attach/Detach 快速参考 ```c /* Probe - Check if we can handle this device */ diff --git a/translations/zh_CN/chapters/part2/chapter-09.md b/translations/zh_CN/chapters/part2/chapter-09.md index 6a814cf..609efdb 100644 --- a/translations/zh_CN/chapters/part2/chapter-09.md +++ b/translations/zh_CN/chapters/part2/chapter-09.md @@ -42,7 +42,7 @@ estimatedReadTime: 195 - `/dev/myfirst/0` 处的主 cdev,所有权为 `root:operator`,模式为 `0660`。 - `/dev/myfirst` 处指向主设备的别名 cdev。 - 每次 `open(2)` 分配的 `struct myfirst_fh`,通过 `devfs_set_cdevpriv(9)` 注册,由每个描述符恰好触发一次的析构函数释放。 -- 桩函数 `d_read` 和 `d_write` 处理程序检索每次打开的状态,可选地查看它,并立即返回: `d_read` returns zero bytes (EOF), `d_write` claims to have consumed every byte by setting `uio_resid = 0`. +- 桩函数 `d_read` 和 `d_write` 处理程序检索每次打开的状态,可选地查看它,并立即返回:`d_read` 返回零字节(EOF),`d_write` 通过设置 `uio_resid = 0` 声称已消耗所有字节。 第九章将这些桩函数变成真正的。 驱动的外部形状变化不大。 新读者仍然应该看到 `/dev/myfirst/0`,仍然看到别名,仍然看到 sysctl。 变化的是 `cat /dev/myfirst/0` 现在会产生输出,`echo hello > /dev/myfirst/0` 现在会将文本存储到驱动内存中,第二次 `cat` 会读回第一次写入的确切内容。 到本章结束时,你的驱动将是一个小型的、纪律严明的内存缓冲区,你可以向其中推送字节并从中拉取字节。 它还不会是带有阻塞读取的循环缓冲区;那是第十章的工作。 它将是一个正确移动字节的驱动。 @@ -98,7 +98,7 @@ estimatedReadTime: 195 - 你有一个等效于 `examples/part-02/ch08-working-with-device-files/stage2-perhandle/` 下第八章阶段 2 源码的工作 `myfirst` 驱动。如果你还没有到达第八章结尾,在此暂停并回来。 - 你的实验机器运行带有匹配 `/usr/src` 的 FreeBSD 14.3。 - 你已经阅读过第四章关于指针、结构和内存布局的讨论,以及第五章关于内核空间习惯和安全性的讨论。 -- You understand what a `struct cdev` is and how it is related to a `cdevsw`. Chapter 8 covered this in detail. +- 你理解 `struct cdev` 是什么以及它如何与 `cdevsw` 相关联。第八章已详细介绍了这些内容。 如果你对这些中的任何一个不确定,本章的其余部分会比它需要的更难。先重温相关部分。 @@ -128,7 +128,7 @@ estimatedReadTime: 195 10. 内部缓冲区:静态、动态和固定大小。如何选择一个、如何安全地拥有它、你应该识别的内核辅助函数。 11. 错误处理:对 I/O 重要的 errno 值、如何发出文件结束信号、以及如何思考部分传输。 12. 三阶段 `myfirst` 实现,包括驱动源码。 -13. A step-by-step trace of `read(2)` from user space through the kernel down to your handler, plus a mirrored write trace. +13. 从用户空间通过内核到你的处理程序的 `read(2)` 的逐步追踪,加上镜像的写入追踪。 14. 测试的实用工作流:`cat`、`echo`、`dd`、`truss`、`ktrace`,以及将它们变成开发节奏的纪律。 15. 可观测性:sysctl、dmesg 和 `vmstat -m`,带有驱动在轻负载下的具体快照。 16. 有符号、无符号和差一的危害——简短但高价值的章节。 @@ -457,9 +457,9 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) ### 实际使用中的签名:myfirst_read 阶段 1 -Here is what our Stage 1 `d_read` will look like. Do not type it in yet; we will walk through the full source in the implementation section. Seeing it here and now is mostly to anchor the discussion. +这是我们的阶段 1 `d_read` 的样子。先不要输入它;我们将在实现部分完整演练源码。现在在这里看到它主要是为了锚定讨论。 -Before you read the code, pause on one detail that will recur in almost every handler for the rest of this chapter. The first four lines of any per-open-aware handler follow a fixed **boilerplate pattern**: +在阅读代码之前,请停在一个将在本章余下几乎每个处理程序中重复出现的细节上。任何感知每次打开的处理程序的前四行都遵循固定的**样板模式**: ```c struct myfirst_fh *fh; @@ -470,7 +470,7 @@ if (error != 0) return (error); ``` -This pattern retrieves the per-descriptor `fh` that `d_open` registered through `devfs_set_cdevpriv(9)`, and it propagates any failure back to the kernel unchanged. You will see it at the top of `myfirst_read`, `myfirst_write`, `myfirst_ioctl`, `myfirst_poll`, and the `kqfilter` helpers. When a later lab says "retrieve the per-open state with the usual `devfs_get_cdevpriv` boilerplate", this is the block it refers to, and the rest of the chapter will not re-explain it. If a handler ever re-orders these lines, treat that as a red flag: running any logic before this call means the handler does not yet know which open it is serving. The one subtlety worth remembering is that the `sc == NULL` liveness check comes *after* this boilerplate, not before, because you need the per-open state retrieved safely even on a device that is being torn down. +这个模式检索 `d_open` 通过 `devfs_set_cdevpriv(9)` 注册的每次描述符 `fh`,并将任何失败原封不动地传播回内核。你将在 `myfirst_read`、`myfirst_write`、`myfirst_ioctl`、`myfirst_poll` 和 `kqfilter` 辅助函数的顶部看到它。当后面的实验说"用通常的 `devfs_get_cdevpriv` 样板检索每次打开状态"时,它指的就是这个代码块,本章余下部分不会重新解释它。如果一个处理程序曾经重新排列了这些行,请将其视为一个危险信号:在此调用之前运行任何逻辑意味着处理程序尚不知道它正在为哪次打开服务。一个值得记住的微妙之处是 `sc == NULL` 存活检查位于这个样板*之后*,而不是之前,因为你需要安全地检索每次打开状态,即使设备正在被拆除。 ```c static int @@ -642,9 +642,9 @@ myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) **第五步:找到状态转换。** 处理程序增加什么计数器?它触及什么每次句柄字段?这些转换是驱动的行为签名,通常是驱动之间差异最大的部分。 -Apply this protocol to `zero_read` in `/usr/src/sys/dev/null/null.c`. The argument names are the standard ones. The `uiomove` call hands the kernel pointer `zbuf` (pointing at `zero_region`) and a length clamped by `ZERO_REGION_SIZE`. There is no lock; the data is constant. The only errno the handler can return is whatever `uiomove` returned. There are no state transitions; `/dev/zero` is stateless. +将此协议应用于 `/usr/src/sys/dev/null/null.c` 中的 `zero_read`。参数名称是标准的。`uiomove` 调用传递内核指针 `zbuf`(指向 `zero_region`)和由 `ZERO_REGION_SIZE` 限制的长度。没有锁;数据是常量。处理程序可以返回的唯一 errno 是 `uiomove` 返回的任何值。没有状态转换;`/dev/zero` 是无状态的。 -Now apply the same protocol to `myfirst_write` at Stage 3. Argument names: standard. `uiomove` call: kernel pointer `sc->buf + bufhead + bufused`, length `MIN((size_t)uio->uio_resid, avail)`. Lock: `sc->mtx` taken before and released after. Errno returns: `ENXIO` (device gone), `ENOSPC` (buffer full), `EFAULT` via `uiomove`, or zero. State transitions: `sc->bufused += towrite`, `sc->bytes_written += towrite`, `fh->writes += towrite`. +现在将同样的协议应用于阶段 3 的 `myfirst_write`。参数名称:标准的。`uiomove` 调用:内核指针 `sc->buf + bufhead + bufused`,长度 `MIN((size_t)uio->uio_resid, avail)`。锁:`sc->mtx` 在之前获取、在之后释放。Errno 返回值:`ENXIO`(设备已消失)、`ENOSPC`(缓冲区满)、通过 `uiomove` 产生的 `EFAULT` 或零。状态转换:`sc->bufused += towrite`、`sc->bytes_written += towrite`、`fh->writes += towrite`。 两个驱动,同样的协议,两个关于处理程序功能的连贯描述。一旦你应用这种阅读习惯五六次,不熟悉的处理程序就不再看起来陌生。 @@ -1397,7 +1397,7 @@ npages = howmany(buflen, PAGE_SIZE); ## 错误处理和边界情况 -一个"只在正常路径上工作"的初学者驱动最终会崩溃内核。 I/O 处理的有趣部分不是正常路径的部分: 零长度读取、部分写入、错误的用户指针、调用中途传递的信号、耗尽的缓冲区, and several dozen variations of those. 本节讨论常见情况和与之相关的 errno 值。 +一个"只在正常路径上工作"的初学者驱动最终会崩溃内核。 I/O 处理的有趣部分不是正常路径的部分:零长度读取、部分写入、错误的用户指针、调用中途传递的信号、耗尽的缓冲区,以及这些情况的几十种变体。本节讨论常见情况和与之相关的 errno 值。 ### I/O 中重要的 errno 值 @@ -1610,7 +1610,7 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) 其次,`before` 在条目处捕获 `uio->uio_offset`,以便我们可以计算移动了多少字节。`uiomove_frombuf` 返回后,差异就是传输大小,我们将其添加到每次描述符 `reads` 计数器。这是第八章中 `fh->reads` 字段最终发挥作用的地方。 -The `__DECONST` cast is a FreeBSD idiom for casting away `const`. `uiomove_frombuf` takes a non-`const` `void *` because it is prepared to move in either direction, but in this context we know the direction is kernel-to-user (a read), so we know the kernel buffer will not be modified. Stripping the `const` here is safe; using a plain `(void *)` cast would work as well but is less self-documenting. +`__DECONST` 转换是 FreeBSD 中去除 `const` 的惯用法。`uiomove_frombuf` 接受非 `const` 的 `void *`,因为它准备在任一方向移动,但在这种上下文中我们知道方向是内核到用户(读取),所以我们知道内核缓冲区不会被修改。在这里去除 `const` 是安全的;使用普通的 `(void *)` 转换也可以,但不够自文档化。 `myfirst_write` 在阶段 1 保持第八章留下的样子: @@ -1714,7 +1714,7 @@ SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), &sc->bufused, 0, "Current byte count in the buffer"); ``` -`bufused` is a `size_t`, and the sysctl macro for unsigned integer is `SYSCTL_ADD_UINT` on 32-bit platforms or `SYSCTL_ADD_U64` on 64-bit platforms. Since this driver targets FreeBSD 14.3 on amd64 in the typical lab, `SYSCTL_ADD_UINT` is fine; the field will be presented as an `unsigned int` even though the internal type is `size_t`. If you target arm64 or another 64-bit platform, use `SYSCTL_ADD_U64` and cast accordingly. +`bufused` 是 `size_t`,无符号整数的 sysctl 宏在 32 位平台上是 `SYSCTL_ADD_UINT`,在 64 位平台上是 `SYSCTL_ADD_U64`。由于此驱动在典型实验室中针对 amd64 上的 FreeBSD 14.3,`SYSCTL_ADD_UINT` 就可以;即使内部类型是 `size_t`,该字段也将被呈现为 `unsigned int`。如果你针对 arm64 或其他 64 位平台,使用 `SYSCTL_ADD_U64` 并相应转换。 在 `attach` 中分配缓冲区: @@ -1739,7 +1739,7 @@ if (sc->buf != NULL) { } ``` -Adjust the error-unwind in `attach` to include the buffer free: +调整 `attach` 中的错误展开以包含缓冲区释放: ```c fail_dev: @@ -1757,7 +1757,7 @@ fail_mtx: return (error); ``` -Now the read handler: +现在来看读取处理程序: ```c static int @@ -1791,7 +1791,7 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) 读取处理程序获取互斥锁以一致地读取 `bufused`,然后以当前高水位标记作为有效缓冲区大小调用 `uiomove_frombuf`。在任何写入之前运行的读取者将看到 `have = 0`,`uiomove_frombuf` 将返回零,调用者将其解释为 EOF。在一些写入之后运行的读取者将看到当前 `bufused` 并接收最多那么多字节。 -The write handler: +写入处理程序: ```c static int @@ -1828,7 +1828,7 @@ myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) 注意限制:`towrite = MIN(uio->uio_resid, avail)`。如果用户请求写入 8 KiB 而我们有 512 字节空间,我们接受 512 字节并让内核向用户空间报告 512 的短写入。行为良好的调用者会用剩余字节循环;行为不太好的调用者会丢失多余部分。那是调用者的责任;驱动已经诚实地完成了它的部分。 -Smoke-test from userland: +从用户态进行冒烟测试: ```sh % sudo kldload ./myfirst.ko @@ -1844,9 +1844,9 @@ dev.myfirst.0.stats.bufused: 11 % ``` -The buffer grew by 6 bytes for `"hello\n"`, then by 5 more for `"more\n"`, yielding 11 bytes. `cat` reads all 11 bytes back. A second `cat` from a fresh open starts at offset zero and reads them again. +缓冲区因 `"hello\n"` 增长了 6 字节,然后因 `"more\n"` 又增长了 5 字节,总共 11 字节。`cat` 读回所有 11 字节。从一个新打开的描述符的第二次 `cat` 从偏移零开始并再次读取它们。 -What happens if we write more than the buffer can hold? +如果我们写入的数据超过缓冲区容量会发生什么? ```sh % dd if=/dev/zero bs=1024 count=8 | sudo tee /dev/myfirst/0 > /dev/null @@ -1856,7 +1856,7 @@ tee: /dev/myfirst/0: No space left on device 7+0 records out ``` -`dd` wrote 7 blocks of 1024 bytes before the 8th one failed. `tee` reports the error. The driver accepted up to its limit and then returned `ENOSPC` cleanly. The kernel carried the errno value back to user space. +`dd` 写入了 7 个 1024 字节的块,第 8 个失败了。`tee` 报告了错误。驱动接受到其限制后干净地返回了 `ENOSPC`。内核将 errno 值传回用户空间。 ### 阶段 3:先进先出回显驱动 @@ -1864,7 +1864,7 @@ tee: /dev/myfirst/0: No space left on device 缓冲区保持线性:没有环绕。在排空所有数据的读取之后,`bufused` 为零,下一次写入再次从 `sc->buf` 中的偏移零开始。这使记录保持最少,并将阶段集中在 I/O 方向变化而不是环形缓冲区机制上。 -The softc gains one more field: +softc 再增加一个字段: ```c struct myfirst_softc { @@ -1879,14 +1879,14 @@ struct myfirst_softc { `bufhead` 是仍然要读取的第一个字节的偏移。`bufused` 是从 `bufhead` 开始的有效字节数。不变量 `bufhead + bufused <= buflen` 总是成立。 -Reset both in `attach`: +在 `attach` 中重置两者: ```c sc->bufhead = 0; sc->bufused = 0; ``` -New read handler: +新的读取处理程序: ```c static int @@ -1927,7 +1927,7 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) 这种"空时折叠"技巧不是环形缓冲区,但对于教学 FIFO 足够接近。额外的重新对齐步骤是 `O(1)`;几乎不花费任何代价。 -New write handler (mostly unchanged from Stage 2, but note where it appends): +新的写入处理程序(与阶段 2 大部分相同,但注意追加的位置): ```c static int @@ -1963,9 +1963,9 @@ myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) } ``` -The write appends at `sc->bufhead + sc->bufused`, not at `sc->bufused` alone, because the valid data slice has moved as reads drained it. +写入在 `sc->bufhead + sc->bufused` 处追加,而不是仅在 `sc->bufused` 处,因为随着读取排空,有效数据切片已经移动了。 -Smoke-test: +冒烟测试: ```sh % echo "one" | sudo tee /dev/myfirst/0 > /dev/null @@ -1977,143 +1977,143 @@ two % ``` -After the first `cat`, the buffer is empty. The second `cat` sees no data and exits immediately. +第一次 `cat` 之后,缓冲区为空。第二次 `cat` 看不到数据并立即退出。 -This is the Stage 3 shape. The driver is a small, honest, in-memory FIFO. Users can push bytes in, pull them out, and observe the counters from sysctl. That is real I/O, and it is the waypoint Chapter 10 builds from. +这就是阶段 3 的形状。驱动是一个小型、诚实、内存中的 FIFO。用户可以向其中推入字节、从中拉出字节,并通过 sysctl 观察计数器。这就是真正的 I/O,也是第十章构建的基础。 ## 从用户空间到你的处理程序追踪 read(2) -Before you start working through the labs, take a step-by-step look at exactly what happens when a user program calls `read(2)` on one of your nodes. Understanding this path is one of those things that changes how you read driver code. Every handler you see in the tree is sitting at the bottom of the call chain described below; once you recognise the chain, every handler starts to look familiar. +在开始做实验之前,逐步仔细看看当用户程序在你其中一个节点上调用 `read(2)` 时到底发生了什么。理解这条路径是改变你阅读驱动代码方式的事情之一。你在源码树中看到的每个处理程序都位于下面描述的调用链底部;一旦你认识到这个链条,每个处理程序都会变得眼熟。 ### 步骤 1:用户程序调用 read(2) -The C library's `read` wrapper is a thin translation of the call into a system-call trap: it places the file descriptor, the buffer pointer, and the count into the appropriate registers and executes the trap instruction for the current architecture. Control transfers to the kernel. +C 库的 `read` 包装器将调用简单转换为系统调用陷阱:它将文件描述符、缓冲区指针和计数放入适当的寄存器,并执行当前架构的陷阱指令。控制权转移到内核。 -This part has nothing to do with drivers. It is the same for every syscall. What matters is that the kernel is now executing on behalf of the user process, in the kernel's address space, with the user's registers saved and the process's credentials visible through `curthread->td_ucred`. +这部分与驱动无关。每个系统调用都是相同的。重要的是,内核现在代表用户进程执行,在内核的地址空间中,用户的寄存器已保存,进程的凭据通过 `curthread->td_ucred` 可见。 ### 步骤 2:内核查找文件描述符 -The kernel calls `sys_read(2)` (in `/usr/src/sys/kern/sys_generic.c`), which validates the arguments, looks up the file descriptor in the calling process's file table, and acquires a reference on the resulting `struct file`. +内核调用 `sys_read(2)`(位于 `/usr/src/sys/kern/sys_generic.c`),它验证参数,在调用进程的文件表中查找文件描述符,并获取对结果 `struct file` 的引用。 -If the descriptor is not open, the call fails here with `EBADF`. If the descriptor is open but is not readable (for instance, the user opened the device with `O_WRONLY`), the call fails with `EBADF` as well. The driver is not involved; `sys_read` enforces the access mode. +如果描述符未打开,调用在此处以 `EBADF` 失败。如果描述符已打开但不可读(例如,用户使用 `O_WRONLY` 打开了设备),调用同样以 `EBADF` 失败。驱动不参与;`sys_read` 强制执行访问模式。 ### 步骤 3:通用文件操作向量分派 -The `struct file` has a file-type tag (`f_type`) and a file-operations vector (`f_ops`). For a regular file the vector dispatches to the VFS layer; for a socket it dispatches to sockets; for a device opened through devfs, it dispatches to `vn_read`, which in turn calls the vnode operation `VOP_READ` on the vnode behind the file. +`struct file` 有一个文件类型标签(`f_type`)和一个文件操作向量(`f_ops`)。对于常规文件,向量分派到 VFS 层;对于套接字,它分派到套接字;对于通过 devfs 打开的设备,它分派到 `vn_read`,后者又调用文件背后 vnode 上的 vnode 操作 `VOP_READ`。 -This may sound like indirection for its own sake. It is actually how the kernel keeps the rest of the syscall path identical for every kind of file. Drivers do not need to know about this layer; devfs and VFS hand the call to your handler eventually. +这听起来可能像是为间接而间接。实际上这是内核如何保持系统调用路径的其余部分对每种文件都相同的方式。驱动不需要了解这一层;devfs 和 VFS 最终会将调用传递给你的处理程序。 ### 步骤 4:VFS 调用 devfs -The vnode's filesystem ops point to devfs's implementation of the vnode interface (`devfs_vnops`). `VOP_READ` on a devfs vnode calls `devfs_read_f`, which looks at the cdev behind the vnode, acquires a thread-count reference on it (incrementing `si_threadcount`), and calls `cdevsw->d_read`. That is your function. +vnode 的文件系统操作指向 devfs 对 vnode 接口的实现(`devfs_vnops`)。devfs vnode 上的 `VOP_READ` 调用 `devfs_read_f`,它查看 vnode 背后的 cdev,获取其上的线程计数引用(递增 `si_threadcount`),并调用 `cdevsw->d_read`。那就是你的函数。 -Two details from this step carry implications for your driver. +这一步的两个细节对你的驱动有影响。 -First, **the `si_threadcount` increment is what `destroy_dev(9)` uses to know your handler is active**. When a module unloads and `destroy_dev` runs, it waits until every current invocation of every handler returns. The reference is incremented before your `d_read` is called and released after it returns. The mechanism is why your driver can be safely unloaded while a user is in the middle of `read(2)`. +首先,**`si_threadcount` 递增是 `destroy_dev(9)` 用来知道你的处理程序是否活跃的方式**。当模块卸载并且 `destroy_dev` 运行时,它会等待直到每个处理程序的每次当前调用都返回。引用在你的 `d_read` 被调用之前递增,并在它返回之后释放。这个机制是你的驱动可以在用户正在进行 `read(2)` 时安全卸载的原因。 -Second, **the call is synchronous from the VFS layer's point of view**. VFS calls your handler, waits for it to return, and then propagates the result. You do not need to do anything special to participate in this synchronisation; just return from your handler when you are done. +其次,**从 VFS 层的角度来看,调用是同步的**。VFS 调用你的处理程序,等待它返回,然后传播结果。你不需要做任何特殊的事情来参与这种同步;完成时从处理程序返回即可。 ### 步骤 5:你的 d_read 处理程序运行 -This is where we have been all chapter. The handler: +这就是我们整章所在的位置。处理程序: -- Receives a `struct cdev *dev` (the node being read), a `struct uio *uio` (the I/O description), and an `int ioflag` (flags from the file-table entry). -- Retrieves per-open state via `devfs_get_cdevpriv(9)`. -- Verifies liveness. -- Transfers bytes through `uiomove(9)`. -- Returns zero or an errno. +- 接收一个 `struct cdev *dev`(被读取的节点)、一个 `struct uio *uio`(I/O 描述)和一个 `int ioflag`(来自文件表条目的标志)。 +- 通过 `devfs_get_cdevpriv(9)` 检索每次打开的状态。 +- 验证活跃性。 +- 通过 `uiomove(9)` 传输字节。 +- 返回零或 errno。 -Nothing about this step should be mysterious by now. +到目前为止,这个步骤应该没有任何神秘之处了。 ### 步骤 6:内核展开并报告 -`devfs_read_f` sees your return value. If zero, it computes the byte count from the decrease in `uio->uio_resid` and returns that count. If non-zero, it converts the errno into the syscall's error return. VFS's `vn_read` passes the result upward to `sys_read`. `sys_read` writes the result into the return-value register. +`devfs_read_f` 看到你的返回值。如果为零,它从 `uio->uio_resid` 的减少量计算字节计数并返回该计数。如果非零,它将 errno 转换为系统调用的错误返回。VFS 的 `vn_read` 将结果向上传递给 `sys_read`。`sys_read` 将结果写入返回值寄存器。 -Control transfers back to user space. The C library's `read` wrapper examines the result: a positive value is returned as the return value of `read(2)`; a negative value sets `errno` and returns `-1`. +控制权转移回用户空间。C 库的 `read` 包装器检查结果:正值作为 `read(2)` 的返回值返回;负值设置 `errno` 并返回 `-1`。 -The user program sees the integer it expected, and its control flow continues. +用户程序看到它期望的整数,其控制流继续。 ### 步骤 7:引用计数展开 -On the way out, `devfs_read_f` releases the thread-count reference on the cdev. If `destroy_dev(9)` had been waiting for `si_threadcount` to reach zero, it may now proceed with the tear-down. +在返回途中,`devfs_read_f` 释放 cdev 上的线程计数引用。如果 `destroy_dev(9)` 一直在等待 `si_threadcount` 达到零,它现在可以继续拆除了。 -This is why the whole chain is structured as carefully as it is. Every reference is paired; every increment has a matching decrement; every piece of state the handler touches is either owned by the handler, owned by the softc, or owned by the per-open `fh`. If any of those invariants breaks, unload becomes unsafe. +这就是为什么整个链的结构如此仔细。每个引用都是配对的;每次递增都有匹配的递减;处理程序触及的每段状态要么由处理程序拥有,要么由 softc 拥有,要么由每次打开的 `fh` 拥有。如果这些不变量中的任何一个被破坏,卸载就会变得不安全。 ### 为什么这个追踪对你重要 -Three takeaways. +三个要点。 -**The first**: the mechanism above is why your handler does not need to do anything exotic to coexist with module unload. Provided you return from `d_read` in finite time, the kernel will let your driver unload cleanly. This is part of why Chapter 9 keeps all reads non-blocking at the driver level. +**第一个**:上述机制是你的处理程序不需要做任何奇特操作就能与模块卸载共存的原因。只要你在有限时间内从 `d_read` 返回,内核就能让你的驱动干净地卸载。这是第九章在驱动级别保持所有读取为非阻塞的部分原因。 -**The second**: every layer between `read(2)` and your handler is set up by the kernel before your code runs. The user's buffer is valid (or `uiomove` will report `EFAULT`), the cdev is alive (or devfs would have refused the call), the access mode is compatible with the descriptor (or `sys_read` would have refused), and the process's credentials are the current thread's. You can focus on your driver's job and trust the layers. +**第二个**:`read(2)` 和你的处理程序之间的每一层都是由内核在你的代码运行之前设置的。用户的缓冲区是有效的(否则 `uiomove` 会报告 `EFAULT`),cdev 是活跃的(否则 devfs 会拒绝调用),访问模式与描述符兼容(否则 `sys_read` 会拒绝),进程的凭据是当前线程的。你可以专注于你的驱动工作并信任这些层。 -**The third**: when you read an unfamiliar driver in the tree and its `d_read` looks weird, you can walk the chain in reverse. Who called this handler? What state did they prepare? What invariants does my handler promise on return? The chain tells you. The answers are usually the same as they are for `myfirst`. +**第三个**:当你在源码树中阅读一个不熟悉的驱动,其 `d_read` 看起来很奇怪时,你可以反向追踪调用链。谁调用了这个处理程序?他们准备了什么状态?我的处理程序在返回时承诺了什么不变量?调用链会告诉你。答案通常与 `myfirst` 的相同。 ### 镜像:追踪 write(2) -A write follows the same kind of chain, mirrored. A full seven-step breakdown would be mostly a restatement of the read trace with words substituted, so the paragraph below is deliberately compressed. +写入遵循相同类型的链,是镜像的。完整的七步分解大部分会是对读取追踪的重复,只是替换了词语,所以下面的段落是刻意压缩的。 -The user calls `write(fd, buf, 1024)`. The C library traps into the kernel. `sys_write(2)` in `/usr/src/sys/kern/sys_generic.c` validates arguments, looks up the descriptor, and acquires a reference on its `struct file`. The file-ops vector dispatches to `vn_write`, which calls `VOP_WRITE` on the devfs vnode. `devfs_write_f` in `/usr/src/sys/fs/devfs/devfs_vnops.c` acquires the thread-count reference on the cdev, composes the `ioflag` from `fp->f_flag`, and calls `cdevsw->d_write` with the uio describing the caller's buffer. +用户调用 `write(fd, buf, 1024)`。C 库陷入内核。`/usr/src/sys/kern/sys_generic.c` 中的 `sys_write(2)` 验证参数,查找描述符,并获取其 `struct file` 的引用。文件操作向量分派到 `vn_write`,后者调用 devfs vnode 上的 `VOP_WRITE`。`/usr/src/sys/fs/devfs/devfs_vnops.c` 中的 `devfs_write_f` 获取 cdev 上的线程计数引用,从 `fp->f_flag` 组合 `ioflag`,并使用描述调用者缓冲区的 uio 调用 `cdevsw->d_write`。 -Your `d_write` handler runs. It retrieves per-open state via `devfs_get_cdevpriv(9)`, checks liveness, takes whatever lock the driver needs around the buffer, clamps the transfer length to whatever space is available, and calls `uiomove(9)` to copy bytes from user space into the kernel buffer. On success, the handler updates its bookkeeping and returns zero. `devfs_write_f` releases the thread-count reference. `vn_write` unwinds through `sys_write`, which computes the byte count from the decrease in `uio_resid` and returns it. The user sees the return value of `write(2)`. +你的 `d_write` 处理程序运行。它通过 `devfs_get_cdevpriv(9)` 检索每次打开的状态,检查活跃性,获取驱动在缓冲区周围需要的任何锁,将传输长度限制到可用空间,并调用 `uiomove(9)` 将字节从用户空间复制到内核缓冲区。成功时,处理程序更新其记账并返回零。`devfs_write_f` 释放线程计数引用。`vn_write` 通过 `sys_write` 展开,后者从 `uio_resid` 的减少量计算字节计数并返回它。用户看到 `write(2)` 的返回值。 -Three things differ from the read chain in substantive ways. +与读取链在实质上有三个方面不同。 -**First, the kernel runs `copyin` inside `uiomove` instead of `copyout`.** Same mechanism, opposite direction. The fault handling is identical: a bad user pointer returns `EFAULT`, a short copy leaves `uio_resid` consistent with whatever did transfer, and the handler just propagates the error code. +**首先,内核在 `uiomove` 内部运行 `copyin` 而不是 `copyout`。** 相同的机制,相反的方向。故障处理是相同的:错误的用户指针返回 `EFAULT`,短复制使 `uio_resid` 与实际传输的内容保持一致,处理程序只需传播错误代码。 -**Second, `ioflag` carries `IO_NDELAY` in the same way, but the driver's interpretation is different.** On a read, non-blocking means "return `EAGAIN` if there is no data". On a write, non-blocking means "return `EAGAIN` if there is no space". Symmetric conditions, symmetric errno values. +**其次,`ioflag` 以相同方式携带 `IO_NDELAY`,但驱动的解释不同。** 在读取上,非阻塞意味着"如果没有数据则返回 `EAGAIN`"。在写入上,非阻塞意味着"如果没有空间则返回 `EAGAIN`"。对称的条件,对称的 errno 值。 -**Third, the `atime` / `mtime` updates are direction-specific.** `devfs_read_f` stamps `si_atime` if bytes moved; `devfs_write_f` stamps `si_mtime` (and `si_ctime` in some paths) if bytes moved. These are what `stat(2)` on the node reports, and why `ls -lu /dev/myfirst/0` shows different timestamps for reads versus writes. Your driver does not manage these fields; devfs does. +**第三,`atime` / `mtime` 更新是方向特定的。** `devfs_read_f` 在字节移动时标记 `si_atime`;`devfs_write_f` 在字节移动时标记 `si_mtime`(在某些路径中还有 `si_ctime`)。这些是 `stat(2)` 在节点上报告的内容,也是为什么 `ls -lu /dev/myfirst/0` 对于读取和写入显示不同的时间戳。你的驱动不管理这些字段;devfs 管理。 -Once you recognise the read and write traces as mirror images, you have internalised most of the character-device dispatch path. Every chapter from here on will add hooks (a `d_poll`, a `d_kqfilter`, a `d_ioctl`, an `mmap` path) that sit on the same chain at slightly different slots. The chain itself stays constant. +一旦你认识到读取和写入追踪是镜像的,你就已经内化了字符设备分派路径的大部分。从这里开始的每一章都会在同一个链的略微不同的槽位上添加钩子(`d_poll`、`d_kqfilter`、`d_ioctl`、`mmap` 路径)。链本身保持不变。 ## 实用工作流:从 shell 测试你的驱动 -The base-system tools are your first and best test harness. This section is a short field guide to using them well on a driver you are developing. None of the commands below are new to you, but using them for driver work has a rhythm worth learning explicitly. +基本系统工具是你首先也是最好的测试工具。本节是一个简短的实地指南,介绍在开发驱动时如何很好地使用它们。下面的命令对你来说都不陌生,但将它们用于驱动工作有一种值得明确学习的节奏。 ### cat(1):第一次检查 -`cat` reads from its arguments and writes to standard output. For a driver that serves a static message or a drained buffer, `cat` is the fastest way to see what the read path produces: +`cat` 从其参数读取并写入标准输出。对于提供静态消息或已排空缓冲区的驱动,`cat` 是查看读取路径产生什么的最快方式: ```sh % cat /dev/myfirst/0 ``` -If the output is what you expect, the read path is alive. If it is empty, either your driver has nothing to deliver (check `sysctl dev.myfirst.0.stats.bufused`) or your handler is returning EOF on the first call. If the output is garbled, either your buffer is uninitialised or you are handing out bytes past `bufused`. +如果输出符合预期,读取路径就是活跃的。如果为空,要么你的驱动没有内容可以提供(检查 `sysctl dev.myfirst.0.stats.bufused`),要么你的处理程序在第一次调用时返回 EOF。如果输出乱码,要么你的缓冲区未初始化,要么你在 `bufused` 之外传递了字节。 -`cat` opens its argument once and reads from it until EOF. Every `read(2)` is a separate call into your `d_read`. Use `truss(1)` to see how many calls `cat` makes: +`cat` 打开其参数一次并从中读取直到 EOF。每次 `read(2)` 都是对你 `d_read` 的独立调用。使用 `truss(1)` 查看 `cat` 进行了多少次调用: ```sh % truss cat /dev/myfirst/0 2>&1 | grep read ``` -The output shows each `read(2)` with its arguments and return value. If you expected one read and see three, that tells you about your buffer sizing; if you expected three reads and see one, your handler delivered all the data in a single call. +输出显示每次 `read(2)` 及其参数和返回值。如果你预期一次读取却看到三次,这告诉了你关于缓冲区大小的信息;如果你预期三次读取却看到一次,你的处理程序在单次调用中传递了所有数据。 ### echo(1) 和 printf(1):简单写入 -`echo` is the quickest way to get a known string into your driver's write path: +`echo` 是将已知字符串放入驱动写入路径的最快方式: ```sh % echo "hello" | sudo tee /dev/myfirst/0 > /dev/null ``` -Two things to notice. First, `echo` appends a newline by default; the string you sent is six bytes, not five. Use `echo -n` to suppress the newline when that matters. Second, the `tee` invocation is there to solve a permission problem: shell redirection (`>`) runs with the user's privileges, so a `sudo echo > /dev/myfirst/0` fails to open the node. Piping through `tee`, which runs under `sudo`, sidesteps that. +有两点需要注意。首先,`echo` 默认追加换行符;你发送的字符串是 6 字节,不是 5 字节。在需要时使用 `echo -n` 抑制换行符。其次,`tee` 调用是为了解决权限问题:shell 重定向(`>`)以用户权限运行,所以 `sudo echo > /dev/myfirst/0` 无法打开节点。通过在 `sudo` 下运行的 `tee` 管道传递,可以避开这个问题。 -`printf` gives you more control: +`printf` 给你更多控制: ```sh % printf 'abc' | sudo tee /dev/myfirst/0 > /dev/null ``` -Three bytes, no newline. Use `printf '\x41\x42\x43'` for binary patterns. +三个字节,没有换行符。使用 `printf '\x41\x42\x43'` 生成二进制模式。 ### dd(1):精确工具 -For any test that needs a specific byte count or a specific block size, `dd` is the right tool. `dd` is also one of the only base-system tools that reports short reads and short writes in its summary, which makes it uniquely useful for testing driver behaviour: +对于需要特定字节计数或特定块大小的任何测试,`dd` 是正确的工具。`dd` 也是基本系统工具中少数在其摘要中报告短读取和短写入的工具之一,这使其对测试驱动行为特别有用: ```sh % sudo dd if=/dev/urandom of=/dev/myfirst/0 bs=128 count=4 @@ -2122,47 +2122,47 @@ For any test that needs a specific byte count or a specific block size, `dd` is 512 bytes transferred in 0.001234 secs (415000 bytes/sec) ``` -The `X+Y records in` / `X+Y records out` counters have a precise meaning: `X` is the number of full-block transfers, `Y` is the number of short transfers. A line reading `0+4 records out` means every block was accepted only partially. That is a driver telling you something. +`X+Y records in` / `X+Y records out` 计数器有精确含义:`X` 是完整块传输的次数,`Y` 是短传输的次数。一行显示 `0+4 records out` 意味着每个块只被部分接受。那是驱动在告诉你某些信息。 -`dd` also lets you read with a known block size: +`dd` 还允许你以已知块大小读取: ```sh % sudo dd if=/dev/myfirst/0 of=/tmp/dump bs=64 count=1 ``` -This issues exactly one `read(2)` for 64 bytes. Your handler sees `uio_resid = 64`; you respond with whatever you have; the result is what `dd` writes to `/tmp/dump`. +这恰好发出一个 64 字节的 `read(2)`。你的处理程序看到 `uio_resid = 64`;你用你有的内容响应;结果就是 `dd` 写入 `/tmp/dump` 的内容。 -The `iflag=fullblock` flag tells `dd` to loop on short reads until it has filled the requested block. Useful when you want to soak all of the driver's output without losing bytes to the short-read default. +`iflag=fullblock` 标志告诉 `dd` 在短读取时循环,直到填满请求的块。当你想吸收驱动的所有输出而不因短读取默认行为丢失字节时很有用。 ### od(1) 和 hexdump(1):字节级检查 -For driver testing, `od` and `hexdump` let you see the exact bytes your driver emitted: +对于驱动测试,`od` 和 `hexdump` 让你看到驱动发出的确切字节: ```sh % sudo dd if=/dev/myfirst/0 bs=32 count=1 | od -An -tx1z 68 65 6c 6c 6f 0a >hello.< ``` -The `-An` flag suppresses address printing. `-tx1z` shows bytes in hex and ASCII. If the expected output is text, you see it on the right; if it is binary, you see the hex on the left. +`-An` 标志抑制地址打印。`-tx1z` 以十六进制和 ASCII 显示字节。如果预期输出是文本,你在右侧看到它;如果是二进制,你在左侧看到十六进制。 -These tools become essential when a read produces unexpected bytes. "It looks weird" and "I can see every byte in hex" are very different debugging states. +这些工具在读取产生意外字节时变得不可或缺。"它看起来很奇怪"和"我能以十六进制看到每个字节"是非常不同的调试状态。 ### sysctl(8) 和 dmesg(8):内核的声音 -Your driver publishes counters through `sysctl` and lifecycle events through `dmesg`. Both are worth checking during every test: +你的驱动通过 `sysctl` 发布计数器,通过 `dmesg` 发布生命周期事件。两者都值得在每次测试时检查: ```sh % sysctl dev.myfirst.0 % dmesg | tail -20 ``` -The sysctl output is your view into the driver's state right now. `dmesg` is your view into the driver's history since boot (or since the ring buffer wrapped). +sysctl 输出是你对驱动当前状态的视图。`dmesg` 是你对驱动自启动以来(或自环形缓冲区环绕以来)历史的视图。 -A useful habit: after every test, run both. If the numbers do not match your expectation, you have narrowed down the bug quickly. +一个有用的习惯:每次测试后,都运行两者。如果数字不符合你的预期,你就快速缩小了 bug 的范围。 ### fstat(1):谁打开了描述符? -When your driver refuses to unload ("module busy"), the question is "who has `/dev/myfirst/0` open right now?". `fstat(1)` answers it: +当你的驱动拒绝卸载时("module busy"),问题是"现在谁打开了 `/dev/myfirst/0`?"。`fstat(1)` 回答它: ```sh % fstat -p $(pgrep cat) /dev/myfirst/0 @@ -2170,18 +2170,18 @@ USER CMD PID FD MOUNT INUM MODE SZ|DV R/W NAME ebrandi cat 1234 3 /dev 0 crw-rw---- myfirst/0 r /dev/myfirst/0 ``` -Alternatively, `fuser(8)`: +或者,使用 `fuser(8)`: ```sh % sudo fuser /dev/myfirst/0 /dev/myfirst/0: 1234 ``` -Either tool names the processes holding the descriptor. Kill the culprit (carefully; do not kill anything you did not start) and the module will unload. +两种工具都能命名持有描述符的进程。终止罪魁祸首(小心;不要终止任何你没启动的进程)后模块就可以卸载了。 ### truss(1) 和 ktrace(1):观察系统调用 -For a user program whose interaction with your driver you want to inspect, `truss` shows every syscall and its return value: +对于你想检查其与驱动交互的用户程序,`truss` 显示每个系统调用及其返回值: ```sh % truss ./rw_myfirst @@ -2191,28 +2191,28 @@ close(3) = 0 (0x0) ... ``` -`ktrace` records to a file that `kdump` prints later; it is the right tool when you want to capture a trace of a long-running program. +`ktrace` 记录到文件,稍后用 `kdump` 打印;当你想捕获长时间运行程序的追踪时,它是正确的工具。 -These two tools are not driver-specific, but they are how you confirm from the outside that your driver is producing the results a user program will see. +这两个工具不是驱动特定的,但它们是你从外部确认驱动正在产生用户程序将看到的结果的方式。 ### 建议的测试节奏 -For each stage of the chapter, try this loop: +对于章节的每个阶段,尝试这个循环: -1. Build and load. -2. `cat` to produce initial output, confirm by eye. -3. `sysctl dev.myfirst.0` to see counters match. -4. `dmesg | tail` to see lifecycle events. -5. Write something with `echo` or `dd`. -6. Read it back. -7. Repeat with a larger size, a boundary size, and a pathological size. -8. Unload. +1. 构建并加载。 +2. 使用 `cat` 产生初始输出,目视确认。 +3. 使用 `sysctl dev.myfirst.0` 查看计数器是否匹配。 +4. 使用 `dmesg | tail` 查看生命周期事件。 +5. 用 `echo` 或 `dd` 写入一些内容。 +6. 读回内容。 +7. 用更大的尺寸、边界尺寸和异常尺寸重复测试。 +8. 卸载。 -After a couple of iterations this becomes automatic and fast. It is the kind of rhythm that turns driver development from a slog into a routine. +经过几次迭代后,这变得自动化且快速。正是这种节奏将驱动开发从苦差事变成了例行公事。 ### 一个具体的 truss 演示 -Running a userland program under `truss(1)` is one of the fastest ways to see exactly what syscalls it makes to your driver and what return values the kernel produces. Here is a typical session with the Stage 3 driver loaded and empty: +在 `truss(1)` 下运行用户态程序是查看它对你的驱动发出了什么系统调用以及内核产生了什么返回值的最快方式之一。以下是加载了阶段 3 驱动且缓冲区为空时的典型会话: ```sh % truss ./rw_myfirst rt 2>&1 @@ -2225,9 +2225,9 @@ close(3) = 0 (0x0) exit(0x0) ``` -A few things are worth pausing on. Each line shows a single syscall, its arguments, and its return value in both decimal and hex. The `write` call received 29 bytes and the driver accepted all 29 (the return value matches the request length). The `read` call received a buffer of 255 bytes of room and the driver produced 29 bytes of content; a short read, which the user program explicitly accepts. Both `open` calls returned 3, because file descriptors 0, 1, and 2 are standard streams and the first free descriptor is 3. +有几件事值得停下来注意。每一行显示一个系统调用、其参数及其以十进制和十六进制表示的返回值。`write` 调用接收了 29 字节,驱动接受了全部 29 字节(返回值与请求长度匹配)。`read` 调用接收了 255 字节空间的缓冲区,驱动产生了 29 字节的内容;一个短读取,用户程序显式接受。两次 `open` 调用都返回了 3,因为文件描述符 0、1 和 2 是标准流,第一个空闲描述符是 3。 -If you force a short write by limiting the driver, `truss` will show it plainly: +如果你通过限制驱动来强制短写入,`truss` 将清楚地显示它: ```sh % truss ./write_big 2>&1 | head @@ -2237,17 +2237,17 @@ write(3,"<4096 bytes of data>",4096) ERR#28 'No space left on device close(3) = 0 (0x0) ``` -The first write requested 8192 bytes and was accepted for 4096. The second write had nothing to say because the buffer is full; the driver returned `ENOSPC`, which `truss` rendered as `ERR#28 'No space left on device'`. This is the view from the user side; your driver side was returning zero (with `uio_resid` decremented to 4096) for the first call and `ENOSPC` for the second. Comparing what `truss` sees against what your `device_printf` says is an excellent way to catch mismatches between the driver's intent and the kernel's reporting. +第一次写入请求了 8192 字节并被接受了 4096 字节。第二次写入没有什么可说的,因为缓冲区已满;驱动返回了 `ENOSPC`,`truss` 将其呈现为 `ERR#28 'No space left on device'`。这是用户侧的视图;你的驱动侧对第一次调用返回零(`uio_resid` 递减到 4096),对第二次调用返回 `ENOSPC`。将 `truss` 看到的与你的 `device_printf` 输出进行比较是捕获驱动意图与内核报告之间不匹配的绝佳方式。 -`truss -f` follows forks, which is useful when your test harness spawns worker processes. `truss -d` prefixes each line with a relative timestamp; useful for reasoning about latency between calls. Both flags are small investments; the rewards add up quickly when you start running multi-process stress tests. +`truss -f` 跟踪派生,当你的测试工具生成工作进程时很有用。`truss -d` 为每行添加相对时间戳前缀;用于推理调用之间的延迟。两个标志都是小的投入;当你开始运行多进程压力测试时,回报会迅速累积。 ### 关于 ktrace 的简要说明 -`ktrace(1)` is `truss`'s bigger sibling. It records a binary trace to a file (`ktrace.out` by default) which you then format with `kdump(1)`. It is the right tool when: +`ktrace(1)` 是 `truss` 的更大的兄弟。它将二进制追踪记录到文件(默认为 `ktrace.out`),然后用 `kdump(1)` 格式化。它是以下情况的正确工具: -- The test run is long and you do not want to watch output live. -- You want to capture detail that is too fine-grained for `truss` (syscall timing, signal delivery, namei lookups). -- You want to replay a trace later, perhaps on a different machine. +- 测试运行很长,你不想实时观看输出。 +- 你想捕获对 `truss` 来说太细粒度的细节(系统调用时间、信号传递、namei 查找)。 +- 你想稍后重放追踪,也许在不同的机器上。 A typical session: @@ -2264,11 +2264,11 @@ A typical session: ... ``` -For Chapter 9 the difference between `truss` and `ktrace` is small. Use `truss` as the default; reach for `ktrace` when you need more detail or a recorded trace. +对于第九章,`truss` 和 `ktrace` 之间的差异很小。默认使用 `truss`;当你需要更多细节或记录的追踪时使用 `ktrace`。 ### 用 vmstat -m 观察内核内存 -Your driver allocates kernel memory through `malloc(9)` with the `M_DEVBUF` type. FreeBSD's `vmstat -m` reveals how many allocations are active in each type bucket. Run it while your driver is loaded and idle, then again while it has a buffer allocated, and the increase will be visible in the `devbuf` row: +你的驱动通过 `malloc(9)` 以 `M_DEVBUF` 类型分配内核内存。FreeBSD 的 `vmstat -m` 揭示每个类型桶中有多少活跃分配。在驱动加载且空闲时运行它,然后在它有已分配缓冲区时再次运行,增加量将在 `devbuf` 行中可见: ```sh % vmstat -m | head -1 @@ -2277,88 +2277,88 @@ Your driver allocates kernel memory through `malloc(9)` with the `M_DEVBUF` type devbuf 415 4120K - 39852 16,32,64,128,256,512,1024,2048,... ``` -The `InUse` column is the current count of live allocations of this type. `MemUse` is the total size currently in use. `HighUse` is the all-time high-water mark since boot. `Requests` is the lifetime count of `malloc` calls that selected this type. +`InUse` 列是此类型的当前活跃分配计数。`MemUse` 是当前使用的总大小。`HighUse` 是自启动以来的历史高水位标记。`Requests` 是选择此类型的 `malloc` 调用的生命周期计数。 -Load the Stage 2 driver. `InUse` goes up by one (the 4096-byte buffer), `MemUse` goes up by approximately 4 KiB, and `Requests` increments. Unload. `InUse` goes down by one; `MemUse` goes down by the 4 KiB. If it does not, you have a memory leak, and `vmstat -m` just told you so. +加载阶段 2 驱动。`InUse` 增加一(4096 字节缓冲区),`MemUse` 增加约 4 KiB,`Requests` 递增。卸载。`InUse` 减少一;`MemUse` 减少那 4 KiB。如果不是这样,你就有内存泄漏,而 `vmstat -m` 刚刚告诉了你。 -This is the second observability channel worth adding to your test rhythm. `sysctl` shows driver-owned counters. `dmesg` shows driver-owned log lines. `vmstat -m` shows kernel-owned allocation counts, and it catches a class of bug (forgot to free) that the first two cannot see. +这是值得添加到测试节奏中的第二个可观测性通道。`sysctl` 显示驱动拥有的计数器。`dmesg` 显示驱动拥有的日志行。`vmstat -m` 显示内核拥有的分配计数,它捕获一类前两个无法看到的 bug(忘记释放)。 -For a driver that declares its own malloc type via `MALLOC_DEFINE(M_MYFIRST, "myfirst", ...)`, `vmstat -m | grep myfirst` is even better: it isolates your driver's allocations from the generic `devbuf` pool. `myfirst` stays with `M_DEVBUF` throughout this chapter for simplicity, but upgrading to a dedicated type is a small change you may want to make before shipping a driver outside the book's lab environment. +对于通过 `MALLOC_DEFINE(M_MYFIRST, "myfirst", ...)` 声明自己 malloc 类型的驱动,`vmstat -m | grep myfirst` 更好:它将你的驱动的分配从通用 `devbuf` 池中隔离出来。`myfirst` 在本章中为简单起见一直使用 `M_DEVBUF`,但在将驱动发布到本书实验环境之外之前,升级到专用类型是一个你可能想做的小更改。 ## 可观测性:让你的驱动可读 -A driver that does the right thing is worth more if you can confirm, from outside the kernel, that it is doing the right thing. This section is a short meditation on the observability choices this chapter has been making, and why. +一个做正确事情的驱动,如果你能从内核外部确认它在做正确的事情,就更有价值。本节是对本章一直在做的可观测性选择的简短思考,以及为什么这样做。 ### 三个接口:sysctl、dmesg、用户态 -Your driver presents three surfaces to the operator: +你的驱动向操作员呈现三个界面: -- **sysctl** for live counters: point-in-time values the operator can poll. -- **dmesg (device_printf)** for lifecycle events: open, close, errors, transitions. -- **/dev** nodes for the data path: the actual bytes. +- **sysctl** 用于实时计数器:操作员可以轮询的即时值。 +- **dmesg (device_printf)** 用于生命周期事件:打开、关闭、错误、转换。 +- **/dev** 节点用于数据路径:实际的字节。 -Each has a distinct role. sysctl tells the operator *what is true right now*. dmesg tells the operator *what changed recently*. `/dev` is the thing the operator is actually using. +每个都有不同的角色。sysctl 告诉操作员*现在什么是真的*。dmesg 告诉操作员*最近发生了什么变化*。`/dev` 是操作员实际使用的东西。 -A well-observed driver uses all three, deliberately. A minimally-observed driver uses only the third, and debugging it requires either a debugger or a lot of guessing. +一个可观测性好的驱动刻意使用所有三个。一个可观测性最小的驱动只使用第三个,调试它需要调试器或大量猜测。 ### Sysctl:计数器与状态 -`myfirst` exposes counters through the sysctl tree under `dev.myfirst.0.stats`: +`myfirst` 通过 `dev.myfirst.0.stats` 下的 sysctl 树暴露计数器: -- `attach_ticks`: a point-in-time value (when the driver attached). -- `open_count`: a monotonically-increasing counter (lifetime opens). -- `active_fhs`: a live count (current descriptors). -- `bytes_read`, `bytes_written`: monotonically-increasing counters. -- `bufused`: a live value (current buffer occupancy). +- `attach_ticks`:即时值(驱动附加的时间)。 +- `open_count`:单调递增计数器(生命周期打开次数)。 +- `active_fhs`:实时计数(当前描述符数)。 +- `bytes_read`、`bytes_written`:单调递增计数器。 +- `bufused`:实时值(当前缓冲区占用)。 -Monotonically-increasing counters are easier to reason about than live values, because their rate of change is informative even when the absolute value is not. An operator who sees `bytes_read` increasing at 1 MB/s has learned something even if 1 MB/s is meaningless out of context. +单调递增计数器比实时值更容易推理,因为即使绝对值没有意义,它们的变化率也是有用的信息。看到 `bytes_read` 以 1 MB/s 增长的操作员已经学到了某些东西,即使 1 MB/s 在上下文之外没有意义。 -Live values are essential when the state matters for decisions (`active_fhs > 0` means unload will fail). Choose monotonically-increasing counters first, live values when you need them. +实时值在状态对决策有影响时是必不可少的(`active_fhs > 0` 意味着卸载将失败)。优先选择单调递增计数器,在需要时使用实时值。 ### dmesg:值得查看的事件 -`device_printf(9)` writes to the kernel message buffer, which `dmesg` shows. Every line is worth seeing exactly once: use dmesg for events, not for continuous status. +`device_printf(9)` 写入内核消息缓冲区,`dmesg` 显示它。每一行都值得恰好看到一次:将 dmesg 用于事件,而不是用于连续状态。 -The events `myfirst` logs: +`myfirst` 记录的事件: -- Attach (once per instance). -- Open (once per open). -- Destructor (once per descriptor close). -- Detach (once per instance). +- 附加(每个实例一次)。 +- 打开(每次打开一次)。 +- 析构函数(每个描述符关闭一次)。 +- 拆离(每个实例一次)。 -That is four lines per instance per load/unload cycle, plus two lines per open/close pair. Comfortable. +即每个实例每次加载/卸载周期四行,加上每次打开/关闭对两行。舒适。 -What we do not log: +我们不记录的内容: -- Every `read` or `write` call. That would flood dmesg in any real workload. -- Every sysctl read. Those are passive. -- Every successful transfer. The sysctl counters carry that information, and they carry it more compactly. +- 每次 `read` 或 `write` 调用。那会在任何真实工作负载下淹没 dmesg。 +- 每次 sysctl 读取。那些是被动的。 +- 每次成功传输。sysctl 计数器携带该信息,而且携带得更紧凑。 -If a driver needs to log something that happens many times a second, the usual answer is to guard the logging with `if (bootverbose)`, so it is silent on production systems but available to developers who boot with `boot -v`. For `myfirst` we do not need even that. +如果驱动需要记录每秒发生很多次的事情,通常的答案是用 `if (bootverbose)` 保护日志,这样在生产系统上它是静默的,但对使用 `boot -v` 启动的开发者可用。对于 `myfirst`,我们甚至不需要那样做。 ### 过度日志记录的陷阱 -A driver that logs every operation is a driver that hides its important events in a sea of noise. If your dmesg shows ten thousand lines of `read returned 0 bytes`, the line that says `buffer full, returning ENOSPC` is invisible. +一个记录每次操作的驱动是一个将重要事件隐藏在噪音海洋中的驱动。如果你的 dmesg 显示一万行 `read returned 0 bytes`,那行说 `buffer full, returning ENOSPC` 的消息就是不可见的。 -Keep logs sparse. Log transitions, not states. Log once per instance, not once per call. When in doubt, silence. +保持日志稀疏。记录转换,而不是状态。每个实例记录一次,而不是每次调用记录一次。有疑问时,保持静默。 ### 你稍后要添加的计数器 -Chapters 10 and beyond will extend the counter tree with: +第十章及以后将通过以下内容扩展计数器树: -- `reads_blocked`, `writes_blocked`: count of calls that had to sleep (Chapter 10). -- `poll_waiters`: count of active `poll(2)` subscribers (Chapter 10). -- `drain_waits`, `overrun_events`: ring-buffer diagnostics (Chapter 10). +- `reads_blocked`、`writes_blocked`:不得不睡眠的调用计数(第十章)。 +- `poll_waiters`:活跃 `poll(2)` 订阅者计数(第十章)。 +- `drain_waits`、`overrun_events`:环形缓冲区诊断(第十章)。 -Each one is one more thing an operator can look at to understand what the driver is doing. The pattern is the same: expose the counters, keep the mechanism silent, let the operator decide when to inspect. +每一个都是操作员可以查看以了解驱动正在做什么的又一个东西。模式是相同的:暴露计数器,保持机制静默,让操作员决定何时检查。 ### 你的驱动在轻负载下的样子 -A concrete example is more useful than abstract advice. Load Stage 3, run the companion `stress_rw` program for a few seconds with `sysctl dev.myfirst.0.stats` watching from another terminal, and you see something like this: +一个具体的例子比抽象的建议更有用。加载阶段 3,从另一个终端用 `sysctl dev.myfirst.0.stats` 监控运行伴随的 `stress_rw` 程序几秒钟,你会看到类似这样的内容: -**Before `stress_rw` starts:** +**`stress_rw` 启动前:** ```text dev.myfirst.0.stats.attach_ticks: 12345678 @@ -2369,9 +2369,9 @@ dev.myfirst.0.stats.bytes_written: 0 dev.myfirst.0.stats.bufused: 0 ``` -Zero activity, one attach, buffer empty. +零活动,一次附加,缓冲区为空。 -**During `stress_rw`, with `watch -n 0.5 sysctl dev.myfirst.0.stats`:** +**`stress_rw` 运行期间,使用 `watch -n 0.5 sysctl dev.myfirst.0.stats`:** ```text dev.myfirst.0.stats.attach_ticks: 12345678 @@ -2382,9 +2382,9 @@ dev.myfirst.0.stats.bytes_written: 1359040 dev.myfirst.0.stats.bufused: 64 ``` -Two active descriptors (writer + reader), counters climbing, buffer holding 64 bytes of in-flight data. `bytes_written` is slightly ahead of `bytes_read`, which is exactly what you would expect: the writer produced a chunk the reader has not quite consumed yet. The difference equals `bufused`. +两个活跃描述符(写入者 + 读取者),计数器攀升,缓冲区持有 64 字节的在途数据。`bytes_written` 略微领先于 `bytes_read`,这正是你期望的:写入者产生了读取者尚未完全消耗的一块数据。差值等于 `bufused`。 -**After `stress_rw` exits:** +**`stress_rw` 退出后:** ```text dev.myfirst.0.stats.attach_ticks: 12345678 @@ -2395,73 +2395,73 @@ dev.myfirst.0.stats.bytes_written: 4800000 dev.myfirst.0.stats.bufused: 0 ``` -Both descriptors closed. Lifetime opens is 2 (cumulative). Active is 0. `bytes_read` equals `bytes_written`; the reader caught up fully. Buffer is empty. +两个描述符都已关闭。生命周期打开次数为 2(累计)。活跃数为 0。`bytes_read` 等于 `bytes_written`;读取者已完全赶上。缓冲区为空。 -Three signatures to notice. First, `active_fhs` always tracks live descriptors; it is a live value, not a cumulative counter. Second, `bytes_read == bytes_written` at steady state when the reader is keeping up, plus whatever is sitting in `bufused`. Third, the `open_count` is a lifetime value that never decreases; a quick way to spot churn is to watch it grow while `active_fhs` stays stable. +三个特征值得注意。首先,`active_fhs` 始终跟踪活跃描述符;它是实时值,不是累计计数器。其次,当读取者跟上时,稳态下 `bytes_read == bytes_written`,加上 `bufused` 中的任何内容。第三,`open_count` 是一个永不减少的生命周期值;发现搅动的一个快速方式是观察它增长而 `active_fhs` 保持稳定。 -A driver that behaves predictably under load is a driver you can operate with confidence. Once the counters line up the way this paragraph describes, you have your first real driver, not a toy. +一个在负载下行为可预测的驱动是你能自信操作的驱动。一旦计数器按照本段描述的方式排列,你就拥有了你的第一个真正的驱动,而不是一个玩具。 ## 有符号、无符号和差一的危害 -A short section on a class of bug that has caused more kernel panics than almost any other. It shows up especially often in I/O handlers. +关于一类几乎比任何其他类型都导致了更多内核崩溃的 bug 的简短章节。它在 I/O 处理程序中尤其频繁出现。 ### ssize_t 与 size_t -Two types dominate I/O code: +两种类型主导 I/O 代码: -- `size_t`: unsigned, used for sizes and counts. `sizeof(x)` returns `size_t`. `malloc(9)` takes `size_t`. `memcpy` takes `size_t`. -- `ssize_t`: signed, used when a value could be negative (usually -1 for error). `read(2)` and `write(2)` return `ssize_t`. `uio_resid` is `ssize_t`. +- `size_t`:无符号,用于大小和计数。`sizeof(x)` 返回 `size_t`。`malloc(9)` 接受 `size_t`。`memcpy` 接受 `size_t`。 +- `ssize_t`:有符号,用于值可能为负的情况(通常 -1 表示错误)。`read(2)` 和 `write(2)` 返回 `ssize_t`。`uio_resid` 是 `ssize_t`。 -The two types have the same width on every platform FreeBSD supports, but they do not silently convert between each other without warnings, and they behave very differently when arithmetic underflows. +这两种类型在 FreeBSD 支持的每个平台上具有相同的宽度,但它们不会在没有警告的情况下在彼此之间静默转换,并且在算术下溢时行为非常不同。 -A subtraction of `size_t` values that would produce a negative result instead wraps around to a huge positive value, because `size_t` is unsigned. For example: +`size_t` 值的减法如果会产生负数结果,则会回绕成一个巨大的正数,因为 `size_t` 是无符号的。例如: ```c size_t avail = sc->buflen - sc->bufused; ``` -If `sc->bufused` is larger than `sc->buflen`, `avail` is an enormous number, and the next `uiomove` attempts a transfer that blows past the end of the buffer. +如果 `sc->bufused` 大于 `sc->buflen`,`avail` 将是一个巨大的数字,下一次 `uiomove` 会尝试一个超过缓冲区末尾的传输。 -The defence is the invariant. In every buffer-management section of the chapter, we maintain `sc->bufhead + sc->bufused <= sc->buflen`. As long as that invariant holds, `sc->buflen - (sc->bufhead + sc->bufused)` cannot underflow. +防御手段就是不变量。在本章的每个缓冲区管理部分,我们维护 `sc->bufhead + sc->bufused <= sc->buflen`。只要这个不变量成立,`sc->buflen - (sc->bufhead + sc->bufused)` 就不可能下溢。 -The risk is in code paths that violate the invariant accidentally. A double-free that restores an already-consumed value; a write that updates `bufused` twice; a race between writers. Those are the bugs to hunt for when `avail` ever looks wrong. +风险在于意外违反不变量的代码路径。一个恢复了已消耗值的重复释放;一个两次更新 `bufused` 的写入;写入者之间的竞争。这些是当 `avail` 看起来不对时要寻找的 bug。 ### uio_resid 可以与无符号值比较 -`uio_resid` is `ssize_t`. Your buffer sizes are `size_t`. Code like this: +`uio_resid` 是 `ssize_t`。你的缓冲区大小是 `size_t`。像这样的代码: ```c if (uio->uio_resid > sc->buflen) ... ``` -Will be compiled with a signed-vs-unsigned comparison. Modern compilers warn about this; the warning should be taken seriously. +将以有符号与无符号比较的方式编译。现代编译器对此发出警告;应该认真对待这个警告。 -The safer pattern is to cast explicitly: +更安全的模式是显式转换: ```c if ((size_t)uio->uio_resid > sc->buflen) ... ``` -Or to use `MIN`, which we have been using: +或者使用我们一直在用的 `MIN`: ```c towrite = MIN((size_t)uio->uio_resid, avail); ``` -The cast is defensible because `uio_resid` is documented to be non-negative in valid uios (and `uiomove` `KASSERT`s on it). The cast makes the compiler happy and makes the intent explicit. +这个转换是合理的,因为 `uio_resid` 在有效 uio 中被文档化为非负的(并且 `uiomove` 对其进行 `KASSERT`)。转换使编译器满意并使意图明确。 ### 计数器中的差一错误 -A counter updated on the wrong side of an error check is a classic bug: +在错误检查的错误一侧更新的计数器是一个经典 bug: ```c sc->bytes_read += towrite; /* BAD: happens even on error */ error = uiomove(sc->buf, towrite, uio); ``` -The correct shape is to increment after success: +正确的形状是在成功后递增: ```c error = uiomove(sc->buf, towrite, uio); @@ -2469,11 +2469,11 @@ if (error == 0) sc->bytes_read += towrite; ``` -This is why we have `if (error == 0)` guarding every counter update in the chapter. The cost is one line of code. The benefit is that your counters match reality. +这就是为什么我们在章节中用 `if (error == 0)` 保护每个计数器更新。代价是一行代码。好处是你的计数器与实际情况匹配。 ### uio_offset - before 惯用法 -When you want to know "how many bytes did `uiomove` actually move?", the cleanest way is to compare `uio_offset` before and after: +当你想知道"`uiomove` 实际移动了多少字节?"时,最干净的方式是比较前后的 `uio_offset`: ```c off_t before = uio->uio_offset; @@ -2481,64 +2481,64 @@ error = uiomove_frombuf(sc->buf, sc->buflen, uio); size_t moved = uio->uio_offset - before; ``` -This works for both full and short transfers. `moved` is the actual byte count, regardless of what the caller asked for or how much was available. +这对完整和短传输都有效。`moved` 是实际的字节计数,不管调用者请求了多少或有多少可用。 -The idiom is free at runtime (two subtractions) and unambiguous in code. Use it when your driver wants to count bytes; the alternative, inferring the count from `uio_resid`, requires knowing the original request size, which is more bookkeeping. +这个惯用法在运行时是免费的(两次减法),在代码中是明确的。当你的驱动想计数字节时使用它;替代方案——从 `uio_resid` 推断计数——需要知道原始请求大小,这需要更多簿记。 ## 额外故障排除:边界情况 -Expanding on the earlier troubleshooting section, here are a few more scenarios you are likely to hit the first time you write a real driver. +扩展前面的故障排除部分,以下是你第一次编写真正驱动时可能遇到的更多场景。 -### "The second read on the same descriptor returns zero" +### "同一描述符上的第二次读取返回零" -Expected for a static-message driver (Stage 1): once `uio_offset` reaches the end of the message, `uiomove_frombuf` returns zero. +对于静态消息驱动(阶段 1)是预期的:一旦 `uio_offset` 到达消息末尾,`uiomove_frombuf` 返回零。 -Unexpected for a FIFO driver (Stage 3): the first read drained the buffer, and no writer has refilled it. The caller should not be issuing a second read back-to-back without a write happening in between. +对于 FIFO 驱动(阶段 3)是意外的:第一次读取排空了缓冲区,没有写入者重新填充它。调用者不应该在没有写入发生的情况下连续发出第二次读取。 -To distinguish the two cases, check `sysctl dev.myfirst.0.stats.bufused`. If it is zero, the buffer is empty. If it is non-zero and you still see zero bytes, you have a bug. +要区分这两种情况,检查 `sysctl dev.myfirst.0.stats.bufused`。如果为零,缓冲区为空。如果非零但你仍然看到零字节,你有一个 bug。 -### "The driver returns zero bytes immediately when the buffer has data" +### "驱动在缓冲区有数据时立即返回零字节" -The read handler is taking the wrong branch. Common causes: +读取处理程序走了错误的分支。常见原因: -- A `bufused == 0` check placed in the wrong spot. If the check runs before the per-open state retrieval, it might short-circuit the read before the real work. -- An accidental `return 0;` earlier in the handler (for example, in a debug branch left from a previous experiment). -- A missing `mtx_unlock` on an error path, making every subsequent call block on the mutex forever. Symptom: the second call hangs, not a zero-byte return; but it is worth checking. +- `bufused == 0` 检查放在了错误的位置。如果检查在每次打开状态检索之前运行,它可能在真正工作之前就短路了读取。 +- 处理程序中较早处有一个意外的 `return 0;`(例如,之前实验留下的调试分支)。 +- 错误路径上缺少 `mtx_unlock`,使后续每次调用永远阻塞在互斥锁上。症状:第二次调用挂起,而不是零字节返回;但值得检查。 -### "My `uiomove_frombuf` always returns zero regardless of the buffer" +### "我的 `uiomove_frombuf` 无论缓冲区如何都总是返回零" -Two common causes: +两个常见原因: -- The `buflen` argument is zero. `uiomove_frombuf` returns zero immediately if `buflen <= 0`. -- `uio_offset` is already at or past `buflen`. `uiomove_frombuf` returns zero to signal EOF in that case. +- `buflen` 参数为零。如果 `buflen <= 0`,`uiomove_frombuf` 立即返回零。 +- `uio_offset` 已经达到或超过 `buflen`。在这种情况下,`uiomove_frombuf` 返回零以发出 EOF 信号。 -Add a `device_printf` logging the arguments at entry to confirm which case you are in. +在入口处添加一个 `device_printf` 记录参数以确认你属于哪种情况。 -### "The buffer overflows into adjacent memory" +### "缓冲区溢出到相邻内存" -Your arithmetic is wrong. Somewhere you are calling `uiomove(sc->buf + X, N, uio)` where `X + N > sc->buflen`. The write proceeds silently and corrupts kernel memory. +你的算术是错误的。某处你调用了 `uiomove(sc->buf + X, N, uio)` 其中 `X + N > sc->buflen`。写入静默进行并损坏内核内存。 -Your kernel will usually panic shortly thereafter, possibly in a completely unrelated subsystem. The panic message will not mention your driver; it will mention whichever heap neighbour got clobbered. +你的内核通常随后会崩溃,可能在一个完全不相关的子系统中。崩溃消息不会提及你的驱动;它会提及被破坏的堆邻居。 -If you suspect this, rebuild with `INVARIANTS` and `WITNESS` (and on many targets, KASAN on amd64). These kernel features catch buffer overruns much earlier than the default kernel does. +如果你怀疑这一点,用 `INVARIANTS` 和 `WITNESS`(在许多目标上还有 amd64 上的 KASAN)重新构建。这些内核特性比默认内核更早捕获缓冲区溢出。 -### "A process reading from the device hangs forever" +### "从设备读取的进程永远挂起" -Since Chapter 9 does not implement blocking I/O, this should not happen with `myfirst` Stage 3. If it does, the most likely cause is the process holding a file descriptor while you tried to unload the driver; `destroy_dev(9)` is waiting for `si_threadcount` to reach zero, and the process is sitting inside your handler for some reason. +由于第九章不实现阻塞 I/O,这不应该在 `myfirst` 阶段 3 中发生。如果发生了,最可能的原因是进程在你尝试卸载驱动时持有一个文件描述符;`destroy_dev(9)` 正在等待 `si_threadcount` 达到零,而进程因某种原因停留在你的处理程序内部。 -To diagnose: `ps auxH | grep `; `gdb -p ` and `bt`. The stack should reveal where the thread is parked. +诊断方法:`ps auxH | grep `;`gdb -p ` 和 `bt`。栈应该揭示线程停在哪里。 -If your Stage 3 handler accidentally sleeps (for instance, because you added a `tsleep` while experimenting with Chapter 10 material early), the fix is to remove the sleep. Chapter 9's driver does not block. +如果你的阶段 3 处理程序意外睡眠(例如,因为你在提前实验第十章材料时添加了 `tsleep`),修复方法是移除睡眠。第九章的驱动不阻塞。 -### "`kldunload` says `kldunload: can't unload file: Device busy`" +### "`kldunload` 提示 `kldunload: can't unload file: Device busy`" -Classic symptom of a descriptor still open. Use `fuser /dev/myfirst/0` to find the offending process, close the descriptor or kill the process, and retry. +描述符仍然打开的经典症状。使用 `fuser /dev/myfirst/0` 找到有问题的进程,关闭描述符或终止进程,然后重试。 -### "I modified the driver and `make` compiles but `kldload` fails with version mismatch" +### "我修改了驱动,`make` 编译成功但 `kldload` 因版本不匹配而失败" -Your build environment does not match your running kernel. Check: +你的构建环境与运行中的内核不匹配。检查: ```sh % freebsd-version -k @@ -2546,90 +2546,90 @@ Your build environment does not match your running kernel. Check: % ls /usr/obj/usr/src/amd64.amd64/sys/GENERIC ``` -If `/usr/src` is for a different release, your headers produce a module that the kernel refuses. Rebuild against the matching sources. In a lab VM this usually means syncing `/usr/src` with the running release via `fetch` or `freebsd-update src-install`. +如果 `/usr/src` 是不同版本的,你的头文件产生的模块会被内核拒绝。用匹配的源码重新构建。在实验虚拟机中,这通常意味着通过 `fetch` 或 `freebsd-update src-install` 将 `/usr/src` 与运行中的版本同步。 -### "I see every byte written through the device printed twice in dmesg" +### "我看到通过设备写入的每个字节在 dmesg 中打印了两次" -You have a `device_printf` inside the hot path that prints every transfer. Remove it or guard it with `if (bootverbose)`. +你在热路径中有一个打印每次传输的 `device_printf`。移除它或用 `if (bootverbose)` 保护它。 -A milder version of the same bug: a single-line log that prints the length of every transfer. For small test workloads that looks fine; for a real user workload it will bury dmesg and cause timestamp compression in the kernel buffer. +同一个 bug 的更温和版本:打印每次传输长度的单行日志。对于小型测试工作负载看起来没问题;对于真正的用户工作负载,它会淹没 dmesg 并导致内核缓冲区中的时间戳压缩。 -### "My `d_read` is called but my `d_write` is not" +### "我的 `d_read` 被调用了但 `d_write` 没有被调用" -Either the user program never calls `write(2)` on the device, or it calls `write(2)` with the descriptor not opened for writing (`O_RDONLY`). Check both. +要么是用户程序从未在设备上调用 `write(2)`,要么是调用 `write(2)` 时描述符没有以写入方式打开(`O_RDONLY`)。检查两者。 -Also: confirm that `cdevsw.d_write` is assigned to `myfirst_write`. A copy-paste bug that assigns it to `myfirst_read` results in both directions hitting the read handler, with predictably confusing results. +另外:确认 `cdevsw.d_write` 被分配给了 `myfirst_write`。将其分配给 `myfirst_read` 的复制粘贴 bug 会导致两个方向都命中读取处理程序,产生可预见的混乱结果。 ## 设计说明:为什么每个阶段停在它停的地方 -A short meta-section on why Chapter 9's three stages have the boundaries they have. This is the kind of chapter-design reasoning that is worth making explicit, because it is the reasoning you will apply when you design your own drivers. +一个简短的元节,解释第九章的三个阶段为什么有这些边界。这是值得明确的章节设计推理类型,因为这是你在设计自己的驱动时将应用的推理。 ### 为什么存在阶段 1 -Stage 1 is the smallest possible `d_read` that is not `/dev/null`. It introduces: +阶段 1 是不是 `/dev/null` 的最小可能 `d_read`。它介绍了: -- The `uiomove_frombuf(9)` helper, the easiest way to get a fixed buffer out to user space. -- Per-descriptor offset handling. -- The pattern of using `uio_offset` as the state carrier. +- `uiomove_frombuf(9)` 辅助函数,将固定缓冲区输出到用户空间的最简单方式。 +- 每次描述符偏移处理。 +- 使用 `uio_offset` 作为状态载体的模式。 -Stage 1 does not do anything with writes; the Chapter 8 stub is fine. +阶段 1 不对写入做任何事情;第八章的桩函数就可以。 -Without Stage 1, the jump from stubs to a buffered read/write driver is too large. Stage 1 lets you confirm, with minimal code, that the read handler is wired up correctly. Everything else builds on that confirmation. +没有阶段 1,从桩函数到缓冲区读/写驱动的跳跃就太大了。阶段 1 让你用最少的代码确认读取处理程序已正确连接。其他一切都建立在那个确认之上。 ### 为什么存在阶段 2 -Stage 2 introduces: +阶段 2 介绍了: -- A dynamically-allocated kernel buffer. -- A write path that accepts user data. -- A read path that honours the caller's offset across the accumulating buffer. -- The first realistic use of the softc mutex in an I/O handler. +- 动态分配的内核缓冲区。 +- 接受用户数据的写入路径。 +- 遵守调用者偏移穿越累积缓冲区的读取路径。 +- softc 互斥锁在 I/O 处理程序中的首次实际使用。 -Stage 2 deliberately does not drain reads. The buffer grows until full; subsequent writes return `ENOSPC`. This lets two concurrent readers confirm that they each have their own `uio_offset`, which is the property Stage 1 couldn't demonstrate (because Stage 1 had nothing to write). +阶段 2 刻意不排空读取。缓冲区增长直到满;后续写入返回 `ENOSPC`。这让两个并发读取者可以确认它们各自有自己的 `uio_offset`,这是阶段 1 无法演示的属性(因为阶段 1 没有可写入的内容)。 ### 为什么存在阶段 3 -Stage 3 introduces: +阶段 3 介绍了: -- Reads that drain the buffer. -- The coordination between a head pointer and a used count. -- The FIFO semantics that most real drivers approximate. +- 排空缓冲区的读取。 +- 头指针和已用计数之间的协调。 +- 大多数真正驱动近似使用的 FIFO 语义。 -Stage 3 does not wrap around. The head and used pointers walk forward through the buffer and the buffer collapses to the beginning when empty. A proper ring buffer (with head and tail wrapping around a fixed-size array) belongs in Chapter 10 because it pairs naturally with blocking reads and `poll(2)`: a ring makes steady-state operation efficient, and efficient steady-state operation is exactly what a blocking reader needs. +阶段 3 不会环绕。头指针和已用指针在缓冲区中向前移动,当缓冲区为空时折叠回开头。真正的环形缓冲区(头和尾在固定大小数组中环绕)属于第十章,因为它与阻塞读取和 `poll(2)` 自然配对:环形使稳态操作高效,而高效的稳态操作正是阻塞读取者所需要的。 ### 为什么这里没有环形缓冲区 -A ring buffer is five to fifteen lines of additional bookkeeping beyond what Stage 3 does. Adding it now would not be a large amount of code. The reason it is deferred is pedagogical: the two concepts ("I/O path semantics" and "ring buffer mechanics") are independently confusing to a beginner, and splitting them into two chapters lets each chapter address one pile of confusion at a time. +环形缓冲区比阶段 3 多五到十五行的额外簿记。现在添加它不会是大量的代码。推迟的原因是教学性的:两个概念("I/O 路径语义"和"环形缓冲区机制")对初学者来说各自都容易混淆,将它们分成两章让每章一次解决一堆困惑。 -By the time Chapter 10 introduces the ring, the reader is fluent in the I/O path. The new material is only the ring bookkeeping. +到第十章引入环形时,读者已经熟练掌握 I/O 路径。新的材料只是环形簿记。 ### 为什么没有阻塞 -Blocking is useful, but it introduces `msleep(9)`, condition variables, the `d_purge` teardown hook, and a thicket of correctness issues around what to wake and when. Each of those is a substantial topic. Mixing them into Chapter 9 would double its length and halve its clarity. +阻塞是有用的,但它引入了 `msleep(9)`、条件变量、`d_purge` 拆卸钩子,以及围绕何时唤醒和唤醒什么的大量正确性问题。其中每一个都是实质性的主题。将它们混入第九章会使长度翻倍、清晰度减半。 -Chapter 10's first section is "when your driver has to wait". It is a natural follow-on. +第十章的第一节是"当你的驱动必须等待时"。这是一个自然的延续。 ### 各阶段**不**试图成为什么 -The stages are not a simulation of a hardware driver. They do not mimic DMA. They do not simulate interrupts. They do not pretend to be anything other than what they are: in-memory drivers that exercise the UNIX I/O path. +这些阶段不是硬件驱动的模拟。它们不模拟 DMA。它们不模拟中断。它们不假装成它们不是的东西:它们是锻炼 UNIX I/O 路径的内存中驱动。 -This matters because later in the book, when we write actual hardware drivers, the I/O path will look identical. The hardware specifics (where the bytes come from, where the bytes go to) will change, but the handler shape, the uiomove usage, the errno conventions, the counter patterns, all of these will be recognisable from Chapter 9. +这很重要,因为在本书后面,当我们编写真正的硬件驱动时,I/O 路径看起来会是相同的。硬件细节(字节从哪里来,字节到哪里去)会改变,但处理程序形状、uiomove 用法、errno 约定、计数器模式,所有这些都将从第九章中可以识别。 -A driver that moves bytes correctly across the user/kernel trust boundary is 80% of any real driver. Chapter 9 teaches that 80%. +一个正确跨越用户/内核信任边界移动字节的驱动是任何真正驱动的 80%。第九章教你那 80%。 ## 动手实验 -The labs below track the three stages above. Each lab is a checkpoint that proves your driver is doing the thing the text just described. Read the lab fully before starting, and do them in order. +下面的实验跟踪上面的三个阶段。每个实验都是一个检查点,证明你的驱动正在做文本刚才描述的事情。在开始之前完整阅读实验,并按顺序进行。 ### 实验 9.1:构建并加载阶段 1 -**Goal:** Build the Stage 1 driver, load it, read the static message, and confirm per-descriptor offset handling. +**目标:** 构建阶段 1 驱动,加载它,读取静态消息,并确认每次描述符的偏移处理。 -**Steps:** +**步骤:** 1. Start from the companion tree: `cp -r examples/part-02/ch09-reading-and-writing/stage1-static-message ~/drivers/ch09-stage1`. Alternatively, modify your Chapter 8 stage 2 driver according to the Stage 1 walkthrough above. 2. Change into the directory and build: @@ -2667,29 +2667,29 @@ The labs below track the three stages above. Each lab is a checkpoint that prove ```sh % dmesg | tail -5 ``` - You should see the `open via /dev/myfirst/0 fh=...` and `per-open dtor fh=...` lines from Chapter 8, plus the message body was read. + 你应该会看到第 8 章的 `open via /dev/myfirst/0 fh=...` 和 `per-open dtor fh=...` 行,以及消息正文已被读取的信息。 8. Unload: ```sh % sudo kldunload myfirst ``` -**Success criteria:** +**成功标准:** -- `cat` prints the message. -- The userland tool shows 75 bytes on the first read and 0 bytes on the second. -- `dmesg` shows one open and one destructor per `./rw_myfirst read` invocation. +- `cat` 打印消息。 +- 用户态工具在第一次读取时显示 75 字节,第二次读取时显示 0 字节。 +- `dmesg` 为每次 `./rw_myfirst read` 调用显示一次打开和一次析构。 -**Common mistakes:** +**常见错误:** -- Forgetting the `-1` on `sizeof(myfirst_message) - 1`. The message will include a trailing NUL byte that appears as a stray character in user output. -- Not calling `devfs_get_cdevpriv` before the `sc == NULL` check. The rest of the chapter depends on this order; run it to see why it is the right one. -- Using `(void *)sc->message` instead of `__DECONST(void *, sc->message)`. Both work on most compilers; the `__DECONST` form is the convention and suppresses a warning on some compiler configurations. +- 忘记 `sizeof(myfirst_message) - 1` 中的 `-1`。消息将包含一个作为杂散字符出现在用户输出中的末尾 NUL 字节。 +- 在 `sc == NULL` 检查之前没有调用 `devfs_get_cdevpriv`。本章的其余部分依赖于这个顺序;运行它来看看为什么这是正确的。 +- 使用 `(void *)sc->message` 而不是 `__DECONST(void *, sc->message)`。两者在大多数编译器上都能工作;`__DECONST` 形式是约定并在某些编译器配置上抑制警告。 ### 实验 9.2:用写入和读取练习阶段 2 -**Goal:** Build Stage 2, push data in from userland, pull it back out, and observe the sysctl counters. +**目标:** 构建阶段 2,从用户态推入数据,拉回出来,并观察 sysctl 计数器。 -**Steps:** +**步骤:** 1. From the companion tree: `cp -r examples/part-02/ch09-reading-and-writing/stage2-readwrite ~/drivers/ch09-stage2`. 2. Build and load: @@ -2730,7 +2730,7 @@ The labs below track the three stages above. Each lab is a checkpoint that prove ```sh % dd if=/dev/zero bs=1024 count=8 | sudo tee /dev/myfirst/0 > /dev/null ``` - Expect a short-write error. Inspect `sysctl dev.myfirst.0.stats.bufused`; it should be 4096 (the buffer size). + 预期会出现短写错误。检查 `sysctl dev.myfirst.0.stats.bufused`;它应该是 4096(缓冲区大小)。 8. Confirm reads still deliver the content: ```sh % sudo cat /dev/myfirst/0 | od -An -c | head -3 @@ -2740,24 +2740,24 @@ The labs below track the three stages above. Each lab is a checkpoint that prove % sudo kldunload myfirst ``` -**Success criteria:** +**成功标准:** -- Writes deposit bytes; reads deliver them back. -- `bufused` matches the number of bytes written since the last reset. -- `dd` exhibits a short write when the buffer fills; the driver returns `ENOSPC`. -- `dmesg` shows open and destructor lines for every process that opened the device. +- 写入存入字节;读取传回它们。 +- `bufused` 与自上次重置以来写入的字节数匹配。 +- 当缓冲区填满时 `dd` 表现出短写入;驱动返回 `ENOSPC`。 +- `dmesg` 为每个打开设备的进程显示打开和析构行。 -**Common mistakes:** +**常见错误:** -- Forgetting to free `sc->buf` in `detach`. The driver will unload without complaint, but a subsequent kernel memory leak check (`vmstat -m | grep devbuf`) will show drift. -- Holding the softc mutex while calling `uiomove`, without being sure the mutex is an `MTX_DEF` and not a spin lock. Chapter 7's `mtx_init(..., MTX_DEF)` is the right choice; do not change it. -- Omitting the `sc->bufused = 0` reset in `attach`. `Newbus` initialises softc to zero for you, but making the initialisation explicit is the convention; it also makes a later refactor less error-prone. +- 忘记在 `detach` 中释放 `sc->buf`。驱动将无提示地卸载,但后续的内核内存泄漏检查(`vmstat -m | grep devbuf`)将显示漂移。 +- 在调用 `uiomove` 时持有 softc 互斥锁,但不确定互斥锁是 `MTX_DEF` 而不是自旋锁。第七章的 `mtx_init(..., MTX_DEF)` 是正确的选择;不要更改它。 +- 在 `attach` 中省略 `sc->bufused = 0` 重置。Newbus 为你将 softc 初始化为零,但使初始化显式是约定;它也使后续重构更不容易出错。 ### 实验 9.3:阶段 3 FIFO 行为 -**Goal:** Build Stage 3, exercise FIFO behaviour from two terminals, and confirm that reads drain the buffer. +**目标:** 构建阶段 3,从两个终端练习 FIFO 行为,并确认读取排空缓冲区。 -**Steps:** +**步骤:** 1. From the companion tree: `cp -r examples/part-02/ch09-reading-and-writing/stage3-echo ~/drivers/ch09-stage3`. 2. Build and load: @@ -2779,7 +2779,7 @@ The labs below track the three stages above. Each lab is a checkpoint that prove ```sh % cat /dev/myfirst/0 ``` - Expect no output. The buffer is empty. + 预期没有输出。缓冲区是空的。 6. In terminal A, write two lines in rapid succession: ```sh % echo "first" | sudo tee /dev/myfirst/0 > /dev/null @@ -2791,7 +2791,7 @@ The labs below track the three stages above. Each lab is a checkpoint that prove first second ``` - Expect the two lines concatenated. Both writes appended to the same buffer before either read happened. + 预期两行会拼接在一起。两次写入在任一读取发生之前追加到了同一个缓冲区。 8. Inspect the counters: ```sh % sysctl dev.myfirst.0.stats @@ -2802,23 +2802,23 @@ The labs below track the three stages above. Each lab is a checkpoint that prove % sudo kldunload myfirst ``` -**Success criteria:** +**成功标准:** -- Writes append to the buffer; reads drain it. -- A read after the buffer is drained returns immediately (EOF-on-empty). -- `bytes_read` always equals `bytes_written` once the reader has caught up. +- 写入追加到缓冲区;读取排空它。 +- 缓冲区排空后的读取立即返回(空时 EOF)。 +- 一旦读取者跟上,`bytes_read` 总是等于 `bytes_written`。 -**Common mistakes:** +**常见错误:** -- Not resetting `bufhead = 0` when `bufused` reaches zero. The buffer will "drift" toward the end of `sc->buf` and refuse writes long before it is full. -- Forgetting to update `bufhead` as reads drain. The driver will read the same bytes repeatedly. -- Using `uio->uio_offset` as a per-descriptor offset. In a FIFO, offsets are shared; a per-descriptor offset does not make sense and will confuse testers. +- 当 `bufused` 达到零时不重置 `bufhead = 0`。缓冲区将向 `sc->buf` 末尾"漂移",在满之前很久就拒绝写入。 +- 忘记在读取排空时更新 `bufhead`。驱动将重复读取相同的字节。 +- 使用 `uio->uio_offset` 作为每次描述符的偏移。在 FIFO 中,偏移是共享的;每次描述符偏移没有意义,会使测试者困惑。 ### 实验 9.4:使用 dd 测量传输行为 -**Goal:** Use `dd(1)` to generate known-size transfers, read the results back, and check that the counters agree. +**目标:** 使用 `dd(1)` 生成已知大小的传输,读回结果,并检查计数器是否一致。 -`dd` is the tool of choice here because it lets you control the block size, the number of blocks, and the behaviour on short transfers. +`dd` 是这里的工具选择,因为它让你控制块大小、块数量和短传输上的行为。 1. Reload the Stage 3 driver fresh: ```sh @@ -2856,7 +2856,7 @@ The labs below track the three stages above. Each lab is a checkpoint that prove 0+0 records out 0 bytes transferred ``` - The driver accepted 4096 bytes (the buffer size) of the 8192 requested and returned a short write for the rest. + 驱动接受了 8192 字节请求中的 4096 字节(缓冲区大小),其余部分返回了短写入。 7. Alternatively, use `bs=4096` with `count=2`: ```sh % sudo dd if=/dev/urandom of=/dev/myfirst/0 bs=4096 count=2 @@ -2865,22 +2865,22 @@ The labs below track the three stages above. Each lab is a checkpoint that prove 0+0 records out 4096 bytes transferred ``` - The first block of 4096 bytes succeeded in full; the second block failed with `ENOSPC`. + 第一个 4096 字节的块完全成功;第二个块以 `ENOSPC` 失败。 8. Drain: ```sh % sudo dd if=/dev/myfirst/0 of=/tmp/out bs=4096 count=1 % sudo kldunload myfirst ``` -**Success criteria:** +**成功标准:** -- `dd` reports the expected byte counts at each step. -- The driver accepts up to 4096 bytes and refuses the rest with `ENOSPC`. -- `bufused` tracks the buffer state after every operation. +- `dd` 在每一步报告预期的字节计数。 +- 驱动接受最多 4096 字节,对剩余部分返回 `ENOSPC`。 +- `bufused` 在每次操作后跟踪缓冲区状态。 ### 实验 9.5:一个小型往返 C 程序 -**Goal:** Write a short userland C program that opens the device, writes known bytes, closes the descriptor, opens it again, reads the bytes back, and verifies they match. +**目标:** 编写一个短的用户态 C 程序,打开设备,写入已知字节,关闭描述符,再次打开,读回字节,并验证它们匹配。 1. Save the following as `rw_myfirst.c` in `~/drivers/ch09-stage3`: @@ -2934,20 +2934,20 @@ main(void) ``` 3. Inspect `dmesg` to see the two opens and two destructors. -**Success criteria:** +**成功标准:** -- The program prints `round-trip OK: 24 bytes`. -- `dmesg` shows one open/destructor pair for the write and one for the read. +- 程序打印 `round-trip OK: 24 bytes`。 +- `dmesg` 显示一次写入的打开/析构对和一次读取的打开/析构对。 -**Common mistakes:** +**常见错误:** -- Writing fewer bytes than the payload and not checking the return value. `write(2)` can return a short count; your test must handle it. -- Forgetting `O_WRONLY` vs `O_RDONLY`. `open(2)` enforces the mode against the access bits of the node; opening with the wrong mode returns `EACCES` (or similar). -- Assuming `read(2)` returns the requested count. It can return less; again, the caller loops. +- 写入的字节少于载荷且未检查返回值。`write(2)` 可以返回短计数;你的测试必须处理它。 +- 忘记 `O_WRONLY` 与 `O_RDONLY` 的区别。`open(2)` 根据节点的访问位强制执行模式;以错误模式打开返回 `EACCES`(或类似的错误)。 +- 假设 `read(2)` 返回请求的计数。它可以返回更少;同样,调用者需要循环。 ### 实验 9.6:检查二进制往返 -**Goal:** Confirm that the driver handles arbitrary binary data, not only text, by pushing random bytes through and checking that the same bytes come back. +**目标:** 通过推送随机字节并检查相同字节返回,确认驱动处理任意二进制数据,而不仅仅是文本。 1. With Stage 3 loaded and empty, write 256 random bytes: ```sh @@ -2970,19 +2970,19 @@ main(void) ``` 5. Try a pathological pattern: all zeros, all `0xff`, then a file full of a single byte. Confirm every pattern round-trips exactly. -**Success criteria:** +**成功标准:** -- `cmp` reports no differences. -- The driver preserves every bit of the input. -- No byte-ordering, no "helpful" interpretation, no surprise transformations. +- `cmp` 报告没有差异。 +- 驱动保留输入的每一位。 +- 没有字节顺序问题,没有"有帮助的"解释,没有意外的转换。 -This lab is short but important: it verifies that your driver is a transparent byte store, not a text filter that accidentally interprets some bytes specially. If you ever see differences between the sent and received files, you have a bug in the transfer path, probably a length miscount or an off-by-one in the buffer arithmetic. +这个实验很短但很重要:它验证你的驱动是一个透明的字节存储,而不是一个意外特殊解释某些字节的文本过滤器。如果你在发送和接收的文件之间看到差异,你的传输路径中有 bug,可能是长度误算或缓冲区算术中的差一错误。 ### 实验 9.7:端到端观察运行中的驱动 -**Goal:** Combine sysctl, dmesg, truss, and vmstat into a single end-to-end observation of the Stage 3 driver under real load. This lab has no new code; it is the bridge from "I wrote the driver" to "I can see what it is doing". +**目标:** 将 sysctl、dmesg、truss 和 vmstat 组合成对阶段 3 驱动在真实负载下的单一端到端观察。这个实验没有新代码;它是从"我写了驱动"到"我能看到它在做什么"的桥梁。 -**Steps:** +**步骤:** 1. With Stage 3 loaded fresh, open four terminals. Terminal A will run the driver load / unload cycles. Terminal B will monitor sysctl. Terminal C will tail dmesg. Terminal D will run a user workload. 2. **Terminal A:** @@ -2990,7 +2990,7 @@ This lab is short but important: it verifies that your driver is a transparent b % sudo kldload ./myfirst.ko % vmstat -m | grep devbuf ``` - Note the `devbuf` row's `InUse` and `MemUse` values. + 注意 `devbuf` 行的 `InUse` 和 `MemUse` 值。 3. **Terminal B:** ```sh % watch -n 1 sysctl dev.myfirst.0.stats @@ -3000,7 +3000,7 @@ This lab is short but important: it verifies that your driver is a transparent b % sudo dmesg -c > /dev/null % sudo dmesg -w ``` - The `-c` clears accumulated messages; the `-w` watches for new ones. + `-c` 清除累积的消息;`-w` 监视新消息。 5. **Terminal D:** ```sh % cd examples/part-02/ch09-reading-and-writing/userland @@ -3014,7 +3014,7 @@ This lab is short but important: it verifies that your driver is a transparent b ```sh % sudo ./stress_rw -s 5 ``` - Watch terminal B. You should see `bufused` oscillate, counters climb, and `active_fhs` hit 2 while the test runs. + 观察终端 B。你应该会看到 `bufused` 在振荡,计数器在攀升,并且测试运行期间 `active_fhs` 达到了 2。 10. When the stress run finishes, in terminal B verify `active_fhs` is 0. In terminal A, ```sh % sudo kldunload myfirst @@ -3022,193 +3022,193 @@ This lab is short but important: it verifies that your driver is a transparent b ``` `InUse` should have returned to its pre-load baseline. If it has not, your driver leaked an allocation and `vmstat -m` just told you. -**Success criteria:** +**成功标准:** -- Sysctl counters match the workload you ran. -- Dmesg shows one open/destructor pair per descriptor open/close. -- Truss output matches your mental model of what the program did. -- `vmstat -m | grep devbuf` returns to its baseline after unload. -- No panics, no warnings, no unexplained counter drift. +- Sysctl 计数器与你运行的工作负载匹配。 +- Dmesg 为每个描述符的打开/关闭显示一个打开/析构对。 +- Truss 输出与你对程序所做操作的心理模型匹配。 +- `vmstat -m | grep devbuf` 在卸载后回到其基线。 +- 没有崩溃、没有警告、没有无法解释的计数器漂移。 -**Why this lab matters:** this is the first lab that exercises the full observability toolchain at once. In production, the signal that something is wrong almost never comes from a crash; it comes from a counter that has drifted out of bounds, a `dmesg` line nobody expected, or a `vmstat -m` reading that does not match reality. Building the habit of looking at all four surfaces together is what separates "I wrote a driver" from "I am responsible for a driver". +**为什么这个实验重要:** 这是第一个同时锻炼完整可观测性工具链的实验。在生产中,出问题的信号几乎从不来自崩溃;它来自一个超出范围的计数器、一条没人预期的 `dmesg` 行,或一个与现实不匹配的 `vmstat -m` 读数。建立同时查看所有四个界面的习惯是区分"我写了一个驱动"和"我对一个驱动负责"的关键。 ## 挑战练习 -These challenges stretch the material without introducing topics that belong to later chapters. Each one uses only the primitives we have introduced. Try them before looking at the companion tree; the learning is in the attempt, not the answer. +这些挑战扩展了材料而没有引入属于后续章节的主题。每一个都只使用我们已介绍的原语。在看伴随树之前先尝试它们;学习在于尝试,而不在于答案。 ### 挑战 9.1:每次描述符的读取计数器 -Extend Stage 2 so that the per-descriptor `reads` counter is exposed via a sysctl. The counter should be available per active descriptor, which means a per-`fh` sysctl rather than a per-softc one. +扩展阶段 2,使每次描述符的 `reads` 计数器通过 sysctl 暴露。计数器应该对每个活跃描述符可用,这意味着是每次 `fh` 的 sysctl 而不是每次 softc 的。 -This challenge is harder than it looks: sysctls are allocated and freed at known points in the softc lifecycle, and the per-descriptor structure lives only as long as its descriptor. A clean solution registers a sysctl node per `fh` in `d_open` and unregisters it in the destructor. Be careful about lifetimes; the sysctl context must be freed before the `fh` memory. +这个挑战比看起来更难:sysctl 在 softc 生命周期的已知点分配和释放,而每次描述符的结构只在其描述符存活期间存在。一个干净的解决方案在 `d_open` 中为每个 `fh` 注册一个 sysctl 节点,并在析构函数中取消注册。注意生命周期;sysctl 上下文必须在 `fh` 内存之前释放。 -*Hint:* `sysctl_ctx_init` and `sysctl_ctx_free` are per-context. You can give each `fh` its own context, and free it in the destructor. +*提示:* `sysctl_ctx_init` 和 `sysctl_ctx_free` 是每次上下文的。你可以给每个 `fh` 自己的上下文,并在析构函数中释放它。 -*Alternative:* keep a linked list of `fh` pointers in the softc (under the mutex) and expose it through a custom sysctl handler that walks the list on demand. This is the pattern `/usr/src/sys/kern/tty_info.c` uses for per-process stats. +*替代方案:* 在 softc 中(在互斥锁下)保持一个 `fh` 指针链表,并通过按需遍历链表的自定义 sysctl 处理程序暴露它。这是 `/usr/src/sys/kern/tty_info.c` 用于每次进程统计的模式。 ### 挑战 9.2:一个支持 readv(2) 的测试 -Write a user program that uses `readv(2)` to read from the driver into three separate buffers of sizes 8, 16, and 32 bytes. Confirm that the driver delivers bytes into all three buffers in sequence. +编写一个用户程序,使用 `readv(2)` 从驱动读取到三个大小分别为 8、16 和 32 字节的独立缓冲区。确认驱动按顺序将字节传递到所有三个缓冲区。 -The kernel and `uiomove(9)` already handle `readv(2)`; the driver does not need changes. The purpose of this challenge is to convince yourself of that fact. +内核和 `uiomove(9)` 已经处理 `readv(2)`;驱动不需要更改。这个挑战的目的是让你自己确信这个事实。 -*Hint:* `struct iovec iov[3] = {{buf1, 8}, {buf2, 16}, {buf3, 32}};`, then `readv(fd, iov, 3)`. The return value is the total bytes delivered across all three buffers; the individual `iov_len` values are not modified on the user side. +*提示:* `struct iovec iov[3] = {{buf1, 8}, {buf2, 16}, {buf3, 32}};`,然后 `readv(fd, iov, 3)`。返回值是所有三个缓冲区传递的总字节数;用户端不会修改各个 `iov_len` 值。 ### 挑战 9.3:短写入演示 -Modify Stage 2's `myfirst_write` to accept at most 128 bytes per call, regardless of `uio_resid`. A user program that writes 1024 bytes should see a short write of 128 every time. +修改阶段 2 的 `myfirst_write` 使其每次调用最多接受 128 字节,不管 `uio_resid` 是多少。写入 1024 字节的用户程序应该每次看到 128 字节的短写入。 -Then write a short test program that writes 1024 bytes in a single `write(2)` call, observes the short-write return value, and loops until all 1024 bytes have been accepted. +然后编写一个短测试程序,在单次 `write(2)` 调用中写入 1024 字节,观察短写入返回值,并循环直到所有 1024 字节都被接受。 -Questions to think through: +值得思考的问题: -- Does `cat` handle short writes correctly? (Yes.) -- Does `echo > /dev/myfirst/0 "..."` handle them correctly? (Usually, via `printf` in the shell, but sometimes not; worth testing.) -- What happens if you remove the short-write behaviour and try to exceed the buffer size? (You get `ENOSPC` after the first 4096-byte write.) +- `cat` 是否正确处理短写入?(是的。) +- `echo > /dev/myfirst/0 "..."` 是否正确处理它们?(通常通过 shell 中的 `printf` 处理,但有时不会;值得测试。) +- 如果你移除短写入行为并尝试超过缓冲区大小会发生什么?(在第一次 4096 字节写入后你会得到 `ENOSPC`。) -This challenge teaches you to separate "the driver does the right thing" from "user programs assume what drivers do". +这个挑战教你区分"驱动做正确的事"和"用户程序假设驱动做什么"。 ### 挑战 9.4:一个 ls -l 传感器 -Make the driver's response to a read depend on the `ls -l` output of the device itself. That is: every read produces the current timestamp of the device node. +使驱动对读取的响应取决于设备本身的 `ls -l` 输出。即:每次读取产生设备节点的当前时间戳。 -*Hint:* `sc->cdev->si_ctime` and `sc->cdev->si_mtime` are `struct timespec` fields on the cdev. You can convert them to a string with `printf` formatting, place the string in a kernel buffer, and `uiomove_frombuf(9)` it out. +*提示:* `sc->cdev->si_ctime` 和 `sc->cdev->si_mtime` 是 cdev 上的 `struct timespec` 字段。你可以用 `printf` 格式化将它们转换为字符串,将字符串放入内核缓冲区,然后用 `uiomove_frombuf(9)` 输出。 -*Warning:* `si_ctime` / `si_mtime` may be updated by devfs as nodes are touched. Observe what happens when you `touch /dev/myfirst/0` and read again. +*警告:* `si_ctime` / `si_mtime` 可能会在节点被触及时由 devfs 更新。观察当你 `touch /dev/myfirst/0` 并再次读取时会发生什么。 ### 挑战 9.5:一个反向回显驱动 -Modify Stage 3 so that every read returns the bytes in reverse order from how they were written. A write of `"hello"` followed by a read should produce `"olleh"`. +修改阶段 3,使每次读取以写入顺序的相反顺序返回字节。写入 `"hello"` 后跟读取应该产生 `"olleh"`。 -This challenge is entirely about buffer bookkeeping. The `uiomove` calls stay the same; you change the addresses you hand to them. +这个挑战完全关于缓冲区簿记。`uiomove` 调用保持不变;你改变传递给它们的地址。 -*Hint:* You can either reverse the buffer on every read (expensive) or store bytes in reverse order on the write side (cheaper). Neither is the "right" answer; each has different correctness and concurrency properties. Pick one and argue for it in a comment. +*提示:* 你可以在每次读取时反转缓冲区(昂贵),或者在写入端以相反顺序存储字节(更便宜)。两者都不是"正确"的答案;每个都有不同的正确性和并发属性。选择一个并在注释中论证它。 ### 挑战 9.6:二进制往返 -Write a user program that writes a `struct timespec` to the driver, then reads one back. Compare the two structures. Are they equal? They should be, because `myfirst` is a transparent byte store. +编写一个用户程序,向驱动写入一个 `struct timespec`,然后读回一个。比较两个结构。它们相等吗?它们应该相等,因为 `myfirst` 是一个透明字节存储。 -Extend the program to write two `struct timespec` values, then `lseek(fd, sizeof(struct timespec), SEEK_SET)` and read the second one. What happens? (Clue: the FIFO does not support seeks meaningfully.) +扩展程序写入两个 `struct timespec` 值,然后 `lseek(fd, sizeof(struct timespec), SEEK_SET)` 并读取第二个。会发生什么?(线索:FIFO 不有意义地支持寻址。) -This challenge illustrates the "read and write carry bytes, not types" point from the safe-data-transfer section. The bytes round-trip perfectly; the type information does not. +这个挑战说明了安全数据传输部分的"读取和写入携带字节,而不是类型"的观点。字节完美往返;类型信息则不会。 ### 挑战 9.7:一个十六进制查看测试工具 -Write a short shell script that, given a byte count N, generates N random bytes with `dd if=/dev/urandom bs=$N count=1`, pipes them into your Stage 3 driver, then reads them back with `dd if=/dev/myfirst/0 bs=$N count=1`, and compares the two streams with `cmp`. The script should report success for matching streams and diff-like output for mismatching streams. Run it with N = 1, 2, 4, ..., 4096 to sweep small, boundary, and capacity-filling sizes. +编写一个短 shell 脚本,给定字节计数 N,用 `dd if=/dev/urandom bs=$N count=1` 生成 N 个随机字节,通过管道传入你的阶段 3 驱动,然后用 `dd if=/dev/myfirst/0 bs=$N count=1` 读回它们,并用 `cmp` 比较两个流。脚本应该对匹配的流报告成功,对不匹配的流报告类似 diff 的输出。用 N = 1, 2, 4, ..., 4096 运行它来覆盖小型、边界和容量填满的大小。 -Questions to answer as you run the sweep: +运行扫描时要回答的问题: -- Does every size round-trip cleanly up to and including 4096? -- At 4097, what does the driver do? Does the test harness report the error meaningfully? -- Is there any size at which `cmp` reports a difference? If so, what was the underlying cause? +- 每个大小(包括 4096)是否都能干净地往返? +- 在 4097 时,驱动做什么?测试工具是否有意义地报告错误? +- 是否有任何大小使得 `cmp` 报告差异?如果有,根本原因是什么? -This challenge rewards combining the tools in the Practical Workflow section: `dd` for precise transfers, `cmp` for byte-level verification, `sysctl` for counters, and the shell for orchestration. A robust test harness like this is the kind of habit that pays for itself every time you refactor a driver and want to know quickly whether the behaviour is still right. +这个挑战奖励你在实用工作流部分组合工具:`dd` 用于精确传输,`cmp` 用于字节级验证,`sysctl` 用于计数器,shell 用于编排。像这样健壮的测试工具是每次重构驱动并想快速知道行为是否仍然正确时都会回报的习惯。 ### 挑战 9.8:谁打开了描述符? -Write a small C program that opens `/dev/myfirst/0`, blocks on `pause()` (so it holds the descriptor indefinitely), and runs until `SIGTERM`. In a second terminal, run `fstat | grep myfirst` and then `fuser /dev/myfirst/0`. Note the output. Now try to `kldunload myfirst`. What error do you get? Why? +编写一个小型 C 程序,打开 `/dev/myfirst/0`,在 `pause()` 上阻塞(从而无限期持有描述符),运行直到收到 `SIGTERM`。在第二个终端中,运行 `fstat | grep myfirst` 然后运行 `fuser /dev/myfirst/0`。注意输出。现在尝试 `kldunload myfirst`。你得到什么错误?为什么? -Now kill the holder with `SIGTERM` or plain `kill`. Observe the destructor fire in `dmesg`. Try `kldunload` again. It should succeed. +现在用 `SIGTERM` 或普通 `kill` 终止持有者。观察 `dmesg` 中析构函数的触发。再次尝试 `kldunload`。它应该成功。 -This challenge is short, but it grounds one of the chapter's subtler invariants: a driver cannot unload while any descriptor is open on one of its cdevs, and FreeBSD gives operators a standard set of tools to find the holder. The next time a real-world `kldunload` fails with `EBUSY`, you will have seen the shape of the problem before. +这个挑战很短,但它巩固了本章一个更微妙的不变量:当任何描述符在其某个 cdev 上打开时,驱动无法卸载,FreeBSD 给操作员提供了一套标准工具来找到持有者。下次真正的 `kldunload` 因 `EBUSY` 失败时,你将已经见过这种问题的形状。 ## 常见错误故障排除 -Every `d_read` / `d_write` mistake you are likely to make falls into one of a small number of categories. This section is a short field guide. +你可能犯的每个 `d_read` / `d_write` 错误都属于少数几个类别之一。本节是一个简短的实地指南。 -### "My driver returns zero bytes even though I wrote data" +### "我的驱动即使写入了数据也返回零字节" -This is usually one of two bugs. +这通常是两个 bug 之一。 -**Bug 1**: You forgot to update `bufused` (or equivalent) after the successful `uiomove`. The write arrived, the bytes moved, but the driver's state never reflected the arrival. The next read sees `bufused == 0` and reports EOF. +**Bug 1**:你在成功的 `uiomove` 之后忘记更新 `bufused`(或等价物)。写入到达了,字节移动了,但驱动的状态从未反映到达。下一次读取看到 `bufused == 0` 并报告 EOF。 -Fix: always update your tracking fields inside `if (error == 0) { ... }` after `uiomove` returns. +修复:总是在 `uiomove` 返回后在 `if (error == 0) { ... }` 内更新你的跟踪字段。 -**Bug 2**: You reset `bufused` (or `bufhead`) somewhere inappropriate. A common pattern is adding a reset line inside `d_open` or `d_close` "for cleanliness". That wipes out the data the previous caller wrote. +**Bug 2**:你在不合适的地方重置了 `bufused`(或 `bufhead`)。一个常见的模式是在 `d_open` 或 `d_close` 中添加重置行"为了整洁"。那会擦除前一个调用者写入的数据。 -Fix: reset driver-wide state only in `attach` (at load) or `detach` (at unload). Per-descriptor state belongs in `fh`, reset by `malloc(M_ZERO)` and cleaned up by the destructor. +修复:仅在 `attach`(加载时)或 `detach`(卸载时)中重置驱动范围的状态。每次描述符的状态属于 `fh`,由 `malloc(M_ZERO)` 重置并由析构函数清理。 -### "My reads return garbage" +### "我的读取返回垃圾" -The buffer is uninitialised. `malloc(9)` without `M_ZERO` returns a block of memory whose contents are undefined. If your `d_read` reaches past `bufused`, or reads from offsets that have not been written, the bytes you see are leftovers from whatever memory the kernel recycled. +缓冲区未初始化。不带 `M_ZERO` 的 `malloc(9)` 返回内容未定义的内存块。如果你的 `d_read` 越过 `bufused`,或从尚未写入的偏移读取,你看到的字节是内核回收的任何内存的残留。 -Fix: always pass `M_ZERO` to `malloc` in `attach`. Always clamp reads to the current high-water mark (`bufused`), not to the buffer's total size (`buflen`). +修复:在 `attach` 中总是传递 `M_ZERO` 给 `malloc`。总是将读取限制在当前高水位标记(`bufused`),而不是缓冲区的总大小(`buflen`)。 -There is a more serious variant of this bug. A driver that returns uninitialised kernel memory to user space has just leaked kernel state into user space. In production that is a security hole. In development it is a bug; in production it is a CVE. +这个 bug 有一个更严重的变体。将未初始化的内核内存返回给用户空间的驱动刚刚将内核状态泄露到了用户空间。在开发中这是一个 bug;在生产中这是一个安全漏洞和一个 CVE。 -### "The kernel panics with a pagefault on a user address" +### "内核在用户地址上发生页错误而崩溃" -You called `memcpy` or `bcopy` directly on a user pointer instead of going through `uiomove` / `copyin` / `copyout`. The access faulted, the kernel had no fault handler installed, and the result was a panic. +你直接在用户指针上调用了 `memcpy` 或 `bcopy`,而不是通过 `uiomove` / `copyin` / `copyout`。访问出错,内核没有安装故障处理程序,结果是崩溃。 -Fix: never dereference a user pointer directly. Route through `uiomove(9)` (in handlers) or `copyin(9)` / `copyout(9)` (in other contexts). +修复:永远不要直接解引用用户指针。通过 `uiomove(9)`(在处理程序中)或 `copyin(9)` / `copyout(9)`(在其他上下文中)路由。 -### "The driver refuses to unload" +### "驱动拒绝卸载" -You have at least one file descriptor still open. `detach` returns `EBUSY` when `active_fhs > 0`; the module will not unload until every `fh` has been destroyed. +你至少有一个文件描述符仍然打开。当 `active_fhs > 0` 时 `detach` 返回 `EBUSY`;在所有 `fh` 被销毁之前模块不会卸载。 -Fix: close the descriptor in userland. If a background process is holding it, kill the process (after confirming it is yours; do not kill system daemons). `fstat -p ` shows which files a process has open; `fuser /dev/myfirst/0` shows which processes have the node open. +修复:在用户态关闭描述符。如果后台进程持有它,终止进程(在确认它是你的之后;不要终止系统守护进程)。`fstat -p ` 显示进程打开了哪些文件;`fuser /dev/myfirst/0` 显示哪些进程打开了节点。 -Chapter 10 will introduce `destroy_dev_drain` patterns for drivers that need to coerce a blocked reader to exit. Chapter 9 does not block, so this issue does not arise in normal operation; when it arises, it is because userland is holding the descriptor somewhere unexpected. +第十章将为需要强制阻塞读取者退出的驱动引入 `destroy_dev_drain` 模式。第九章不阻塞,所以这个问题在正常操作中不会出现;当它出现时,是因为用户态在某个意外的地方持有描述符。 -### "My write handler returns EFAULT" +### "我的写入处理程序返回 EFAULT" -Your `uiomove` call hit an invalid user address. The common causes: +你的 `uiomove` 调用遇到了无效的用户地址。常见原因: -- A user program called `write(fd, NULL, n)` or `write(fd, (void*)0xdeadbeef, n)`. -- A user program wrote a pointer it had freed. -- You accidentally passed a kernel pointer as the destination to `uiomove`. This can happen if you build a uio by hand for kernel-space data and then pass it to a handler expecting a user-space uio. The resulting `copyout` sees a "user" address that is actually a kernel address; depending on the architecture, you either get `EFAULT` or a subtle corruption. +- 用户程序调用了 `write(fd, NULL, n)` 或 `write(fd, (void*)0xdeadbeef, n)`。 +- 用户程序写入了一个它已释放的指针。 +- 你意外地将内核指针作为目标传递给 `uiomove`。如果你手工构建了一个用于内核空间数据的 uio,然后将其传递给期望用户空间 uio 的处理程序,就会发生这种情况。由此产生的 `copyout` 看到一个实际上是内核地址的"用户"地址;取决于架构,你要么得到 `EFAULT`,要么得到微妙的损坏。 -Fix: check `uio->uio_segflg`. For user-driven handlers, it should be `UIO_USERSPACE`. If you are passing around a kernel-space uio, make sure `uio_segflg == UIO_SYSSPACE` and that your code paths know the difference. +修复:检查 `uio->uio_segflg`。对于用户驱动的处理程序,它应该是 `UIO_USERSPACE`。如果你传递的是内核空间 uio,确保 `uio_segflg == UIO_SYSSPACE` 并且你的代码路径知道区别。 -### "My counters are wrong under concurrent writes" +### "并发写入下我的计数器是错误的" -Two writers raced on `bufused`. Each read the current value, added to it, and wrote back, and the second writer overwrote the first writer's update with a stale value. +两个写入者在 `bufused` 上竞争。每个都读取当前值,添加到它,然后写回,第二个写入者用陈旧的值覆盖了第一个写入者的更新。 -Fix: take `sc->mtx` around every read-modify-write of shared state. Part 3 makes this a first-class topic; for Chapter 9, a single mutex around the whole critical section is enough. +修复:在共享状态的每次读-修改-写周围获取 `sc->mtx`。第三部分将此作为一等主题;对于第九章,整个临界区周围的一个互斥锁就足够了。 -### "sysctl counters do not reflect the real state" +### "sysctl 计数器不反映真实状态" -Two variants. +两个变体。 -**Variant A**: the counter is a `size_t`, but the sysctl macro is `SYSCTL_ADD_U64`. On 32-bit architectures, the macro reads 8 bytes where the field is only 4 bytes wide; half the value is junk. +**变体 A**:计数器是 `size_t`,但 sysctl 宏是 `SYSCTL_ADD_U64`。在 32 位架构上,宏读取 8 字节而字段只有 4 字节宽;值的一半是垃圾。 -Fix: match the sysctl macro to the field type. `size_t` pairs with `SYSCTL_ADD_UINT` on 32-bit platforms and `SYSCTL_ADD_U64` on 64-bit platforms. To be portable, use `uint64_t` for counters and cast when updating. +修复:将 sysctl 宏与字段类型匹配。`size_t` 在 32 位平台上与 `SYSCTL_ADD_UINT` 配对,在 64 位平台上与 `SYSCTL_ADD_U64` 配对。为了可移植性,使用 `uint64_t` 作为计数器并在更新时转换。 -**Variant B**: the counter is never updated because the update is inside the `if (error == 0)` block and `uiomove` returned a non-zero error. That is actually correct behaviour: you should not count bytes you did not move. The symptom only looks like a bug if you are trying to use the counter to debug the error. +**变体 B**:计数器从未更新,因为更新在 `if (error == 0)` 块内,而 `uiomove` 返回了非零错误。这实际上是正确的行为:你不应该计算你没有移动的字节。症状只在你想用计数器调试错误时看起来像 bug。 -Fix: add an `error_count` counter that ticks on every non-zero return, independently of `bytes_read` and `bytes_written`. Useful for debugging. +修复:添加一个 `error_count` 计数器,在每次非零返回时递增,独立于 `bytes_read` 和 `bytes_written`。对调试有用。 -### "The first read after a fresh load returns zero bytes" +### "全新加载后的第一次读取返回零字节" -Usually intentional. In Stage 3, an empty buffer returns zero bytes. If you expected the static message from Stage 1, check that you are running the Stage 1 driver, not a later one. +通常是有意的。在阶段 3 中,空缓冲区返回零字节。如果你期望阶段 1 的静态消息,检查你运行的是阶段 1 驱动,而不是更高版本。 -If it is unintentional, double-check that `attach` is setting `sc->buf`, `sc->buflen`, and `sc->message_len` as expected. A common bug is copy-pasting the attach code from Stage 1 into Stage 2 and leaving the `sc->message = ...` assignment in place, which then takes precedence over the `malloc` line. +如果是无意的,仔细检查 `attach` 是否按预期设置了 `sc->buf`、`sc->buflen` 和 `sc->message_len`。一个常见的 bug 是从阶段 1 复制粘贴附加代码到阶段 2 并保留了 `sc->message = ...` 赋值,然后它优先于 `malloc` 行。 -### "The build fails with unknown reference to uiomove_frombuf" +### "构建失败,提示未知的 uiomove_frombuf 引用" -You forgot to include ``. Add it to the top of `myfirst.c`. +你忘记包含 ``。将它添加到 `myfirst.c` 的顶部。 -### "My handler is called twice for one read(2)" +### "我的处理程序对一次 read(2) 被调用了两次" -It almost certainly is not. What is more likely: your handler is being called once with `uio_iovcnt > 1` (a `readv(2)` call), and inside `uiomove` each iovec entry is being drained in turn. The internal loop in `uiomove` may make multiple `copyout` calls in what is a single invocation of your handler. +几乎肯定不是。更可能的是:你的处理程序被调用了一次,`uio_iovcnt > 1`(一个 `readv(2)` 调用),在 `uiomove` 内部每个 iovec 条目依次被排空。`uiomove` 中的内部循环可能在处理程序的单次调用中进行多次 `copyout` 调用。 -Verify by adding a `device_printf` at entry and exit of your `d_read`. You should see one entry and one exit per user-space `read(2)` call, regardless of iovec count. +通过在 `d_read` 的入口和出口添加 `device_printf` 来验证。你应该看到每次用户空间 `read(2)` 调用有一个入口和一个出口,不管 iovec 计数是多少。 ## 对比模式:正确与有问题的处理程序 -The troubleshooting guide above is reactive: it helps when something has already gone wrong. This section is the prescriptive companion. Each entry shows a plausible but wrong way to write part of a handler, pairs it with the correct rewrite, and explains the distinction. Studying the contrasts in advance is the fastest way to avoid the bugs in the first place. +上面的故障排除指南是被动的:它帮助处理已经出错的情况。本节是规范性的配套。每个条目展示编写处理程序某部分的一个看似合理但错误的方式,将其与正确的重写配对,并解释区别。提前学习对比是避免 bug 的最快方式。 -Read each pair carefully. The correct version is the pattern you should reach for; the buggy version is the shape your own hands may produce when you are moving fast. Recognising the mistake in the wild, months from now, is worth the five minutes it takes to internalise the difference today. +仔细阅读每对。正确的版本是你应该采用的模式;有 bug 的版本是你在快速移动时自己的手可能产生的形状。在几个月后从野外识别出错误,值得今天花五分钟来内化差异。 ### 对比 1:返回字节计数 -**Buggy:** +**有 bug 的:** ```c static int @@ -3222,7 +3222,7 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Correct:** +**正确的:** ```c static int @@ -3233,13 +3233,13 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Why it matters.** The handler's return value is an errno, not a count. The kernel computes the byte count from the change in `uio->uio_resid` and reports it to user space. A non-zero positive return is interpreted as an errno; if you returned `sc->message_len`, the caller would receive a very strange `errno` value. For example, returning `75` would manifest as `errno = 75`, which on FreeBSD happens to be `EPROGMISMATCH`. The bug is both wrong and deeply confusing to anybody looking at it from the user side. +**为什么重要。** 处理程序的返回值是 errno,不是计数。内核从 `uio->uio_resid` 的变化计算字节计数并报告给用户空间。非零正返回被解释为 errno;如果你返回 `sc->message_len`,调用者会收到一个非常奇怪的 `errno` 值。例如,返回 `75` 会表现为 `errno = 75`,在 FreeBSD 上恰好是 `EPROGMISMATCH`。这个 bug 既错误又对从用户侧查看它的任何人来说非常困惑。 -The rule is simple and absolute: handlers return errno values, never counts. If you want to know the byte count, compute it from the uio. +规则简单且绝对:处理程序返回 errno 值,永远不返回计数。如果你想知道字节计数,从 uio 计算。 ### 对比 2:处理零长度请求 -**Buggy:** +**有 bug 的:** ```c static int @@ -3251,7 +3251,7 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Correct:** +**正确的:** ```c static int @@ -3262,11 +3262,11 @@ myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -**Why it matters.** A `read(fd, buf, 0)` call is legal UNIX. A driver that rejects it with `EINVAL` breaks programs that use zero-byte reads to check descriptor state. `uiomove` returns zero immediately if the uio has nothing to move; your handler does not need to special-case it. Special-casing it wrong is worse than not special-casing it at all. +**为什么重要。** `read(fd, buf, 0)` 调用是合法的 UNIX 操作。用 `EINVAL` 拒绝它的驱动会破坏使用零字节读取检查描述符状态的程序。如果 uio 没有东西要移动,`uiomove` 立即返回零;你的处理程序不需要特殊情况处理它。错误地特殊情况处理它比完全不特殊情况处理更糟糕。 ### 对比 3:缓冲区容量计算 -**Buggy:** +**有 bug 的:** ```c mtx_lock(&sc->mtx); @@ -3279,7 +3279,7 @@ mtx_unlock(&sc->mtx); return (error); ``` -**Correct:** +**正确的:** ```c mtx_lock(&sc->mtx); @@ -3296,13 +3296,13 @@ mtx_unlock(&sc->mtx); return (error); ``` -**Why it matters.** The buggy version hands `uiomove` a length of `uio_resid`, which may exceed the buffer's remaining capacity. `uiomove` will not move more than `uio_resid` bytes, but the *destination* is `sc->buf + sc->bufused`, and the math does not know about `sc->buflen`. If the user writes 8 KiB into a 4 KiB buffer with `bufused = 0`, the handler will write 4 KiB past the end of `sc->buf`. That is a classic kernel heap overflow: the crash will not be immediate, will not implicate your driver, and may reveal itself as a panic inside a completely unrelated subsystem half a second later. +**为什么重要。** 有 bug 的版本传递给 `uiomove` 的长度是 `uio_resid`,可能超过缓冲区的剩余容量。`uiomove` 不会移动超过 `uio_resid` 字节,但*目标*是 `sc->buf + sc->bufused`,数学计算不知道 `sc->buflen`。如果用户向 `bufused = 0` 的 4 KiB 缓冲区写入 8 KiB,处理程序将在 `sc->buf` 末尾之后写入 4 KiB。这是一个经典的内核堆溢出:崩溃不会立即发生,不会牵连你的驱动,可能在半秒后作为完全不相关子系统内的崩溃显现。 -The correct version clamps the transfer to `avail`, guaranteeing that the pointer arithmetic stays inside the buffer. The clamp is one `MIN` call, and it is not optional. +正确的版本将传输限制到 `avail`,保证指针算术留在缓冲区内。限制是一个 `MIN` 调用,而且它不是可选的。 ### 对比 4:跨 uiomove 持有自旋锁 -**Buggy:** +**有 bug 的:** ```c mtx_lock_spin(&sc->spin); /* BAD: spin lock, not a regular mutex */ @@ -3311,7 +3311,7 @@ mtx_unlock_spin(&sc->spin); return (error); ``` -**Correct:** +**正确的:** ```c mtx_lock(&sc->mtx); /* MTX_DEF mutex */ @@ -3320,13 +3320,13 @@ mtx_unlock(&sc->mtx); return (error); ``` -**Why it matters.** `uiomove(9)` may sleep. When it calls `copyin` or `copyout`, the user page may be paged out, and the kernel may need to page it in from disk, which requires waiting on I/O. A sleep while holding a spin lock (`MTX_SPIN`) deadlocks the system. FreeBSD's `WITNESS` framework panics on this the first time it happens, if `WITNESS` is enabled. On a non-`WITNESS` kernel the result is silent livelock. +**为什么重要。** `uiomove(9)` 可能睡眠。当它调用 `copyin` 或 `copyout` 时,用户页面可能被换出,内核可能需要从磁盘换入,这需要等待 I/O。持有自旋锁(`MTX_SPIN`)时睡眠会死锁系统。如果启用了 `WITNESS`,FreeBSD 的 `WITNESS` 框架在第一次发生时会崩溃。在非 `WITNESS` 内核上,结果是静默的活锁。 -The rule is straightforward: spin locks cannot be held across functions that may sleep, and `uiomove` may sleep. Use an `MTX_DEF` mutex (the default, and the one `myfirst` uses) for softc state that is touched by I/O handlers. +规则很简单:自旋锁不能跨可能睡眠的函数持有,而 `uiomove` 可能睡眠。对 I/O 处理程序触及的 softc 状态使用 `MTX_DEF` 互斥锁(默认的,也是 `myfirst` 使用的)。 ### 对比 5:在 d_open 中重置共享状态 -**Buggy:** +**有 bug 的:** ```c static int @@ -3342,7 +3342,7 @@ myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -**Correct:** +**正确的:** ```c static int @@ -3357,13 +3357,13 @@ myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -**Why it matters.** `d_open` runs once per descriptor. If two readers open the device, the second open will wipe whatever the first open left behind. Driver-wide state (`sc->bufused`, `sc->buf`, counters) belongs to the whole driver, and is reset only at `attach` and `detach`. Per-descriptor state belongs in `fh`, which `malloc(M_ZERO)` initialises to zeros automatically. +**为什么重要。** `d_open` 每个描述符运行一次。如果两个读取者打开设备,第二次打开将擦除第一次打开留下的所有内容。驱动范围的状态(`sc->bufused`、`sc->buf`、计数器)属于整个驱动,仅在 `attach` 和 `detach` 时重置。每次描述符的状态属于 `fh`,`malloc(M_ZERO)` 自动将其初始化为零。 -A driver that resets shared state in `d_open` looks like it works under a single opener and silently corrupts state when two openers appear. The bug is invisible until the day two users read the device at once. +在 `d_open` 中重置共享状态的驱动在单一打开者下看起来正常工作,当两个打开者出现时静默地损坏状态。这个 bug 在两个用户同时读取设备的那一天之前是不可见的。 ### 对比 6:在知道结果之前记账 -**Buggy:** +**有 bug 的:** ```c sc->bytes_written += towrite; /* BAD: count before success */ @@ -3372,7 +3372,7 @@ if (error == 0) sc->bufused += towrite; ``` -**Correct:** +**正确的:** ```c error = uiomove(sc->buf + tail, towrite, uio); @@ -3382,13 +3382,13 @@ if (error == 0) { } ``` -**Why it matters.** If `uiomove` fails part-way through, some bytes may have moved and some may not. The `sc->bytes_written` counter should reflect what actually reached the buffer, not what the driver attempted. Updating counters before the outcome is known makes the counters lie. If a user reads the sysctl to diagnose a problem, they see numbers that do not correspond to reality. +**为什么重要。** 如果 `uiomove` 中途失败,一些字节可能已移动而另一些没有。`sc->bytes_written` 计数器应该反映实际到达缓冲区的内容,而不是驱动尝试的内容。在知道结果之前更新计数器使计数器说谎。如果用户读取 sysctl 来诊断问题,他们看到的数字与现实不符。 -The rule: update counters inside the `if (error == 0)` branch, so success is the only path that increments them. This is a small cost for a large correctness benefit. +规则:在 `if (error == 0)` 分支内更新计数器,这样成功是递增它们的唯一路径。这是小的代价换来大的正确性收益。 ### 对比 7:直接解引用用户指针 -**Buggy:** +**有 bug 的:** ```c /* Imagine the driver somehow gets a user pointer, maybe through ioctl. */ @@ -3401,7 +3401,7 @@ handle_user_string(void *user_ptr) } ``` -**Correct:** +**正确的:** ```c static int @@ -3417,13 +3417,13 @@ handle_user_string(void *user_ptr) } ``` -**Why it matters.** `memcpy` assumes both pointers refer to memory accessible in the current address space. A user pointer does not. Depending on the platform, the result of passing a user pointer to `memcpy` in kernel context ranges from an `EFAULT`-equivalent fault (on amd64 with SMAP enabled) to silent data corruption (on platforms without user/kernel separation) to an outright kernel panic. +**为什么重要。** `memcpy` 假设两个指针都引用当前地址空间中可访问的内存。用户指针不是。取决于平台,在内核上下文中将用户指针传递给 `memcpy` 的结果从 `EFAULT` 等效故障(在启用了 SMAP 的 amd64 上)到静默数据损坏(在没有用户/内核分离的平台上)到彻底的内核崩溃。 -`copyin` and `copyout` are the one-and-only correct way to access user memory from kernel context. They install a fault handler, validate the address, walk page tables safely, and return `EFAULT` on any failure. The performance cost is a few extra instructions; the correctness benefit is "the kernel does not panic when a buggy user program is running". +`copyin` 和 `copyout` 是从内核上下文访问用户内存的唯一正确方式。它们安装故障处理程序、验证地址、安全地遍历页表,并在任何失败时返回 `EFAULT`。性能成本是几条额外的指令;正确性收益是"当有 bug 的用户程序运行时内核不会崩溃"。 ### 对比 8:在 d_open 失败时泄漏每次打开的结构 -**Buggy:** +**有 bug 的:** ```c static int @@ -3441,7 +3441,7 @@ myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -**Correct:** +**正确的:** ```c static int @@ -3461,53 +3461,53 @@ myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -**Why it matters.** When `devfs_set_cdevpriv` fails, the kernel does not register the destructor, so the destructor will never run on this `fh`. If the handler returns without freeing `fh`, the memory is leaked. Under steady load, repeated `d_open` failures can leak enough memory to destabilise the kernel. +**为什么重要。** 当 `devfs_set_cdevpriv` 失败时,内核不会注册析构函数,所以析构函数永远不会在这个 `fh` 上运行。如果处理程序返回而不释放 `fh`,内存就泄漏了。在持续负载下,重复的 `d_open` 失败可以泄漏足够的内存使内核不稳定。 -The rule: in error-unwind paths, every allocation made so far must be freed. The Chapter 8 reader has seen this pattern for attach; it applies equally to `d_open`. +规则:在错误展开路径中,到目前为止所做的每个分配都必须被释放。第八章的读者已经在 attach 中见过这个模式;它同样适用于 `d_open`。 ### 如何使用这个对比表 -These eight pairs are not an exhaustive list. They are the bugs we have seen most often in early student drivers, and the bugs the chapter's text has been trying to help you avoid. Read through them once now. Before you write your first real driver outside this book, read them again. +这八对不是详尽的列表。它们是我们早期学生驱动中最常见到的 bug,也是本章文本一直在试图帮你避免的 bug。现在通读它们一次。在你写本书之外的第一个真正驱动之前,再读一遍。 -A useful habit while developing: whenever you finish a handler, walk it against the contrast table mentally. Does the handler return a count? Does it special-case zero-resid? Does it have a capacity clamp? Is the mutex type right? Does it reset shared state in `d_open`? Does it account for bytes on failure? Does it dereference any user pointer directly? Does it leak on `d_open` failure? Eight questions, five minutes. The price of the check is small; the cost of shipping one of these bugs into production is large. +开发过程中的一个有用习惯:每当你完成一个处理程序,在脑海中对照对比表走一遍。处理程序返回计数了吗?它特殊情况处理零 resid 了吗?它有容量限制吗?互斥锁类型正确吗?它在 `d_open` 中重置共享状态了吗?它在失败时计入字节了吗?它直接解引用任何用户指针了吗?它在 `d_open` 失败时泄漏了吗?八个问题,五分钟。检查的代价很小;将这些 bug 中的一个发布到生产的成本很大。 ## 第十章前的自我评估 -Chapter 9 has covered a lot of ground. Before you put it down, run through the following checklist. If any item makes you hesitate, the relevant section is worth re-reading before moving on. This is not a test; it is a quick way to identify the spots where your mental model may still be thin. +第九章涵盖了很多内容。在你放下它之前,过一遍以下检查清单。如果任何项目让你犹豫,相关章节值得在继续之前重读。这不是测试;这是识别你的心理模型可能仍然薄弱的地方的快速方式。 -**Concepts:** +**概念:** -- [ ] I can explain in one sentence what `struct uio` is for. -- [ ] I can name the three fields of `struct uio` my driver reads most often. -- [ ] I can explain why `uiomove(9)` is preferred over `copyin` / `copyout` inside `d_read` and `d_write`. -- [ ] I can explain why `memcpy` across the user / kernel boundary is unsafe. -- [ ] I can explain the difference between `ENXIO`, `EAGAIN`, `ENOSPC`, and `EFAULT` in driver terms. +- [ ] 我可以用一句话解释 `struct uio` 是用来做什么的。 +- [ ] 我能说出 `struct uio` 中我的驱动最常读取的三个字段。 +- [ ] 我可以解释为什么在 `d_read` 和 `d_write` 内部 `uiomove(9)` 优于 `copyin` / `copyout`。 +- [ ] 我可以解释为什么跨用户/内核边界使用 `memcpy` 是不安全的。 +- [ ] 我可以解释在驱动语境下 `ENXIO`、`EAGAIN`、`ENOSPC` 和 `EFAULT` 之间的区别。 -**Mechanics:** +**机制:** -- [ ] I can write a minimal `d_read` handler that serves a fixed buffer using `uiomove_frombuf(9)`. -- [ ] I can write a minimal `d_write` handler that appends to a kernel buffer with a correct capacity clamp. -- [ ] I know where to put the mutex acquire and release around the transfer. -- [ ] I know how to propagate an errno from `uiomove` back to user space. -- [ ] I know how to mark a write as fully consumed with `uio_resid = 0`. +- [ ] 我可以编写一个使用 `uiomove_frombuf(9)` 提供固定缓冲区的最小 `d_read` 处理程序。 +- [ ] 我可以编写一个以正确的容量限制向内核缓冲区追加的最小 `d_write` 处理程序。 +- [ ] 我知道在传输周围放置互斥锁获取和释放的位置。 +- [ ] 我知道如何将 errno 从 `uiomove` 传播回用户空间。 +- [ ] 我知道如何用 `uio_resid = 0` 标记写入为完全消耗。 -**Observability:** +**可观测性:** -- [ ] I can read `sysctl dev.myfirst.0.stats` and interpret each counter. -- [ ] I can spot a memory leak with `vmstat -m | grep devbuf`. -- [ ] I can use `truss(1)` to see what syscalls my test program makes. -- [ ] I can use `fstat(1)` or `fuser(8)` to find who is holding a descriptor. +- [ ] 我可以读取 `sysctl dev.myfirst.0.stats` 并解释每个计数器。 +- [ ] 我可以用 `vmstat -m | grep devbuf` 发现内存泄漏。 +- [ ] 我可以用 `truss(1)` 查看我的测试程序发出了什么系统调用。 +- [ ] 我可以用 `fstat(1)` 或 `fuser(8)` 找到谁持有描述符。 -**Traps:** +**陷阱:** -- [ ] I would not return a byte count from `d_read` / `d_write`. -- [ ] I would not reject a zero-length request with `EINVAL`. -- [ ] I would not reset `sc->bufused` inside `d_open`. -- [ ] I would not hold a spin lock across a `uiomove` call. +- [ ] 我不会从 `d_read` / `d_write` 返回字节计数。 +- [ ] 我不会用 `EINVAL` 拒绝零长度请求。 +- [ ] 我不会在 `d_open` 内重置 `sc->bufused`。 +- [ ] 我不会在 `uiomove` 调用期间持有自旋锁。 -Any "no" here is a signal, not a verdict. Re-read the relevant section; run a small experiment in your lab; come back to the checklist. By the time every box is ticked, you are solidly ready for Chapter 10. +任何"否"都是一个信号,而不是判决。重读相关章节;在你的实验室运行一个小实验;回到检查清单。当每个复选框都打勾时,你就稳稳地为第十章做好了准备。 @@ -3515,71 +3515,71 @@ Any "no" here is a signal, not a verdict. Re-read the relevant section; run a sm 你刚刚实现了使驱动活跃的入口点。 在第七章结束时你的驱动有了一个骨架。 在第八章结束时它有了一个形状良好的门。 现在,在第九章结束时,数据双向流过这扇门。 -本章的核心教训比看起来更短。 你将编写的每个 `d_read` 都有相同的三行骨架:获取每次打开的状态、验证活跃性、调用 `uiomove`。 你将编写的每个 `d_write` 都有类似的骨架,加上一个额外的决定(我有多少空间?)和一个防止缓冲区溢出的钳制(`MIN(uio_resid, avail)`)。 Everything else in the chapter is context: why `struct uio` looks the way it does, why `uiomove` is the only safe mover, why errno values matter, why counters matter, why the buffer has to be freed on every error path. +本章的核心教训比看起来更短。 你将编写的每个 `d_read` 都有相同的三行骨架:获取每次打开的状态、验证活跃性、调用 `uiomove`。 你将编写的每个 `d_write` 都有类似的骨架,加上一个额外的决定(我有多少空间?)和一个防止缓冲区溢出的钳制(`MIN(uio_resid, avail)`)。本章的其他一切都是上下文:为什么 `struct uio` 看起来是这个样子,为什么 `uiomove` 是唯一安全的移动器,为什么 errno 值重要,为什么计数器重要,为什么缓冲区必须在每个错误路径上被释放。 ### 最重要的三个想法 -**First, `struct uio` is the contract between your driver and the kernel's I/O machinery.** It carries everything your handler needs to know about a call: what the user asked for, where the user's memory is, what direction the transfer should move, and how much progress has been made. You do not need to memorise all seven fields. You need to recognise `uio_resid` (the remaining work), `uio_offset` (the position, if you care), and `uio_rw` (the direction), and you need to trust `uiomove(9)` with the rest. +**首先,`struct uio` 是你的驱动和内核 I/O 机制之间的契约。** 它携带你的处理程序需要知道的关于调用的所有信息:用户请求了什么、用户的内存在哪里、传输应该向哪个方向移动、已经取得了多少进展。你不需要记住所有七个字段。你需要识别 `uio_resid`(剩余工作)、`uio_offset`(位置,如果你关心的话)和 `uio_rw`(方向),你需要信任 `uiomove(9)` 处理其余的。 -**Second, `uiomove(9)` is the boundary between user memory and kernel memory.** Everything your driver ever moves between the two passes through it (or through one of its close relatives: `uiomove_frombuf`, `copyin`, `copyout`). This is not a suggestion. Direct pointer access across the trust boundary either corrupts memory or leaks information, and the kernel has no cheap way to catch the mistake before it becomes a CVE. If a pointer came from user space, route it through the kernel's trust-boundary functions. Always. +**其次,`uiomove(9)` 是用户内存和内核内存之间的边界。** 你的驱动在两者之间移动的所有东西都通过它(或通过其近亲:`uiomove_frombuf`、`copyin`、`copyout`)。这不是建议。跨信任边界的直接指针访问要么损坏内存要么泄露信息,内核没有廉价的方法在错误变成 CVE 之前捕获它。如果指针来自用户空间,通过内核的信任边界函数路由它。永远如此。 -**Third, a correct handler is usually a short one.** If your `d_read` or `d_write` is longer than fifteen lines, something is probably wrong. Longer handlers either duplicate logic that belongs elsewhere (in the buffer management, in the per-open state setup, in the sysctls), or they are trying to do something the driver should not be doing in a data-path handler (typically, something that belongs in `d_ioctl`). Keep the handlers short. Put the machinery they call into well-named helper functions. Your future self will thank you. +**第三,正确的处理程序通常是短的处理程序。** 如果你的 `d_read` 或 `d_write` 超过十五行,可能有问题。更长的处理程序要么复制了属于其他地方的逻辑(在缓冲区管理中、在每次打开状态设置中、在 sysctl 中),要么它们试图做一些驱动不应该在数据路径处理程序中做的事情(通常是属于 `d_ioctl` 的事情)。保持处理程序短。将它们调用的机制放入命名良好的辅助函数。你未来的自己会感谢你。 ### 你结束本章时的驱动形状 -Your Stage 3 `myfirst` is a small, honest, in-memory FIFO. The salient features: +你的阶段 3 `myfirst` 是一个小型、诚实、内存中的 FIFO。显著特征: -- A 4 KiB kernel buffer, allocated in `attach` and freed in `detach`. -- A per-instance mutex guarding `bufhead`, `bufused`, and the associated counters. -- A `d_read` that drains the buffer and advances `bufhead`, collapsing to zero when the buffer empties. -- A `d_write` that appends to the buffer and returns `ENOSPC` when it fills. -- Per-descriptor counters stored in `struct myfirst_fh`, allocated in `d_open`, freed in the destructor. -- A sysctl tree exposing the live driver state. -- Clean `attach` error unwind and clean `detach` ordering. +- 一个 4 KiB 内核缓冲区,在 `attach` 中分配,在 `detach` 中释放。 +- 一个保护 `bufhead`、`bufused` 和相关计数器的每次实例互斥锁。 +- 一个排空缓冲区并推进 `bufhead` 的 `d_read`,在缓冲区为空时折叠到零。 +- 一个追加到缓冲区并在填满时返回 `ENOSPC` 的 `d_write`。 +- 存储在 `struct myfirst_fh` 中的每次描述符计数器,在 `d_open` 中分配,在析构函数中释放。 +- 暴露实时驱动状态的 sysctl 树。 +- 干净的 `attach` 错误展开和干净的 `detach` 排序。 -That shape will come back, recognisable, in half the drivers you will read in Part 4 and Part 6. It is a general pattern, not a one-off demo. +这个形状会在你在第四部分和第六部分读到的一半驱动中回来,是可识别的。它是一个通用模式,不是一次性的演示。 ### 开始第十章前你应该练习什么 -Five exercises, in rough order of increasing challenge: +五个练习,大致按难度递增排列: -1. Rebuild all three stages from scratch, without looking at the companion tree. Compare your result to the tree afterward; the differences are what you have left to internalise. -2. Introduce an intentional bug in Stage 3: forget to reset `bufhead` when `bufused` reaches zero. Observe what happens on the second big write. Explain the symptom in terms of the code. -3. Add a sysctl that exposes `sc->buflen`. Make it read-only. Then convert it into a tunable that can be set at load time via `kenv` or `loader.conf` and picked up in `attach`. (Chapter 10 revisits tunables formally; this is a preview.) -4. Write a shell script that writes random data of a known length to `/dev/myfirst/0` and then reads it back through `sha256`. Compare the hashes. Do the hashes match even when the write size exceeds the buffer? (They should not; think about why.) -5. Find a driver under `/usr/src/sys/dev` that implements both `d_read` and `d_write`. Read its handlers. Map them against the patterns in this chapter. Good candidates: `/usr/src/sys/dev/null/null.c` (you already know it), `/usr/src/sys/dev/random/randomdev.c`, `/usr/src/sys/dev/speaker/spkr.c`. +1. 从头开始重建所有三个阶段,不看伴随树。之后将你的结果与树比较;差异是你还需要内化的内容。 +2. 在阶段 3 中引入一个故意 bug:当 `bufused` 达到零时忘记重置 `bufhead`。观察第二次大写入时发生什么。用代码的术语解释症状。 +3. 添加一个暴露 `sc->buflen` 的 sysctl。使其只读。然后将其转换为可在加载时通过 `kenv` 或 `loader.conf` 设置并在 `attach` 中获取的可调参数。(第十章正式回顾可调参数;这是一个预览。) +4. 编写一个 shell 脚本,将已知长度的随机数据写入 `/dev/myfirst/0`,然后通过 `sha256` 读回。比较哈希值。当写入大小超过缓冲区时哈希值是否匹配?(不应该匹配;想想为什么。) +5. 在 `/usr/src/sys/dev` 下找一个同时实现 `d_read` 和 `d_write` 的驱动。阅读其处理程序。将它们映射到本章的模式。好的候选:`/usr/src/sys/dev/null/null.c`(你已经知道它)、`/usr/src/sys/dev/random/randomdev.c`、`/usr/src/sys/dev/speaker/spkr.c`。 ### 展望第十章 -Chapter 10 takes the Stage 3 driver and makes it scale. Four new capabilities show up: +第十章采用阶段 3 驱动并使其扩展。四个新能力出现: -- **A circular buffer** replaces the linear buffer. Writes and reads can both happen continuously without the explicit collapse that Stage 3 uses. -- **Blocking reads** arrive. A reader that calls `read(2)` on an empty buffer can sleep until data is available, rather than returning zero bytes immediately. The kernel's `msleep(9)` is the primitive; the `d_purge` handler is the teardown safety net. -- **Non-blocking I/O** becomes a first-class feature. `O_NONBLOCK` users get `EAGAIN` where a blocking caller would sleep. -- **`poll(2)` and `kqueue(9)` integration**. A user program can wait for the device to become readable or writable without actively attempting the operation. This is the standard way to integrate a device into an event loop. +- **环形缓冲区**取代线性缓冲区。写入和读取都可以持续发生,而不需要阶段 3 使用的显式折叠。 +- **阻塞读取**到来。在空缓冲区上调用 `read(2)` 的读取者可以睡眠直到数据可用,而不是立即返回零字节。内核的 `msleep(9)` 是原语;`d_purge` 处理程序是拆卸安全网。 +- **非阻塞 I/O**成为一等特性。`O_NONBLOCK` 用户在阻塞调用者会睡眠的地方得到 `EAGAIN`。 +- **`poll(2)` 和 `kqueue(9)` 集成**。用户程序可以等待设备变得可读或可写,而不需要主动尝试操作。这是将设备集成到事件循环中的标准方式。 -All four of these build on the same `d_read` / `d_write` shapes you just implemented. You will extend the handlers rather than rewriting them, and the per-descriptor state you have in place will carry the necessary bookkeeping. The chapter before that (this one) is the one where the I/O path itself is correct. Chapter 10 is where the I/O path becomes efficient. +所有这四个都建立在你刚刚实现的相同 `d_read` / `d_write` 形状之上。你将扩展处理程序而不是重写它们,你已经就位的每次描述符状态将承载必要的簿记。前面的那一章(这一章)是 I/O 路径本身正确的章节。第十章是 I/O 路径变得高效的章节。 -Before you close the file, a last reassurance. The material in this chapter is not as difficult as it may feel on a first read. The pattern is small. The ideas are real, but they are finite, and you have just exercised every one of them against working code. When you read a real driver's `d_read` or `d_write` in the tree, you will now recognise what the function is doing and why. You are not a beginner at this any more. You are an apprentice with a real tool in your hands. +在关闭文件之前,最后一个安慰。本章的材料并不像第一次阅读时感觉的那么难。模式很小。想法是真实的,但它们是有限的,你刚刚针对工作代码练习了每一个。当你在源码树中阅读真正驱动的 `d_read` 或 `d_write` 时,你现在将能识别函数在做什么以及为什么。你不再是这个的初学者了。你是一个手握真正工具的学徒。 ## 参考:本章使用的签名和辅助函数 -A consolidated reference for the declarations, helpers, and constants the chapter leans on. Keep this page bookmarked while you write drivers; most beginner questions are a lookup in one of these tables. +本章依赖的声明、辅助函数和常量的综合参考。在编写驱动时将此页面加入书签;大多数初学者问题都可以在这些表格之一中找到答案。 -### `d_read` and `d_write` Signatures +### `d_read` 和 `d_write` 签名 -From `/usr/src/sys/sys/conf.h`: +来自 `/usr/src/sys/sys/conf.h`: ```c typedef int d_read_t(struct cdev *dev, struct uio *uio, int ioflag); typedef int d_write_t(struct cdev *dev, struct uio *uio, int ioflag); ``` -The return value is zero on success, a positive errno on failure. The byte count is computed from the change in `uio->uio_resid` and reported to user space as the return value of `read(2)` / `write(2)`. +返回值成功时为零,失败时为正 errno。字节计数从 `uio->uio_resid` 的变化计算,并作为 `read(2)` / `write(2)` 的返回值报告给用户空间。 -### The Canonical `struct uio` +### 规范的 `struct uio` 来自 `/usr/src/sys/sys/uio.h`: @@ -3595,16 +3595,16 @@ struct uio { }; ``` -### The `uio_seg` and `uio_rw` Enumerations +### `uio_seg` 和 `uio_rw` 枚举 -From `/usr/src/sys/sys/_uio.h`: +来自 `/usr/src/sys/sys/_uio.h`: ```c enum uio_rw { UIO_READ, UIO_WRITE }; enum uio_seg { UIO_USERSPACE, UIO_SYSSPACE, UIO_NOCOPY }; ``` -### `uiomove` Family +### `uiomove` 系列 来自 `/usr/src/sys/sys/uio.h`: @@ -3617,7 +3617,7 @@ int uiomove_nofault(void *cp, int n, struct uio *uio); int uiomove_object(struct vm_object *obj, off_t obj_size, struct uio *uio); ``` -In beginner driver code, only `uiomove` and `uiomove_frombuf` are common. The others support specific kernel subsystems (physical-page I/O, page-fault-free copies, VM-backed objects) and are out of scope for this chapter. +在初学者驱动代码中,只有 `uiomove` 和 `uiomove_frombuf` 是常见的。其他的支持特定的内核子系统(物理页 I/O、无页故障复制、VM 支持的对象),超出了本章的范围。 ### `copyin` and `copyout` @@ -3633,32 +3633,32 @@ int copyinstr(const void * __restrict udaddr, size_t * __restrict lencopied); ``` -Use these in control paths (`d_ioctl`) where a user pointer arrives outside the uio abstraction. Inside `d_read` and `d_write`, prefer `uiomove`. +在控制路径(`d_ioctl`)中使用这些函数,当用户指针在 uio 抽象之外到达时。在 `d_read` 和 `d_write` 内部,优先使用 `uiomove`。 -### `ioflag` Bits That Matter for Character Devices +### 字符设备重要的 `ioflag` 位 -From `/usr/src/sys/sys/vnode.h`: +来自 `/usr/src/sys/sys/vnode.h`: ```c #define IO_NDELAY 0x0004 /* FNDELAY flag set in file table */ ``` -Set when the descriptor is in non-blocking mode. Your `d_read` or `d_write` can use this to decide whether to block (missing flag) or return `EAGAIN` (flag set). Most of the other `IO_*` flags are filesystem-level and irrelevant to character devices. +当描述符处于非阻塞模式时设置。你的 `d_read` 或 `d_write` 可以使用它来决定是阻塞(缺少标志)还是返回 `EAGAIN`(设置了标志)。大多数其他 `IO_*` 标志是文件系统级别的,与字符设备无关。 -### Memory Allocation +### 内存分配 -From `/usr/src/sys/sys/malloc.h`: +来自 `/usr/src/sys/sys/malloc.h`: ```c void *malloc(size_t size, struct malloc_type *type, int flags); void free(void *addr, struct malloc_type *type); ``` -Common flags: `M_WAITOK`, `M_NOWAIT`, `M_ZERO`. Common types for drivers: `M_DEVBUF` (generic) or a driver-specific type declared via `MALLOC_DECLARE` / `MALLOC_DEFINE`. +常见标志:`M_WAITOK`、`M_NOWAIT`、`M_ZERO`。驱动的常见类型:`M_DEVBUF`(通用)或通过 `MALLOC_DECLARE` / `MALLOC_DEFINE` 声明的驱动特定类型。 -### Per-Open State (Chapter 8 carryover, used here) +### 每次打开状态(第八章延续,在此使用) -From `/usr/src/sys/sys/conf.h`: +来自 `/usr/src/sys/sys/conf.h`: ```c int devfs_set_cdevpriv(void *priv, d_priv_dtor_t *dtr); @@ -3666,9 +3666,9 @@ int devfs_get_cdevpriv(void **datap); void devfs_clear_cdevpriv(void); ``` -The pattern is: allocate in `d_open`, register with `devfs_set_cdevpriv`, retrieve in every later handler with `devfs_get_cdevpriv`, clean up in the destructor that `devfs_set_cdevpriv` registered. +模式是:在 `d_open` 中分配,用 `devfs_set_cdevpriv` 注册,在每个后续处理程序中用 `devfs_get_cdevpriv` 检索,在 `devfs_set_cdevpriv` 注册的析构函数中清理。 -### Errno Values Used in This Chapter +### 本章使用的 Errno 值 | Errno | Meaning in a driver context | |---------------|------------------------------------------------------------| @@ -3682,7 +3682,7 @@ The pattern is: allocate in `d_open`, register with `devfs_set_cdevpriv`, retrie | `EACCES` | Permission denied at `open(2)`. | | `EPIPE` | Broken pipe. Not used by `myfirst`. | -### Helpful `device_printf(9)` Patterns +### 有用的 `device_printf(9)` 模式 ```c device_printf(sc->dev, "open via %s fh=%p\n", devtoname(sc->cdev), fh); @@ -3692,9 +3692,9 @@ device_printf(sc->dev, "read delivered %zd bytes\n", (ssize_t)(before - uio->uio_offset)); ``` -These are written for readability. A line in `dmesg` you have to decode is a line that probably will not be read when it matters. +这些是为可读性编写的。`dmesg` 中你需要解码的行可能是在重要时刻不会被阅读的行。 -### The Three Stages at a Glance +### 三个阶段一览 | Stage | `d_read` | `d_write` | |-------|------------------------------------------------------|------------------------------------| @@ -3702,11 +3702,11 @@ These are written for readability. A line in `dmesg` you have to decode is a lin | 2 | Serve buffer up to `bufused` | Append to buffer, `ENOSPC` if full | | 3 | Drain buffer from `bufhead`, reset on empty | Append at `bufhead + bufused`, `ENOSPC` if full | -Stage 3 is the foundation Chapter 10 builds on. +阶段 3 是第十章构建的基础。 -### Consolidated File List for the Chapter +### 本章的综合文件列表 -Companion files under `examples/part-02/ch09-reading-and-writing/`: +伴随文件位于 `examples/part-02/ch09-reading-and-writing/`: - `stage1-static-message/`: Stage 1 driver source and Makefile. - `stage2-readwrite/`: Stage 2 driver source and Makefile. @@ -3715,26 +3715,26 @@ Companion files under `examples/part-02/ch09-reading-and-writing/`: - `userland/stress_rw.c`: multi-process stress test for Lab 9.3 and beyond. - `README.md`: a short map of the companion tree. -Each stage is independent; you can build, load, and exercise any of them without building the others. The Makefiles are identical except for the driver name (always `myfirst`) and optional tuning flags. +每个阶段都是独立的;你可以构建、加载和练习它们中的任何一个而不需要构建其他的。Makefile 除了驱动名称(始终为 `myfirst`)和可选的调优标志外完全相同。 ## 附录 A:深入查看 uiomove 的内部循环 -For readers who want to see exactly what `uiomove(9)` does, this appendix walks through the core loop of `uiomove_faultflag` as it appears in `/usr/src/sys/kern/subr_uio.c`. You do not need to read this to write a driver. It is here because one reading of the loop will clarify every later question you have about uio semantics. +对于想确切了解 `uiomove(9)` 做什么的读者,本附录演练 `uiomove_faultflag` 核心循环在 `/usr/src/sys/kern/subr_uio.c` 中的样子。你不需要阅读这个来编写驱动。它在这里是因为一次循环阅读将澄清你后续关于 uio 语义的每个问题。 -### The Setup +### 设置 -At entry, the function has: +在入口处,函数有: - A kernel pointer `cp` provided by the caller (your driver). - An integer `n` provided by the caller (the max bytes to move). - The uio provided by the kernel dispatch. - A boolean `nofault` indicating whether page faults during the copy should be handled or fatal. -It sanity-checks a few invariants: the direction is `UIO_READ` or `UIO_WRITE`, the owning thread is the current thread when the segment is user-space, and `uio_resid` is non-negative. Any violation is a `KASSERT` and will panic a kernel with `INVARIANTS` enabled. +它对几个不变量进行健全性检查:方向是 `UIO_READ` 或 `UIO_WRITE`,当段是用户空间时拥有线程是当前线程,`uio_resid` 是非负的。任何违反都是一个 `KASSERT`,会使启用了 `INVARIANTS` 的内核崩溃。 -### The Main Loop +### 主循环 ```c while (n > 0 && uio->uio_resid) { @@ -3784,57 +3784,57 @@ while (n > 0 && uio->uio_resid) { } ``` -Each iteration does one unit of work: copy up to `cnt` bytes (where `cnt` is `MIN(iov->iov_len, n)`) between the current iovec entry and the kernel buffer. The direction is chosen by the two nested `switch` statements. After a successful copy, all the accounting fields advance in lockstep: the iovec entry shrinks by `cnt`, the uio's resid shrinks by `cnt`, the uio's offset grows by `cnt`, the kernel pointer `cp` advances by `cnt`, and the caller's `n` shrinks by `cnt`. +每次迭代做一个工作单元:在当前 iovec 条目和内核缓冲区之间复制最多 `cnt` 字节(其中 `cnt` 是 `MIN(iov->iov_len, n)`)。方向由两个嵌套的 `switch` 语句选择。成功复制后,所有记账字段同步推进:iovec 条目缩小 `cnt`,uio 的 resid 缩小 `cnt`,uio 的偏移增长 `cnt`,内核指针 `cp` 推进 `cnt`,调用者的 `n` 缩小 `cnt`。 -When an iovec entry is fully drained (`cnt == 0` at loop entry), the function advances to the next entry. When the caller's `n` reaches zero or the uio's resid reaches zero, the loop terminates. +当 iovec 条目完全排空时(循环入口处 `cnt == 0`),函数推进到下一个条目。当调用者的 `n` 达到零或 uio 的 resid 达到零时,循环终止。 -If `copyin` or `copyout` returns non-zero, the function jumps to `out` without updating the fields for that iteration, so the partial-copy accounting is consistent: whatever bytes did copy are reflected in `uio_resid`, whatever did not copy is still pending. +如果 `copyin` 或 `copyout` 返回非零,函数跳到 `out` 而不更新该迭代的字段,所以部分复制的记账是一致的:已复制的任何字节反映在 `uio_resid` 中,未复制的仍然待处理。 -### What You Should Take Away +### 你应该带走什么 -Three invariants fall out of the loop that matter for your driver code. +循环中产生三个对你的驱动代码重要的不变量。 -- **Your call to `uiomove(cp, n, uio)` moves at most `MIN(n, uio->uio_resid)` bytes.** There is no way to ask for more than the uio has room for; the function caps at whichever side is smaller. -- **On a partial transfer, the state is consistent.** `uio_resid` reflects exactly the bytes that did not move. You can make another call and it will pick up correctly. -- **The fault handling is inside the loop, not around it.** A fault during a `copyin` / `copyout` returns `EFAULT` for the remainder; the fields are still consistent. +- **你对 `uiomove(cp, n, uio)` 的调用最多移动 `MIN(n, uio->uio_resid)` 字节。** 没有办法请求超过 uio 有空间的内容;函数以较小的一方为上限。 +- **在部分传输时,状态是一致的。** `uio_resid` 精确反映未移动的字节。你可以再进行一次调用,它会正确地继续。 +- **故障处理在循环内部,而不是周围。** `copyin` / `copyout` 期间的故障为剩余部分返回 `EFAULT`;字段仍然一致。 -These three facts are why the three-line spine we keep returning to (`uiomove`, check error, update state) is sufficient. The kernel is doing the complicated work inside the loop; your driver just has to cooperate. +这三个事实就是为什么我们一直回到的三行骨架(`uiomove`、检查错误、更新状态)是足够的。内核在循环内部做复杂的工作;你的驱动只需配合。 ## 附录 B:为什么允许 read(fd, buf, 0) -A short note on a question that comes up frequently: why does UNIX allow a `read(fd, buf, 0)` or `write(fd, buf, 0)` call at all? +一个关于频繁出现的问题的简短说明:为什么 UNIX 允许 `read(fd, buf, 0)` 或 `write(fd, buf, 0)` 调用? -There are two answers, and both are worth knowing. +有两个答案,两个都值得了解。 -**The practical answer**: zero-length I/O is a free test. A user program that wants to check whether a descriptor is in a reasonable state can call `read(fd, NULL, 0)` without committing to a real transfer. If the descriptor is broken, the call returns an error. If it is fine, the call returns zero and costs almost nothing. +**实际答案**:零长度 I/O 是免费测试。想检查描述符是否处于合理状态的用户程序可以调用 `read(fd, NULL, 0)` 而不提交真正的传输。如果描述符坏了,调用返回错误。如果没问题,调用返回零,几乎不花费任何代价。 -**The semantic answer**: the UNIX I/O interface uses byte counts consistently, and special-casing zero is more work than allowing it. A call with `count == 0` is a well-defined no-op: the kernel has to do nothing, and can return zero immediately. The alternative, returning `EINVAL` for zero-count calls, would force every user program that computed a count dynamically to guard against the case. That is the kind of change that breaks decades of code for no benefit. +**语义答案**:UNIX I/O 接口一致地使用字节计数,特殊处理零比允许它更费事。`count == 0` 的调用是定义良好的无操作:内核不需要做任何事,可以立即返回零。替代方案——对零计数调用返回 `EINVAL`——将迫使每个动态计算计数的用户程序防范这种情况。那是那种为了没有好处而破坏几十年代码的改变。 -The driver-side consequence, which we noted earlier: your handler must not panic or error on a zero `uio_resid`. The kernel effectively handles the case for you when you go through `uiomove`, which returns zero immediately if there is nothing to move. +驱动侧的后果,我们之前已经注意到:你的处理程序不能在零 `uio_resid` 上崩溃或报错。当你通过 `uiomove` 时,内核实际上为你处理了这种情况,如果没有东西要移动,它会立即返回零。 -If you ever find yourself writing `if (uio->uio_resid == 0) return (EINVAL);` in a driver, stop. That is the wrong answer. Zero-count I/O is valid; return zero. +如果你曾经发现自己编写 `if (uio->uio_resid == 0) return (EINVAL);`,停下来。那是错误的答案。零计数 I/O 是有效的;返回零。 ## 附录 C:/dev/zero 读取路径简短导览 -As a closing piece of analysis, it is worth walking through exactly what happens when a user program calls `read(2)` on `/dev/zero`. The driver is `/usr/src/sys/dev/null/null.c` and the handler is `zero_read`. Once you understand this path, you understand everything in Chapter 9. +作为结束分析,值得演练当用户程序在 `/dev/zero` 上调用 `read(2)` 时到底发生了什么。驱动是 `/usr/src/sys/dev/null/null.c`,处理程序是 `zero_read`。一旦你理解了这个路径,你就理解了第九章的一切。 -### From User Space to Kernel Dispatch +### 从用户空间到内核分派 -The user calls: +用户调用: ```c ssize_t n = read(fd, buf, 1024); ``` -The C library makes the `read` syscall. The kernel looks up `fd` in the calling process's file table, retrieves the `struct file`, identifies its vnode, dispatches the call into devfs. +C 库发起 `read` 系统调用。内核在调用进程的文件表中查找 `fd`,检索 `struct file`,识别其 vnode,将调用分派到 devfs。 -devfs identifies the cdev associated with the vnode, acquires a reference on it, and calls its `d_read` function pointer (`zero_read`) with the uio the kernel prepared. +devfs 识别与 vnode 关联的 cdev,获取其上的引用,并使用内核准备的 uio 调用其 `d_read` 函数指针(`zero_read`)。 -### Inside `zero_read` +### `zero_read` 内部 ```c static int @@ -3857,87 +3857,87 @@ zero_read(struct cdev *dev __unused, struct uio *uio, int flags __unused) } ``` -- Assert that the direction is correct. Good practice; a `KASSERT` costs nothing in production kernels. -- Set `zbuf` to point at `zero_region`, a large pre-allocated zero-filled area. -- Loop: while the caller wants more bytes, determine the transfer size (min of `uio_resid` and the zero region's size), call `uiomove`, accumulate any error. -- Return. +- 断言方向是正确的。好习惯;`KASSERT` 在生产内核中不花费任何代价。 +- 将 `zbuf` 设置为指向 `zero_region`,一个大型预分配的零填充区域。 +- 循环:当调用者需要更多字节时,确定传输大小(`uio_resid` 和零区域大小的最小值),调用 `uiomove`,累积任何错误。 +- 返回。 -### Inside `uiomove` +### `uiomove` 内部 -For the first iteration, `uiomove` sees `uio_resid = 1024`, `len = 1024` (since `ZERO_REGION_SIZE` is much larger), `uio_segflg = UIO_USERSPACE`, `uio_rw = UIO_READ`. It selects `copyout(zbuf, buf, 1024)`. The kernel performs the copy, handling any page fault on the user buffer. On success, `uio_resid` drops to zero, `uio_offset` grows by 1024, and the iovec is fully consumed. +对于第一次迭代,`uiomove` 看到 `uio_resid = 1024`、`len = 1024`(因为 `ZERO_REGION_SIZE` 大得多)、`uio_segflg = UIO_USERSPACE`、`uio_rw = UIO_READ`。它选择 `copyout(zbuf, buf, 1024)`。内核执行复制,处理用户缓冲区上的任何页面故障。成功时,`uio_resid` 降到零,`uio_offset` 增长 1024,iovec 被完全消耗。 -### Back Up the Stack +### 回溯调用栈 -`uiomove` returns zero. The loop in `zero_read` sees `uio_resid == 0` and exits. `zero_read` returns zero. +`uiomove` 返回零。`zero_read` 中的循环看到 `uio_resid == 0` 并退出。`zero_read` 返回零。 -devfs releases its reference on the cdev. The kernel computes the byte count as `1024 - 0 = 1024`. `read(2)` returns 1024 to the user. +devfs 释放其在 cdev 上的引用。内核计算字节计数为 `1024 - 0 = 1024`。`read(2)` 向用户返回 1024。 -The user's buffer now holds 1024 zero bytes. +用户的缓冲区现在持有 1024 个零字节。 -### What This Tells You About Your Own Driver +### 这告诉你关于你自己驱动的什么 -Two observations. +两个观察。 -First, every data-path decision in `zero_read` is one you are now making too. How large of a chunk to move per iteration; which buffer to read from; how to handle the error from `uiomove`. Your driver's decisions will differ in the specifics (your buffer is not a pre-allocated zero region, your chunk size is not `ZERO_REGION_SIZE`), but the shape is identical. +首先,`zero_read` 中的每个数据路径决策都是你现在也在做的决策。每次迭代移动多大的块;从哪个缓冲区读取;如何处理 `uiomove` 的错误。你的驱动的决策在细节上会有所不同(你的缓冲区不是预分配的零区域,你的块大小不是 `ZERO_REGION_SIZE`),但形状是相同的。 -Second, everything above `zero_read` is kernel machinery you do not have to write. You implement the handler, and the kernel takes care of the syscall, the file-descriptor lookup, the VFS dispatch, the devfs routing, the reference counting, and the fault handling. That is the power of the abstraction: you add your driver's knowledge, and everything else comes for free. +其次,`zero_read` 之上的所有东西是你不需要编写的内核机制。你实现处理程序,内核负责系统调用、文件描述符查找、VFS 分派、devfs 路由、引用计数和故障处理。这就是抽象的力量:你添加驱动的知识,其他一切都免费获得。 -The flip side is that when you write a driver, you are committing to *cooperating* with that machinery. Every invariant that `uiomove` and devfs rely on is now your responsibility to uphold. The chapter has been walking you through those invariants one at a time, by building three small drivers that each exercise a different subset. +反面是,当你编写驱动时,你承诺与该机制*合作*。`uiomove` 和 devfs 依赖的每个不变量现在都是你要维护的责任。本章一直在一次一个地引导你了解这些不变量,通过构建三个小驱动,每个驱动锻炼不同的子集。 -By now, the pattern should be familiar. +到目前为止,模式应该已经很熟悉了。 ## 附录 D:用户侧常见的 read(2)/write(2) 返回值 -A short cheat sheet for what a user program sees when it talks to your driver. This is not driver code; it is the view from the other side of the trust boundary. Reading it occasionally is the best inoculation against the subtle bugs that arise when the driver does something other than what a well-behaved UNIX program expects. +用户程序与你的驱动通信时看到的内容的简短速查表。这不是驱动代码;这是信任边界另一侧的视图。偶尔阅读它是针对驱动做了行为良好的 UNIX 程序期望之外的事情时出现的微妙 bug 的最好预防。 ### `read(2)` -- A positive integer: that many bytes were placed into the caller's buffer. Less than the requested count means a short read; the caller loops. -- Zero: end of file. No more bytes will ever be produced on this descriptor. The caller stops. -- `-1` with `errno = EAGAIN`: non-blocking mode, no data available right now. The caller waits (via `select(2)` / `poll(2)` / `kqueue(2)`) and tries again. -- `-1` with `errno = EINTR`: a signal interrupted the read. The caller usually retries unless the signal handler tells it not to. -- `-1` with `errno = EFAULT`: the buffer pointer was invalid. The caller has a bug. -- `-1` with `errno = ENXIO`: the device is gone. The caller should close the descriptor and give up. -- `-1` with `errno = EIO`: the device reported a hardware error. The caller may retry or report. +- 正整数:那么多字节被放入调用者的缓冲区。少于请求计数意味着短读取;调用者循环。 +- 零:文件结束。此描述符上不再会产生字节。调用者停止。 +- `-1` 且 `errno = EAGAIN`:非阻塞模式,现在没有可用数据。调用者等待(通过 `select(2)` / `poll(2)` / `kqueue(2)`)并重试。 +- `-1` 且 `errno = EINTR`:信号中断了读取。调用者通常重试,除非信号处理程序告诉它不要。 +- `-1` 且 `errno = EFAULT`:缓冲区指针无效。调用者有 bug。 +- `-1` 且 `errno = ENXIO`:设备已消失。调用者应该关闭描述符并放弃。 +- `-1` 且 `errno = EIO`:设备报告了硬件错误。调用者可以重试或报告。 ### `write(2)` -- A positive integer: that many bytes were accepted. Less than the offered count means a short write; the caller loops with the remainder. -- Zero: theoretically possible, rarely seen in practice. Usually treated the same as a short write of zero bytes. -- `-1` with `errno = EAGAIN`: non-blocking mode, no space right now. The caller waits and retries. -- `-1` with `errno = ENOSPC`: permanently no space. The caller either stops writing or reopens the descriptor. -- `-1` with `errno = EPIPE`: the reader closed. Relevant for pipe-like devices, not for `myfirst`. -- `-1` with `errno = EFAULT`: the buffer pointer was invalid. -- `-1` with `errno = EINTR`: interrupted by a signal. Usually retried. +- 正整数:那么多字节被接受。少于提供的计数意味着短写入;调用者用剩余部分循环。 +- 零:理论上可能,实践中很少见到。通常被视为零字节的短写入。 +- `-1` 且 `errno = EAGAIN`:非阻塞模式,现在没有空间。调用者等待并重试。 +- `-1` 且 `errno = ENOSPC`:永久没有空间。调用者要么停止写入,要么重新打开描述符。 +- `-1` 且 `errno = EPIPE`:读取者关闭了。与管道类设备相关,与 `myfirst` 无关。 +- `-1` 且 `errno = EFAULT`:缓冲区指针无效。 +- `-1` 且 `errno = EINTR`:被信号中断。通常重试。 -### What This Means for Your Driver +### 这对你的驱动意味着什么 -Two takeaways. +两个要点。 -First, `EAGAIN` is how non-blocking callers expect a driver to say "no data / no room right now, come back later". A non-blocking caller that sees `EAGAIN` does not treat it as an error; it waits for a wake-up (usually via `poll(2)`) and retries. Chapter 10 makes this mechanism work for `myfirst`. +首先,`EAGAIN` 是非阻塞调用者期望驱动说"现在没有数据/没有空间,稍后再来"的方式。看到 `EAGAIN` 的非阻塞调用者不将其视为错误;它等待唤醒(通常通过 `poll(2)`)并重试。第十章使这个机制为 `myfirst` 工作。 -Second, `ENOSPC` is how a driver signals a permanent out-of-room condition on a write. It differs from `EAGAIN` in that the caller does not expect retries to succeed soon. For `myfirst` Stage 3 we use `ENOSPC` when the buffer fills and there is no reader actively draining; Chapter 10 will layer `EAGAIN` on top of the same condition for non-blocking readers and writers. +其次,`ENOSPC` 是驱动在写入时发出永久没有空间信号的方式。它与 `EAGAIN` 的区别在于调用者不期望重试很快成功。对于 `myfirst` 阶段 3,当缓冲区填满且没有读取者主动排空时我们使用 `ENOSPC`;第十章将在非阻塞读取者和写入者的相同条件之上叠加 `EAGAIN`。 -A driver that returns the wrong errno here is almost indistinguishable from a driver that is misbehaving. The cost of getting it right is tiny. The cost of getting it wrong shows up in confused user programs months later. +在这里返回错误 errno 的驱动几乎与行为不当的驱动无法区分。正确的代价很小。错误的代价在几个月后以困惑的用户程序的形式出现。 ## 附录 E:一页速查表 -If you only have five minutes before starting Chapter 10, here is the one-page version of everything above. +如果你在开始第十章之前只有五分钟,这是上面所有内容的一页版本。 -**The signatures:** +**签名:** ```c static int myfirst_read(struct cdev *dev, struct uio *uio, int ioflag); static int myfirst_write(struct cdev *dev, struct uio *uio, int ioflag); ``` -Return zero on success, a positive errno on failure. Never return a byte count. +成功时返回零,失败时返回正 errno。永远不返回字节计数。 -**The three-line spine for reads:** +**读取的三行骨架:** ```c error = devfs_get_cdevpriv((void **)&fh); @@ -3945,7 +3945,7 @@ if (error) return error; return uiomove_frombuf(sc->buf, sc->buflen, uio); ``` -Or, for a dynamic buffer: +或者,对于动态缓冲区: ```c mtx_lock(&sc->mtx); @@ -3956,7 +3956,7 @@ mtx_unlock(&sc->mtx); return error; ``` -**The three-line spine for writes:** +**写入的三行骨架:** ```c mtx_lock(&sc->mtx); @@ -3969,14 +3969,14 @@ mtx_unlock(&sc->mtx); return error; ``` -**What to remember about uio:** +**关于 uio 要记住的:** - `uio_resid`: bytes still pending. `uiomove` decrements this. - `uio_offset`: position, if meaningful. `uiomove` increments this. - `uio_rw`: direction. Trust `uiomove` to use it. - Everything else: do not touch. -**What not to do:** +**不要做什么:** - Do not dereference user pointers directly. - Do not use `memcpy` / `bcopy` between user and kernel. @@ -3985,7 +3985,7 @@ return error; - Do not forget `M_ZERO` on `malloc(9)`. - Do not hold a spin lock across `uiomove`. -**Errno values:** +**Errno 值:** - `0`: success. - `ENXIO`: device not ready. @@ -3994,7 +3994,7 @@ return error; - `EFAULT`: from `uiomove`, propagate. - `EIO`: hardware error. -That is the chapter. +以上就是本章内容。 diff --git a/translations/zh_CN/chapters/part2/chapter-10.md b/translations/zh_CN/chapters/part2/chapter-10.md index 4fc7a33..03e44b9 100644 --- a/translations/zh_CN/chapters/part2/chapter-10.md +++ b/translations/zh_CN/chapters/part2/chapter-10.md @@ -106,7 +106,7 @@ estimatedReadTime: 210 在开始本章之前,确认: - 你的驱动源码匹配 `examples/part-02/ch09-reading-and-writing/stage3-echo/` 下第9章阶段 3 的示例。如果不匹配,在这里停下并先将其调整到该形状。第10章假设它已经如此。 -- 你的实验机器运行带有匹配 `/usr/src` 的 FreeBSD 14.3。 The APIs and file layouts you will see in this chapter align with that release. +- 你的实验机器运行带有匹配 `/usr/src` 的 FreeBSD 14.3。本章中的 API 和文件布局与该版本对齐。 - 你仔细阅读了第9章,包括附录 E(一页速查表)。那里的读写"三行骨架"正是我们即将扩展的内容。 - 你能够熟练加载和卸载自己的模块、观察 `dmesg`、读取 `sysctl dev.myfirst.0.stats`,以及在测试让你惊讶时读取 `truss(1)` 或 `ktrace(1)` 的输出。 @@ -227,7 +227,7 @@ estimatedReadTime: 210 顺序很重要。每一节都假设前一节的更改已到位。如果你跳过,你会进入不编译或以令人惊讶的方式行为的代码。像往常一样,慢路径就是快路径。 -### Wrapping Up Section 1 +### 第1节总结 我们命名了非缓冲和缓冲 I/O 之间的区别,并命名了各自的成本和收益。我们选择了一个可以不断回顾的类比(桶与管道)。我们讨论了缓冲在驱动代码中的回报、常见的反压策略,以及我们为本章其余部分承诺的策略。我们为驱动整个数据结构搭好了舞台:循环缓冲区。 @@ -237,7 +237,7 @@ estimatedReadTime: 210 循环缓冲区是那种比我们现在使用的操作系统更古老的数据结构之一。它出现在串口芯片、音频采样队列、网络接收路径、键盘事件队列、追踪缓冲区、`dmesg(8)`、`printf(3)` 库以及几乎所有一段代码想要留下字节供另一段代码稍后提取的地方。结构简单。实现简短。初学者在其中犯的 bug 是可预测的。我们将用一次、在用户态、小心地构建它,然后在第3节中将验证过的版本带入驱动。 -### What a Circular Buffer Is +### 什么是循环缓冲区 线性缓冲区是可能工作的最简单的东西:一块内存加上一个"下一个空闲字节"索引。你从头开始写入,到达末尾时停止。一旦填满,你要么增长它、复制它,要么停止接受新数据。 @@ -379,7 +379,7 @@ size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); 两个函数中恰好有一个步骤会环绕。要么目标环绕(写入中),要么源环绕(读取中),但绝不会两者同时。这是使实现可管理的关键属性:缓冲区的环绕是内部数据的属性,不是调用者数据的属性,所以调用者的源和目标总是被视为普通的连续内存。 -### Avoiding Overwrites and Data Loss +### 避免覆盖和数据丢失 初学者常犯的一个错误是在缓冲区填满时让 `cbuf_write` 覆盖旧数据,理论是"更新的数据更重要"。这有时是正确的策略,正如我们在第1节中指出的,但它必须是*刻意的*设计选择,且对调用者可见,而不是状态的静默变更。传统的默认值是 `cbuf_write` 返回它实际写入的字节数,调用者应该查看返回值。 @@ -387,7 +387,7 @@ size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); 如果你想要一个具有覆盖语义的循环缓冲区(例如 `dmesg` 风格的日志),最干净的方法是写一个单独的 `cbuf_overwrite` 函数并保持 `cbuf_write` 严格。两个不同的名字意味着两个不同的意图,未来的代码读者不必猜测哪种行为生效。 -### Implementing It in Userland +### 在用户态实现 学习这个结构的正确方式是在用户态输入一次并通过一些小测试运行它,然后才让内核信任它。相同的源码可以几乎不变地移入内核模块,除了分配和释放调用。 @@ -1485,9 +1485,9 @@ $ dd if=/dev/myfirst of=/dev/null bs=512 2>/tmp/dd-r ## 第5节:实现非阻塞 I/O -到目前为止,当调用者请求无法立即满足的传输时,驱动一直做两件事之一. 它返回零(在读取时,模仿文件结束)或在中途停止且没有传输字节(在写入时,告诉用户"接受了零字节"). 这两种行为都不是真正的字符设备应该做的. 本节用两种正确行为替换两者: a blocking wait for the default case, and a clean `EAGAIN` for callers that opened the descriptor non-blocking. +到目前为止,当调用者请求无法立即满足的传输时,驱动一直做两件事之一. 它返回零(在读取时,模仿文件结束)或在中途停止且没有传输字节(在写入时,告诉用户"接受了零字节"). 这两种行为都不是真正的字符设备应该做的. 本节用两种正确行为替换两者:默认情况下的阻塞等待,以及为非阻塞描述符调用者提供的干净 `EAGAIN`。 -在触及驱动之前,让我们确保理解"非阻塞"在信任边界两侧意味着什么 from each side of the trust boundary. That vocabulary is what ties the implementation together. +在触及驱动之前,让我们确保从信任边界的每一侧理解"非阻塞"的含义。该词汇表是将实现联系在一起的基础。 ### 什么是非阻塞 I/O @@ -1503,7 +1503,7 @@ $ dd if=/dev/myfirst of=/dev/null bs=512 2>/tmp/dd-r - 当描述符有 `O_DIRECT` 时设置 `IO_DIRECT`. - 当描述符有 `O_FSYNC` 时在 `d_write` 上设置 `IO_SYNC`. -转换比看起来更简单. /usr/src/sys/fs/devfs/devfs_vnops.c 中的 `CTASSERT` 声明 `O_NONBLOCK == IO_NDELAY`. 位值的选择使两个名称可互换, 你可以根据哪个约定更清晰写 `(ioflag & IO_NDELAY)` 或 `(ioflag & O_NONBLOCK)`. 两者都有效. FreeBSD 源码树更常使用 `IO_NDELAY`,所以我们遵循它. +转换比看起来更简单。`/usr/src/sys/fs/devfs/devfs_vnops.c` 中的 `CTASSERT` 声明 `O_NONBLOCK == IO_NDELAY`。位值的选择使两个名称可互换,你可以根据哪个约定更清晰写 `(ioflag & IO_NDELAY)` 或 `(ioflag & O_NONBLOCK)`。两者都有效。FreeBSD 源码树更常使用 `IO_NDELAY`,所以我们遵循它。 ### 非阻塞行为何时有用 @@ -1515,7 +1515,7 @@ $ dd if=/dev/myfirst of=/dev/null bs=512 2>/tmp/dd-r ### IO_NDELAY 标志:它如何流向驱动 -追踪一次流程,这样你知道标志从哪里来. 用户在设置了 `O_NONBLOCK` 的描述符上调用 `read(fd, buf, n)`. Inside the kernel: +追踪一次流程,这样你知道标志从哪里来。用户在设置了 `O_NONBLOCK` 的描述符上调用 `read(fd, buf, n)`。在内核内部: 1. `sys_read` 查找文件描述符并找到 `fp->f_flag` 包含 `O_NONBLOCK` 的 `struct file`. 2. `vn_read` 或(对于字符设备)`devfs_read_f` 通过屏蔽 `fp->f_flag` 中驱动关心的位来组装 `ioflag`. 具体来说,它计算 `ioflag = fp->f_flag & (O_NONBLOCK | O_DIRECT);`. @@ -1580,7 +1580,7 @@ while (cbuf_used(&sc->cb) == 0) { 第四个是 **拆离检查**. `mtx_sleep` 返回后,可能 `myfirst_detach` 已开始且 `sc->is_attached` 现在为零. 我们检查并在如果是时返回 `ENXIO`. 这防止读取针对部分拆除的驱动继续进行. 拆离代码路径必须在拆除互斥锁之前调用 `wakeup(&sc->cb)` 来释放任何睡眠者;我们将在下面添加该调用. -### The Writer Side +### 写入侧 写入路径是镜像: @@ -1744,7 +1744,7 @@ myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) ### 在拆离时唤醒睡眠者 -我们还需要教会 `myfirst_detach` 释放任何睡眠者. The pattern is: +我们还需要教会 `myfirst_detach` 释放任何睡眠者。模式如下: ```c static int @@ -2045,7 +2045,7 @@ main(int argc, char *argv[]) } ``` -有了这个工具,你可以用现实大小驱动驱动. For example: +有了这个工具,你可以用现实大小驱动驱动。例如: ```sh $ ./rw_myfirst_v2 fill 4096 @@ -2497,15 +2497,15 @@ clean: **`sc->bytes_read`, `sc->bytes_written`。** 由两个 I/O 处理程序在 `sc->mtx` 下更新. 由 sysctl 通过 `SYSCTL_ADD_U64` 直接读取(没有处理程序插入). sysctl 读取在大多数架构上是单个 64 位加载,这在某些 32 位平台上是撕裂读取风险,但在 amd64 和 arm64 上是原子的. *大部分安全;见下面的撕裂读取说明。* -**`sc->open_count`, `sc->active_fhs`.** Updated under `sc->mtx`. Read by sysctl directly. Same torn-read consideration. +**`sc->open_count`、`sc->active_fhs`。** 在 `sc->mtx` 下更新。由 sysctl 直接读取。相同的撕裂读取考虑。 **`sc->is_attached`.** Read by every handler at entry, set by attach (without lock, before `make_dev`), cleared by detach (under lock). The unlocked write at attach time is safe because no one else can see the device yet. The locked clear at detach time is correctly ordered with the wakeup. *看起来安全。* -**`sc->cdev`, `sc->cdev_alias`.** Set by attach, cleared by detach. Once attach is done, these are stable for the lifetime of the device. The handlers reach the softc through `dev->si_drv1` (set during attach) and never dereference these directly during I/O. *Safe by construction.* +**`sc->cdev`、`sc->cdev_alias`。** 由 attach 设置,由 detach 清除。一旦 attach 完成,它们在设备生命周期内稳定。处理程序通过 `dev->si_drv1`(在 attach 期间设置)到达 softc,在 I/O 期间从不直接解引用这些。*构造上安全。* -**`sc->rsel`, `sc->wsel`.** The `selinfo` machinery is internally locked (it uses the kernel's `selspinlock` and per-mutex `knlist` if you initialise one). For pure `select(2)`/`poll(2)` use, the `selrecord` and `selwakeup` calls handle their own concurrency. *Safe.* +**`sc->rsel`、`sc->wsel`。** `selinfo` 机制内部加锁(它使用内核的 `selspinlock` 和每互斥锁 `knlist`,如果你初始化了一个)。对于纯 `select(2)`/`poll(2)` 使用,`selrecord` 和 `selwakeup` 调用处理自己的并发。*安全。* -**`sc->open_count` and friends, again.** The torn-read note above is worth being explicit about. On 32-bit platforms (i386, armv7), a 64-bit field can be split across two memory operations, and a concurrent write can yield a read that contains the high half of one value and the low half of another (a "torn read"). The chapter is targeting amd64 where this is not an issue, but it is the kind of thing a real driver should think about. The fix, if needed, is to add a sysctl handler (like the `cb_used` one) that takes the mutex around the load. +**`sc->open_count` 和朋友们,再议。** 上面的撕裂读取注释值得明确说明。在 32 位平台(i386、armv7)上,64 位字段可以跨两次内存操作分割,并发写入可能产生包含一个值的高半部分和另一个值的低半部分的读取("撕裂读取")。本章针对 amd64,这不是问题,但这是真正的驱动应该考虑的事情。修复方法(如果需要)是添加一个 sysctl 处理程序(像 `cb_used` 那样),在加载周围持有互斥锁。 上面的审计给出了健康证明. 更大的重构机会不是竞态条件而是*代码形状*:缓冲区逻辑与 I/O 逻辑混合的地方、辅助函数可以澄清意图的地方、以及第11章可以在不触及 I/O 处理程序的情况下引入新锁类别的地方. @@ -2707,11 +2707,11 @@ myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) */ ``` -That comment is enough for Chapter 11 to either follow the same convention or to deliberately change it. A driver that explains its own rules makes future maintenance easier; a driver that does not explain its rules leaves every future reader to infer them from the source, which is slow and error-prone. +这个注释足以让第11章要么遵循相同的约定,要么刻意改变它。解释自己规则的驱动使未来维护更容易;不解释规则的驱动让每个未来的读者从源码推断规则,这是缓慢且容易出错的。 -### Splitting `cbuf` Out of `myfirst.c` +### 将 `cbuf` 从 `myfirst.c` 中拆分出来 -In Stage 2 and Stage 3, the `cbuf` source lived alongside `myfirst.c` in the same module directory but in its own `.c` file. The Makefile is updated to compile both: +在阶段 2 和阶段 3 中,`cbuf` 源码与 `myfirst.c` 并列存放在同一模块目录中,但有自己的 `.c` 文件。Makefile 被更新为编译两者: ```make KMOD= myfirst @@ -2723,19 +2723,19 @@ SRCS+= device_if.h bus_if.h 两个小细节值得注意。 -The first is that `cbuf.c` declares its own `MALLOC_DEFINE`. Each `MALLOC_DEFINE` for the same tag in the same module would be a duplicate definition; we therefore put the declaration in exactly one source file (`cbuf.c`) and an `extern` declaration in `cbuf.h` if needed. In our setup, the tag is local to `cbuf.c` and no external use is needed. +第一点是 `cbuf.c` 声明了自己的 `MALLOC_DEFINE`。同一模块中相同标签的每个 `MALLOC_DEFINE` 都将是重复定义;因此我们将声明恰好放在一个源文件(`cbuf.c`)中,并在需要时在 `cbuf.h` 中放一个 `extern` 声明。在我们的设置中,标签是 `cbuf.c` 的局部标签,不需要外部使用。 -The second is that `cbuf.c` does not need any of the `myfirst` headers. It is a self-contained library that the driver happens to use. If you ever wanted to share `cbuf` with a second driver, you could pull it out into its own KLD or into `/usr/src/sys/sys/cbuf.h` and `/usr/src/sys/kern/subr_cbuf.c` (a hypothetical placement). The discipline of keeping `cbuf` self-contained makes that possible. +第二点是 `cbuf.c` 不需要任何 `myfirst` 头文件。它是一个自包含的库,驱动碰巧使用它。如果你曾想与第二个驱动共享 `cbuf`,你可以将其拉出到自己的 KLD 中,或放到 `/usr/src/sys/sys/cbuf.h` 和 `/usr/src/sys/kern/subr_cbuf.c`(假设的放置位置)。保持 `cbuf` 自包含的纪律使这成为可能。 -### Naming Conventions +### 命名约定 -A small but useful pattern: name your buffer-related fields and functions consistently. We have used `sc->cb` for the buffer, `cbuf_*` for buffer functions, `myfirst_buf_*` for the driver's wrappers. The pattern lets a reader scan the code and instantly know whether a function is touching the raw buffer (`cbuf_*`) or going through the locked driver wrappers (`myfirst_buf_*`). +一个小但有用的模式:一致地命名缓冲区相关的字段和函数。我们使用 `sc->cb` 表示缓冲区,`cbuf_*` 表示缓冲区函数,`myfirst_buf_*` 表示驱动的封装。该模式让读者扫描代码时立即知道函数是触及原始缓冲区(`cbuf_*`)还是通过带锁的驱动封装(`myfirst_buf_*`)。 -Avoid mixing styles. Calling the buffer `sc->ring` in some places and `sc->cb` in others, or `cbuf_get` and `cbuf_read`, makes the code harder to skim. Pick one set of names and use them throughout. +避免混合风格。在某些地方调用缓冲区 `sc->ring` 而在其他地方调用 `sc->cb`,或者 `cbuf_get` 和 `cbuf_read`,会使代码更难浏览。选择一组名称并始终如一地使用。 -### Defending Against Buffer-Size Surprises +### 防御缓冲区大小意外 -The `MYFIRST_BUFSIZE` macro determines the capacity of the ring. Right now it is hard-coded to 4096. There is nothing wrong with that, but a `sysctl` knob (read-only) that exposes the value, plus a `module_param`-style override at module load time, would make the driver more usable in tests without needing to recompile. +`MYFIRST_BUFSIZE` 宏决定了环形缓冲区的容量。目前它被硬编码为 4096。这没有问题,但一个暴露该值的 `sysctl` 旋钮(只读),加上模块加载时的 `module_param` 风格覆盖,将使驱动在测试中更可用,而无需重新编译。 这是使用 `TUNABLE_INT` 的加载时覆盖模式: @@ -2746,49 +2746,49 @@ SYSCTL_INT(_hw_myfirst, OID_AUTO, bufsize, CTLFLAG_RDTUN, &myfirst_bufsize, 0, "Default buffer size for new myfirst attaches"); ``` -`TUNABLE_INT` reads the value from the kernel environment at boot or `kldload` time. A user can set it from the loader prompt (`set hw.myfirst.bufsize=8192`) or by running `kenv hw.myfirst.bufsize=8192` before `kldload`. The `CTLFLAG_RDTUN` flag indicates "read-only at runtime, but tunable at load time." After load, `sysctl hw.myfirst.bufsize` shows the chosen value. +`TUNABLE_INT` 在启动或 `kldload` 时从内核环境读取该值。用户可以从 loader 提示符设置(`set hw.myfirst.bufsize=8192`)或在 `kldload` 之前运行 `kenv hw.myfirst.bufsize=8192`。`CTLFLAG_RDTUN` 标志表示"运行时只读,但加载时可调"。加载后,`sysctl hw.myfirst.bufsize` 显示所选值。 -然后在 `myfirst_attach` 中,在 `cbuf_init` 调用中使用 `myfirst_bufsize` 而不是 `MYFIRST_BUFSIZE`。 The change is small but useful: now you can experiment with different buffer sizes without rebuilding the module. +然后在 `myfirst_attach` 中,在 `cbuf_init` 调用中使用 `myfirst_bufsize` 而不是 `MYFIRST_BUFSIZE`。更改很小但有用:现在你可以试验不同的缓冲区大小而无需重新构建模块。 -### Goals for the Next Milestone +### 下一个里程碑的目标 第11章带驱动去的地方: -- The single mutex you have today protects everything. Chapter 11 will discuss whether a single lock is the right design under heavy contention, whether sleepable locks (`sx_*`) would be more appropriate, and how to reason about lock ordering when multiple subsystems get involved. -- The blocking path uses `mtx_sleep`, which is the right primitive for this kind of work. Chapter 11 will introduce `cv_wait(9)` (condition variables) as a more structured alternative for some patterns, and discuss when each is preferable. -- The wake-up strategy uses `wakeup(9)` (wake everyone). Chapter 11 will discuss `wakeup_one(9)` and the thundering-herd problem, and when each is appropriate. -- The cbuf is intentionally not thread-safe by itself. Chapter 11 will revisit this decision and discuss the tradeoffs of building locking *into* the data structure versus leaving it to the caller. -- The detach path's "wait for descriptors to close" rule is conservative. Chapter 11 will discuss alternative strategies (forced revocation, reference counting at the cdev level, the `destroy_dev_drain(9)` mechanism) for drivers that need to detach despite open descriptors. +- 你今天拥有的单个互斥锁保护一切。第11章将讨论在重度竞争下单个锁是否是正确的设计、可睡眠锁(`sx_*`)是否更合适、以及当多个子系统参与时如何推理锁排序。 +- 阻塞路径使用 `mtx_sleep`,这是此类工作的正确原语。第11章将引入 `cv_wait(9)`(条件变量)作为某些模式的更结构化替代方案,并讨论何时各有优劣。 +- 唤醒策略使用 `wakeup(9)`(唤醒所有人)。第11章将讨论 `wakeup_one(9)` 和惊群问题,以及何时各有适用。 +- cbuf 有意设计为自身非线程安全。第11章将重新审视这个决策,并讨论将锁定构建*到*数据结构中与留给调用者的权衡。 +- 拆离路径的"等待描述符关闭"规则是保守的。第11章将讨论替代策略(强制撤销、cdev 级别的引用计数、`destroy_dev_drain(9)` 机制),适用于需要在描述符打开时拆离的驱动。 -You do not need to know any of this material yet. The point is that the current code's *shape* is what makes those topics approachable in Chapter 11. You can swap the mutex for an `sx` lock without touching the helpers' signatures. You can swap `wakeup` for `wakeup_one` with one-line changes. You can introduce a per-reader sleep channel without restructuring the I/O handlers. The refactor pays off as soon as you start asking the next chapter's questions. +你还不需要知道这些材料中的任何一个。要点是当前代码的*形状*使这些主题在第11章中变得可接近。你可以在不触及辅助函数签名的情况下将互斥锁交换为 `sx` 锁。你可以用一行更改将 `wakeup` 交换为 `wakeup_one`。你可以引入每读取者睡眠通道而无需重构 I/O 处理程序。重构在你开始问下一章的问题时立即产生回报。 -### A Reading Order for the Next Chapter +### 下一章的阅读顺序 -When you start Chapter 11, three files in `/usr/src/sys` will repay careful reading. +当你开始第11章时,`/usr/src/sys` 中的三个文件值得仔细阅读。 -`/usr/src/sys/kern/subr_sleepqueue.c` is where `mtx_sleep`, `tsleep`, and `wakeup` are implemented. Read it once for context. The implementation is more elaborate than the man pages suggest, but the core of it (chan-keyed sleep queues, atomic dequeue on wake) is straightforward. +`/usr/src/sys/kern/subr_sleepqueue.c` 是 `mtx_sleep`、`tsleep` 和 `wakeup` 实现的地方。阅读一次以获取上下文。实现比手册页暗示的更复杂,但其核心(通道键控的睡眠队列、唤醒时的原子出队)是直接的。 -`/usr/src/sys/sys/sx.h` and `/usr/src/sys/kern/kern_sx.c` together explain the sleepable-shared-exclusive lock. We mentioned `sx` above as an alternative to `mtx`; reading the actual implementation is the best way to understand the tradeoffs. +`/usr/src/sys/sys/sx.h` 和 `/usr/src/sys/kern/kern_sx.c` 一起解释了可睡眠共享排他锁。我们在上面提到 `sx` 作为 `mtx` 的替代方案;阅读实际实现是理解权衡的最佳方式。 -`/usr/src/sys/sys/condvar.h` and `/usr/src/sys/kern/kern_condvar.c` document the `cv_wait` family of condition-variable primitives. Like `mtx_sleep`, they build on the kernel's sleep-queue machinery in `subr_sleepqueue.c`, but they expose a distinct structured API where each wait point has its own named `struct cv` instead of an arbitrary address as the channel. Chapter 11 will explain when to prefer each, and why a dedicated `struct cv` is often the cleaner choice for a well-defined wait condition. +`/usr/src/sys/sys/condvar.h` 和 `/usr/src/sys/kern/kern_condvar.c` 记录了 `cv_wait` 系列条件变量原语。像 `mtx_sleep` 一样,它们构建在 `subr_sleepqueue.c` 中内核的睡眠队列机制之上,但它们暴露了一个不同的结构化 API,其中每个等待点都有自己的命名 `struct cv`,而不是任意地址作为通道。第11章将解释何时优先选择每种方式,以及为什么专用的 `struct cv` 通常是明确定义的等待条件的更清晰选择。 -These are not required reading; they are the next step on a long path you are clearly already on. +这些不是必读材料;它们是你显然已经踏上的漫长道路上的下一步。 ### 第7节总结 -The driver is now in the shape Chapter 11 wants. The buffer abstraction is in its own file, exercised in userland, and called from the driver through a small set of locked wrappers. The locking strategy is documented in a comment that names exactly what the mutex protects and what the rules are. The blocking path is correct, the non-blocking path is correct, the poll path is correct, and the detach path correctly waits for and wakes any sleepers. +驱动现在处于第11章想要的形状。缓冲区抽象在自己的文件中,在用户态经过测试,并通过一小组带锁封装从驱动调用。锁定策略记录在注释中,精确命名了互斥锁保护什么以及规则是什么。阻塞路径正确,非阻塞路径正确,poll 路径正确,拆离路径正确等待并唤醒任何睡眠者。 -Most of what you do in Chapter 11 will be additive to this base, not a rewrite of it. The patterns we have built (lock around state changes, sleep with the mutex as interlock, wake on every transition) are the same patterns the rest of the kernel uses. The vocabulary is the same, the primitives are the same, the discipline is the same. You are close to being able to read most character-device drivers in the tree without help. +你在第11章做的大部分工作将是对此基础的增量添加,而不是重写。我们构建的模式(围绕状态变化锁定、以互斥锁作为互锁睡眠、每次转换时唤醒)与内核其余部分使用的模式相同。词汇相同,原语相同,纪律相同。你已接近能够在没有帮助的情况下阅读树中大多数字符设备驱动。 -Before we move on to the chapter's supplementary topics and the labs, take a moment to look at your own source. The Stage 4 driver should be roughly 500 lines of code (`myfirst.c`) plus about 110 lines of `cbuf.c` and 20 lines of `cbuf.h`. The total is small, the layering is clean, and almost every line is doing something specific. That density is what well-shaped driver code looks like. +在我们进入本章的补充主题和实验之前,花点时间看看你自己的源码。阶段 4 驱动应该大约 500 行代码(`myfirst.c`)加上大约 110 行 `cbuf.c` 和 20 行 `cbuf.h`。总量很小,分层清晰,几乎每一行都在做特定的事情。这种密度就是形状良好的驱动代码的样子。 -## Section 8: Three Supplementary Topics +## 第8节:三个补充主题 -This section covers three topics that often appear alongside buffered I/O in the real world. Each one is large enough to fill an entire chapter on its own; we are not going to do that. Instead we are going to introduce each at the level a reader of this book needs in order to recognise the pattern, talk about it sensibly, and know where to look when the time comes to use it. The deeper treatments come later, in the chapters where each topic is the main subject. +本节涵盖现实中经常与缓冲 I/O 一起出现的三个主题。每个主题都足够大,可以独自填满一整章;我们不打算那样做。相反,我们将以本书读者识别模式、明智地讨论它、并在需要使用时知道去哪找所需的水平来介绍每个主题。更深入的处理在后面的章节中进行,那里每个主题都是主要主题。 -The three topics are: `d_mmap(9)` for letting user space map a kernel buffer; zero-copy considerations and what they really mean; and the readahead and write-coalescing patterns used by high-throughput drivers. +三个主题是:让用户空间映射内核缓冲区的 `d_mmap(9)`;零拷贝考虑及其真正含义;以及高吞吐量驱动使用的预读和写合并模式。 -### Topic 1: `d_mmap(9)` and Mapping a Kernel Buffer +### 主题 1:`d_mmap(9)` 和映射内核缓冲区 `d_mmap(9)` is the character-device callback that the kernel invokes when a user-space program calls `mmap(2)` on `/dev/myfirst`. The handler's job is to translate a *file offset* into a *physical address* the VM system can map into the user's process. The signature is: @@ -2903,7 +2903,7 @@ first 64 bytes: - 用户空间想要查看或处理大缓冲区中的特定位置而不复制整个内容. - 驱动代表硬件,其寄存器或 DMA 区域可作为内存寻址(例如,GPU 的命令 FIFO). -对于我们的伪设备,`d_mmap` 主要是一个学习练习. Building it teaches you the call signature, the relationship to the VM system, and the `vtophys`/`contigmalloc` distinction. 真正的生产用途在你编写需要吞吐量的驱动时出现. +对于我们的伪设备,`d_mmap` 主要是一个学习练习。构建它教你调用签名、与 VM 系统的关系以及 `vtophys`/`contigmalloc` 的区别。真正的生产用途在你编写需要吞吐量的驱动时出现。 ### 主题 2:零拷贝考虑 @@ -2999,22 +2999,22 @@ first 64 bytes: **步骤:** -1. Create `examples/part-02/ch10-handling-io-efficiently/stage2-circular/`. -2. Copy `cbuf.h` from your userland directory into the new directory. -3. Type the kernel-side `cbuf.c` from Section 3 (this is the `MALLOC_DEFINE`-using version). -4. Copy `myfirst.c` from `examples/part-02/ch09-reading-and-writing/stage3-echo/` into the new directory. -5. Modify `myfirst.c` to use the cbuf abstraction. The changes are: - - Add `#include "cbuf.h"` near the top. - - Replace `char *buf; size_t buflen, bufhead, bufused;` with `struct cbuf cb;` in the softc. - - Update `myfirst_attach` to call `cbuf_init(&sc->cb, MYFIRST_BUFSIZE)`. Update the failure path to call `cbuf_destroy`. - - Update `myfirst_detach` to call `cbuf_destroy(&sc->cb)`. - - Replace `myfirst_read` and `myfirst_write` with the loop-and-bounce versions from Section 3. - - Update the sysctl handlers as in Section 3 (use the `myfirst_sysctl_cb_used` and `myfirst_sysctl_cb_free` helpers). -6. Update the `Makefile` to build both source files: `SRCS= myfirst.c cbuf.c device_if.h bus_if.h`. -7. Build with `make`. Fix any compilation errors. -8. Load with `kldload ./myfirst.ko` and verify with `dmesg | tail`. +1. 创建 `examples/part-02/ch10-handling-io-efficiently/stage2-circular/`。 +2. 从你的用户态目录复制 `cbuf.h` 到新目录。 +3. 按第3节所示输入内核侧 `cbuf.c`(这是使用 `MALLOC_DEFINE` 的版本)。 +4. 从 `examples/part-02/ch09-reading-and-writing/stage3-echo/` 复制 `myfirst.c` 到新目录。 +5. 修改 `myfirst.c` 以使用 cbuf 抽象。更改如下: + - 在顶部附近添加 `#include "cbuf.h"`。 + - 在 softc 中将 `char *buf; size_t buflen, bufhead, bufused;` 替换为 `struct cbuf cb;`。 + - 更新 `myfirst_attach` 以调用 `cbuf_init(&sc->cb, MYFIRST_BUFSIZE)`。更新失败路径以调用 `cbuf_destroy`。 + - 更新 `myfirst_detach` 以调用 `cbuf_destroy(&sc->cb)`。 + - 将 `myfirst_read` 和 `myfirst_write` 替换为第3节的循环和弹跳版本。 + - 按第3节更新 sysctl 处理程序(使用 `myfirst_sysctl_cb_used` 和 `myfirst_sysctl_cb_free` 辅助函数)。 +6. 更新 `Makefile` 以编译两个源文件:`SRCS= myfirst.c cbuf.c device_if.h bus_if.h`。 +7. 用 `make` 构建。修复任何编译错误。 +8. 用 `kldload ./myfirst.ko` 加载并用 `dmesg | tail` 验证。 -**Verification:** +**验证:** ```sh $ printf 'helloworld' > /dev/myfirst @@ -3026,23 +3026,23 @@ $ sysctl dev.myfirst.0.stats.cb_used dev.myfirst.0.stats.cb_used: 0 ``` -**Stretch goal 1:** write enough bytes to wrap the buffer (write 3000 bytes, read 2000, write 2000 again). Verify that `cb_head` is non-zero in `sysctl` and that the data still comes back correctly. +**延伸目标 1:** 写入足够多的字节使缓冲区环绕(写入 3000 字节,读取 2000,再写入 2000)。验证 `sysctl` 中 `cb_head` 非零且数据仍然正确返回。 -**Stretch goal 2:** add a sysctl-controlled debug flag (`myfirst_debug`) and a `MYFIRST_DBG` macro (Section 3 shows the pattern). Use it to log every successful `cbuf_read` and `cbuf_write` in the I/O handlers. Set the flag with `sysctl dev.myfirst.debug=1` and watch `dmesg`. +**延伸目标 2:** 添加一个 sysctl 控制的调试标志(`myfirst_debug`)和一个 `MYFIRST_DBG` 宏(第3节展示了模式)。用它记录 I/O 处理程序中每次成功的 `cbuf_read` 和 `cbuf_write`。用 `sysctl dev.myfirst.debug=1` 设置标志并观察 `dmesg`。 -### Lab 3: The Stage 3 Driver (Blocking and Non-Blocking) +### 实验 3:阶段 3 驱动(阻塞和非阻塞) -**Goal:** Add blocking-on-empty, blocking-on-full, and `EAGAIN` for non-blocking callers. +**目标:** 添加空时阻塞、满时阻塞,以及非阻塞调用者的 `EAGAIN`。 **步骤:** -1. Create `examples/part-02/ch10-handling-io-efficiently/stage3-blocking/` and copy your Stage 2 source into it. -2. Modify `myfirst_read` to add the inner sleep loop (Section 5). The new shape includes the `nbefore = uio->uio_resid` snapshot, the `mtx_sleep` call, and the `wakeup(&sc->cb)` after a successful read. -3. Modify `myfirst_write` to add the symmetric sleep loop and the matching `wakeup(&sc->cb)`. -4. Update `myfirst_detach` to set `sc->is_attached = 0` *before* calling `wakeup(&sc->cb)`, all under the mutex. -5. Build, load, and verify. +1. 创建 `examples/part-02/ch10-handling-io-efficiently/stage3-blocking/` 并将你的阶段 2 源码复制到其中。 +2. 修改 `myfirst_read` 以添加内部睡眠循环(第5节)。新形状包括 `nbefore = uio->uio_resid` 快照、`mtx_sleep` 调用,以及成功读取后的 `wakeup(&sc->cb)`。 +3. 修改 `myfirst_write` 以添加对称的睡眠循环和匹配的 `wakeup(&sc->cb)`。 +4. 更新 `myfirst_detach` 以在调用 `wakeup(&sc->cb)` *之前*设置 `sc->is_attached = 0`,全部在互斥锁下完成。 +5. 构建、加载并验证。 -**Verification:** +**验证:** ```sh $ cat /dev/myfirst & @@ -3056,7 +3056,7 @@ $ kill -INT %1 [1] Interrupt: 2 ``` -**Verification of `EAGAIN`:** +**`EAGAIN` 的验证:** ```sh $ ./rw_myfirst_nb # from the userland directory @@ -3065,29 +3065,29 @@ step 2: poll(POLLIN, 0) = 0 revents=0x0 ... ``` -If step 1 still says `read returned 0`, your `IO_NDELAY` check in `myfirst_read` is missing or wrong. +如果第1步仍然显示 `read returned 0`,你的 `myfirst_read` 中的 `IO_NDELAY` 检查缺失或错误。 -**Stretch goal 1:** open two `cat` processes against `/dev/myfirst` simultaneously. Write 100 bytes from a third terminal. Both `cat`s should wake up; one will get the bytes (whichever wins the race for the lock), the other will block again. You can verify the assignment by tagging each `cat` with a different output stream: `cat /dev/myfirst > /tmp/a &` and `cat /dev/myfirst > /tmp/b &`, then `cmp /tmp/a /tmp/b` (one will be empty). +**延伸目标 1:** 同时打开两个 `cat` 进程对 `/dev/myfirst`。从第三个终端写入 100 字节。两个 `cat` 都应该醒来;一个将获得字节(谁赢得锁的竞争),另一个将再次阻塞。你可以通过给每个 `cat` 标记不同的输出流来验证分配:`cat /dev/myfirst > /tmp/a &` 和 `cat /dev/myfirst > /tmp/b &`,然后 `cmp /tmp/a /tmp/b`(一个将为空)。 -**Stretch goal 2:** time how long `cat /dev/myfirst` takes to wake up after a write, using `time(1)`. The wake-up latency should be in the low microseconds; if it is in milliseconds, something is buffering between the write and the wake (or your machine is heavily loaded). +**延伸目标 2:** 使用 `time(1)` 测量 `cat /dev/myfirst` 在写入后醒来需要多长时间。唤醒延迟应在低微秒范围;如果在毫秒范围,说明写入和唤醒之间有缓冲(或你的机器负载很重)。 -### Lab 4: The Stage 4 Driver (Poll Support and Refactor) +### 实验 4:阶段 4 驱动(Poll 支持和重构) -**Goal:** Add `d_poll`, refactor buffer access into helpers, and document the locking strategy. +**目标:** 添加 `d_poll`,将缓冲区访问重构为辅助函数,并文档化锁定策略。 **步骤:** -1. Create `examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/` and copy your Stage 3 source. -2. Add `struct selinfo rsel; struct selinfo wsel;` to the softc. -3. Implement `myfirst_poll` as in Section 5. -4. Add `selwakeup(&sc->wsel)` after the read's successful `cbuf_read`, and `selwakeup(&sc->rsel)` after the write's successful `cbuf_write`. -5. Add `seldrain(&sc->rsel); seldrain(&sc->wsel);` to detach. -6. Add `.d_poll = myfirst_poll,` to the `cdevsw`. -7. Refactor the I/O handlers to use the four helpers from Section 7 (`myfirst_buf_read`, `myfirst_buf_write`, `myfirst_wait_data`, `myfirst_wait_room`). -8. Add the locking-strategy comment from Section 7. -9. Build, load, and verify. +1. 创建 `examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/` 并复制你的阶段 3 源码。 +2. 向 softc 添加 `struct selinfo rsel; struct selinfo wsel;`。 +3. 按第5节实现 `myfirst_poll`。 +4. 在读取成功 `cbuf_read` 后添加 `selwakeup(&sc->wsel)`,在写入成功 `cbuf_write` 后添加 `selwakeup(&sc->rsel)`。 +5. 在拆离时添加 `seldrain(&sc->rsel); seldrain(&sc->wsel);`。 +6. 向 `cdevsw` 添加 `.d_poll = myfirst_poll,`。 +7. 将 I/O 处理程序重构为使用第7节的四个辅助函数(`myfirst_buf_read`、`myfirst_buf_write`、`myfirst_wait_data`、`myfirst_wait_room`)。 +8. 添加第7节的锁定策略注释。 +9. 构建、加载并验证。 -**Verification:** +**验证:** ```sh $ ./rw_myfirst_nb @@ -3098,24 +3098,24 @@ step 4: poll(POLLIN, 0) = 1 revents=0x41 step 5: read 12 bytes: hello world ``` -The key change from Lab 3 is that step 4 should now return `1` (not `0`), with `revents=0x41` (POLLIN | POLLRDNORM). If it still returns 0, your `selwakeup` call is missing from the write path or the `myfirst_poll` handler is wrong. +与实验 3 的关键区别是第4步现在应该返回 `1`(不是 `0`),且 `revents=0x41`(POLLIN | POLLRDNORM)。如果仍返回 0,你的写入路径中缺少 `selwakeup` 调用或 `myfirst_poll` 处理程序有误。 -**Stretch goal 1:** run `producer_consumer` with `TOTAL_BYTES = 8 * 1024 * 1024` (8 MB) and verify that the test completes with no mismatches. The producer is generating bytes faster than the consumer is reading them, so the buffer should fill up and trigger the blocking path repeatedly. Watch `sysctl dev.myfirst.0.stats.cb_used` in another terminal; it should oscillate. +**延伸目标 1:** 以 `TOTAL_BYTES = 8 * 1024 * 1024`(8 MB)运行 `producer_consumer` 并验证测试完成时无不匹配。生产者生成字节的速度快于消费者读取的速度,因此缓冲区应该填满并反复触发阻塞路径。在另一个终端观察 `sysctl dev.myfirst.0.stats.cb_used`;它应该振荡。 -**Stretch goal 2:** run two `producer_consumer`s in parallel against the same device. The two writers will compete for buffer space; the two readers will compete for bytes. Each pair should still see consistent checksums, but the *interleaving* of bytes will be unpredictable. This shows that the driver is single-stream per device, not per descriptor; if you need per-descriptor streams, that is a different driver design. +**延伸目标 2:** 针对同一设备并行运行两个 `producer_consumer`。两个写入者将竞争缓冲区空间;两个读取者将竞争字节。每对仍应看到一致的校验和,但字节的*交错*将是不可预测的。这表明驱动是每个设备单流,而不是每个描述符;如果你需要每描述符流,那是不同的驱动设计。 -### Lab 5: Memory Mapping +### 实验 5:内存映射 -**Goal:** Add `d_mmap` so user space can map the cbuf read-only. +**目标:** 添加 `d_mmap`,使户空间可以只读映射 cbuf。 **步骤:** -1. Create `examples/part-02/ch10-handling-io-efficiently/stage5-mmap/` and copy your Stage 4 source. -2. Add `myfirst_mmap` from Section 8 to the source. -3. 将 `.d_mmap = myfirst_mmap,` 添加到 `cdevsw`. -4. Build, load, and verify. +1. 创建 `examples/part-02/ch10-handling-io-efficiently/stage5-mmap/` 并复制你的阶段 4 源码。 +2. 将第8节的 `myfirst_mmap` 添加到源码。 +3. 将 `.d_mmap = myfirst_mmap,` 添加到 `cdevsw`。 +4. 构建、加载并验证。 -**Verification:** +**验证:** ```sh $ printf 'ABCDEFGHIJKL' > /dev/myfirst @@ -3124,366 +3124,366 @@ first 64 bytes: 41 42 43 44 45 46 47 48 49 4a 4b 4c 00 00 00 ... ``` -The first twelve bytes are the bytes you wrote. +前十二字节是你写入的字节。 -**Stretch goal 1:** write a small program that maps the buffer and reads bytes from `offset = sc->cb_size - 32` (i.e. the last 32 bytes). Verify that the program does not crash. Then write enough bytes to push the buffer head into the wrap region and read from the same offset. The contents will be different, because the *raw* bytes in memory are not the same as the *live* bytes from the cbuf's perspective. +**延伸目标 1:** 编写一个小程序映射缓冲区并从 `offset = sc->cb_size - 32`(即最后 32 字节)读取。验证程序不会崩溃。然后写入足够多的字节将缓冲区头部推入环绕区域并从相同偏移读取。内容将不同,因为内存中的*原始*字节与 cbuf 视角的*活跃*字节不同。 -**Stretch goal 2:** try to map the buffer with `PROT_WRITE`. Your program should see `mmap` fail with `EACCES`, because the driver refuses writable mappings. +**延伸目标 2:** 尝试用 `PROT_WRITE` 映射缓冲区。你的程序应该看到 `mmap` 因 `EACCES` 失败,因为驱动拒绝可写映射。 -### Lab 6: Stress and Long-Running Tests +### 实验 6:压力和长时间运行测试 -**Goal:** Run the driver under sustained load for at least an hour without errors. +**目标:** 在持续负载下运行驱动至少一小时而不出错。 **步骤:** -1. Set up four parallel test processes: +1. 设置四个并行测试进程: - `dd if=/dev/zero of=/dev/myfirst bs=4k 2>/dev/null &` - `dd if=/dev/myfirst of=/dev/null bs=4k 2>/dev/null &` - `./producer_consumer` - - A loop that polls `sysctl dev.myfirst.0.stats` every 5 seconds. -2. Let the test run for at least an hour. -3. Check `dmesg` for any kernel warnings, panics, or `WITNESS` complaints. Check `vmstat -m | grep cbuf` to confirm no leak. Verify that `producer_consumer` reports zero mismatches. + - 一个每 5 秒轮询 `sysctl dev.myfirst.0.stats` 的循环。 +2. 让测试运行至少一小时。 +3. 检查 `dmesg` 中是否有任何内核警告、恐慌或 `WITNESS` 投诉。检查 `vmstat -m | grep cbuf` 确认没有泄漏。验证 `producer_consumer` 报告零不匹配。 -**Verification:** No kernel warnings. No memory growth in `vmstat`. `producer_consumer` returns 0. +**验证:** 无内核警告。`vmstat` 中无内存增长。`producer_consumer` 返回 0。 -**Stretch goal:** run the same test under a `WITNESS`-enabled debug kernel. The kernel will be slower but will catch any locking-discipline violations. If your driver is correct, no warnings should appear. +**延伸目标:** 在启用 `WITNESS` 的调试内核下运行相同的测试。内核会更慢但会捕获任何锁定纪律违规。如果你的驱动正确,不应出现任何警告。 -### Lab 7: Deliberate Failures +### 实验 7:故意制造故障 -**Goal:** Break the driver in three specific ways and observe what happens. This lab teaches you to recognise the failure modes you most want to avoid. +**目标:** 以三种特定方式破坏驱动并观察发生什么。本实验教你识别你最想避免的故障模式。 -**Steps for failure 1: hold the lock across `uiomove`.** +**故障 1 的步骤:跨 `uiomove` 持有锁。** -1. Edit your Stage 4 driver. In `myfirst_read`, comment out the `mtx_unlock(&sc->mtx)` that comes before `uiomove(bounce, got, uio)`. -2. Add a matching `mtx_unlock` after the `uiomove` so the code still compiles. -3. Build and load on a `WITNESS`-enabled kernel. -4. Run a single `cat /dev/myfirst` and write some bytes from another terminal. +1. 编辑你的阶段 4 驱动。在 `myfirst_read` 中,注释掉 `uiomove(bounce, got, uio)` 之前的 `mtx_unlock(&sc->mtx)`。 +2. 在 `uiomove` 之后添加匹配的 `mtx_unlock`,使代码仍能编译。 +3. 在启用 `WITNESS` 的内核上构建并加载。 +4. 运行一个 `cat /dev/myfirst` 并从另一个终端写入一些字节。 -**What you should observe:** A `WITNESS` warning in `dmesg` complaining about "sleeping with mutex held". The system may continue running but the warning is the bug. +**你应该观察到的:** `dmesg` 中一条关于"sleeping with mutex held"的 `WITNESS` 警告。系统可能继续运行但警告就是 bug。 -**Cleanup:** restore the original code. +**清理:** 恢复原始代码。 -**Steps for failure 2: forget the `wakeup` after a write.** +**故障 2 的步骤:忘记写入后的 `wakeup`。** -1. In `myfirst_write`, comment out `wakeup(&sc->cb)`. -2. Build and load. -3. Run `cat /dev/myfirst &` and `echo hi > /dev/myfirst`. +1. 在 `myfirst_write` 中,注释掉 `wakeup(&sc->cb)`。 +2. 构建并加载。 +3. 运行 `cat /dev/myfirst &` 和 `echo hi > /dev/myfirst`。 -**What you should observe:** The `cat` does not wake up. It will sit in `myfrd` state forever (or until you interrupt it with Ctrl-C). +**你应该观察到的:** `cat` 不会醒来。它将永远停留在 `myfrd` 状态(直到你用 Ctrl-C 中断它)。 -**Cleanup:** restore the wakeup. Verify that `cat` now wakes up immediately. +**清理:** 恢复 wakeup。验证 `cat` 现在立即醒来。 -**Steps for failure 3: missing `PCATCH`.** +**故障 3 的步骤:缺少 `PCATCH`。** -1. In `myfirst_wait_data`, change `PCATCH` to `0` in the `mtx_sleep` call. -2. Build and load. -3. Run `cat /dev/myfirst &` and try `kill -INT %1`. +1. 在 `myfirst_wait_data` 中,将 `mtx_sleep` 调用中的 `PCATCH` 改为 `0`。 +2. 构建并加载。 +3. 运行 `cat /dev/myfirst &` 并尝试 `kill -INT %1`。 -**What you should observe:** The `cat` does not respond to Ctrl-C until you write some bytes to wake it. With `PCATCH`, the signal would interrupt the sleep immediately. +**你应该观察到的:** `cat` 不响应 Ctrl-C,直到你写入一些字节唤醒它。有了 `PCATCH`,信号会立即中断睡眠。 -**Cleanup:** restore `PCATCH`. Verify that `kill -INT` works as expected. +**清理:** 恢复 `PCATCH`。验证 `kill -INT` 按预期工作。 -These three failures are the most common driver bugs in this chapter's territory. Doing them deliberately, once, is the best way to recognise them when they happen accidentally. +这三种故障是本章领域中最常见的驱动 bug。故意做一次,是在它们意外发生时识别它们的最佳方式。 -### Lab 8: Reading Real FreeBSD Drivers +### 实验 8:阅读真实的 FreeBSD 驱动 -**Goal:** Read three character-device drivers in `/usr/src/sys/dev/` and identify how each implements its buffer, sleep, and poll patterns. +**目标:** 阅读 `/usr/src/sys/dev/` 中的三个字符设备驱动并识别每个如何实现其缓冲区、睡眠和 poll 模式。 **步骤:** -1. Read `/usr/src/sys/dev/evdev/cdev.c`. Identify: - - Where the per-client ring buffer is allocated. - - Where the read handler blocks (look for `mtx_sleep`). - - How `EVDEV_CLIENT_EMPTYQ` is implemented. - - How `kqueue` is set up alongside `select/poll` (we have not done `kqueue` yet; just notice the calls to `knlist_*`). -2. Read `/usr/src/sys/dev/random/randomdev.c`. Identify: - - Where `randomdev_poll` is defined. - - How it handles a not-yet-seeded random device. -3. Read `/usr/src/sys/dev/null/null.c`. Identify: - - How `zero_read` loops over `uio_resid`. - - Why there is no buffer, no sleep, and no poll handler. +1. 阅读 `/usr/src/sys/dev/evdev/cdev.c`。识别: + - 每客户端环形缓冲区在哪里分配。 + - 读取处理程序在哪里阻塞(寻找 `mtx_sleep`)。 + - `EVDEV_CLIENT_EMPTYQ` 如何实现。 + - `kqueue` 如何与 `select/poll` 一起设置(我们还没有做 `kqueue`;只需注意 `knlist_*` 调用)。 +2. 阅读 `/usr/src/sys/dev/random/randomdev.c`。识别: + - `randomdev_poll` 在哪里定义。 + - 它如何处理尚未种子的随机设备。 +3. 阅读 `/usr/src/sys/dev/null/null.c`。识别: + - `zero_read` 如何循环 `uio_resid`。 + - 为什么没有缓冲区、没有睡眠、没有 poll 处理程序。 **检查点问题:** -- Why does `evdev`'s read handler use `mtx_sleep` while `null`'s does not? -- What would `randomdev`'s poll handler return if called while the device is unseeded? -- How does `evdev` detect that a client has been disconnected (revoked)? +- 为什么 `evdev` 的读取处理程序使用 `mtx_sleep` 而 `null` 的不使用? +- 如果在设备未种子时调用 `randomdev` 的 poll 处理程序会返回什么? +- `evdev` 如何检测客户端已断开连接(撤销)? -The point of this lab is not to memorise these drivers. It is to confirm that the patterns you have built in `myfirst` are the same patterns the kernel uses elsewhere. By the end of the lab you should feel that the rest of `dev/` is largely *legible* now, where it might have looked impenetrable two chapters ago. +本实验的重点不是记住这些驱动。而是确认你在 `myfirst` 中构建的模式与内核其他地方使用的模式相同。到实验结束时,你应该感到 `dev/` 的其余部分现在基本上是*可读的*,而两章前它可能看起来不可渗透。 ## 挑战练习 -The labs above ensure you have a working driver and a working test kit. The challenges below are stretch exercises. Each one extends the chapter's material in a useful direction, and each one rewards careful work. Take your time; some of them are more involved than they look. +上面的实验确保你有一个工作的驱动和测试套件。下面的挑战是延伸练习。每个都沿着有用的方向扩展本章材料,每个都奖励仔细的工作。慢慢来;有些比看起来更复杂。 -### Challenge 1: Add a Tunable Buffer Size +### 挑战 1:添加可调缓冲区大小 -The `MYFIRST_BUFSIZE` macro hard-codes the buffer at 4 KB. Make it configurable. +`MYFIRST_BUFSIZE` 宏将缓冲区硬编码为 4 KB。让它可配置。 -- Add a `TUNABLE_INT("hw.myfirst.bufsize", &myfirst_bufsize)` and a matching `SYSCTL_INT(_hw_myfirst, OID_AUTO, bufsize, ...)` so the user can set the buffer size at module load time. -- Use the value in `myfirst_attach` to size the cbuf. -- Validate the value (reject zero, reject sizes larger than 1 MB, fall back to a sensible default if the input is bad). -- Verify with `kenv hw.myfirst.bufsize=8192; kldload ./myfirst.ko; sysctl dev.myfirst.0.stats.cb_size`. +- 添加一个 `TUNABLE_INT("hw.myfirst.bufsize", &myfirst_bufsize)` 和匹配的 `SYSCTL_INT(_hw_myfirst, OID_AUTO, bufsize, ...)`,这样用户可以在模块加载时设置缓冲区大小。 +- 在 `myfirst_attach` 中使用该值来调整 cbuf 大小。 +- 验证该值(拒绝零、拒绝大于 1 MB 的大小、如果输入不好则回退到合理默认值)。 +- 用 `kenv hw.myfirst.bufsize=8192; kldload ./myfirst.ko; sysctl dev.myfirst.0.stats.cb_size` 验证。 -**Stretch:** make the buffer size *runtime-tunable* via `sysctl`. This is harder than the load-time tunable because it requires safely reallocating the cbuf while the device may be in use; you will need to drain or copy existing bytes, take and release the lock at the right moments, and decide what to do with sleeping callers. (Hint: it may be easier to require that all descriptors be closed before allowing a runtime resize.) +**延伸:** 通过 `sysctl` 使缓冲区大小*运行时可调*。这比加载时可调更难,因为它需要在设备可能正在使用时安全地重新分配 cbuf;你需要排空或复制现有字节、在正确时刻获取和释放锁、并决定如何处理睡眠中的调用者。(提示:可能更容易要求所有描述符在允许运行时调整大小之前关闭。) -### Challenge 2: Implement Overwrite Semantics as an Optional Mode +### 挑战 2:实现覆盖语义作为可选模式 -Add an `ioctl(2)` (or, simpler for now, a `sysctl`) that switches the buffer between "block on full" mode (the default) and "overwrite oldest on full" mode. In overwrite mode, `myfirst_write` always succeeds: when `cbuf_free` is zero, the driver advances `cb_head` to make room and then writes the new bytes. +添加一个 `ioctl(2)`(或者,现在更简单的,一个 `sysctl`),在"满时阻塞"模式(默认)和"满时覆盖最旧"模式之间切换缓冲区。在覆盖模式下,`myfirst_write` 总是成功:当 `cbuf_free` 为零时,驱动推进 `cb_head` 腾出空间然后写入新字节。 -- Add a `cbuf_overwrite` function alongside `cbuf_write` that implements the overwrite semantics. Do not modify `cbuf_write`; the two should be siblings. -- Add a sysctl `dev.myfirst.0.overwrite_mode` (read-write integer, 0 or 1). -- In `myfirst_write`, dispatch to `cbuf_overwrite` if the flag is set. -- Test with a small writer that produces bytes faster than the reader consumes; in overwrite mode, the reader should see the most recent bytes only, while in normal mode the writer blocks. +- 在 `cbuf_write` 旁边添加一个 `cbuf_overwrite` 函数来实现覆盖语义。不要修改 `cbuf_write`;两者应该是兄弟关系。 +- 添加一个 sysctl `dev.myfirst.0.overwrite_mode`(读写整数,0 或 1)。 +- 在 `myfirst_write` 中,如果标志被设置则分派到 `cbuf_overwrite`。 +- 用一个比读取者产生字节更快的写入者测试;在覆盖模式下,读取者应该只看到最近的字节,而在正常模式下写入者阻塞。 -**Stretch:** add a counter for the number of bytes overwritten (lost). Expose it as a sysctl so the user can see how much data has been dropped. +**延伸:** 为被覆盖(丢失)的字节数添加一个计数器。将其暴露为 sysctl,以便用户可以看到丢失了多少数据。 -### Challenge 3: Per-Reader Position +### 挑战 3:每读取者位置 -The current driver has one shared read position (`cb_head`). When two readers consume bytes, each `read(2)` call drains some bytes from the buffer; the two readers split the stream between them. Some drivers want the opposite: each reader should see *every* byte, so two readers each get the full stream independently. +当前驱动有一个共享的读取位置(`cb_head`)。当两个读取者消耗字节时,每次 `read(2)` 调用从缓冲区排空一些字节;两个读取者之间分割流。一些驱动想要相反:每个读取者应该看到*每个*字节,这样两个读取者各自独立获得完整流。 -This is a substantial refactor: +这是一个实质性的重构: -- Maintain a per-descriptor read position in `myfirst_fh`. -- Track the global "earliest live byte" across all descriptors. The cbuf's effective `head` becomes `min(per_fh_head)`. -- `myfirst_read` advances only the per-descriptor position; `cbuf_read` is replaced by a per-fh equivalent. -- A new descriptor opened mid-stream sees only bytes written after its open. -- When the buffer is "full" depends on the slowest descriptor; you need backpressure logic that accounts for laggards. +- 在 `myfirst_fh` 中维护每描述符的读取位置。 +- 跟踪所有描述符的全局"最早活跃字节"。cbuf 的有效 `head` 变为 `min(per_fh_head)`。 +- `myfirst_read` 只推进每描述符位置;`cbuf_read` 被每 fh 的等价物替换。 +- 在流中途打开的新描述符只看到打开后写入的字节。 +- 缓冲区何时"满"取决于最慢的描述符;你需要考虑落后者的反压逻辑。 -This challenge is harder than it sounds; it is essentially building a multicast pipe. Try it only if you have time to think through the locking carefully. +这个挑战比听起来更难;它本质上是构建一个多播管道。只有在你有时间仔细思考锁定时才尝试。 -### Challenge 4: Implement `d_kqfilter` +### 挑战 4:实现 `d_kqfilter` -Add `kqueue(2)` support alongside the `d_poll` you already have. +在你已有的 `d_poll` 旁边添加 `kqueue(2)` 支持。 -- Implement a `myfirst_kqfilter` function dispatched from `cdevsw->d_kqfilter`. -- For `EVFILT_READ`, register a filter that becomes ready when `cbuf_used > 0`. -- For `EVFILT_WRITE`, register a filter that becomes ready when `cbuf_free > 0`. -- Use `knlist_add(9)` and `knlist_remove(9)` to manage the per-filter list. -- Trigger `KNOTE_LOCKED(...)` from the I/O handlers when the buffer transitions. -- Test with a small `kqueue(2)` user program that opens the device, registers `EVFILT_READ`, calls `kevent(2)`, and reports when the descriptor becomes readable. +- 实现一个从 `cdevsw->d_kqfilter` 分派的 `myfirst_kqfilter` 函数。 +- 对于 `EVFILT_READ`,注册一个在 `cbuf_used > 0` 时变为就绪的过滤器。 +- 对于 `EVFILT_WRITE`,注册一个在 `cbuf_free > 0` 时变为就绪的过滤器。 +- 使用 `knlist_add(9)` 和 `knlist_remove(9)` 管理每过滤器列表。 +- 当缓冲区转换时从 I/O 处理程序触发 `KNOTE_LOCKED(...)`。 +- 用一个小型 `kqueue(2)` 用户程序测试,该程序打开设备、注册 `EVFILT_READ`、调用 `kevent(2)`、并报告描述符何时变为可读。 -This challenge is the natural extension of Stage 4. It also previews the `kqueue` material that Chapter 11 will discuss in more depth alongside concurrency. +这个挑战是阶段 4 的自然延伸。它也预览了第11章将与并发一起更深入讨论的 `kqueue` 材料。 -### Challenge 5: Per-CPU Counters +### 挑战 5:每 CPU 计数器 -The `bytes_read` and `bytes_written` counters are updated under the mutex. Under heavy multi-CPU load, this can become a contention point. FreeBSD's `counter(9)` API provides per-CPU counters that can be incremented without a lock and summed for read access. +`bytes_read` 和 `bytes_written` 计数器在互斥锁下更新。在重度多 CPU 负载下,这可能成为竞争点。FreeBSD 的 `counter(9)` API 提供每 CPU 计数器,可以无锁递增并求和用于读取访问。 -- Replace `sc->bytes_read` and `sc->bytes_written` with `counter_u64_t` instances. -- Allocate them with `counter_u64_alloc(M_WAITOK)` in attach; free them with `counter_u64_free` in detach. -- Use `counter_u64_add(counter, n)` to increment. -- Use `counter_u64_fetch(counter)` (with a sysctl handler) to read. +- 将 `sc->bytes_read` 和 `sc->bytes_written` 替换为 `counter_u64_t` 实例。 +- 在 attach 中用 `counter_u64_alloc(M_WAITOK)` 分配;在 detach 中用 `counter_u64_free` 释放。 +- 使用 `counter_u64_add(counter, n)` 递增。 +- 使用 `counter_u64_fetch(counter)`(通过 sysctl 处理程序)读取。 -**Stretch:** measure the difference. Run `producer_consumer` against the old and new versions and compare wall-clock time. With a small test the difference will be invisible; with a heavily threaded test (multiple producers and consumers) the per-CPU version should be measurably faster. +**延伸:** 测量差异。对旧版本和新版本运行 `producer_consumer` 并比较挂钟时间。小型测试的差异将不可见;重度线程测试(多个生产者和消费者)下每 CPU 版本应该明显更快。 -### Challenge 6: A Hardware-Style Interrupt Simulator +### 挑战 6:硬件风格中断模拟器 -Real driver buffers are usually filled by an interrupt handler, not by a `write(2)` syscall. Simulate this: +真正的驱动缓冲区通常由中断处理程序填充,而不是由 `write(2)` 系统调用。模拟这一点: -- Use `callout(9)` (Chapter 13 covers it; you can read ahead) to run a callback every 100 ms. -- The callback writes a small piece of data into the cbuf (for example, the current time as a string). -- The user reads from `/dev/myfirst` and sees a stream of timestamped lines. +- 使用 `callout(9)`(第13章涵盖它;你可以提前阅读)每 100 毫秒运行一个回调。 +- 回调向 cbuf 写入一小段数据(例如,当前时间作为字符串)。 +- 用户从 `/dev/myfirst` 读取并看到带时间戳的行流。 -This challenge previews Chapter 13's deferred-execution material and shows how the same buffer abstraction supports either a syscall-driven producer or a kernel-thread-driven producer. +这个挑战预览了第13章的延迟执行材料,并展示相同的缓冲区抽象如何支持系统调用驱动的生产者或内核线程驱动的生产者。 -### Challenge 7: A Logging Buffer with `dmesg`-Style Behaviour +### 挑战 7:具有 `dmesg` 风格行为的日志缓冲区 -Build a second character device, `/dev/myfirst_log`, that uses an overwrite-mode cbuf to keep a circular log of recent driver events. Every `MYFIRST_DBG` macro call would write into this log instead of (or in addition to) calling `device_printf`. +构建第二个字符设备 `/dev/myfirst_log`,使用覆盖模式的 cbuf 保持最近驱动事件的循环日志。每个 `MYFIRST_DBG` 宏调用将写入此日志而不是(或附加于)调用 `device_printf`。 -- Use a separate `struct cbuf` in the softc. -- Provide a way for the kernel side to push lines into the log (`myfirst_log_printf(sc, fmt, ...)`). -- The user can `cat /dev/myfirst_log` to see the recent N lines. -- A new line that overflows the buffer evicts the oldest line, not just the oldest byte (this requires line-aware eviction logic). +- 在 softc 中使用单独的 `struct cbuf`。 +- 为内核侧提供向日志推入行的方式(`myfirst_log_printf(sc, fmt, ...)`)。 +- 用户可以 `cat /dev/myfirst_log` 查看最近的 N 行。 +- 溢出缓冲区的新行驱逐最旧的行,而不是最旧的字节(这需要行感知的驱逐逻辑)。 -This challenge introduces a fairly common driver pattern (a private debug log) and gives you practice with a second, independently designed buffer use case in the same module. +这个挑战引入了一个相当常见的驱动模式(私有调试日志),并让你在同一模块中练习第二个独立设计的缓冲区用例。 -### Challenge 8: Performance Measurement +### 挑战 8:性能测量 -Build a measurement harness that times the throughput of the driver across the four stages. +构建一个测量工具,对四个阶段的驱动吞吐量进行计时。 -- Write a small C program that opens the device, writes 100 MB of data, and times the operation. -- Mirror it with a reader that drains 100 MB and times itself. -- Run the pair against Stage 2, Stage 3, and Stage 4 of the chapter, and produce a small table of throughput numbers. -- Identify which stage is slowest and explain why. +- 编写一个小型 C 程序,打开设备、写入 100 MB 数据,并对操作计时。 +- 用一个排空 100 MB 并为自己计时的读取者镜像它。 +- 针对阶段 2、阶段 3 和阶段 4 运行这对程序,并生成一个小的吞吐量数字表。 +- 识别哪个阶段最慢并解释原因。 -The expected answer is "Stage 3 is slower than Stage 2 because of the extra `wakeup` and `selwakeup` calls per iteration; Stage 4 is similar to Stage 3 within measurement noise". But the actual numbers are interesting and may surprise you, depending on your CPU, memory bandwidth, and system load. +预期答案是"阶段 3 比阶段 2 慢,因为每次迭代有额外的 `wakeup` 和 `selwakeup` 调用;阶段 4 在测量噪声内与阶段 3 相似"。但实际数字很有趣,可能令你惊讶,取决于你的 CPU、内存带宽和系统负载。 -**Stretch:** profile the driver under load with `pmcstat(8)` and identify the top three functions by CPU time. If `uiomove` is in the top three, you have validated the discussion in Section 8 about zero-copy. If `mtx_lock` is in the top three, you have a contention problem that Chapter 11's locking material will address. +**延伸:** 用 `pmcstat(8)` 在负载下分析驱动并识别按 CPU 时间排前三的函数。如果 `uiomove` 在前三,你验证了第8节关于零拷贝的讨论。如果 `mtx_lock` 在前三,你有一个第11章锁定材料将解决的竞争问题。 -### Challenge 9: Cross-Reading Real Drivers +### 挑战 9:交叉阅读真实驱动 -Pick three drivers in `/usr/src/sys/dev/` that you have not read before. For each one, identify: +在 `/usr/src/sys/dev/` 中选择三个你之前没有读过的驱动。对每一个,识别: -- Where the buffer is allocated and freed. -- Whether it is a circular buffer, a queue, or a different shape. -- What protects it (mutex, sx, lock-free, none). -- How `read` and `write` handlers consume from or produce into it. -- How `select`/`poll`/`kqueue` integrate with the buffer state changes. +- 缓冲区在哪里分配和释放。 +- 它是循环缓冲区、队列还是其他形状。 +- 什么保护它(互斥锁、sx、无锁、无)。 +- `read` 和 `write` 处理程序如何从中消费或向其生产。 +- `select`/`poll`/`kqueue` 如何与缓冲区状态变化集成。 -Suggested starting points: `/usr/src/sys/dev/iicbus/iiconf.c` (different category but uses some of the same primitives) and `/usr/src/sys/fs/cuse/cuse.c` (a driver that exposes its buffer to user space). You will see variations on the same themes you have just built. +建议的起点:`/usr/src/sys/dev/iicbus/iiconf.c`(不同类别但使用一些相同的原语)和 `/usr/src/sys/fs/cuse/cuse.c`(一个向用户空间暴露缓冲区的驱动)。你将看到你刚刚构建的相同主题的变体。 -### Challenge 10: Document Your Driver +### 挑战 10:文档化你的驱动 -Write a one-page README in your `examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/` directory. The README should cover: +在你的 `examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/` 目录中编写一页 README。README 应涵盖: -- What the driver does. -- How to build it (`make`). -- How to load and unload (`kldload`, `kldunload`). -- The user-space interface: device path, mode, reader/writer expectations, blocking behaviour. -- What the sysctls expose. -- How to enable debug logging. -- A reference to the chapter that produced it. +- 驱动做什么。 +- 如何构建(`make`)。 +- 如何加载和卸载(`kldload`、`kldunload`)。 +- 用户空间接口:设备路径、模式、读取者/写入者期望、阻塞行为。 +- sysctl 暴露什么。 +- 如何启用调试日志。 +- 对产生它的章节的引用。 -Documentation is the part of driver work most often skipped. A driver that only its author understands is a maintenance liability. Even a one-page README that explains the basics makes the difference between code that survives a hand-off and code that does not. +文档化是驱动工作中最常被跳过的部分。只有作者理解的驱动是维护负担。即使一页解释基础的 README 也决定了代码是否能在交接中存活。 -## Troubleshooting and Common Mistakes +## 故障排除和常见错误 -Most of the bugs that appear in this chapter's territory cluster into a small number of categories. The list below catalogues the categories, the symptoms each one produces, and the fix. Read it once before you work through the labs; come back to it when something goes wrong. +本章领域中出现的大多数 bug 聚集在少数几个类别中。下面的列表分类了这些类别、每个产生的症状以及修复方法。在做实验之前读一遍;出问题时再回来查看。 -### Symptom: `cat /dev/myfirst` blocks forever, even after `echo` writes data +### 症状:`cat /dev/myfirst` 永远阻塞,即使 `echo` 写入了数据 -**Cause.** The write handler is not calling `wakeup(&sc->cb)` after a successful `cbuf_write`. The reader is asleep on the channel `&sc->cb`; without a matching `wakeup`, it will never return. +**原因。** 写入处理程序在成功 `cbuf_write` 后没有调用 `wakeup(&sc->cb)`。读取者在通道 `&sc->cb` 上睡眠;没有匹配的 `wakeup`,它永远不会返回。 -**Fix.** Add `wakeup(&sc->cb)` after every state-changing operation that might unblock a waiter. In `myfirst_write`, that means after the `cbuf_write` call. In `myfirst_read`, that means after the `cbuf_read` call (which may unblock a waiting writer). +**修复。** 在每个可能解除等待者阻塞的状态改变操作后添加 `wakeup(&sc->cb)`。在 `myfirst_write` 中,这意味着在 `cbuf_write` 调用之后。在 `myfirst_read` 中,这意味着在 `cbuf_read` 调用之后(可能解除等待写入者的阻塞)。 -**How to verify.** Run `ps -AxH -o pid,wchan,command | grep cat`. If the `wchan` column shows `myfrd` (or whatever wmesg you used), the reader is sleeping. The channel address you slept on must match the channel address you wake. +**如何验证。** 运行 `ps -AxH -o pid,wchan,command | grep cat`。如果 `wchan` 列显示 `myfrd`(或你使用的任何 wmesg),读取者正在睡眠。你睡眠的通道地址必须与你唤醒的通道地址匹配。 -### Symptom: Data corruption under heavy load +### 症状:重负载下数据损坏 -**Cause.** Almost always a wrap-around bug or a missing lock around the cbuf access. Either the cbuf's internal arithmetic is wrong, or two threads are touching it concurrently without synchronization. +**原因。** 几乎总是环绕 bug 或 cbuf 访问周围缺少锁。要么 cbuf 的内部算术有误,要么两个线程在没有同步的情况下同时触及它。 -**Fix.** Re-read the cbuf source carefully. Run the userland `cb_test` against your current `cbuf.c` (compile it directly with `cc`). If the userland tests pass, the problem is in the driver's locking, not in the cbuf. Check that every `cbuf_*` call is bracketed by `mtx_lock` and `mtx_unlock`. Use `INVARIANTS` and `WITNESS` in your kernel config to catch violations. +**修复。** 仔细重读 cbuf 源码。用你当前的 `cbuf.c` 运行用户态 `cb_test`(直接用 `cc` 编译)。如果用户态测试通过,问题在驱动的锁定中,不在 cbuf 中。检查每个 `cbuf_*` 调用是否由 `mtx_lock` 和 `mtx_unlock` 包围。在内核配置中使用 `INVARIANTS` 和 `WITNESS` 捕获违规。 -**How to verify.** Run `producer_consumer` with a known checksum. If the checksums match but mismatches are reported, the data is being reordered (a wrap-around bug). If the checksums differ, bytes are being lost or duplicated (a locking bug). +**如何验证。** 用已知校验和运行 `producer_consumer`。如果校验和匹配但报告了不匹配,数据正在被重新排序(环绕 bug)。如果校验和不同,字节正在丢失或重复(锁定 bug)。 -### Symptom: Kernel panic with "sleeping with mutex held" +### 症状:内核恐慌 "sleeping with mutex held" -**Cause.** You called `uiomove(9)`, `copyin(9)`, `copyout(9)`, or another sleeping function while holding `sc->mtx`. The sleeping function tried to fault on user memory, and the page-fault handler tried to sleep, but holding a non-sleepable mutex during a sleep is forbidden. +**原因。** 你在持有 `sc->mtx` 时调用了 `uiomove(9)`、`copyin(9)`、`copyout(9)` 或其他睡眠函数。睡眠函数尝试对用户内存进行页面故障处理,页面故障处理程序尝试睡眠,但在睡眠期间持有不可睡眠互斥锁是被禁止的。 -**Fix.** Release the mutex before any call that might sleep. The Stage 4 handlers do this carefully: lock to access the cbuf, unlock to call `uiomove`, lock again to update state. +**修复。** 在任何可能睡眠的调用之前释放互斥锁。阶段 4 处理程序仔细地做到了这一点:锁定访问 cbuf、解锁调用 `uiomove`、再次锁定更新状态。 -**How to verify.** A `WITNESS`-enabled kernel will print a warning before panicking. The warning identifies the mutex and the sleeping function. The first time this happens, copy the message into a debug log so you can find the call site. +**如何验证。** 启用 `WITNESS` 的内核会在恐慌之前打印警告。警告标识互斥锁和睡眠函数。第一次发生时,将消息复制到调试日志中以便找到调用位置。 -### Symptom: `EAGAIN` is returned even when data is available +### 症状:即使有可用数据也返回 `EAGAIN` -**Cause.** The handler is checking the wrong flag, or it is checking the flag in the wrong place in the loop. Two common variants: checking `ioflag & O_RDONLY` instead of `ioflag & IO_NDELAY`, or returning `EAGAIN` after some bytes have already been transferred (which is the rule from Section 4 you must not break). +**原因。** 处理程序检查了错误的标志,或者在循环中错误的位置检查标志。两种常见变体:检查 `ioflag & O_RDONLY` 而不是 `ioflag & IO_NDELAY`,或者已经传输了一些字节后返回 `EAGAIN`(这是第4节的规则,你不能违反)。 -**Fix.** Re-read Section 5's handler code carefully. The `EAGAIN` path is inside the inner `while (cbuf_used(&sc->cb) == 0)` loop, after the `nbefore` check, only when `ioflag & IO_NDELAY` is non-zero. +**修复。** 仔细重读第5节的处理程序代码。`EAGAIN` 路径在内部 `while (cbuf_used(&sc->cb) == 0)` 循环中,在 `nbefore` 检查之后,只有当 `ioflag & IO_NDELAY` 非零时。 -**How to verify.** Run `rw_myfirst_nb`. Step 5 should successfully read the bytes. If it shows `EAGAIN`, the bug is at one of the two locations above. +**如何验证。** 运行 `rw_myfirst_nb`。第5步应该成功读取字节。如果显示 `EAGAIN`,bug 在上述两个位置之一。 -### Symptom: A write succeeds but a subsequent read gets fewer bytes +### 症状:写入成功但后续读取获得更少字节 -**Cause.** The byte counter is being updated incorrectly, or the cbuf is being modified outside the handlers. A specific failure mode: counting `want` bytes as written when `cbuf_write` only stored `put` bytes (a race in Stage 2 between the cbuf_free check and the cbuf_write call, even though it is not exercised in single-writer use). +**原因。** 字节计数器更新不正确,或 cbuf 在处理程序之外被修改。特定失败模式:当 `cbuf_write` 只存储了 `put` 字节时,将 `want` 字节计为已写入(阶段 2 中 cbuf_free 检查和 cbuf_write 调用之间的竞争,虽然在单写入者使用中不会被触发)。 -**Fix.** Look at the `bytes_written += put` line in `myfirst_write`; it must use the actual return value of `cbuf_write`, not the requested size. Compare `sc->bytes_written` and `sc->bytes_read` over time; they should differ by at most `cbuf_size`. +**修复。** 查看 `myfirst_write` 中的 `bytes_written += put` 行;它必须使用 `cbuf_write` 的实际返回值,而不是请求的大小。比较 `sc->bytes_written` 和 `sc->bytes_read` 随时间的变化;它们最多应该相差 `cbuf_size`。 -**How to verify.** Add a log line: `device_printf(dev, "wrote %zu of %zu\n", put, want);`. If `put != want` ever appears in `dmesg`, you have found the discrepancy. +**如何验证。** 添加日志行:`device_printf(dev, "wrote %zu of %zu\n", put, want);`。如果 `put != want` 出现在 `dmesg` 中,你找到了差异。 -### Symptom: `kldunload` returns `EBUSY` +### 症状:`kldunload` 返回 `EBUSY` -**Cause.** Some descriptor is still open against the device. The detach refuses to proceed when `active_fhs > 0`. +**原因。** 某个描述符仍然对设备打开。拆离在 `active_fhs > 0` 时拒绝继续。 -**Fix.** Find the process that holds the descriptor open and close it. `fstat | grep myfirst` lists the offending processes. `kill` them if necessary. +**修复。** 找到持有描述符打开的进程并关闭它。`fstat | grep myfirst` 列出有问题的进程。必要时 `kill` 它们。 -**How to verify.** After closing all descriptors (or killing the offending processes), `sysctl dev.myfirst.0.stats.active_fhs` should drop to zero. `kldunload myfirst` should then succeed. +**如何验证。** 关闭所有描述符(或终止有问题的进程)后,`sysctl dev.myfirst.0.stats.active_fhs` 应该降至零。`kldunload myfirst` 应该随后成功。 -### Symptom: Memory growth in `vmstat -m | grep cbuf` +### 症状:`vmstat -m | grep cbuf` 中内存增长 -**Cause.** The driver is allocating without freeing. Either the attach failure path forgot to call `cbuf_destroy`, or the detach path forgot, or there is more than one cbuf being allocated per attach. +**原因。** 驱动在分配后没有释放。要么 attach 失败路径忘记调用 `cbuf_destroy`,要么 detach 路径忘记了,或者每次 attach 分配了多个 cbuf。 -**Fix.** Audit every code path that calls `cbuf_init`. Each call must be matched by exactly one `cbuf_destroy` call before the surrounding context goes away. The standard idiom is to put `cbuf_init` near the top of `attach` and `cbuf_destroy` near the bottom of `detach`, with the failure-path `goto fail_*` chain calling `cbuf_destroy` if attach fails after `cbuf_init`. +**修复。** 审计每个调用 `cbuf_init` 的代码路径。每个调用必须在周围上下文消失之前恰好被一个 `cbuf_destroy` 调用匹配。标准习惯是将 `cbuf_init` 放在 `attach` 顶部附近,`cbuf_destroy` 放在 `detach` 底部附近,失败路径的 `goto fail_*` 链在 attach 在 `cbuf_init` 之后失败时调用 `cbuf_destroy`。 -**How to verify.** `kldload` and `kldunload` the module several times. `vmstat -m | grep cbuf` should show `0` after each `kldunload`. +**如何验证。** `kldload` 和 `kldunload` 模块几次。`vmstat -m | grep cbuf` 应该在每次 `kldunload` 后显示 `0`。 -### Symptom: `select(2)` or `poll(2)` does not wake up +### 症状:`select(2)` 或 `poll(2)` 不唤醒 -**Cause.** The driver is missing a `selwakeup` call when state changes. Either the read path forgot to call `selwakeup(&sc->wsel)` after draining bytes, or the write path forgot to call `selwakeup(&sc->rsel)` after adding bytes. +**原因。** 驱动在状态改变时缺少 `selwakeup` 调用。要么读取路径在排空字节后忘记调用 `selwakeup(&sc->wsel)`,要么写入路径在添加字节后忘记调用 `selwakeup(&sc->rsel)`。 -**Fix.** The pattern: every state change that might make a previously-not-ready condition into a ready condition must be paired with a `selwakeup` call. Drain bytes -> `selwakeup(&sc->wsel)`. Add bytes -> `selwakeup(&sc->rsel)`. +**修复。** 模式:每个可能将先前不就绪条件变为就绪条件的状态改变必须配对一个 `selwakeup` 调用。排空字节 -> `selwakeup(&sc->wsel)`。添加字节 -> `selwakeup(&sc->rsel)`。 -**How to verify.** Run `rw_myfirst_nb`. Step 4 should show `revents=0x41`. If it shows `revents=0x0`, your `selwakeup` is missing or the `myfirst_poll` handler is not setting `revents` correctly. +**如何验证。** 运行 `rw_myfirst_nb`。第4步应该显示 `revents=0x41`。如果显示 `revents=0x0`,你的 `selwakeup` 缺失或 `myfirst_poll` 处理程序没有正确设置 `revents`。 -### Symptom: `truss` shows `EINVAL` for zero-byte reads +### 症状:`truss` 显示零字节读取的 `EINVAL` -**Cause.** Your handler is rejecting zero-byte reads with `EINVAL`. As discussed in Section 4, zero-byte reads and writes are legal and the handler must not error on them. +**原因。** 你的处理程序用 `EINVAL` 拒绝零字节读取。如第4节讨论的,零字节读写是合法的,处理程序不能对它们报错。 -**Fix.** Remove any `if (uio->uio_resid == 0) return (EINVAL);` early return at the top of `myfirst_read` or `myfirst_write`. +**修复。** 移除 `myfirst_read` 或 `myfirst_write` 顶部任何 `if (uio->uio_resid == 0) return (EINVAL);` 的早期返回。 -**How to verify.** A program that calls `read(fd, NULL, 0)` should see the call return `0`, not `-1` with `EINVAL`. +**如何验证。** 调用 `read(fd, NULL, 0)` 的程序应该看到调用返回 `0`,而不是 `-1` 和 `EINVAL`。 -### Symptom: `ps` shows the reader stuck in a sleep state called something different +### 症状:`ps` 显示读取者卡在一个不同名称的睡眠状态 -**Cause.** Your `mtx_sleep` is being called with a different `wmesg` than you expected. Two common variants: typo (`mfyrd` instead of `myfrd`), or the same handler is being called from a code path where the wait reason is actually different. +**原因。** 你的 `mtx_sleep` 被调用时使用了与预期不同的 `wmesg`。两种常见变体:拼写错误(`mfyrd` 而不是 `myfrd`),或者同一处理程序从等待原因实际不同的代码路径被调用。 -**Fix.** Standardise the `wmesg` strings. `myfrd` for "myfirst read", `myfwr` for "myfirst write". A unique short string per wait point makes `ps -AxH` immediately informative. +**修复。** 标准化 `wmesg` 字符串。`myfrd` 表示"myfirst read",`myfwr` 表示"myfirst write"。每个等待点唯一的短字符串使 `ps -AxH` 立即提供信息。 -**How to verify.** `ps -AxH` should show `myfrd` for sleeping readers and `myfwr` for sleeping writers. +**如何验证。** `ps -AxH` 应该为睡眠中的读取者显示 `myfrd`,为睡眠中的写入者显示 `myfwr`。 -### Symptom: A signal does not interrupt a blocked read +### 症状:信号不中断阻塞的读取 -**Cause.** The `mtx_sleep` is being called without `PCATCH`. Without `PCATCH`, signals are deferred until the sleep ends for some other reason. +**原因。** `mtx_sleep` 被调用时没有 `PCATCH`。没有 `PCATCH`,信号被推迟直到睡眠因其他原因结束。 -**Fix.** Always pass `PCATCH` for user-driven sleeps. The exception is sleeps that should be uninterruptible (kernel internal logic that must not be cancelled by a signal). For `myfirst_read` and `myfirst_write`, both are user-driven and both should pass `PCATCH`. +**修复。** 对于用户驱动的睡眠始终传递 `PCATCH`。例外是不应被中断的睡眠(不能被信号取消的内核内部逻辑)。对于 `myfirst_read` 和 `myfirst_write`,两者都是用户驱动的,两者都应该传递 `PCATCH`。 -**How to verify.** `cat /dev/myfirst &` followed by `kill -INT %1` should cause `cat` to exit. If `cat` does not exit until you also write to the device (or send `kill -9`), `PCATCH` is missing. +**如何验证。** `cat /dev/myfirst &` 后跟 `kill -INT %1` 应该导致 `cat` 退出。如果 `cat` 在你也向设备写入(或发送 `kill -9`)之前不退出,`PCATCH` 缺失。 -### Symptom: Compiler warns about a missing prototype for `cbuf_read` +### 症状:编译器警告 `cbuf_read` 缺少原型 -**Cause.** The driver source uses `cbuf_read` but does not include `cbuf.h`. +**原因。** 驱动源码使用 `cbuf_read` 但没有包含 `cbuf.h`。 -**Fix.** Add `#include "cbuf.h"` near the top of `myfirst.c`. The file path is relative to the source directory, so as long as both files are in the same directory the include will resolve. +**修复。** 在 `myfirst.c` 顶部附近添加 `#include "cbuf.h"`。文件路径相对于源码目录,所以只要两个文件在同一目录中,include 就会解析。 -**How to verify.** A clean build with no warnings. +**如何验证。** 干净构建无警告。 -### Symptom: `make` complains about missing `bus_if.h` or `device_if.h` +### 症状:`make` 抱怨缺少 `bus_if.h` 或 `device_if.h` -**Cause.** The Makefile is missing the standard `SRCS+= device_if.h bus_if.h` line that pulls in the auto-generated kobj headers for Newbus. +**原因。** Makefile 缺少标准的 `SRCS+= device_if.h bus_if.h` 行,该行拉入 Newbus 的自动生成 kobj 头文件。 -**Fix.** Use the Makefile from Section 3. +**修复。** 使用第3节的 Makefile。 -**How to verify.** `make clean && make` should succeed without missing-header errors. +**如何验证。** `make clean && make` 应该成功,不出现缺少头文件的错误。 -### Symptom: `kldload` fails with `Exec format error` +### 症状:`kldload` 失败并显示 "Exec format error" -**Cause.** The .ko was built against a different kernel than the one currently running. This typically happens when you reboot into a different kernel without rebuilding, or when you copy a .ko from one machine to another with different kernel sources. +**原因。** .ko 是针对与当前运行内核不同的内核构建的。这通常发生在你重启到不同内核而没有重新构建,或从具有不同内核源码的机器复制 .ko 时。 -**Fix.** `make clean && make` against the running kernel's `/usr/src`. +**修复。** 针对运行中内核的 `/usr/src` 执行 `make clean && make`。 -**How to verify.** `uname -a` should match the kernel version that built the .ko. Check `dmesg` after the failed `kldload` for more details. +**如何验证。** `uname -a` 应该匹配构建 .ko 的内核版本。检查失败 `kldload` 后的 `dmesg` 获取更多详情。 -### Symptom: The driver reports correct data but loses it after several runs +### 症状:驱动报告正确数据但在多次运行后丢失 -**Cause.** The cbuf is not being reset between attaches, or the softc is not being zero-initialised. With `M_ZERO` on the `malloc(9)` call (and the `cbuf_init` call zero-initializing its own state), this should not happen, but a partial fix that misses one of these can leave stale state. +**原因。** cbuf 在 attach 之间没有被重置,或 softc 没有被零初始化。使用 `malloc(9)` 调用上的 `M_ZERO`(和 `cbuf_init` 调用零初始化自身状态),这不应该发生,但错过其中之一的的部分修复可能留下陈旧状态。 -**Fix.** Audit `myfirst_attach` to make sure every field of the softc is initialised explicitly. Use `M_ZERO` on the `malloc(9)` call that allocates the softc (Newbus does this automatically with `device_get_softc`, but verify). Use `cbuf_init` to set the cbuf's indices to zero. +**修复。** 审计 `myfirst_attach` 确保 softc 的每个字段都被显式初始化。在分配 softc 的 `malloc(9)` 调用上使用 `M_ZERO`(Newbus 通过 `device_get_softc` 自动完成,但请验证)。使用 `cbuf_init` 将 cbuf 的索引设置为零。 -**How to verify.** `kldload`, write some data, `kldunload`, `kldload` again. The new attach should report `cb_used = 0`. +**如何验证。** `kldload`,写入一些数据,`kldunload`,再次 `kldload`。新的 attach 应该报告 `cb_used = 0`。 -### Symptom: `producer_consumer` reports a small number of mismatches under heavy load +### 症状:`producer_consumer` 在重负载下报告少量不匹配 -**Cause.** A subtle locking bug, often related to the order of `wakeup` calls and the inner sleep loop's re-check. The classic symptom: under contention, occasionally a thread wakes up and consumes bytes that another thread had thought were still available. +**原因。** 一个微妙的锁定 bug,通常与 `wakeup` 调用的顺序和内部睡眠循环的重新检查有关。典型症状:在竞争下,偶尔线程醒来并消耗另一个线程认为仍然可用的字节。 -**Fix.** Verify that every `mtx_sleep` is in a `while` (not `if`) loop, and that the loop re-checks the condition after waking. The wakeup is a *hint*, not a guarantee; a woken thread might find the condition false again because another thread got there first. +**修复。** 验证每个 `mtx_sleep` 在 `while`(不是 `if`)循环中,并且循环在醒来后重新检查条件。wakeup 是一个*提示*,不是保证;醒来的线程可能发现条件再次为假,因为另一个线程先到了。 -**How to verify.** `producer_consumer` should report zero mismatches across multiple runs. A mismatch count that varies between runs suggests a race; a mismatch count that is always exactly N suggests an off-by-one bug. +**如何验证。** `producer_consumer` 应该在多次运行中报告零不匹配。运行之间变化的不匹配计数建议存在竞争;总是恰好为 N 的不匹配计数建议差一错误。 -### General Advice for Debugging +### 调试的一般建议 -Three habits make driver debugging much faster. +三个习惯使驱动调试快得多。 -The first is to have a `WITNESS`-enabled kernel ready. `WITNESS` catches lock-ordering violations and "sleeping with mutex held" bugs that a production kernel would silently allow. The performance overhead is significant, so run `WITNESS` in your lab environment, not in production. +第一个是准备好启用 `WITNESS` 的内核。`WITNESS` 捕获生产内核会静默允许的锁排序违规和"持有互斥锁睡眠"bug。性能开销很大,所以在实验室环境中运行 `WITNESS`,而不是在生产中。 -The second is to add `device_printf` log lines liberally during development, then remove them or guard them behind `myfirst_debug` before committing. The log buffer is finite, so do not log per-byte; one line per I/O call is the right granularity. +第二个是在开发期间大量添加 `device_printf` 日志行,然后在提交之前移除它们或用 `myfirst_debug` 保护。日志缓冲区是有限的,所以不要逐字节记录;每次 I/O 调用一行是正确的粒度。 -The third is to compile with `-Wall -Wextra` and treat warnings as bugs. The kernel build system passes a lot of warning flags by default; pay attention to them. Almost every warning is the kernel telling you about a real or potential bug. +第三个是用 `-Wall -Wextra` 编译并将警告视为 bug。内核构建系统默认传递很多警告标志;注意它们。几乎每个警告都是内核在告诉你一个真实的或潜在的 bug。 -When all else fails, sit back and trace through the code path on paper. A driver this size is small enough to fit on a single sheet. Ninety percent of the time, drawing the call graph and the lock acquisitions in order shows you the bug. +当所有其他方法都失败时,坐下来在纸上追踪代码路径。这个大小的驱动足够小,可以放在一张纸上。百分之九十的时间,按顺序画出调用图和锁获取就会显示 bug。 -## Quick Reference: Patterns and Primitives +## 快速参考:模式和原语 -This reference is the chapter's material reduced to fast-lookup form. Use it after you have read the chapter; it is a reminder, not a tutorial. +此参考将本章材料缩减为快速查找形式。在阅读完章节后使用它;它是提醒,不是教程。 -### The Circular Buffer API +### 循环缓冲区 API ```c struct cbuf { @@ -3503,12 +3503,12 @@ size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); ``` -Rules: -- The cbuf does not lock; the caller is responsible. -- `cbuf_write` and `cbuf_read` clamp `n` to available space or live data and return the actual count. -- `cbuf_used` and `cbuf_free` return current state under the assumption that the caller holds whatever lock protects the cbuf. +规则: +- cbuf 不加锁;调用者负责。 +- `cbuf_write` 和 `cbuf_read` 将 `n` 限制为可用空间或活跃数据并返回实际计数。 +- `cbuf_used` 和 `cbuf_free` 在假设调用者持有保护 cbuf 的任何锁的情况下返回当前状态。 -### The Driver-Level Helpers +### 驱动级辅助函数 ```c size_t myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n); @@ -3519,12 +3519,12 @@ int myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, struct uio *uio); ``` -Rules: -- All four helpers assert that `sc->mtx` is held with `mtx_assert(MA_OWNED)`. -- The wait helpers return `-1` to mean "break the outer loop, return 0 to user space". -- The wait helpers return `EAGAIN`, `EINTR`, `ERESTART`, or `ENXIO` for the corresponding conditions. +规则: +- 所有四个辅助函数用 `mtx_assert(MA_OWNED)` 断言 `sc->mtx` 被持有。 +- 等待辅助函数返回 `-1` 表示"中断外部循环,向用户空间返回 0"。 +- 等待辅助函数为相应条件返回 `EAGAIN`、`EINTR`、`ERESTART` 或 `ENXIO`。 -### The Read Handler Spine +### 读取处理程序骨架 ```c nbefore = uio->uio_resid; @@ -3550,7 +3550,7 @@ while (uio->uio_resid > 0) { return (0); ``` -### The Write Handler Spine +### 写入处理程序骨架 ```c nbefore = uio->uio_resid; @@ -3581,7 +3581,7 @@ while (uio->uio_resid > 0) { return (0); ``` -### The Sleep Pattern +### 睡眠模式 ```c mtx_lock(&sc->mtx); @@ -3599,13 +3599,13 @@ while (CONDITION) { /* condition is false now; act on the buffer */ ``` -Rules: -- Use `while`, not `if`, around the condition. -- Always pass `PCATCH` for user-driven sleeps. -- Always re-check the condition after `mtx_sleep` returns. -- Always check `is_attached` after waking, in case detach is pending. +规则: +- 在条件周围使用 `while`,不是 `if`。 +- 对于用户驱动的睡眠始终传递 `PCATCH`。 +- 在 `mtx_sleep` 返回后始终重新检查条件。 +- 醒来后始终检查 `is_attached`,以防拆离待处理。 -### The Wake Pattern +### 唤醒模式 ```c /* After a state change that might unblock a sleeper: */ @@ -3613,13 +3613,13 @@ wakeup(CHANNEL); selwakeup(SELINFO); ``` -Rules: -- The channel must match the channel passed to `mtx_sleep`. -- The selinfo must be the one that `selrecord` registered against. -- Use `wakeup` (wake all) for shared waiters; `wakeup_one` for single-handoff patterns. -- Spurious wakeups are safe; missing wakeups are bugs. +规则: +- 通道必须匹配传递给 `mtx_sleep` 的通道。 +- selinfo 必须是 `selrecord` 注册的那个。 +- 对共享等待者使用 `wakeup`(唤醒所有);对单次交接模式使用 `wakeup_one`。 +- 虚假唤醒是安全的;缺失唤醒是 bug。 -### The `d_poll` Handler +### `d_poll` 处理程序 ```c static int @@ -3646,7 +3646,7 @@ myfirst_poll(struct cdev *dev, int events, struct thread *td) } ``` -### The `d_mmap` Handler +### `d_mmap` 处理程序 ```c static int @@ -3666,7 +3666,7 @@ myfirst_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, } ``` -### The `cdevsw` +### `cdevsw` ```c static struct cdevsw myfirst_cdevsw = { @@ -3703,7 +3703,7 @@ static struct cdevsw myfirst_cdevsw = { | `IO_DIRECT` | `O_DIRECT` | Bypass caching where possible | | `IO_SYNC` | `O_FSYNC` | (write only) Synchronous semantics | -`O_NONBLOCK == IO_NDELAY` per the kernel's CTASSERT. +`O_NONBLOCK == IO_NDELAY` 根据内核的 CTASSERT。 ### `poll(2)` Events @@ -3717,7 +3717,7 @@ static struct cdevsw myfirst_cdevsw = { | `POLLHUP` | Hangup (peer closed) | | `POLLNVAL` | Invalid file descriptor | -A driver typically handles `POLLIN | POLLRDNORM` for read readiness and `POLLOUT | POLLWRNORM` for write readiness. The other events are usually set by the kernel, not the driver. +驱动通常处理 `POLLIN | POLLRDNORM` 表示读取就绪,`POLLOUT | POLLWRNORM` 表示写入就绪。其他事件通常由内核设置,不是驱动。 ### Memory Allocator Reference @@ -3825,31 +3825,31 @@ examples/part-02/ch10-handling-io-efficiently/ Makefile ``` -Each stage directory is independent; you can `make` and `kldload` any of them without touching the others. The userland tools are shared across all stages. +每个阶段目录是独立的;你可以 `make` 和 `kldload` 其中任何一个而不触及其他的。用户态工具在所有阶段之间共享。 -### A Mental Model in One Paragraph +### 一段话的心智模型 -The driver owns a circular buffer, protected by a single mutex. A reader holds the mutex while transferring bytes out of the buffer into a stack-resident bounce, releases the mutex, copies the bounce into user space with `uiomove`, wakes any waiting writers, and loops until the user's request is satisfied or the buffer is empty. A writer mirrors this: holds the mutex, copies user bytes into a bounce, releases the mutex, copies the bounce into the buffer, wakes any waiting readers, and loops. When either the buffer is empty (for reads) or full (for writes), the handler either sleeps with the mutex as interlock (default mode) or returns `EAGAIN` (non-blocking mode). `select(2)` and `poll(2)` integration is provided through `selrecord` (in `d_poll`) and `selwakeup` (in the I/O handlers). The detach path waits for all descriptors to close and then frees everything. +驱动拥有一个循环缓冲区,由单个互斥锁保护。读取者持有互斥锁将字节从缓冲区传输到栈驻留弹跳缓冲区,释放互斥锁,用 `uiomove` 将弹跳缓冲区复制到用户空间,唤醒任何等待的写入者,并循环直到用户请求满足或缓冲区为空。写入者镜像此过程:持有互斥锁,将用户字节复制到弹跳缓冲区,释放互斥锁,将弹跳缓冲区复制到缓冲区,唤醒任何等待的读取者,并循环。当缓冲区为空(对于读取)或满(对于写入)时,处理程序要么以互斥锁作为互锁睡眠(默认模式),要么返回 `EAGAIN`(非阻塞模式)。`select(2)` 和 `poll(2)` 集成通过 `selrecord`(在 `d_poll` 中)和 `selwakeup`(在 I/O 处理程序中)提供。拆离路径等待所有描述符关闭然后释放一切。 -That paragraph fits in your head. Everything else in this chapter is the careful elaboration of how to make each piece of it work. +这段话适合放在你脑中。本章其余部分是关于如何使每一部分工作的详细阐述。 -## Appendix: A Source-Reading Walkthrough of `evdev/cdev.c` +## 附录:`evdev/cdev.c` 的源码阅读演练 -The chapter has pointed at `/usr/src/sys/dev/evdev/cdev.c` several times as the cleanest example in the tree of a character device that does what `myfirst` now does: a per-client ring buffer, blocking reads, non-blocking support, `select`/`poll`/`kqueue` integration. Reading that file once, with the patterns from this chapter in hand, is the fastest way to confirm that the kernel really does work the way the chapter has been describing. This appendix walks through the relevant pieces. +本章多次指向 `/usr/src/sys/dev/evdev/cdev.c`,作为树中做 `myfirst` 现在做的事情的最干净字符设备示例:每客户端环形缓冲区、阻塞读取、非阻塞支持、`select`/`poll`/`kqueue` 集成。带着本章的模式阅读该文件一次,是确认内核确实按照本章描述的方式工作的最快方式。本附录演练相关部分。 -The goal is *not* to teach `evdev`. It is to use `evdev` as an exhibit. By the end of this walkthrough you should feel that what you built in `myfirst` is the same shape as what the kernel uses for real input devices. The differences are in the details (the protocol, the structures, the layered driver stack), not in the underlying patterns. +目标*不是*教授 `evdev`。而是使用 `evdev` 作为展示。到演练结束时,你应该感到你在 `myfirst` 中构建的与内核用于真实输入设备的是相同形状。差异在细节中(协议、结构、分层驱动栈),而不在底层模式。 -### What `evdev` Is +### `evdev` 是什么 -`evdev` is FreeBSD's port of the Linux event-device interface. It exposes input devices (keyboards, mice, touchscreens) through `/dev/input/eventN` nodes that user-space programs (X servers, Wayland compositors, console handlers) read from to get a stream of input events. Each event is a fixed-size structure with a timestamp, a type, a code, and a value. +`evdev` 是 FreeBSD 对 Linux 事件设备接口的移植。它通过 `/dev/input/eventN` 节点暴露输入设备(键盘、鼠标、触摸屏),用户空间程序(X 服务器、Wayland 合成器、控制台处理程序)从中读取以获取输入事件流。每个事件是一个固定大小的结构,包含时间戳、类型、代码和值。 -The driver layer that interests us is the per-client cdev. When a process opens `/dev/input/event0`, the kernel creates a `struct evdev_client` for that descriptor, attaches it to the underlying device, and uses it as the per-open buffer. Reads pull events out of the buffer; writes push events into it (for some devices); `select`/`poll`/`kqueue` report when events are available. +我们感兴趣的驱动层是每客户端 cdev。当进程打开 `/dev/input/event0` 时,内核为该描述符创建一个 `struct evdev_client`,将其附加到底层设备,并将其用作每次打开的缓冲区。读取从缓冲区拉取事件;写入向其推送事件(对于某些设备);`select`/`poll`/`kqueue` 报告何时有事件可用。 -That description should sound very familiar by now. It is the same architecture as `myfirst` Stage 4, with three differences: the buffer is per-descriptor rather than per-device; the unit of transfer is a fixed-size structure rather than a byte; and the driver participates in a larger framework of input handling. +这个描述现在应该听起来非常熟悉。它与 `myfirst` 阶段 4 是相同的架构,有三个差异:缓冲区是每描述符而不是每设备;传输单位是固定大小结构而不是字节;驱动参与更大的输入处理框架。 -### The Per-Client State +### 每客户端状态 -Open `/usr/src/sys/dev/evdev/evdev_private.h` (the file is short; you can read the relevant parts in a couple of minutes). The key structure is `struct evdev_client`: +打开 `/usr/src/sys/dev/evdev/evdev_private.h`(文件很短;你可以在几分钟内阅读相关部分)。关键结构是 `struct evdev_client`: ```c struct evdev_client { @@ -3870,21 +3870,21 @@ struct evdev_client { }; ``` -Compare this against your `myfirst` softc: +将此与你的 `myfirst` softc 比较: -- `ec_evdev` is `evdev`'s analogue of `dev->si_drv1` (a back-pointer from the per-client state to the device-wide state). -- `ec_buffer_mtx` is the per-client mutex; `myfirst`'s `sc->mtx` is per-device. -- `ec_buffer_size`, `ec_buffer_head`, `ec_buffer_tail`, `ec_buffer_ready` are the circular-buffer indices. Notice that `evdev` uses an explicit `tail` instead of a derived one; the code is slightly different but the structure is the same. -- `ec_blocked` is a hint flag for the wakeup logic. -- `ec_revoked` flags a forcibly-disconnected client; this is the equivalent of `is_attached` in `myfirst`. -- `ec_selp` is the `selinfo` for `select`/`poll`/`kqueue` support, exactly like `sc->rsel` and `sc->wsel` in your driver (combined here because evdev only does read-readiness; there is no concept of "write would block"). -- `ec_buffer[]` is the flexible-array-member that holds the actual events. +- `ec_evdev` 是 `evdev` 中 `dev->si_drv1` 的等价物(从每客户端状态到设备范围状态的反向指针)。 +- `ec_buffer_mtx` 是每客户端互斥锁;`myfirst` 的 `sc->mtx` 是每设备的。 +- `ec_buffer_size`、`ec_buffer_head`、`ec_buffer_tail`、`ec_buffer_ready` 是循环缓冲区索引。注意 `evdev` 使用显式 `tail` 而不是推导的;代码略有不同但结构相同。 +- `ec_blocked` 是唤醒逻辑的提示标志。 +- `ec_revoked` 标记强制断开的客户端;这是 `myfirst` 中 `is_attached` 的等价物。 +- `ec_selp` 是 `select`/`poll`/`kqueue` 支持的 `selinfo`,与你驱动中的 `sc->rsel` 和 `sc->wsel` 完全相同(这里合并了,因为 evdev 只做读取就绪;没有"写入会阻塞"的概念)。 +- `ec_buffer[]` 是保存实际事件的灵活数组成员。 -The patterns are the same. The naming is different. +模式相同。命名不同。 -### The Read Handler +### 读取处理程序 -Open `/usr/src/sys/dev/evdev/cdev.c` and find `evdev_read`: +打开 `/usr/src/sys/dev/evdev/cdev.c` 并找到 `evdev_read`: ```c static int @@ -3945,21 +3945,21 @@ evdev_read(struct cdev *dev, struct uio *uio, int ioflag) } ``` -Walk through it slowly. +慢慢走一遍。 -The handler retrieves the per-client state with `devfs_get_cdevpriv`, exactly as `myfirst_read` does. The `ec_revoked` check is `evdev`'s equivalent of `myfirst`'s `is_attached` check, except that `evdev` returns `ENODEV` rather than `ENXIO` (both are valid choices for "the device is gone"). +处理程序用 `devfs_get_cdevpriv` 获取每客户端状态,与 `myfirst_read` 完全相同。`ec_revoked` 检查是 `evdev` 中 `myfirst` 的 `is_attached` 检查的等价物,除了 `evdev` 返回 `ENODEV` 而不是 `ENXIO`(两者都是"设备已消失"的有效选择)。 -The handler then validates that the requested transfer size is a multiple of an event-record size (because partial events make no sense to deliver). This is a layer above what `myfirst` does, and it is specific to event-stream devices. +处理程序然后验证请求的传输大小是事件记录大小的倍数(因为传递部分事件没有意义)。这是 `myfirst` 所做之上的一个层,特定于事件流设备。 -Then, exactly as Section 5 described, the handler enters a *check-wait-recheck* loop. If the buffer is empty (`EVDEV_CLIENT_EMPTYQ(client)`), the handler either returns `EWOULDBLOCK` (the same value as `EAGAIN`) for non-blocking callers, or sleeps with `mtx_sleep` and `PCATCH`. The sleep channel is `client` itself; the mutex interlock is `&client->ec_buffer_mtx`. When the sleep returns, the handler re-checks `ec_revoked`, returning `ENODEV` if the client has been disconnected during the sleep. +然后,正如第5节描述的,处理程序进入*检查-等待-重新检查*循环。如果缓冲区为空(`EVDEV_CLIENT_EMPTYQ(client)`),处理程序要么为非阻塞调用者返回 `EWOULDBLOCK`(与 `EAGAIN` 相同的值),要么用 `mtx_sleep` 和 `PCATCH` 睡眠。睡眠通道是 `client` 本身;互斥锁互锁是 `&client->ec_buffer_mtx`。当睡眠返回时,处理程序重新检查 `ec_revoked`,如果客户端在睡眠期间被断开则返回 `ENODEV`。 -After the wait, the handler enters the transfer loop. It picks an event off the buffer (with `bcopy` into a stack-resident `event` variable), advances `ec_buffer_head` modulo the buffer size, releases the mutex, and calls `uiomove` to push the event to user space. Then it reacquires the mutex and continues until either the buffer empties or the user's request is satisfied. +等待之后,处理程序进入传输循环。它从缓冲区取下一个事件(用 `bcopy` 到栈驻留的 `event` 变量),推进 `ec_buffer_head` 取模缓冲区大小,释放互斥锁,并调用 `uiomove` 将事件推送到用户空间。然后重新获取互斥锁并继续,直到缓冲区排空或用户请求满足。 -This is the bounce-buffer pattern from Section 3, with `event` playing the role of `bounce`. The cbuf operation is `bcopy(head, &event.t, evsize)` (single-event copy out of the ring) followed by `uiomove(&event, evsize, uio)` (transfer to user). The mutex is held only across the cbuf operation, never across `uiomove`. This is exactly the rule we made operational in `myfirst`. +这是第3节的弹跳缓冲区模式,`event` 扮演 `bounce` 的角色。cbuf 操作是 `bcopy(head, &event.t, evsize)`(从环形中单事件复制出来)后跟 `uiomove(&event, evsize, uio)`(传输到用户)。互斥锁只跨越 cbuf 操作持有,从不跨越 `uiomove`。这正是我们在 `myfirst` 中实施的规则。 -### The Wakeup +### 唤醒 -Find `evdev_notify_event` (the function that gets called when a new event is delivered into a client's buffer): +找到 `evdev_notify_event`(当新事件被交付到客户端缓冲区时调用的函数): ```c void @@ -3981,13 +3981,13 @@ evdev_notify_event(struct evdev_client *client) } ``` -There is the wake-up. `wakeup(client)` matches the `mtx_sleep(client, ...)` from `evdev_read`. `selwakeup(&client->ec_selp)` matches the `selrecord` we will look at in a moment. `KNOTE_LOCKED` is the `kqueue` analogue of `selwakeup`; we have not built that yet (it is Chapter 11 territory) but the pattern is the same. +这就是唤醒。`wakeup(client)` 匹配 `evdev_read` 中的 `mtx_sleep(client, ...)`。`selwakeup(&client->ec_selp)` 匹配我们稍后将看到的 `selrecord`。`KNOTE_LOCKED` 是 `selwakeup` 的 `kqueue` 等价物;我们还没有构建它(这是第11章的领域)但模式相同。 -The `ec_blocked` flag is an optimisation: if no client is currently sleeping, the wakeup is skipped. This is a small but useful optimisation. `myfirst` does not have it because the cost is negligible in our use case, but you could add the same check trivially. +`ec_blocked` 标志是一个优化:如果没有客户端当前在睡眠,唤醒被跳过。这是一个小但有用的优化。`myfirst` 没有它,因为在我们用例中成本可以忽略不计,但你可以轻松添加相同的检查。 -### The Poll +### Poll -Find `evdev_poll`: +找到 `evdev_poll`: ```c static int @@ -4016,13 +4016,13 @@ evdev_poll(struct cdev *dev, int events, struct thread *td) } ``` -This is essentially identical to the `myfirst_poll` from Section 5, with two differences. `evdev` only handles `POLLIN`; there is no `POLLOUT` because input events are unidirectional. And `evdev` returns `POLLNVAL` if `devfs_get_cdevpriv` fails, which is the conventional "this descriptor is invalid" response (compared to `myfirst`'s simpler return-zero approach). +这与第5节的 `myfirst_poll` 本质上相同,有两个差异。`evdev` 只处理 `POLLIN`;没有 `POLLOUT` 因为输入事件是单向的。而且 `evdev` 在 `devfs_get_cdevpriv` 失败时返回 `POLLNVAL`,这是传统的"此描述符无效"响应(与 `myfirst` 更简单的返回零方法相比)。 -The pattern is the one Section 5 introduced: check the condition, return ready if it is true, register with `selrecord` if it is not. The `ec_selected` flag is again a wakeup-elision optimisation; you can ignore it for understanding. +模式是第5节引入的:检查条件,如果为真则返回就绪,如果不为真则用 `selrecord` 注册。`ec_selected` 标志又是一个唤醒省略优化;理解时可以忽略它。 -### The kqfilter +### kqfilter -Find `evdev_kqfilter`: +找到 `evdev_kqfilter`: ```c static int @@ -4050,122 +4050,122 @@ evdev_kqfilter(struct cdev *dev, struct knote *kn) } ``` -This is the `kqueue` registration handler. It is one of Chapter 11's topics; we are showing it here only to point out that the `selinfo`'s `si_note` field is what `kqueue` hooks into. The `selrecord`/`selwakeup` machinery for `select`/`poll`, and the `knlist_add`/`KNOTE_LOCKED` machinery for `kqueue`, share the same `selinfo` structure. That sharing is what lets a single set of state-change calls (in `evdev_notify_event`) wake all three readiness-notification paths at once. +这是 `kqueue` 注册处理程序。它是第11章的主题之一;我们在这里展示它只是为了指出 `selinfo` 的 `si_note` 字段是 `kqueue` 挂钩的地方。`select`/`poll` 的 `selrecord`/`selwakeup` 机制和 `kqueue` 的 `knlist_add`/`KNOTE_LOCKED` 机制共享相同的 `selinfo` 结构。这种共享让一组状态改变调用(在 `evdev_notify_event` 中)可以同时唤醒所有三个就绪通知路径。 -When we extend `myfirst` with `kqueue` support in Chapter 11, the changes will fit into roughly the same pattern: a `myfirst_kqfilter` handler that registers against `&sc->rsel.si_note`, a `KNOTE_LOCKED(&sc->rsel.si_note, 0)` call alongside each `selwakeup(&sc->rsel)`. The substrate is here already. +当我们在第11章用 `kqueue` 支持扩展 `myfirst` 时,更改将大致符合相同的模式:一个注册到 `&sc->rsel.si_note` 的 `myfirst_kqfilter` 处理程序,一个在每个 `selwakeup(&sc->rsel)` 旁边的 `KNOTE_LOCKED(&sc->rsel.si_note, 0)` 调用。基础已经在这里了。 -### What the Walkthrough Confirms +### 演练确认了什么 -Three things should be clear now. +现在应该清楚三件事。 -The first is that the *patterns* you have been building are not invented for this book. They are the patterns the kernel uses, in a real driver that ships with FreeBSD and is exercised by every keyboard and mouse user every day. You can read this code, recognise what each section is doing, and explain it. That is a real skill that pays off in every later chapter. +第一,你一直在构建的*模式*不是为本书发明的。它们是内核使用的模式,在一个随 FreeBSD 发布的真实驱动中,每天被每个键盘和鼠标用户使用。你可以阅读这段代码,识别每个部分在做什么,并解释它。这是一项在每个后续章节都会产生回报的真实技能。 -The second is that the *details* differ between drivers. `evdev` uses an explicit `tail` index. It uses fixed-size event records instead of bytes. It has per-client buffers instead of per-device. It uses `bcopy` instead of a cbuf abstraction. None of these differences invalidate the underlying pattern; they are choices about how to specialise the pattern for a specific use case. +第二,驱动之间的*细节*不同。`evdev` 使用显式 `tail` 索引。它使用固定大小的事件记录而不是字节。它有每客户端缓冲区而不是每设备。它使用 `bcopy` 而不是 cbuf 抽象。这些差异没有一个使底层模式无效;它们是关于如何为特定用例特化模式的选择。 -The third is that *you can read more*. With a couple of hours and a coffee, you can work through `/usr/src/sys/dev/uart/uart_core.c` or `/usr/src/sys/dev/snp/snp.c`. Each one will look different at first glance, but the buffer, the locking, the sleep / wake, the poll: those will be familiar. The chapter has handed you a vocabulary; the kernel source is where you exercise it. +第三,*你可以阅读更多*。用几个小时和一杯咖啡,你可以读完 `/usr/src/sys/dev/uart/uart_core.c` 或 `/usr/src/sys/dev/snp/snp.c`。每个乍一看都不同,但缓冲区、锁定、睡眠/唤醒、poll:那些将是熟悉的。本章给了你词汇;内核源码是你练习它的地方。 -### A Short Reading Plan +### 短期阅读计划 -If you want to build the habit of reading kernel source as part of your driver development workflow, here is a short plan. Spend an hour a week, for three weeks, on the following. +如果你想养成将阅读内核源码作为驱动开发工作流程一部分的习惯,这里有一个短期计划。每周花一个小时,连续三周,做以下事情。 -Week one: re-read `/usr/src/sys/dev/null/null.c` and `/usr/src/sys/dev/evdev/cdev.c`. Compare them. The first is the simplest possible character device; the second is a competent buffered one. Note exactly which features each file has and why. +第一周:重读 `/usr/src/sys/dev/null/null.c` 和 `/usr/src/sys/dev/evdev/cdev.c`。比较它们。第一个是最简单的可能字符设备;第二个是一个合格的缓冲设备。确切记录每个文件有哪些功能以及为什么。 -Week two: read `/usr/src/sys/dev/random/randomdev.c`. It is bigger than `evdev` but uses the same patterns, with the addition of an entropy-collection layer underneath. Note how `randomdev_read` differs from `evdev_read` and `myfirst_read`, and why. +第二周:阅读 `/usr/src/sys/dev/random/randomdev.c`。它比 `evdev` 更大但使用相同的模式,额外有一个底层的熵收集层。注意 `randomdev_read` 如何与 `evdev_read` 和 `myfirst_read` 不同,以及为什么。 -Week three: pick a driver in `/usr/src/sys/dev/` that interests you (a USB driver, a network driver, a storage driver). Read the part of it that handles user-space I/O. By now the patterns should be familiar enough that the unfamiliar parts (bus binding, hardware register access, DMA setup) stand out as the *new* things to learn, not as obstacles to understanding the I/O path. +第三周:在 `/usr/src/sys/dev/` 中选择一个你感兴趣的驱动(USB 驱动、网络驱动、存储驱动)。阅读处理用户空间 I/O 的部分。现在模式应该足够熟悉,不熟悉的部分(总线绑定、硬件寄存器访问、DMA 设置)将作为要学习的*新*东西突出出来,而不是理解 I/O 路径的障碍。 -After three weeks of this rhythm, you will have read more driver code than most professional kernel developers do in a typical month. The investment compounds. +三周这种节奏后,你将比大多数专业内核开发者在典型一个月中阅读更多驱动代码。投资会复利增长。 ## 章节总结 -This chapter took the in-kernel buffer from Chapter 9, which was a linear FIFO that wasted half its capacity, and turned it into a real circular buffer with proper partial-I/O semantics, blocking and non-blocking modes, and `poll(2)` integration. The driver you finish the chapter with is meaningfully better than the one you started with, in four specific ways. +本章将第9章的内核缓冲区(一个浪费一半容量的线性 FIFO)变成了一个真正的循环缓冲区,具有适当的部分 I/O 语义、阻塞和非阻塞模式以及 `poll(2)` 集成。你完成本章时的驱动在四个具体方面比开始时的驱动明显更好。 -It uses its full capacity. The circular buffer keeps the entire allocation in play. A steady writer and a matching reader can keep the buffer at any fill level indefinitely; the wrap-around is invisible to the I/O handlers because it lives inside the cbuf abstraction. +它使用全部容量。循环缓冲区保持整个分配可用。稳定的生产者和匹配的消费者可以无限期地在任何填充水平保持缓冲区;环绕对 I/O 处理程序不可见,因为它位于 cbuf 抽象内部。 -It honours partial transfers. Both `myfirst_read` and `myfirst_write` loop until they cannot make progress, then return zero with `uio_resid` reflecting the unconsumed portion. A user-space caller that loops on `read(2)` or `write(2)` will see correct UNIX semantics. A caller that does not loop will still see correct counts; the driver does not silently throw bytes away. +它遵循部分传输。`myfirst_read` 和 `myfirst_write` 都循环直到无法取得进展,然后返回零,`uio_resid` 反映未消耗的部分。循环 `read(2)` 或 `write(2)` 的用户空间调用者将看到正确的 UNIX 语义。不循环的调用者仍将看到正确的计数;驱动不会静默丢弃字节。 -It blocks correctly. A reader that finds the buffer empty sleeps on a clear channel, with the mutex released atomically; a writer that adds bytes wakes the sleeper. The same pattern works in the other direction. Signals are honoured through `PCATCH`, so the user's Ctrl-C interrupts a blocked reader within microseconds. +它正确阻塞。发现缓冲区为空的读取者在清晰的通道上睡眠,互斥锁原子释放;添加字节的写入者唤醒睡眠者。相同的模式在相反方向也有效。信号通过 `PCATCH` 被遵循,所以用户的 Ctrl-C 在微秒内中断阻塞的读取者。 -It supports non-blocking mode. A descriptor opened with `O_NONBLOCK` (or with the flag set later via `fcntl(2)`) sees `EAGAIN` instead of a sleep. A `d_poll` handler reports `POLLIN` and `POLLOUT` correctly based on the buffer's state, and `selrecord(9)` plus `selwakeup(9)` ensure that `select(2)` and `poll(2)` callers wake when readiness changes. +它支持非阻塞模式。用 `O_NONBLOCK` 打开的描述符(或稍后通过 `fcntl(2)` 设置标志)看到 `EAGAIN` 而不是睡眠。`d_poll` 处理程序根据缓冲区状态正确报告 `POLLIN` 和 `POLLOUT`,`selrecord(9)` 加 `selwakeup(9)` 确保当就绪状态改变时 `select(2)` 和 `poll(2)` 调用者被唤醒。 -Each of those capabilities is built up in a numbered section, each with code that compiles, loads, and behaves predictably. The chapter's stages (a userland buffer, a kernel splice, a blocking-aware version, a poll-aware refactor, a memory-mapped variant) form a clear progression that matches the order in which a beginner naturally encounters these concerns. +这些能力每一个都在编号的节中构建,每节都有编译、加载和行为可预测的代码。本章的阶段(用户态缓冲区、内核拼接、阻塞感知版本、poll 感知重构、内存映射变体)形成清晰的进展,匹配初学者自然遇到这些关注点的顺序。 -Along the way we covered three supplementary topics that often appear next to buffered I/O in real drivers: `d_mmap(9)`, the patterns and limitations of zero-copy thinking, and the readahead and write-coalescing patterns used by high-throughput drivers. None of these is a Chapter 10 topic in its own right, but each one builds naturally on the buffer abstraction you have just put in place. +沿途我们涵盖了三个经常在真实驱动中与缓冲 I/O 一起出现的补充主题:`d_mmap(9)`、零拷贝思考的模式和限制、以及高吞吐量驱动使用的预读和写合并模式。这些都不是第10章本身的主题,但每一个都自然地建立在你刚刚建立的缓冲区抽象之上。 -We exercised the driver with five new user-space test programs (`rw_myfirst_v2`, `rw_myfirst_nb`, `producer_consumer`, `stress_rw`, `mmap_myfirst`) plus the standard base-system tools (`dd`, `cat`, `hexdump`, `truss`, `sysctl`, `vmstat`). The combination is enough to catch most of the bugs this material typically produces. The Troubleshooting section catalogues those bugs with their symptoms and fixes; keep it bookmarked. +我们用五个新的用户空间测试程序(`rw_myfirst_v2`、`rw_myfirst_nb`、`producer_consumer`、`stress_rw`、`mmap_myfirst`)加上标准基本系统工具(`dd`、`cat`、`hexdump`、`truss`、`sysctl`、`vmstat`)对驱动进行了测试。组合足以捕获这些材料通常产生的大多数 bug。故障排除部分对这些 bug 及其症状和修复进行了分类;保持书签。 -Finally, we refactored the buffer access into a small set of helpers (`myfirst_buf_read`, `myfirst_buf_write`, `myfirst_wait_data`, `myfirst_wait_room`), wrote a one-paragraph locking-strategy comment near the top of the source, and put the cbuf into its own file with its own `MALLOC_DEFINE`. The driver's source is now in the shape that Chapter 11 wants: clear locking discipline, narrow abstractions, no surprises. +最后,我们将缓冲区访问重构为一小组辅助函数(`myfirst_buf_read`、`myfirst_buf_write`、`myfirst_wait_data`、`myfirst_wait_room`),在源码顶部附近写了一段锁定策略注释,并将 cbuf 放入自己带有自己 `MALLOC_DEFINE` 的文件中。驱动的源码现在处于第11章想要的形状:清晰的锁定纪律、窄抽象、无意外。 ## 总结 -The buffered driver you have just finished is the foundation for everything that follows in Part 3. The shape of its I/O path, the discipline of its locking, the way it sleeps and wakes, the way it composes with `poll(2)`: these are not Chapter 10 patterns. They are *the* patterns the kernel uses, and once you recognise them in your own code, you will recognise them in every character-device driver in `/usr/src/sys/dev/`. +你刚刚完成的缓冲驱动是第3部分后续所有内容的基础。其 I/O 路径的形状、锁定纪律、睡眠和唤醒的方式、与 `poll(2)` 组合的方式:这些不是第10章的模式。它们是内核使用的*标准*模式,一旦你在自己的代码中识别它们,你将在 `/usr/src/sys/dev/` 中的每个字符设备驱动中识别它们。 -It is worth taking a moment to feel that shift. When you started Chapter 7, the inside of a driver was probably an opaque set of names and signatures. By the end of Chapter 8 you had a sense of the lifecycle. By the end of Chapter 9 you had a sense of the data path. Now, at the end of Chapter 10, you have a sense of how a driver behaves under load: how it shapes itself around concurrent callers, how it manages a finite resource (the buffer), how it cooperates with the kernel's readiness primitives, how it gets out of its own way so that user-space programs can do real work against it. +值得花点时间感受这种转变。当你开始第7章时,驱动内部可能是一组不透明的名称和签名。到第8章结束时你有了生命周期感。到第9章结束时你有了数据路径感。现在,在第10章结束时,你有了驱动在负载下如何行为的感受:它如何围绕并发调用者塑造自己、如何管理有限资源(缓冲区)、如何与内核的就绪原语合作、如何不阻碍自己以便用户空间程序可以对其做真正的工作。 -Most of what you have built will carry through to Chapter 11. The mutex, the buffer, the helpers, the locking strategy, the test kit, the lab discipline: all of it remains. What changes in Chapter 11 is the *depth* of the questions you ask about each piece. Why one mutex and not two? Why `wakeup` and not `wakeup_one`? Why `mtx_sleep` and not `cv_wait`? What guarantees does the kernel make about when a sleeper wakes, and what guarantees does it not make? How do you prove a piece of code is correct under concurrency, rather than hope? +你构建的大部分内容将延续到第11章。互斥锁、缓冲区、辅助函数、锁定策略、测试套件、实验纪律:所有这些都将保留。第11章改变的是你对每一部分提出问题的*深度*。为什么一个互斥锁而不是两个?为什么 `wakeup` 而不是 `wakeup_one`?为什么 `mtx_sleep` 而不是 `cv_wait`?内核对睡眠者何时醒来做出什么保证,不做出什么保证?你如何证明一段代码在并发下是正确的,而不是期望? -Chapter 11 takes those questions seriously. It introduces `WITNESS` and `INVARIANTS` as the kernel's verification tools, walks through the lock classes, and discusses the patterns that turn merely-working concurrency into provably-correct concurrency. It will be a substantial chapter, but the substrate is what you have just built. +第11章认真对待这些问题。它引入 `WITNESS` 和 `INVARIANTS` 作为内核的验证工具,遍历锁类别,讨论将"刚好能工作"的并发转变为可证明正确的并发的模式。这将是一个实质性的章节,但基础是你刚刚构建的。 -Three closing reminders before you move on. +三个结束提醒。 -The first is to *commit your code*. Whatever version-control system you use, save the four stage directories as a snapshot. The next chapter's first lab will copy your Stage 4 source and modify it; you do not want to lose the working baseline. +第一是*提交你的代码*。无论你使用什么版本控制系统,将四个阶段目录保存为快照。下一章的第一个实验将复制你的阶段 4 源码并修改它;你不想丢失工作基线。 -The second is to *try the labs*. Reading driver code teaches you the patterns; writing driver code teaches you the discipline. The labs in this chapter are short on purpose. Even the long ones can be done in a single sitting. The combination of "I built this" and "I broke it on purpose to see what happens" is what the chapter is designed to produce. +第二是*尝试实验*。阅读驱动代码教你模式;编写驱动代码教你纪律。本章的实验故意简短。即使是长的也可以在一次会话中完成。"我构建了这个"和"我故意破坏它看会发生什么"的组合是本章设计要产生的。 -The third is to *trust the slow path*. The chapter has been deliberately careful, deliberately patient, deliberately repetitive in places. Driver work rewards that style. The bugs that hurt are the ones that look like they could not possibly happen. The defence against them is to be slow, careful, and methodical, even when the code seems simple. The reader who slows down with each step finishes Chapter 11 ready for Chapter 12; the reader who rushes finishes Chapter 11 with a kernel panic and a lost afternoon. +第三是*信任慢路径*。本章一直刻意小心、刻意耐心、在某些地方刻意重复。驱动工作奖励这种风格。真正伤人的 bug 是那些看起来不可能发生的。对它们的防御是缓慢、仔细、有条理,即使代码看起来很简单。每一步都放慢的读者完成第11章后为第12章做好准备;匆忙的读者完成第11章后带着内核恐慌和失去的一个下午。 -You are doing well. Keep going. +你做得很好。继续前进。 -## Part 2 Checkpoint +## 第2部分检查点 -Before you cross into Part 3, pause and check that the ground beneath your feet is solid. Part 2 has carried you from "what is a module" to "a multi-stage pseudo-driver that serves real readers and writers under load." The next part will put that driver on a much heavier scale, so the foundation needs to be firm. +在你进入第3部分之前,暂停并检查你脚下的基础是否坚实。第2部分带你从"什么是模块"到"一个在负载下服务真实读取者和写入者的多阶段伪驱动"。下一部分将把该驱动放在更重的天平上,所以基础需要牢固。 -By now you should be comfortable doing each of the following without hunting for the answer: +现在你应该能够不查找答案就舒适地做以下每件事: -- Writing, compiling, loading, and unloading a kernel module against a running kernel, and reading `dmesg` to confirm the lifecycle. -- Building a Newbus skeleton with `device_probe`, `device_attach`, and `device_detach`, backed by a per-unit softc allocated with `device_get_softc`. -- Exposing a `/dev` node through a `cdevsw` with working `d_open`, `d_close`, `d_read`, `d_write`, and `d_ioctl` handlers, and verifying that `devfs` cleans the node up on unload. -- Managing a circular buffer whose state is protected by a mutex, whose readers can block with `mtx_sleep` and be woken by `wakeup`, and whose readiness is advertised through `selrecord` and `selwakeup`. -- Walking a deliberate failure through the attach path and watching every allocation unwind in reverse order. +- 对运行中的内核编写、编译、加载和卸载内核模块,并阅读 `dmesg` 确认生命周期。 +- 用 `device_probe`、`device_attach` 和 `device_detach` 构建 Newbus 骨架,由通过 `device_get_softc` 分配的每单元 softc 支持。 +- 通过带有工作 `d_open`、`d_close`、`d_read`、`d_write` 和 `d_ioctl` 处理程序的 `cdevsw` 暴露 `/dev` 节点,并验证 `devfs` 在卸载时清理节点。 +- 管理由互斥锁保护状态的循环缓冲区,其读取者可以用 `mtx_sleep` 阻塞并被 `wakeup` 唤醒,其就绪状态通过 `selrecord` 和 `selwakeup` 广告。 +- 将一个故意故障走过 attach 路径并观察每个分配以相反顺序展开。 -If any of those feels unsteady, the labs that anchor them are worth a second pass. A targeted review list: +如果其中任何一个感觉不稳固,锚定它们的实验值得再做一遍。有针对性的复习列表: -- Build, load, and unload discipline: Lab 7.2 (Build, Load, and Verify Lifecycle) and Lab 7.4 (Simulate Attach Failure and Verify Unwinding). -- `cdevsw` hygiene and `devfs` nodes: Lab 8.1 (Structured Name and Tighter Permissions) and Lab 8.5 (Two-Node Driver). -- Data path and round-trip behaviour: Lab 9.2 (Exercise Stage 2 with Writes and Reads) and Lab 9.3 (Stage 3 FIFO Behaviour). -- The Chapter 10 core sequence: Lab 2 (Stage 2 Circular Buffer), Lab 3 (Stage 3 Blocking and Non-Blocking), and Lab 4 (Stage 4 Poll Support and Refactor). +- 构建、加载和卸载纪律:实验 7.2(构建、加载和验证生命周期)和实验 7.4(模拟 Attach 失败并验证展开)。 +- `cdevsw` 卫生和 `devfs` 节点:实验 8.1(结构化名称和更严格权限)和实验 8.5(双节点驱动)。 +- 数据路径和往返行为:实验 9.2(用写入和读取练习阶段 2)和实验 9.3(阶段 3 FIFO 行为)。 +- 第10章核心序列:实验 2(阶段 2 循环缓冲区)、实验 3(阶段 3 阻塞和非阻塞)和实验 4(阶段 4 Poll 支持和重构)。 -Part 3 will assume that all of the above is muscle memory, not a lookup. 具体来说, Chapter 11 will expect: +第3部分将假设以上所有都是肌肉记忆,不是查阅。具体来说,第11章将期望: -- A working Stage 4 `myfirst` that loads, unloads, and survives concurrent readers and writers without corruption. -- Familiarity with `mtx_sleep`/`wakeup` and the `selrecord`/`selwakeup` pair as the kernel's basic blocking and readiness primitives, since Part 3 will compare and contrast them with `cv(9)`, `sx(9)`, and `sema(9)`. -- A kernel built with `INVARIANTS` and `WITNESS`, since every Part 3 chapter leans on both from the first section onward. +- 一个工作的阶段 4 `myfirst`,可以加载、卸载,并在并发读取者和写入者下存活而不损坏。 +- 熟悉 `mtx_sleep`/`wakeup` 和 `selrecord`/`selwakeup` 对作为内核的基本阻塞和就绪原语,因为第3部分将把它们与 `cv(9)`、`sx(9)` 和 `sema(9)` 进行比较和对比。 +- 用 `INVARIANTS` 和 `WITNESS` 构建的内核,因为每个第3部分章节从第一节开始就依赖两者。 -If those three items hold, you are ready to turn the page. If one wobbles, fix that first. A quiet hour now saves a bewildering afternoon later. +如果这三项成立,你准备好翻页了。如果有一项摇晃,先修复它。现在安静的一小时节省之后困惑的一个下午。 -## Looking Ahead: Bridge to Chapter 11 +## 展望:通往第11章的桥梁 -Chapter 11 is titled "Concurrency in Drivers." Its job is to take the driver you have just finished and look at it through the lens of concurrency: not the casual "it works under modest load" sense we have used so far, but the rigorous "I can prove this is correct under any interleaving" sense. +第11章标题为"驱动中的并发"。它的工作是带你刚刚完成的驱动并透过并发的镜头审视它:不是我们迄今为止使用的随意的"在适度负载下能工作"的感觉,而是严格的"我可以证明这在任何交错下都正确"的感觉。 -The bridge is built on three observations from Chapter 10's work. +桥梁建立在第10章工作的三个观察之上。 -First, you already have a single mutex protecting all shared state. That is the simplest non-trivial concurrency design a driver can have, and it is the right starting point for understanding the more elaborate alternatives. Chapter 11 will use your driver as a test case for asking when one mutex is enough, when it is not, and what to do when it is not. +第一,你已经有一个保护所有共享状态的单个互斥锁。这是驱动可以有的最简单的非平凡并发设计,它是理解更精心设计的替代方案的正确起点。第11章将使用你的驱动作为测试用例,问一个互斥锁何时足够,何时不够,以及不够时做什么。 -Second, you already have a sleep / wake pattern that uses the mutex as an interlock. `mtx_sleep` and `wakeup` are the building blocks of every blocking primitive in the kernel. Chapter 11 will introduce condition variables (`cv_*`) as a more structured alternative, and will explain when each is appropriate. +第二,你已经有一个使用互斥锁作为互锁的睡眠/唤醒模式。`mtx_sleep` 和 `wakeup` 是内核中每个阻塞原语的构建块。第11章将引入条件变量(`cv_*`)作为更结构化的替代方案,并解释何时各有优劣。 -Third, you already have a buffer abstraction that is intentionally not thread-safe by itself. The cbuf relies on the caller to provide locking. Chapter 11 will discuss the spectrum from "data structure provides no locking" (your cbuf) through "data structure provides internal locking" (some kernel primitives) to "data structure is lock-free" (`buf_ring(9)`, `epoch(9)`-based readers). Each end of the spectrum has uses; understanding when to choose which is part of becoming a driver writer. +第三,你已经有一个有意设计为自身非线程安全的缓冲区抽象。cbuf 依赖调用者提供锁定。第11章将讨论从"数据结构不提供锁定"(你的 cbuf)到"数据结构提供内部锁定"(某些内核原语)到"数据结构是无锁的"(`buf_ring(9)`、基于 `epoch(9)` 的读取者)的光谱。光谱的每一端都有用途;理解何时选择哪个是成为驱动编写者的一部分。 -Specific topics Chapter 11 will cover include: +第11章将涵盖的具体主题包括: -- The five FreeBSD lock classes (`mtx`, `sx`, `rw`, `rm`, `lockmgr`) and when each is appropriate. -- Lock ordering and how to use `WITNESS` to verify it. -- The interaction between locks and interrupt context. -- Condition variables and when to prefer them over `mtx_sleep`. -- Reader/writer locks and their use cases. -- The `epoch(9)` framework for read-mostly data structures. -- Atomic operations (`atomic_*`) and when they obviate the need for locks. -- A walk-through of common concurrency bugs (lost wakeups, lock-order reversals, ABA, double-free under contention). +- 五种 FreeBSD 锁类别(`mtx`、`sx`、`rw`、`rm`、`lockmgr`)以及何时各有适用。 +- 锁排序以及如何使用 `WITNESS` 验证它。 +- 锁与中断上下文之间的交互。 +- 条件变量以及何时优先于 `mtx_sleep`。 +- 读取者/写入者锁及其用例。 +- 用于读取为主数据结构的 `epoch(9)` 框架。 +- 原子操作(`atomic_*`)以及何时它们使锁变得不必要。 +- 常见并发 bug(丢失唤醒、锁序反转、ABA、竞争下的双重释放)的演练。 -You do not need to read ahead to start Chapter 11. Everything in this chapter is sufficient preparation. Bring your Stage 4 driver, your test kit, and your `WITNESS`-enabled kernel; the next chapter starts where this one ended. +你不需要提前阅读来开始第11章。本章的所有内容都是充分的准备。带上你的阶段 4 驱动、你的测试套件和你启用 `WITNESS` 的内核;下一章从本章结束的地方开始。 -A small farewell from this chapter: you have just turned a beginner driver into a respectable one. The bytes that flow through `/dev/myfirst` are now flowing the way bytes flow through every other character device on the system. The patterns are right, the locking is right, the user-space contracts are honoured. The driver is yours to extend, to specialise, and to use as a baseline for whatever real device comes next. Take a moment to enjoy that, and then turn the page. +本章的一个小告别:你刚刚将一个初学者驱动变成了一个体面的驱动。流过 `/dev/myfirst` 的字节现在以与系统上每个其他字符设备相同的方式流动。模式正确,锁定正确,用户空间契约被遵守。驱动是你的,可以扩展、特化、并用作接下来任何真实设备的基线。花点时间享受这一点,然后翻页。 diff --git a/translations/zh_CN/chapters/part3/chapter-14.md b/translations/zh_CN/chapters/part3/chapter-14.md index d9da5a8..df2c280 100644 --- a/translations/zh_CN/chapters/part3/chapter-14.md +++ b/translations/zh_CN/chapters/part3/chapter-14.md @@ -17,216 +17,216 @@ language: "zh-CN" ## 读者指南与学习成果 -At the end of Chapter 13 your `myfirst` driver gained a small but real sense of internal time. It could schedule periodic work with `callout(9)`, emit a heartbeat, notice stalled drainage with a watchdog, and inject synthetic bytes with a tick source. Every callback obeyed a strict discipline: acquire the registered mutex, check `is_attached`, do short bounded work, maybe re-arm, release the mutex. That discipline is what made the timers safe. It is also what made them narrow. +在第13章结束时,你的 `myfirst` 驱动获得了一种微小但真实的内部时间感。它可以用 `callout(9)` 调度周期性工作,发出心跳,用看门狗检测排放停滞,用 tick 源注入合成字节。每个回调都遵循严格的纪律:获取已注册的互斥锁,检查 `is_attached`,做短小有界的工作,可能重新武装,释放互斥锁。正是这种纪律使定时器安全,也正是这种纪律使它们变得狭窄。 -Chapter 14 confronts the narrowness directly. A callout callback runs in a context that cannot sleep. It cannot call `uiomove(9)`, it cannot call `copyin(9)`, it cannot acquire a sleepable `sx(9)` lock, it cannot allocate memory with `M_WAITOK`, it cannot call `selwakeup(9)` while the sleep mutex is held. If the work a timer wants to trigger needs any of those, the timer has to hand the work off. The same limitation applies to the interrupt handlers you will meet in Part 4, and to several other constrained contexts that appear throughout the kernel. The kernel exposes a single primitive for the hand-off: `taskqueue(9)`. +第14章直面这种狭窄性。callout 回调运行在一个不能睡眠的上下文中。它不能调用 `uiomove(9)`,不能调用 `copyin(9)`,不能获取可睡眠的 `sx(9)` 锁,不能用 `M_WAITOK` 分配内存,不能在持有睡眠互斥锁时调用 `selwakeup(9)`。如果定时器想要触发的工作需要其中任何一种,定时器就必须将工作移交出去。同样的限制也适用于你将在第四部分遇到的中断处理程序,以及整个内核中出现的其他几种受限上下文。内核为此提供了一个单一原语:`taskqueue(9)`。 -A taskqueue is, at its simplest, a queue of small work items paired with one or more kernel threads that consume the queue. Your constrained context enqueues a task; the taskqueue's thread wakes up and runs the task's callback in process context, where the ordinary kernel rules apply. The task can sleep, it can allocate freely, it can touch sleepable locks. The taskqueue subsystem also knows how to coalesce bursts of enqueues, cancel pending work, wait for in-flight work at teardown, and schedule a task for a specific future moment. All of that fits on a small API surface, and all of it is exactly what a callout-using or interrupt-using driver needs. +任务队列最简单的形式是一个由小型工作项组成的队列,配以一个或多个消费该队列的内核线程。你的受限上下文将任务入队;任务队列的线程被唤醒并在进程上下文中运行任务的回调,那里适用普通的内核规则。任务可以睡眠,可以自由分配内存,可以触碰可睡眠的锁。任务队列子系统还知道如何合并突发入队、取消待处理的工作、在拆除时等待进行中的工作,以及在特定的未来时刻调度任务。所有这些都在一个小的 API 表面上实现,并且所有这些正是使用 callout 或中断的驱动程序所需要的。 -This chapter teaches `taskqueue(9)` with the same care Chapter 13 gave to `callout(9)`. We begin with the shape of the problem, walk through the API, then evolve the `myfirst` driver through four stages that add task-based deferral to the existing timer infrastructure. By the end the driver will use a private taskqueue to move every piece of work that cannot run in a callout or interrupt context out of those contexts, and it will tear the taskqueue down at detach without leaking a stale task, waking a dead thread, or corrupting anything. +本章以第13章讲解 `callout(9)` 的同样细致程度来教授 `taskqueue(9)`。我们从问题的形态开始,逐步介绍 API,然后通过四个阶段演进 `myfirst` 驱动,将基于任务的延迟工作添加到现有的定时器基础设施上。到本章结束时,驱动将使用一个私有任务队列,将所有不能在 callout 或中断上下文中运行的工作移出这些上下文,并在分离时干净地拆除任务队列,不会泄漏过时任务、唤醒死线程或损坏任何东西。 ### 为什么本章有其独立的价值 -You could pretend taskqueues do not exist. Instead of enqueuing a task, your callout could try to do the deferred work inline, accept the consequences of panicking the kernel the first time `WITNESS` notices a sleep with a spin lock held, and hope nobody ever loads your driver on a debug kernel. That is not a real option, and we will not humor it. The purpose of this chapter is to give you the honest alternative, the one the rest of the kernel actually uses. +你可以假装任务队列不存在。你的 callout 可以尝试内联执行延迟工作,接受第一次 `WITNESS` 检测到持有自旋锁时睡眠而导致内核崩溃的后果,并希望没有人会在调试内核上加载你的驱动。这不是一个真正的选项,我们不会拿它当回事。本章的目的是给你一个诚实的替代方案,内核其余部分实际使用的那个。 -You could also roll your own deferred-work framework with `kproc_create(9)` and a custom condition variable. That is technically possible and occasionally unavoidable, but it is almost always the wrong first choice. A custom thread is a weightier resource than a task, and it misses the observability that comes for free when you use the shared framework. `ps(1)`, `procstat(1)`, `dtrace(1)`, `ktr(4)`, `wchan` traces, and `ddb(4)` all understand taskqueue threads. They do not understand your one-off helper unless you instrument it yourself. +你也可以用 `kproc_create(9)` 和自定义条件变量来搭建自己的延迟工作框架。这在技术上是可行的,偶尔也不可避免,但几乎总是错误的首选。自定义线程比任务更重量级,而且它缺少使用共享框架时免费获得的可观察性。`ps(1)`、`procstat(1)`、`dtrace(1)`、`ktr(4)`、`wchan` 跟踪和 `ddb(4)` 都理解任务队列线程。除非你自己为一次性的辅助线程添加插桩,否则它们不会理解你的辅助线程。 -Taskqueues are the right answer in almost every case where a driver needs to move work out of a constrained context. The cost of not knowing them is higher than the cost of learning them, and the cost of learning them is modest: the API is smaller than `callout(9)`'s, the rules are regular, and the idioms transfer directly across drivers. Once the mental model clicks, you will start recognising the pattern in nearly every driver under `/usr/src/sys/dev/`. +在几乎每个驱动程序需要将工作移出受限上下文的情况下,任务队列都是正确的答案。不了解它们的代价高于学习它们的代价,而学习它们的代价是适中的:API 比 `callout(9)` 更小,规则是规则的,习语可以直接跨驱动程序转移。一旦心智模型到位,你会开始在 `/usr/src/sys/dev/` 下的几乎每个驱动程序中识别出这种模式。 ### 第13章结束后驱动的状态 -A quick checkpoint before we go further. Chapter 14 extends the driver produced at the end of Chapter 13 Stage 4, not any earlier stage. If any of the items below feels uncertain, return to Chapter 13 before starting this chapter. +在继续之前快速检查一下。第14章扩展的是第13章第4阶段结束时产生的驱动程序,不是任何更早的阶段。如果以下任何一项让你感到不确定,请在开始本章之前返回第13章。 -- Your `myfirst` driver compiles cleanly and identifies itself as version `0.7-timers`. -- It has three callouts declared in the softc: `heartbeat_co`, `watchdog_co`, and `tick_source_co`. -- Each callout is initialised with `callout_init_mtx(&co, &sc->mtx, 0)` in `myfirst_attach` and drained with `callout_drain` in `myfirst_detach` after `is_attached` has been cleared. -- Each callout has an interval sysctl (`heartbeat_interval_ms`, `watchdog_interval_ms`, `tick_source_interval_ms`) that defaults to zero (disabled) and reflects the enable/disable transitions in its handler. -- The detach path runs in the documented order: refuse on `active_fhs`, clear `is_attached`, broadcast both cvs, drain `selinfo`, drain all callouts, destroy devices, free sysctls, destroy cbuf and counters and cvs and the sx and the mutex. -- Your `LOCKING.md` has a Callouts section that names each callout, its callback, its lock, and its lifetime. -- The Chapter 13 stress kit (Chapter 12 testers plus the Chapter 13 timer exercisers) builds and runs cleanly with `WITNESS` and `INVARIANTS` enabled. +- 你的 `myfirst` 驱动编译干净,版本标识为 `0.7-timers`。 +- 它在 softc 中声明了三个 callout:`heartbeat_co`、`watchdog_co` 和 `tick_source_co`。 +- 每个 callout 在 `myfirst_attach` 中用 `callout_init_mtx(&co, &sc->mtx, 0)` 初始化,并在 `is_attached` 被清除后用 `callout_drain` 排空。 +- 每个 callout 有一个间隔 sysctl(`heartbeat_interval_ms`、`watchdog_interval_ms`、`tick_source_interval_ms`),默认为零(禁用),并在其处理程序中反映启用/禁用转换。 +- 分离路径按文档记录的顺序运行:在 `active_fhs` 上拒绝,清除 `is_attached`,广播两个 cv,排空 `selinfo`,排空所有 callout,销毁设备,释放 sysctl,销毁 cbuf、计数器、cv、sx 和互斥锁。 +- 你的 `LOCKING.md` 有一个 Callouts 节,命名每个 callout、其回调、其锁及其生命周期。 +- 第13章压力测试套件(第12章测试器加第13章定时器测试)在启用 `WITNESS` 和 `INVARIANTS` 时构建并干净运行。 -That driver is the shape we extend. Chapter 14 does not rework any of those structures. It adds a new column to the softc, a new initialisation call, a new teardown call, and small changes to the three callout callbacks and one or two other places where the driver would benefit from moving work out of a constrained context. +那个驱动就是我们要扩展的形态。第14章不会重构任何这些结构。它在 softc 中添加一个新列,一个新的初始化调用,一个新的拆除调用,以及对三个 callout 回调和一个或两个其他地方的少量更改,这些地方驱动程序会受益于将工作移出受限上下文。 ### 你将学到什么 -By the end of this chapter you will be able to: +到本章结束时你将能够: -- Explain why some work cannot be done inside a callout callback or an interrupt handler, and recognise the operations that force a hand-off to a different context. -- Describe the three things a taskqueue is: a queue of `struct task`, a thread (or small pool of threads) that consumes the queue, and an enqueue/dispatch policy that ties the two together. -- Initialise a task with `TASK_INIT(&sc->foo_task, 0, myfirst_foo_task, sc)`, understand what each argument means, and place the call in the correct stage of attach. -- Enqueue a task with `taskqueue_enqueue(tq, &sc->foo_task)` from a callout callback, from a sysctl handler, from a read or write path, or from any other driver code where deferral is the right answer. -- Choose between the predefined system taskqueues (`taskqueue_thread`, `taskqueue_swi`, `taskqueue_swi_giant`, `taskqueue_fast`, `taskqueue_bus`) and a private taskqueue you create with `taskqueue_create` and populate with `taskqueue_start_threads`. -- Understand the coalescing contract: when a task is enqueued while it is already pending, the kernel increments `ta_pending` instead of linking it twice, and the callback is handed the final pending count so it can batch. -- Use the `struct timeout_task` variant with `taskqueue_enqueue_timeout` to schedule a task for a specific future moment, and drain it correctly with `taskqueue_drain_timeout`. -- Block and unblock a taskqueue around delicate shutdown steps, and quiesce a taskqueue when you need a guarantee that no task is currently running anywhere in the queue. -- Drain every task a driver owns at detach, in the right order, without deadlocking against the callouts and cvs you already drain. -- Separate the concerns of timer code and task code inside your driver source, so a new reader can tell which work runs in which context just by looking at the file. -- Recognise and apply the network-driver pattern that uses `epoch(9)` and grouptaskqueues for lockless read paths, at the level of knowing when to reach for them and when not to. -- Debug a taskqueue-using driver with `procstat -t`, `ps ax`, `dtrace -l`, and `ktr(4)`, and interpret what each tool shows you. -- Tag the driver as version `0.8-taskqueues` and document the deferral policy in `LOCKING.md` so that the next person who inherits the driver can read it. +- 解释为什么某些工作不能在 callout 回调或中断处理程序中完成,并识别强制将工作移交给不同上下文的操作。 +- 描述任务队列的三要素:`struct task` 的队列、消费该队列的线程(或小型线程池),以及将两者联系在一起的入队/调度策略。 +- 使用 `TASK_INIT(&sc->foo_task, 0, myfirst_foo_task, sc)` 初始化任务,理解每个参数的含义,并将调用放在 attach 的正确阶段。 +- 从 callout 回调、sysctl 处理程序、读或写路径,或任何其他延迟工作是正确答案的驱动程序代码中使用 `taskqueue_enqueue(tq, &sc->foo_task)` 将任务入队。 +- 在预定义的系统任务队列(`taskqueue_thread`、`taskqueue_swi`、`taskqueue_swi_giant`、`taskqueue_fast`、`taskqueue_bus`)与你用 `taskqueue_create` 创建并用 `taskqueue_start_threads` 启动的私有任务队列之间做出选择。 +- 理解合并契约:当任务在已待处理时被入队,内核递增 `ta_pending` 而不是将其链接两次,回调获得最终的待处理计数以便进行批量处理。 +- 使用 `struct timeout_task` 变体配合 `taskqueue_enqueue_timeout` 在特定的未来时刻调度任务,并用 `taskqueue_drain_timeout` 正确排空它。 +- 在精细的关闭步骤周围阻塞和解阻塞任务队列,以及当你需要保证队列中没有任务正在运行时静默任务队列。 +- 在分离时排空驱动拥有的每个任务,以正确的顺序,不会与你已经排空的 callout 和 cv 发生死锁。 +- 在驱动源码中分离定时器代码和任务代码的关注点,使新读者只需查看文件就能判断哪些工作在哪个上下文中运行。 +- 认识并应用使用 `epoch(9)` 和组任务队列实现无锁读路径的网络驱动模式,达到知道何时使用它们何时不用的水平。 +- 使用 `procstat -t`、`ps ax`、`dtrace -l` 和 `ktr(4)` 调试使用任务队列的驱动,并解释每个工具向你展示的内容。 +- 将驱动标记为版本 `0.8-taskqueues`,并在 `LOCKING.md` 中记录延迟策略,使下一个继承驱动的人能够阅读它。 -That is a long list. Most items build on each other, so the progression inside the chapter is the natural path. +这是一个很长的列表。大多数条目相互构建,因此章节内的递进就是自然的路径。 ### 本章不涵盖的内容 -Several adjacent topics are explicitly deferred so Chapter 14 stays focused. +几个相邻主题被明确推迟,以保持第14章的专注。 -- **Interrupt handlers as a primary topic.** Part 4 introduces `bus_setup_intr(9)` and the split between `FILTER` and `ITHREAD` handlers. Chapter 14 mentions interrupt context when it explains why deferred work matters, and the patterns it teaches transfer directly from callouts to real interrupt handlers, but the interrupt API itself is Part 4's job. -- **The full condition-variable and semaphore story.** Chapter 15 extends the synchronisation vocabulary with counting semaphores, signal-interruptible blocking, and cross-component handshakes that coordinate timers, tasks, and user threads. Chapter 14 uses the existing cv infrastructure as-is and does not add new synchronisation primitives beyond what taskqueues themselves bring. -- **Deep coverage of grouptaskqueues and iflib.** The `taskqgroup` family exists and this chapter explains when it is the right answer, but the complete story belongs to the network drivers in Part 6 (Chapter 28). The introduction here is intentionally light. -- **Hardware-driven DMA completion paths.** A taskqueue is the natural place to finish a DMA transfer after the hardware signalled completion via an interrupt, and we mention that pattern, but the mechanics of DMA buffer management wait until the bus-space and DMA chapters. -- **Workloops, kthreads for per-CPU polling, and the advanced scheduler hooks.** These are real parts of the kernel's deferred-work landscape, but they are specialised, and a driver hits them rarely. When they matter, the chapters that need them introduce them. +- **中断处理程序作为主要主题。** 第四部分介绍 `bus_setup_intr(9)` 以及 `FILTER` 和 `ITHREAD` 处理程序之间的分离。第14章在解释延迟工作的重要性时提到中断上下文,它教授的模式可以直接从 callout 转移到真正的中断处理程序,但中断 API 本身是第四部分的工作。 +- **完整的条件变量和信号量故事。** 第15章用计数信号量、信号可中断阻塞和协调定时器、任务和用户线程的跨组件握手来扩展同步词汇。第14章按原样使用现有的 cv 基础设施,不添加超出任务队列本身带来的新同步原语。 +- **组任务队列和 iflib 的深入覆盖。** `taskqgroup` 系列存在,本章解释何时它是正确答案,但完整的故事属于第六部分的网络驱动(第28章)。这里的介绍有意保持轻量。 +- **硬件驱动的 DMA 完成路径。** 任务队列是在中断发出完成信号后完成 DMA 传输的自然场所,我们提到了这种模式,但 DMA 缓冲区管理的机制等到总线空间和 DMA 章节再讲。 +- **工作循环、每 CPU 轮询的内核线程和高级调度器钩子。** 这些是内核延迟工作领域的真实组成部分,但它们是专用的,驱动程序很少触及。当它们重要时,需要它们的章节会引入它们。 -Staying inside those lines keeps the chapter's mental model coherent. Chapter 14 gives you one good tool, taught carefully. Later chapters give you the neighbouring tools and the real hardware contexts that justify using them. +保持在这些界限内使章节的心智模型保持一致。第14章给你一个精心教授的好工具。后续章节给你相邻的工具和证明使用它们合理的真实硬件上下文。 ### 预计时间投入 -- **Reading only**: about three hours. The API surface is smaller than `callout(9)`'s, but the interaction between a taskqueue and the rest of the driver's locking story takes a little time to settle. -- **Reading plus typing the worked examples**: six to eight hours over two sessions. The driver evolves in four stages; each stage changes roughly one concern. -- **Reading plus all labs and challenges**: ten to fourteen hours over three or four sessions, including the time needed to observe taskqueue threads under load with `procstat`, `dtrace`, and a stress workload. +- **仅阅读**:约三小时。API 表面比 `callout(9)` 小,但任务队列与驱动其余锁定故事的交互需要一点时间来消化。 +- **阅读加输入工作示例**:两次会话共六至八小时。驱动分四个阶段演进;每个阶段大约改变一个关注点。 +- **阅读加所有实验和挑战**:三到四次会话共十至十四小时,包括用 `procstat`、`dtrace` 和压力工作负载观察任务队列线程所需的时间。 -If you find the ordering rules at the start of Section 4 disorienting, that is normal. The detach sequence with callouts, cvs, sel handlers, and now tasks has four pieces that must compose. We will walk through the order once, state it, justify it, and reuse it. +如果你发现第4节开头的排序规则令人困惑,那是正常的。带有 callout、cv、sel 处理程序以及现在任务的分离序列有四个必须正确组合的部分。我们将遍历一次顺序,陈述它,论证它,然后重用它。 ### 先决条件 -Before starting this chapter, confirm: +在开始本章之前,请确认: -- Your driver source matches Chapter 13 Stage 4 (`stage4-final`). The starting point assumes the three callouts, the three interval sysctls, the `is_attached` discipline in every callback, and the documented detach order. -- Your lab machine runs FreeBSD 14.3 with `/usr/src` on disk and matching the running kernel. Several of the source references in this chapter are things you should actually open and read. -- A debug kernel with `INVARIANTS`, `WITNESS`, `WITNESS_SKIPSPIN`, `DDB`, `KDB`, and `KDB_UNATTENDED` is built, installed, and booting cleanly. -- Chapter 13 feels comfortable. The lock-aware callout, the `is_attached` discipline in callbacks, and the detach ordering are assumed knowledge here. -- You have run the Chapter 13 stress kit at least once with every timer enabled and seen it pass cleanly. +- 你的驱动源码匹配第13章第4阶段(`stage4-final`)。起始点假设有三个 callout、三个间隔 sysctl、每个回调中的 `is_attached` 纪律,以及文档记录的分离顺序。 +- 你的实验机器运行 FreeBSD 14.3,磁盘上有 `/usr/src` 并与运行中的内核匹配。本章的几个源码引用是你应该实际打开和阅读的内容。 +- 一个启用了 `INVARIANTS`、`WITNESS`、`WITNESS_SKIPSPIN`、`DDB`、`KDB` 和 `KDB_UNATTENDED` 的调试内核已构建、安装并干净启动。 +- 第13章让你感到舒适。锁感知的 callout、回调中的 `is_attached` 纪律和分离排序是这里的假设知识。 +- 你至少运行过一次第13章的压力测试套件,每个定时器都已启用,并看到它干净通过。 -If any of the above is shaky, fixing it now is a better investment than pushing through Chapter 14 and trying to debug from a moving foundation. The Chapter 14 patterns are specifically designed to compose with the Chapter 13 patterns; starting from a Chapter 13 driver that is not quite right makes every Chapter 14 step harder. +如果以上任何一项不够扎实,现在修复它是比勉强推进第14章并试图在不稳固的基础上调试更好的投资。第14章的模式专门设计为与第13章的模式组合;从一个不太正确的第13章驱动开始会使第14章的每一步都更难。 ### 如何从本章获得最大收益 -Three habits will pay off quickly. +三个习惯会很快带来回报。 -First, keep `/usr/src/sys/kern/subr_taskqueue.c` and `/usr/src/sys/sys/taskqueue.h` bookmarked. The header is short, about two hundred lines, and it is the canonical summary of the API. The implementation file is about a thousand lines, well commented, and reading `taskqueue_run_locked` carefully pays for itself the first time you have to reason about what a task's `pending` count actually means. Ten minutes with the header now buys ten hours of confidence later. +首先,将 `/usr/src/sys/kern/subr_taskqueue.c` 和 `/usr/src/sys/sys/taskqueue.h` 加入书签。头文件很短,大约两百行,是 API 的权威总结。实现文件大约一千行,注释完善,仔细阅读 `taskqueue_run_locked` 在你第一次需要推理任务的 `pending` 计数实际含义时会物有所值。现在花十分钟读头文件,日后省十小时的信心。 -Second, run every code change under `WITNESS`. The taskqueue subsystem has its own lock (a spin mutex or a sleep mutex, depending on whether the queue was created with `taskqueue_create` or `taskqueue_create_fast`), and it interacts with your driver's locks in ways that `WITNESS` understands. A misplaced lock acquisition inside a task callback is exactly the kind of bug `WITNESS` catches instantly on a debug kernel and corrupts silently on a production kernel. Do not run Chapter 14 code on the production kernel until it passes the debug kernel. +其次,在 `WITNESS` 下运行每一次代码更改。任务队列子系统有自己的锁(自旋互斥锁或睡眠互斥锁,取决于队列是用 `taskqueue_create` 还是 `taskqueue_create_fast` 创建的),它以 `WITNESS` 理解的方式与你的驱动锁交互。任务回调中错位的锁获取正是 `WITNESS` 在调试内核上立即捕获而在生产内核上静默损坏的那种 bug。在通过调试内核之前不要在生产内核上运行第14章的代码。 -Third, type the changes by hand. The companion source under `examples/part-03/ch14-taskqueues-and-deferred-work/` is the canonical version, but muscle memory is worth more than reading. The chapter introduces small incremental edits; mirror that small-step rhythm in your own copy of the driver. When the test environment passes at one stage, commit that version and move on; when a step breaks, the previous commit is your recovery point. +第三,手动输入更改。`examples/part-03/ch14-taskqueues-and-deferred-work/` 下的配套源码是权威版本,但肌肉记忆比阅读更有价值。本章引入小的增量编辑;在你自己的驱动副本中镜像这种小步节奏。当测试环境在某个阶段通过时,提交那个版本然后继续;当某一步中断时,上一个提交就是你的恢复点。 ### 本章路线图 -The sections in order are: +各节顺序如下: -1. Why use deferred work in a driver. The shape of the problem: what cannot be done in callouts, interrupts, and other constrained contexts; the real-world cases that force the hand-off. -2. Introduction to `taskqueue(9)`. The structures, the API, the predefined queues, and the comparison with callouts. -3. Deferring work from a timer or simulated interrupt. The first refactor, Stage 1: add a single task that a callout enqueues. -4. Taskqueue setup and cleanup. Stage 2: create a private taskqueue, wire the detach sequence, and audit the result against `WITNESS`. -5. Prioritisation and coalescing of work. Stage 3: use the `ta_pending` coalescing behaviour deliberately for batching, introduce `taskqueue_enqueue_timeout` for scheduled tasks, and discuss priorities. -6. Real-world patterns using taskqueues. A tour of patterns that recur in real FreeBSD drivers, presented as small recipes you can lift into your own code. -7. Debugging taskqueues. The tools, the common mistakes, and a guided break-and-fix on a realistic scenario. -8. Refactoring and versioning. Stage 4: consolidate the driver into a coherent whole, bump the version to `0.8-taskqueues`, and extend `LOCKING.md`. +1. 为什么在驱动中使用延迟工作。问题的形态:在 callout、中断和其他受限上下文中不能做什么;迫使移交的真实世界案例。 +2. `taskqueue(9)` 简介。结构、API、预定义队列,以及与 callout 的比较。 +3. 从定时器或模拟中断延迟工作。第一次重构,第1阶段:添加一个由 callout 入队的单一任务。 +4. 任务队列设置与清理。第2阶段:创建私有任务队列,连接分离序列,并对照 `WITNESS` 审计结果。 +5. 工作的优先级与合并。第3阶段:故意使用 `ta_pending` 合并行为进行批处理,引入 `taskqueue_enqueue_timeout` 用于调度任务,并讨论优先级。 +6. 使用任务队列的真实模式。在真实 FreeBSD 驱动中反复出现的模式之旅,以可直接用于你自己代码的小型方案呈现。 +7. 调试任务队列。工具、常见错误,以及一个在真实场景上引导式破坏-修复练习。 +8. 重构与版本化。第4阶段:将驱动整合为一个连贯的整体,将版本提升到 `0.8-taskqueues`,并扩展 `LOCKING.md`。 -After the eight main sections, we cover `epoch(9)`, grouptaskqueues, and per-CPU taskqueues at a light, introductory level, then hands-on labs, challenge exercises, a troubleshooting reference, a wrapping-up section, and a bridge to Chapter 15. +在八个主要节之后,我们以轻松的介绍级别覆盖 `epoch(9)`、组任务队列和每 CPU 任务队列,然后是动手实验、挑战练习、故障排除参考、收尾部分,以及通往第15章的桥梁。 -If this is your first pass, read linearly and do the labs in order. If you are revisiting, Sections 4, 6, and 8 stand alone and make good single-sitting reads. +如果是第一次阅读,请线性阅读并按顺序做实验。如果是复习,第4、6和8节可以独立阅读,适合单次阅读。 ## 第1节:为什么在驱动中使用延迟工作? -Chapter 13 ended with a driver whose callouts did every job the callback could safely do. The heartbeat printed a one-line status report. The watchdog recorded a single count and optionally printed a warning. The tick source wrote a single byte to the circular buffer and signalled a condition variable. Each callback took microseconds, held the mutex for those microseconds, and returned. That is the callout contract at its best: small, predictable, lock-aware, and cheap. +第13章结束时,驱动的 callout 完成了回调可以安全完成的每项工作。心跳打印一行状态报告。看门狗记录单个计数并可选地打印警告。tick 源向循环缓冲区写入单个字节并通知条件变量。每个回调花费微秒,在这几微秒内持有互斥锁,然后返回。这就是 callout 契约的最佳状态:小型、可预测、锁感知、低成本。 -Real driver work does not always fit inside that contract. Some tasks want to run at the same pace as the timer that notices the need for them, but they want to do things the timer cannot safely do. Other tasks are triggered by a different constrained context (an interrupt handler, for example, or a filter routine in the network stack) but have the same "cannot do that here" problem. This section surveys the shape of the problem: what cannot be done in constrained contexts, what kinds of work drivers want to defer, and what options the kernel offers for getting the work to a place where it can actually run. +真实的驱动工作并不总是能适配这个契约。有些任务希望以注意到需求的定时器相同的节奏运行,但它们想做定时器不能安全做的事情。其他任务由不同的受限上下文触发(例如中断处理程序,或网络栈中的过滤例程),但有同样的"不能在这里做"的问题。本节概述问题的形态:在受限上下文中不能做什么、驱动想要延迟什么样的工作,以及内核提供了哪些将工作转移到可以实际运行的地方的选项。 ### 重温定时调用契约 -A short re-reading of the callout rule, because the taskqueue story is entirely about the things callouts cannot do. +简短地重读 callout 规则,因为任务队列的故事完全关于 callout 不能做的事情。 -A `callout(9)` callback runs in one of two modes. The default mode is dispatch-from-callout-thread: the kernel's dedicated callout thread for that CPU wakes up on a hardware-clock boundary, walks the callout wheel, finds the callbacks whose deadlines have arrived, and calls them one by one. The alternative mode, `C_DIRECT_EXEC`, runs the callback directly inside the hardware-clock interrupt handler itself. Your driver rarely picks the alternative; the default is what almost all drivers use. +`callout(9)` 回调以两种模式之一运行。默认模式是从 callout 线程调度:该 CPU 的专用 callout 线程在硬件时钟边界上唤醒,遍历 callout 轮盘,找到截止时间已到的回调,并逐个调用它们。另一种模式 `C_DIRECT_EXEC` 直接在硬件时钟中断处理程序内部运行回调。你的驱动很少选择替代模式;几乎所有驱动都使用默认模式。 -In both modes the callback runs with the callout's registered lock held (for the `callout_init_mtx` family) and cannot cross certain context boundaries. It must not sleep. Sleeping means calling any primitive that can deschedule the thread and block for an indefinite period waiting for a condition. `mtx_sleep`, `cv_wait`, `msleep`, `sx_slock`, `malloc(..., M_WAITOK)`, `uiomove`, `copyin`, and `copyout` all sleep on their slow path. `selwakeup(9)` does not sleep per se, but it takes the per-selinfo mutex, which can be the wrong mutex for the context the callout is running in, and standard practice is to call it with no driver mutex held anyway. None of those calls belong inside a callout callback. +在两种模式下,回调都持有 callout 注册的锁运行(对于 `callout_init_mtx` 系列),并且不能跨越某些上下文边界。它不能睡眠。睡眠意味着调用任何可以取消调度线程并无限期等待条件的原语。`mtx_sleep`、`cv_wait`、`msleep`、`sx_slock`、`malloc(..., M_WAITOK)`、`uiomove`、`copyin` 和 `copyout` 在其慢路径上都会睡眠。`selwakeup(9)` 本身不睡眠,但它获取每 selinfo 的互斥锁,这可能是 callout 运行上下文中错误的互斥锁,标准做法是在没有驱动互斥锁持有的情况下调用它。这些调用都不属于 callout 回调内部。 -Those are hard rules at the kernel level. `INVARIANTS` and `WITNESS` catch many of the violations at runtime. A few of them corrupt the kernel silently, in ways that are hard to debug later. In all cases, a driver that wants the effect of one of those operations must make the call from a context that allows it. That context is the context a taskqueue provides. +这些在内核层面是硬性规则。`INVARIANTS` 和 `WITNESS` 在运行时捕获许多违规。其中一些会静默地损坏内核,以后很难调试。在所有情况下,想要获得这些操作效果的驱动必须从允许它的上下文进行调用。那个上下文就是任务队列提供的上下文。 -The rest of this section expands on the same observation from different angles: what sort of work a driver wants to defer, why the constrained contexts deserve the constraints, and which FreeBSD facilities compete for the job. +本节的其余部分从不同角度扩展同一观察:驱动想要延迟什么样的工作、为什么受限上下文值得这些约束、以及哪些 FreeBSD 设施竞争这项工作。 ### 受限上下文,不仅是定时调用 -The callout is the first constrained context a `myfirst`-style driver meets, but it is not the only one. Several other places in the kernel run code that cannot sleep or cannot do certain kinds of allocation. A driver that wants to take action from any of them faces the same "defer it" decision. +callout 是 `myfirst` 风格驱动遇到的第一个受限上下文,但它不是唯一的。内核中有其他几个地方运行的代码不能睡眠或不能做某些类型的分配。想要从其中任何一个采取行动的驱动都面临同样的"延迟它"的决定。 -**Hardware interrupt filters.** When a real device raises an interrupt, the kernel runs a filter routine synchronously on the CPU that took the interrupt. Filters cannot sleep, cannot acquire sleep mutexes, and cannot call most of the kernel's normal APIs. They are usually split into a tiny filter (read a status register, decide whether the interrupt is ours) that runs in hardware context, plus an associated ithread (interrupt thread) that runs the real work in a full thread context. We will meet the precise filter/ithread split when Part 4 introduces `bus_setup_intr(9)`, but the structural lesson is clear even now: interrupt filters are another place where work must be handed off somewhere else. +**硬件中断过滤器。** 当真实设备引发中断时,内核在接收中断的 CPU 上同步运行过滤例程。过滤器不能睡眠,不能获取睡眠互斥锁,不能调用内核大多数常规 API。它们通常被拆分为一个微型过滤器(读状态寄存器,判断中断是否属于我们)在硬件上下文中运行,加上一个关联的 ithread(中断线程)在完整线程上下文中运行真正的工作。当第四部分引入 `bus_setup_intr(9)` 时,我们将遇到精确的过滤器/ithread 分割,但结构性的教训现在就很清楚:中断过滤器是另一个必须将工作移交到其他地方的位置。 -**Network packet-input paths.** Parts of the `ifnet(9)` reception path run under `epoch(9)` protection, which restricts the kind of lock acquisitions and sleeping operations that are safe. Network drivers frequently enqueue a task when they want to do non-trivial work that belongs in process context. +**网络包输入路径。** `ifnet(9)` 接收路径的某些部分在 `epoch(9)` 保护下运行,限制了安全的锁获取和睡眠操作类型。网络驱动在想要做属于进程上下文的非平凡工作时频繁入队任务。 -**`taskqueue_fast` and `taskqueue_swi` callbacks.** Even when you are already inside a task callback, if the task is running on a spin-mutex-backed queue (`taskqueue_fast`) or a software-interrupt queue (`taskqueue_swi`), the same no-sleeping rule applies as for the originating context. Task callbacks on the default `taskqueue_thread` have no such restriction; they run in full thread context and can sleep freely. That distinction matters and we will return to it in Section 2. +**`taskqueue_fast` 和 `taskqueue_swi` 回调。** 即使你已经在任务回调内部,如果任务运行在自旋互斥锁支持的队列(`taskqueue_fast`)或软件中断队列(`taskqueue_swi`)上,同样的禁止睡眠规则与原始上下文一样适用。在默认的 `taskqueue_thread` 上的任务回调没有这种限制;它们在完整线程上下文中运行,可以自由睡眠。这个区别很重要,我们将在第2节回到这个话题。 -**`epoch(9)` read sections.** A code path bracketed by `epoch_enter()` and `epoch_exit()` cannot sleep. Network drivers use this pattern heavily to make read paths lock-free; write-side work is deferred to outside the epoch. Chapter 14 covers epoch at an introductory level in the later "Additional topics" part of the chapter. +**`epoch(9)` 读段。** 由 `epoch_enter()` 和 `epoch_exit()` 括起来的代码路径不能睡眠。网络驱动大量使用这种模式使读路径无锁;写侧工作被延迟到 epoch 外部。第14章在后面的"附加主题"部分以介绍级别覆盖 epoch。 -The common thread across all those contexts is that something about the surrounding environment forbids thread-context operations. The "something" differs (a spin lock, a filter context, an epoch section, a software-interrupt dispatch), but the remedy is the same: enqueue a task to be run later by a thread that is not in the constrained context. +所有这些上下文的共同线索是,周围环境的某些东西禁止线程上下文操作。"某些东西"各不相同(自旋锁、过滤器上下文、epoch 段、软件中断调度),但补救措施相同:入队一个任务,由不在受限上下文中的线程稍后运行。 ### 实际延迟工作的原因 -Short tours of the kinds of work drivers push out of constrained contexts. Recognising the shapes now gives you vocabulary for the patterns Section 6 will develop. +简要浏览驱动从受限上下文中推出的工作类型。现在识别这些形态会为第6节将要展开的模式提供词汇。 -**Non-trivial `selwakeup(9)`.** `selwakeup` is the kernel's notify-all-select/poll-waiters call. Traditional wisdom says to call it with no driver mutex held, and never from a context that has a spin lock held. A callout callback holds a mutex; an interrupt filter holds nothing, but is itself in a bad place. Drivers that want to notify pollers from those contexts typically enqueue a task whose only job is to call `selwakeup`. +**非平凡的 `selwakeup(9)`。** `selwakeup` 是内核的通知所有 select/poll 等待者的调用。传统做法是在没有驱动互斥锁持有的情况下调用它,并且绝不在持有自旋锁的上下文中调用。callout 回调持有互斥锁;中断过滤器什么都没持有,但本身就处于不好的位置。想要从这些上下文通知 poller 的驱动通常入队一个任务,其唯一工作就是调用 `selwakeup`。 -**`copyin` and `copyout` following a hardware event.** After an interrupt signals that a DMA transfer has completed, the driver may want to copy data to or from a user-space buffer whose address was registered with a previous ioctl. Neither `copyin` nor `copyout` is legal in interrupt context. The driver schedules a task whose callback does the copy in process context. +**硬件事件后的 `copyin` 和 `copyout`。** 中断发出 DMA 传输完成信号后,驱动可能想要将数据复制到或来自先前通过 ioctl 注册的用户空间缓冲区地址。`copyin` 和 `copyout` 在中断上下文中都不合法。驱动调度一个任务,其回调在进程上下文中执行复制。 -**Reconfiguration that requires a sleepable lock.** The driver's configuration is often protected by an `sx(9)` lock, which can sleep. A callout or interrupt cannot acquire a sleepable lock directly. If a timer-driven decision implies a configuration change, the timer enqueues a task; the task acquires the sx lock and performs the change. +**需要可睡眠锁的重新配置。** 驱动的配置通常由 `sx(9)` 锁保护,它可以睡眠。callout 或中断不能直接获取可睡眠锁。如果定时器驱动的决策意味着配置更改,定时器入队一个任务;任务获取 sx 锁并执行更改。 -**Retrying a failed operation after a backoff.** Hardware operations sometimes fail transiently. The sensible response is to wait some interval and retry. An interrupt handler cannot block; it enqueues a `timeout_task` with a delay equal to the backoff interval. The timeout task fires later in thread context, retries the operation, and if it fails again reschedules itself with a longer delay. +**退避后重试失败操作。** 硬件操作有时会瞬态失败。合理的响应是等待某个间隔然后重试。中断处理程序不能阻塞;它入队一个 `timeout_task`,延迟等于退避间隔。超时任务稍后在线程上下文中触发,重试操作,如果再次失败则用更长的延迟重新调度自己。 -**Logging a non-trivial event.** Kernel `printf(9)` is surprisingly tolerant of weird contexts, but `log(9)` and its friends are not. A driver that wants to emit a multi-line diagnostic from an interrupt context writes the bare minimum in the handler (a flag, a counter increment) and schedules a task to do the real logging later. +**记录非平凡事件。** 内核 `printf(9)` 对奇怪上下文出奇地容忍,但 `log(9)` 和其伙伴不是。想要从中断上下文发出多行诊断的驱动在处理程序中只写最少的内容(一个标志、一个计数器递增)并调度一个任务稍后做真正的日志。 -**Draining or reconfiguring a long hardware queue.** A network driver that detects head-of-line blocking may want to walk its transmit ring, free completed descriptors, and reset per-descriptor state. The work is bounded but nontrivial. Doing it inline in the interrupt path monopolises a CPU in a bad context. Doing it in a task lets the interrupt return immediately and the real work happen on a thread. +**排空或重新配置长硬件队列。** 检测到队头阻塞的网络驱动可能想要遍历其发送环,释放已完成的描述符,并重置每描述符状态。工作有界但不平凡。在中断路径中内联做这件事会在不好的上下文中独占 CPU。在任务中做它允许中断立即返回,真正的工作在线程上发生。 -**Deferred teardown.** When a driver detaches while some object still has outstanding references, the driver cannot free the object immediately. A common pattern: defer the free to a task that fires after the reference count is known to be zero, or after a grace period that is long enough for any in-flight references to drain. +**延迟拆除。** 当驱动在某个对象仍有未完成引用时分离,驱动不能立即释放该对象。一个常见模式:将释放延迟到一个任务,该任务在引用计数已知为零后,或在足够长的宽限期内任何进行中的引用都已排空后触发。 -All those cases share the structure: the constrained context detects a need, possibly records a small amount of state, and enqueues a task. The task runs later in thread context, does the real work, and optionally re-enqueues itself or schedules a follow-up. +所有这些情况共享相同结构:受限上下文检测到需求,可能记录少量状态,然后入队一个任务。任务稍后在线程上下文中运行,做真正的工作,并可选地重新入队自己或调度后续操作。 ### 轮询与延迟执行 -A reasonable question at this point: if the constrained context cannot do the work, why not arrange for the work to happen somewhere entirely outside the constrained context? Why not have a single dedicated kernel thread that polls for "anything to do" and wakes up when it sees state that requires action? +此时一个合理的问题是:如果受限上下文不能做工作,为什么不安排工作在受限上下文之外的某个地方发生?为什么不拥有一个专用内核线程轮询"有什么事要做",并在看到需要行动的状态时唤醒? -That is, in effect, what a taskqueue does. A taskqueue thread sleeps until work is available and wakes up to process it. The difference between "a taskqueue" and "a hand-rolled polling thread" is that the taskqueue framework solves the surrounding logistics for you. Enqueue is a single atomic operation. The task structure holds the callback and context directly, so you do not have to design a "work queue entry" type. Coalescing of redundant enqueues is automatic. Draining a task is a single call. Teardown is a single call. Observability via the standard tools comes for free. +这实际上就是任务队列做的事。任务队列线程在有工作可用前一直睡眠,被唤醒后处理它。"任务队列"与"手工制作的轮询线程"之间的区别在于,任务队列框架为你解决了周围的后勤问题。入队是单个原子操作。任务结构直接持有回调和上下文,所以你不必设计"工作队列条目"类型。冗余入队的合并是自动的。排空任务是单个调用。拆除是单个调用。通过标准工具的可观察性免费获得。 -A hand-rolled polling thread can do the same work, and in extreme cases it is the right choice (if, for example, the work has hard real-time constraints, or if it is part of a subsystem that needs a dedicated priority). For ordinary driver work, reaching past `taskqueue(9)` is almost always a mistake. +手工制作的轮询线程可以做同样的工作,在极端情况下它是正确的选择(例如,工作有硬实时约束,或者它是需要专用优先级的子系统的一部分)。对于普通的驱动工作,越过 `taskqueue(9)` 几乎总是一个错误。 -A separate but related question: why not just spin up a new kernel thread for each deferred operation? That is extremely expensive: creating a thread takes time, allocates a full kernel stack, and hands the new thread to the scheduler. For work that happens repeatedly, the sensible design is to reuse a thread, which is exactly what a taskqueue provides. For work that happens once, you might `kproc_create(9)` and have the new thread exit when done, but even then a taskqueue with `taskqueue_drain` is usually simpler and nearly as cheap. +一个独立但相关的问题:为什么不每个延迟操作都启动一个新的内核线程?这极其昂贵:创建线程需要时间,分配完整的内核栈,并将新线程交给调度器。对于重复发生的工作,合理的设计是重用线程,这正是任务队列提供的。对于只发生一次的工作,你可以用 `kproc_create(9)` 并让新线程完成后退出,但即使那样,带有 `taskqueue_drain` 的任务队列通常更简单且成本相近。 -### FreeBSD's Solutions +### FreeBSD 的解决方案 -The kernel offers a small family of facilities for deferred work. Chapter 14 focuses on one of them (`taskqueue(9)`) and mentions the others at the right level of detail for a driver writer to know when they are appropriate. A short tour now; the sections that follow expand on each one as it becomes relevant. +内核为延迟工作提供了一小组设施。第14章专注于其中之一(`taskqueue(9)`),并在驱动编写者需要了解何时使用其他设施的适当细节水平上提及它们。现在做一个简要概览;后续各节在相关时展开每个设施。 -**`taskqueue(9)`.** A queue of `struct task` entries and one or more kernel threads (or a software-interrupt context) that consume the queue. The dominant choice for deferred driver work. Covered in depth throughout this chapter. +**`taskqueue(9)`。** 一个由 `struct task` 条目组成的队列和一个或多个消费该队列的内核线程(或软件中断上下文)。延迟驱动工作的主导选择。本章深入覆盖。 -**`epoch(9)`.** A lockless read-synchronisation mechanism that network drivers use to allow readers to walk shared data structures without locks. Writers defer cleanup via `epoch_call` or `epoch_wait`. Not a general deferred-work mechanism for arbitrary drivers, but important enough to introduce later in this chapter so that you recognise it when you see it in network-driver code. +**`epoch(9)`。** 一种无锁读同步机制,网络驱动用于允许读者在无锁情况下遍历共享数据结构。写入者通过 `epoch_call` 或 `epoch_wait` 延迟清理。不是通用驱动的通用延迟工作机制,但足够重要,本章稍后介绍,以便你在网络驱动代码中看到时能认出它。 -**Grouptaskqueues.** A scalable variation on taskqueues where a group of related tasks share a pool of per-CPU worker threads. Network drivers use this heavily; most other drivers do not. Introduced later in this chapter. +**组任务队列。** 任务队列的可扩展变体,其中一组相关任务共享每 CPU 工作线程池。网络驱动大量使用;大多数其他驱动不用。本章稍后介绍。 -**`kproc_create(9)` / `kthread_add(9)`.** Direct creation of a kernel thread. Useful when the deferred work is a long-running loop that does not fit the "short task" shape, and when the work deserves a dedicated priority or CPU affinity. Almost always overkill for simple deferral; a taskqueue is preferred. +**`kproc_create(9)` / `kthread_add(9)`。** 直接创建内核线程。当延迟工作是不适合"短任务"形态的长运行循环,以及工作值得拥有专用优先级或 CPU 亲和性时有用。对于简单延迟几乎总是过度杀伤;任务队列是首选。 -**Dedicated SWI (software interrupt) handlers via `swi_add(9)`.** A way to register a function that runs in a software-interrupt context. The system taskqueues (`taskqueue_swi`, `taskqueue_swi_giant`, `taskqueue_fast`) are built on top of this mechanism. Driver code rarely calls `swi_add` directly; the taskqueue layer is the right abstraction. +**通过 `swi_add(9)` 的专用 SWI(软件中断)处理程序。** 一种注册在软件中断上下文中运行的函数的方式。系统任务队列(`taskqueue_swi`、`taskqueue_swi_giant`、`taskqueue_fast`)构建在此机制之上。驱动代码很少直接调用 `swi_add`;任务队列层是正确的抽象。 -**The callout itself, rescheduled for "zero-from-now".** A pattern that does not work: you cannot "escape" the callout context by scheduling another callout, because the next callout still runs in callout context. Recognising that this is a dead end is itself useful. Callouts schedule the moment; taskqueues provide the context. +**callout 本身,重新调度为"从现在起零秒后"。** 一种行不通的模式:你不能通过调度另一个 callout 来"逃离" callout 上下文,因为下一个 callout 仍然在 callout 上下文中运行。认识到这是一个死胡同本身是有用的。callout 调度时刻;任务队列提供上下文。 -For the rest of Chapter 14, unless we say otherwise, "defer to a task" or "enqueue a task" means "enqueue a `struct task` onto a `struct taskqueue`". +在第14章的其余部分,除非我们另有说明,"延迟到任务"或"入队任务"意味着"将 `struct task` 入队到 `struct taskqueue`"。 -### When Deferral Is the Wrong Answer +### 何时延迟是错误答案 -Deferral is a tool, not a default. Several situations benefit from doing the work in place rather than deferring it. +延迟是一种工具,不是默认。有几种情况从原地做工作中受益而不是延迟。 -**The work is genuinely short and safe for the current context.** Logging a one-line statistic with `device_printf(9)` from a callout is fine. So is incrementing a counter. So is signalling a cv. Deferring these trivialities to a task costs more than doing them. Only defer when the work actually does not belong in the current context. +**工作确实很短且对当前上下文安全。** 从 callout 中用 `device_printf(9)` 记录一行统计数据是没问题的。递增计数器也是。通知 cv 也是。将这些琐碎操作延迟到任务比直接做成本更高。只在工作确实不属于当前上下文时才延迟。 -**Timing matters and the deferral introduces variance.** A task does not run instantly. It runs when the taskqueue's thread is next scheduled, which may be microseconds or milliseconds away depending on system load. If the work has tight timing requirements (acknowledging a hardware event within a deadline, for example), deferral may miss the deadline. For such work you need a faster mechanism (a hardware-level completion, a `C_DIRECT_EXEC` callout, or an SWI) or a different design. +**时序重要且延迟引入方差。** 任务不会立即运行。它在任务队列线程下次被调度时运行,根据系统负载可能是微秒或毫秒之后。如果工作有严格的时序要求(例如在截止时间内确认硬件事件),延迟可能错过截止时间。对于这类工作,你需要更快的机制(硬件级完成、`C_DIRECT_EXEC` callout 或 SWI)或不同的设计。 -**The deferral would add a hop for no benefit.** If your interrupt handler's only work is already safe to do in interrupt context, adding a task round-trip doubles the latency without improving anything. Only defer the parts of the work that need to be deferred. +**延迟会无益地增加一跳。** 如果中断处理程序的唯一工作已经在中断上下文中安全完成,添加任务往返会使延迟加倍而不改善任何东西。只延迟工作中需要延迟的部分。 -**The work requires a specific thread.** If the work needs to run as a specific user process (for example, to use that process's file-descriptor table), a generic taskqueue thread is the wrong place. That situation is rare in drivers, but it exists. +**工作需要特定线程。** 如果工作需要作为特定用户进程运行(例如,使用该进程的文件描述符表),通用任务队列线程是错误的地方。这种情况在驱动中很少见,但它存在。 -For everything else, deferral via a taskqueue is the right answer, and the rest of the chapter is about how to do it well. +对于其他所有情况,通过任务队列延迟是正确答案,本章的其余部分是关于如何做好它。 -### A Worked Example: Why the Tick Source Cannot Wake Pollers +### 一个实战示例:为什么 Tick 源不能唤醒 Poller -A concrete example from the Chapter 13 driver, worth slowing down for because it is the first place Chapter 14 makes a real change. +来自第13章驱动的一个具体例子,值得放慢速度来看,因为这是第14章做出真正更改的第一个地方。 -The Chapter 13 `tick_source` callback, from `stage4-final/myfirst.c`, looks like this: +第13章的 `tick_source` 回调,来自 `stage4-final/myfirst.c`,看起来是这样的: ```c static void @@ -253,41 +253,41 @@ myfirst_tick_source(void *arg) } ``` -That comment at the bottom is not hypothetical. `selwakeup(9)` enters the per-selinfo mutex and may call into the kqueue subsystem, which is not safe to do inside a callout callback that holds a different driver mutex. A `select(2)`/`poll(2)` user program waiting on `/dev/myfirst` for readability therefore does not get notified when the tick source deposits a byte. The program only wakes when some other path calls `selwakeup`, for example when another thread's `write(2)` arrives. +底部那个注释不是假设的。`selwakeup(9)` 进入每 selinfo 的互斥锁并可能调用 kqueue 子系统,这在持有不同驱动互斥锁的 callout 回调中是不安全的。因此,等待 `/dev/myfirst` 可读性的 `select(2)`/`poll(2)` 用户程序在 tick 源存入字节时不会收到通知。程序只在其他路径调用 `selwakeup` 时才醒来,例如当另一个线程的 `write(2)` 到达时。 -That is a real bug in the Chapter 13 driver. We left it unfixed in Chapter 13 because fixing it required a primitive we had not yet introduced. Chapter 14 introduces that primitive and fixes the bug. +这是第13章驱动中的一个真实 bug。我们在第13章中没有修复它,因为修复它需要一个我们尚未引入的原语。第14章引入该原语并修复了这个 bug。 -The fix is small. Add a `struct task` to the softc. Initialise it in attach. Instead of omitting `selwakeup` from the tick_source callback, enqueue the task; the task runs in thread context, with no driver mutex held, and calls `selwakeup` safely. Drain the task in detach after `is_attached` has been cleared, before freeing the selinfo. +修复很小。在 softc 中添加一个 `struct task`。在 attach 中初始化它。不是从 tick_source 回调中省略 `selwakeup`,而是入队该任务;任务在线程上下文中运行,没有驱动互斥锁持有,安全地调用 `selwakeup`。在分离时,在 `is_attached` 被清除后、释放 selinfo 之前排空该任务。 -We will walk through every step of that change in Section 3. For now the point is that the change is mechanical, and its necessity is not contrived. Chapter 14's first real job is to give you the tool this kind of bug needs. +我们将在第3节中逐步完成该更改的每一步。现在的要点是更改是机械的,其必要性不是虚构的。第14章的第一个真正工作就是给你这种 bug 所需的工具。 ### 一个小型心智模型 -A useful picture, offered once and referenced later. +一个有用的图景,提供一次,后面会引用。 -Think of your driver as being made of two kinds of code. The first kind is the code that runs because somebody asked for it: the `read(2)` handler, the `write(2)` handler, the `ioctl(2)` handler, the sysctl handlers, the open and close handlers. That code runs in thread context, with ordinary rules, and it can sleep, allocate, and touch any lock. Call it "thread-context code". +把你的驱动想象为由两种代码组成。第一种是因为有人请求而运行的代码:`read(2)` 处理程序、`write(2)` 处理程序、`ioctl(2)` 处理程序、sysctl 处理程序、open 和 close 处理程序。这些代码在线程上下文中运行,遵守普通规则,可以睡眠、分配内存和触碰任何锁。称之为"线程上下文代码"。 -The second kind is the code that runs because time or the hardware said so: a callout callback, an interrupt filter, an epoch-protected read. That code runs in a constrained context, with a narrower set of rules, and it must keep its work short and non-sleeping. Call it "edge-context code". +第二种是因为时间或硬件说了什么而运行的代码:callout 回调、中断过滤器、epoch 保护的读。这些代码在受限上下文中运行,规则更窄,必须保持工作短小且不可睡眠。称之为"边缘上下文代码"。 -Most real work belongs in thread-context code. Most of what edge-context code actually needs to do is: notice the edge, record a tiny amount of state, and hand the work to thread-context code. A taskqueue is the hand-off. The task callback runs in thread-context code, because the taskqueue's thread is in thread context. Everything the callback does follows the ordinary rules. +大多数真实工作属于线程上下文代码。边缘上下文代码实际需要做的大多是:注意到边缘,记录少量状态,然后将工作交给线程上下文代码。任务队列就是那个交接。任务回调在线程上下文代码中运行,因为任务队列的线程处于线程上下文。回调做的一切遵循普通规则。 -This mental model lets you read every subsequent section as variations on a single idea: edge-context code detects, thread-context code acts, and the taskqueue is the seam between them. Once you see the driver that way, the rest of the chapter is engineering details. +这个心智模型让你可以将每个后续节阅读为单一思想的变体:边缘上下文代码检测,线程上下文代码行动,任务队列是两者之间的接缝。一旦你这样看待驱动,本章的其余部分就是工程细节。 ### 第1节总结 -Some work must run in a constrained context (callouts, interrupt filters, epoch sections). The rules of those contexts forbid sleeping, heavy allocation, sleepable-lock acquisition, and several other common operations. Drivers with real responsibilities frequently need to do exactly those operations in response to events that arrive in constrained contexts. The remedy is to enqueue a task and let a worker thread do the real work in a context where the rules allow it. +有些工作必须在受限上下文(callout、中断过滤器、epoch 段)中运行。这些上下文的规则禁止睡眠、大量分配、可睡眠锁获取和几种其他常见操作。有真实职责的驱动频繁需要做恰恰这些操作来响应在受限上下文中到达的事件。补救措施是入队一个任务,让工作线程在规则允许的上下文中做真正的工作。 -The kernel exposes that pattern as `taskqueue(9)`. The API is small, the idioms are regular, and the tool composes cleanly with the callouts and synchronisation primitives you already know. Section 2 introduces the primitive. +内核将这种模式暴露为 `taskqueue(9)`。API 很小,习语是规则的,该工具与你已经知道的 callout 和同步原语干净地组合。第2节介绍这个原语。 -## Section 2: Introduction to `taskqueue(9)` +## 第2节:`taskqueue(9)` 简介 -`taskqueue(9)` is, like most of the kernel's well-aged subsystems, a small API on top of a careful implementation. The data structures are short, the lifecycle is regular (init, enqueue, run, drain, free), and the rules are explicit enough that you can verify your usage by reading the source. This section walks through the structures, names the API, lists the predefined queues the kernel provides for free, and compares taskqueues with the callouts from Chapter 13 so you can see when each is the right tool. +`taskqueue(9)` 与内核大多数成熟的子系统一样,是一个精心实现之上的小型 API。数据结构很短,生命周期是规则的(初始化、入队、运行、排空、释放),规则足够明确,你可以通过阅读源码来验证用法。本节逐步介绍结构,命名 API,列出内核免费提供的预定义队列,并将任务队列与第13章的 callout 进行比较,以便你看到各自何时是正确的工具。 ### 任务结构 -The data structure is in `/usr/src/sys/sys/_task.h`: +该数据结构位于 `/usr/src/sys/sys/_task.h`: ```c typedef void task_fn_t(void *context, int pending); @@ -302,25 +302,25 @@ struct task { }; ``` -The fields split into two groups. The `(q)` fields are managed by the taskqueue under its own internal lock; driver code does not touch them directly. The `(c)` fields are const-after-init; driver code sets them once via an initialiser and never modifies them again. +字段分为两组。`(q)` 字段由任务队列在其自己的内部锁下管理;驱动代码不直接触碰它们。`(c)` 字段在初始化后为常量;驱动代码通过初始化器设置一次,之后不再修改。 -`ta_link` is the list linkage used when the task is enqueued. Unused when the task is idle. +`ta_link` 是任务入队时使用的列表链接。任务空闲时未使用。 -`ta_pending` is the coalescing counter. When the task is first enqueued it goes from zero to one and the task is placed on the list. If it is enqueued again before the callback runs, the counter simply increments and the task stays on the list once. When the callback eventually runs, the final pending count is passed as the second argument to the callback, and the counter is reset to zero. The worst mistake you can make with `ta_pending` is to assume that a task will run N times if you enqueue it N times; it will not. It will run once and the callback will know it was enqueued N times. Section 5 covers the design implications in detail. +`ta_pending` 是合计计数器。任务第一次入队时从零变为一,任务被放入列表。如果在回调运行前再次入队,计数器简单递增,任务仍在列表中只出现一次。当回调最终运行时,最终的待处理计数作为第二个参数传递给回调,计数器重置为零。关于 `ta_pending` 你能犯的最大错误是假设任务入队 N 次就会运行 N 次;它不会。它将运行一次,回调将知道它被入队了 N 次。第5节详细讨论设计含义。 -`ta_priority` orders tasks inside a single queue. Higher priority tasks run before lower priority tasks. For most drivers the value is zero (ordinary priority) and the queue is effectively FIFO. +`ta_priority` 在单个队列内排序任务。更高优先级的任务在更低优先级的任务之前运行。对于大多数驱动,值为零(普通优先级),队列实际上是 FIFO。 -`ta_flags` is a small bitfield. The kernel uses it to record whether the task is currently enqueued and, for network tasks, whether the task should be run inside the network epoch. Driver code does not touch it after `TASK_INIT` or `NET_TASK_INIT` has set it. +`ta_flags` 是一个小位域。内核用它来记录任务当前是否已入队,以及对于网络任务,任务是否应该在网络 epoch 内运行。驱动代码在 `TASK_INIT` 或 `NET_TASK_INIT` 设置后不触碰它。 -`ta_func` is the callback function. Its signature is `void (*)(void *context, int pending)`. The first argument is whatever you stored in `ta_context` at init time; the second is the coalescing count. +`ta_func` 是回调函数。其签名为 `void (*)(void *context, int pending)`。第一个参数是你在初始化时存储在 `ta_context` 中的任何内容;第二个是合计计数。 -`ta_context` is the callback's argument. For a device-driver task this is almost always the softc pointer. +`ta_context` 是回调的参数。对于设备驱动任务,这几乎总是 softc 指针。 -The structure is 32 bytes on amd64, plus or minus padding. You embed one per deferred-work pattern into your softc. A driver with three deferral paths has three `struct task` members. +该结构在 amd64 上为 32 字节,加减填充。你为每个延迟工作模式在 softc 中嵌入一个。有三个延迟路径的驱动有三个 `struct task` 成员。 ### 初始化任务 -The canonical macro is `TASK_INIT`, in `/usr/src/sys/sys/taskqueue.h`: +标准的初始化宏是 `TASK_INIT`,位于 `/usr/src/sys/sys/taskqueue.h`: ```c #define TASK_INIT_FLAGS(task, priority, func, context, flags) do { \ @@ -334,27 +334,27 @@ The canonical macro is `TASK_INIT`, in `/usr/src/sys/sys/taskqueue.h`: #define TASK_INIT(t, p, f, c) TASK_INIT_FLAGS(t, p, f, c, 0) ``` -A typical call from a driver's attach routine looks like: +从驱动的 attach 例程中调用通常如下: ```c TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); ``` -The arguments read as: "initialise this task, at ordinary priority zero, to run `myfirst_selwake_task(sc, pending)` when it fires". That is the whole initialisation ritual. There is no corresponding "destroy" call; a task becomes idle again when its callback finishes, and goes out of scope when the surrounding softc is freed. +参数读作:"初始化此任务,普通优先级零,在触发时运行 `myfirst_selwake_task(sc, pending)`"。这就是整个初始化仪式。没有对应的"销毁"调用;任务在回调完成后变为空闲,在周围 softc 释放时超出作用域。 -For network-path tasks there is a variant, `NET_TASK_INIT`, that sets the `TASK_NETWORK` flag so the taskqueue knows to run the callback inside the `net_epoch_preempt` epoch: +对于网络路径任务有一个变体 `NET_TASK_INIT`,它设置 `TASK_NETWORK` 标志,使任务队列知道在 `net_epoch_preempt` epoch 内运行回调: ```c #define NET_TASK_INIT(t, p, f, c) TASK_INIT_FLAGS(t, p, f, c, TASK_NETWORK) ``` -Unless you are writing a network driver, `TASK_INIT` is the one you use. Chapter 14 uses `TASK_INIT` throughout and returns to `NET_TASK_INIT` only in the "Additional topics" section. +除非你在编写网络驱动,否则 `TASK_INIT` 就是你使用的。第14章全程使用 `TASK_INIT`,只在"附加主题"部分回到 `NET_TASK_INIT`。 -### The Taskqueue Structure, From a Driver's Point of View +### 从驱动的角度看任务队列结构 -From a driver's point of view, a taskqueue is a `struct taskqueue *`. The pointer is either a predefined global (`taskqueue_thread`, `taskqueue_swi`, `taskqueue_bus`, etc.) or one the driver created with `taskqueue_create` and stored in its softc. In both cases the pointer is opaque. All interactions go through API calls. The only internal we care about in the chapter is the fact that the taskqueue holds its own lock, which it acquires on enqueue and when its worker thread pulls tasks off the list. +从驱动的角度看,任务队列是一个 `struct taskqueue *`。该指针要么是一个预定义的全局指针(`taskqueue_thread`、`taskqueue_swi`、`taskqueue_bus` 等),要么是驱动用 `taskqueue_create` 创建并存储在其 softc 中的。两种情况下指针都是不透明的。所有交互都通过 API 调用进行。我们在本章中唯一关心的内部细节是任务队列持有自己的锁,它在入队和工作线程从列表中拉取任务时获取该锁。 -For completeness, the definition (from `/usr/src/sys/kern/subr_taskqueue.c`): +为了完整性,定义(来自 `/usr/src/sys/kern/subr_taskqueue.c`): ```c struct taskqueue { @@ -375,15 +375,15 @@ struct taskqueue { }; ``` -`tq_queue` is the pending-task list. `tq_active` records which tasks are currently running, which the drain logic uses to wait for completion. `tq_mutex` is the taskqueue's own lock. `tq_threads` is the array of worker threads, of size `tq_tcount`. `tq_spin` records whether the mutex is a spin mutex (for taskqueues created with `taskqueue_create_fast`) or a sleep mutex (for taskqueues created with `taskqueue_create`). `tq_flags` records shutdown state. +`tq_queue` 是待处理任务列表。`tq_active` 记录当前正在运行的任务,排空逻辑用它来等待完成。`tq_mutex` 是任务队列自己的锁。`tq_threads` 是工作线程数组,大小为 `tq_tcount`。`tq_spin` 记录互斥锁是自旋互斥锁(用于通过 `taskqueue_create_fast` 创建的任务队列)还是睡眠互斥锁(用于通过 `taskqueue_create` 创建的任务队列)。`tq_flags` 记录关闭状态。 -You do not touch any of those fields from driver code. They are shown here once so that the API calls in the rest of the section have a concrete referent. The rest of the chapter treats the taskqueue as opaque. +你不从驱动代码中触碰任何这些字段。这里展示一次是为了让本节其余部分的 API 调用有一个具体的参照物。本章的其余部分将任务队列视为不透明的。 ### API逐一介绍 -The public functions are declared in `/usr/src/sys/sys/taskqueue.h`. A driver typically uses fewer than a dozen of them. We walk through the important ones now, grouped by purpose. +公共函数声明在 `/usr/src/sys/sys/taskqueue.h` 中。驱动通常使用不到一打。我们现在按用途分组逐步介绍重要的函数。 -**Creating and destroying a taskqueue.** +**创建和销毁任务队列。** ```c struct taskqueue *taskqueue_create(const char *name, int mflags, @@ -398,21 +398,21 @@ int taskqueue_start_threads(struct taskqueue **tqp, int count, int pri, void taskqueue_free(struct taskqueue *queue); ``` -`taskqueue_create` creates a taskqueue that uses a sleep mutex internally. Tasks enqueued on it run in a context where sleeping is legal (assuming they are dispatched via `taskqueue_thread_enqueue` and `taskqueue_start_threads`). This is the right choice for almost every driver taskqueue. +`taskqueue_create` 创建一个内部使用睡眠互斥锁的任务队列。在上面入队的任务运行在睡眠合法的上下文中(假设它们通过 `taskqueue_thread_enqueue` 和 `taskqueue_start_threads` 调度)。这是几乎所有驱动任务队列的正确选择。 -`taskqueue_create_fast` creates a taskqueue that uses a spin mutex internally. Required only if you intend to enqueue from a context where a sleep mutex would be wrong (for example, from inside a spin mutex or a filter interrupt). Driver code rarely needs this; the predefined `taskqueue_fast` exists for the cases that do. +`taskqueue_create_fast` 创建一个内部使用自旋互斥锁的任务队列。只有在你打算从睡眠互斥锁会出错的上下文入队时才需要(例如,从自旋互斥锁内部或过滤器中断中)。驱动代码很少需要这个;预定义的 `taskqueue_fast` 存在于需要的情况。 -The `enqueue` callback is called by the taskqueue layer when a task is added to an otherwise-empty queue, and is the way the layer "wakes" a consumer. For queues serviced by kernel threads the enqueue function is `taskqueue_thread_enqueue`, which the kernel provides. For software-interrupt-serviced queues the kernel provides `taskqueue_swi_enqueue`. Driver code almost always passes `taskqueue_thread_enqueue` here. +`enqueue` 回调在任务被添加到原本为空的队列时由任务队列层调用,是层"唤醒"消费者的方式。对于由内核线程服务的队列,入队函数是 `taskqueue_thread_enqueue`,由内核提供。对于由软件中断服务的队列,内核提供 `taskqueue_swi_enqueue`。驱动代码几乎总是传递 `taskqueue_thread_enqueue`。 -The `context` argument is passed back to the enqueue callback. When using `taskqueue_thread_enqueue` the convention is to pass `&your_taskqueue_pointer`, so the function can find the taskqueue it is waking. The Chapter 14 examples follow this convention literally. +`context` 参数被传回给入队回调。使用 `taskqueue_thread_enqueue` 时,约定是传递 `&your_taskqueue_pointer`,以便函数能找到它要唤醒的任务队列。第14章的示例字面遵循此约定。 -`taskqueue_start_threads` creates `count` kernel threads that run the `taskqueue_thread_loop` dispatcher, each sleeping on the queue until a task arrives. The `pri` argument is the thread's priority. `PWAIT` (defined in `/usr/src/sys/sys/priority.h`, numerically 76) is the ordinary choice for driver taskqueues; network drivers often pass `PI_NET` (numerically 4) to run at interrupt-adjacent priority. Chapter 14's worker threads use `PWAIT`. +`taskqueue_start_threads` 创建 `count` 个运行 `taskqueue_thread_loop` 调度器的内核线程,每个在队列上睡眠直到任务到达。`pri` 参数是线程的优先级。`PWAIT`(定义在 `/usr/src/sys/sys/priority.h`,数值为 76)是驱动任务队列的普通选择;网络驱动通常传递 `PI_NET`(数值为 4)以在中断邻近优先级运行。第14章的工作线程使用 `PWAIT`。 -`taskqueue_free` shuts down the taskqueue. It drains all pending and running tasks, terminates the worker threads, and frees the internal state. It must be called with no tasks pending that have not yet been drained; after it returns, the `struct taskqueue *` is invalid and must not be used. +`taskqueue_free` 关闭任务队列。它排空所有待处理和运行中的任务,终止工作线程,并释放内部状态。它必须在没有未排空的待处理任务时调用;它返回后,`struct taskqueue *` 无效且不得使用。 -**Initialising a task.** `TASK_INIT` as shown above. There is no counterpart "destroy" because the task structure is caller-owned. +**初始化任务。** 如上所示的 `TASK_INIT`。没有对应的"销毁",因为任务结构由调用者拥有。 -**Enqueuing a task.** +**入队任务。** ```c int taskqueue_enqueue(struct taskqueue *queue, struct task *task); @@ -425,18 +425,18 @@ int taskqueue_enqueue_timeout_sbt(struct taskqueue *queue, int flags); ``` -`taskqueue_enqueue` is the workhorse. It links the task onto the queue and wakes the worker thread. If the task is already pending, it increments `ta_pending` and returns. Returns zero on success; rarely fails. +`taskqueue_enqueue` 是主力。它将任务链接到队列并唤醒工作线程。如果任务已经待处理,它递增 `ta_pending` 并返回。成功返回零;很少失败。 -`taskqueue_enqueue_flags` is the same, with optional flags: +`taskqueue_enqueue_flags` 相同,带有可选标志: -- `TASKQUEUE_FAIL_IF_PENDING` makes the enqueue return `EEXIST` instead of coalescing if the task is already pending. -- `TASKQUEUE_FAIL_IF_CANCELING` makes the enqueue return `EAGAIN` if the task is currently being cancelled. +- `TASKQUEUE_FAIL_IF_PENDING` 使入队在任务已待处理时返回 `EEXIST` 而不是合并。 +- `TASKQUEUE_FAIL_IF_CANCELING` 使入队在任务当前正在取消时返回 `EAGAIN`。 -The default `taskqueue_enqueue` silently coalesces; the flag variant lets you detect the situation when that matters. +默认的 `taskqueue_enqueue` 静默合并;标志变体让你在重要时检测这种情况。 -`taskqueue_enqueue_timeout` schedules a `struct timeout_task` to fire after the given number of ticks. Behind the scenes it uses an internal `callout` whose callback enqueues the underlying task on the taskqueue when the delay elapses. The `sbt` variant takes sbintime for sub-tick precision. +`taskqueue_enqueue_timeout` 调度一个 `struct timeout_task` 在给定的 tick 数后触发。在幕后它使用一个内部 `callout`,其回调在延迟到期时将底层任务入队到任务队列。`sbt` 变体接受 sbintime 用于亚 tick 精度。 -**Cancelling a task.** +**取消任务。** ```c int taskqueue_cancel(struct taskqueue *queue, struct task *task, @@ -445,11 +445,11 @@ int taskqueue_cancel_timeout(struct taskqueue *queue, struct timeout_task *timeout_task, u_int *pendp); ``` -`taskqueue_cancel` removes a pending task from the queue if it has not yet started running, and writes the previous pending count to `*pendp` if that pointer is non-NULL. If the task is currently running, the function returns `EBUSY` and does not wait; you must follow up with `taskqueue_drain` if you need to wait. +`taskqueue_cancel` 如果任务尚未开始运行则将其从队列中移除,如果指针非 NULL 则将之前的待处理计数写入 `*pendp`。如果任务当前正在运行,函数返回 `EBUSY` 并且不等待;如果需要等待,你必须跟进 `taskqueue_drain`。 -`taskqueue_cancel_timeout` is the same for timeout tasks. +`taskqueue_cancel_timeout` 对超时任务相同。 -**Draining a task.** +**排空任务。** ```c void taskqueue_drain(struct taskqueue *queue, struct task *task); @@ -458,13 +458,13 @@ void taskqueue_drain_timeout(struct taskqueue *queue, void taskqueue_drain_all(struct taskqueue *queue); ``` -`taskqueue_drain(tq, task)` blocks until the given task is no longer pending and no longer running. If the task was pending, the drain waits for it to run and complete. If the task was running, the drain waits for the current invocation to return. If the task was idle, the drain returns immediately. This is the call you use at detach for every task your driver owns. +`taskqueue_drain(tq, task)` 阻塞直到给定任务不再待处理且不再运行。如果任务待处理,排空等待它运行并完成。如果任务正在运行,排空等待当前调用返回。如果任务空闲,排空立即返回。这是你在分离时为驱动拥有的每个任务使用的调用。 -`taskqueue_drain_timeout` is the same for timeout tasks. +`taskqueue_drain_timeout` 对超时任务相同。 -`taskqueue_drain_all` drains every task and every timeout task in the taskqueue. Useful when you own a private taskqueue and want to be sure it is entirely quiet before freeing it. `taskqueue_free` itself does the equivalent work internally, so `taskqueue_drain_all` is not strictly required before `taskqueue_free`, but it is useful when you want to quiesce a taskqueue without destroying it. +`taskqueue_drain_all` 排空任务队列中的每个任务和每个超时任务。当你拥有私有任务队列并想在释放它之前确保它完全安静时有用。`taskqueue_free` 本身在内部做等效工作,所以 `taskqueue_drain_all` 在 `taskqueue_free` 之前不是严格必需的,但当你想在不确定是否销毁任务队列的情况下静默它时很有用。 -**Blocking and unblocking.** +**阻塞和解阻塞。** ```c void taskqueue_block(struct taskqueue *queue); @@ -472,23 +472,23 @@ void taskqueue_unblock(struct taskqueue *queue); void taskqueue_quiesce(struct taskqueue *queue); ``` -`taskqueue_block` stops the queue from running new tasks. Already-running tasks complete; newly enqueued tasks accumulate but do not run until `taskqueue_unblock` is called. The pair is useful for temporarily freezing a queue during a delicate transition without tearing it down. +`taskqueue_block` 停止队列运行新任务。已运行的任务完成;新入队的任务累积但直到调用 `taskqueue_unblock` 才运行。这对在精细过渡期间临时冻结队列而不拆除它很有用。 -`taskqueue_quiesce` waits for the currently running task (if any) to finish and for the queue to be empty of pending tasks. Equivalent to "drain everything, but do not destroy". Safe to call with the queue running. +`taskqueue_quiesce` 等待当前运行的任务(如果有)完成并等待队列中没有待处理任务。等同于"排空一切但不销毁"。在队列运行时安全调用。 -**Membership check.** +**成员检查。** ```c int taskqueue_member(struct taskqueue *queue, struct thread *td); ``` -Returns true if the given thread is one of the taskqueue's worker threads. Useful inside a task callback when you want to branch on "am I running on my own taskqueue", though the more common idiom is to use `curthread` against a stored thread pointer. +如果给定线程是任务队列的工作线程之一则返回 true。在任务回调内部当你想要根据"我是否运行在自己的任务队列上"来分支时有用,尽管更常见的习语是用 `curthread` 与存储的线程指针比较。 -That is the whole API a driver ordinarily uses. A handful of less-common functions exist (`taskqueue_set_callback` for init/shutdown hooks, `taskqueue_poll_is_busy` for polling-style checks) but most drivers never touch them. +这就是驱动通常使用的全部 API。还有一些不太常用的函数(`taskqueue_set_callback` 用于初始化/关闭钩子,`taskqueue_poll_is_busy` 用于轮询式检查),但大多数驱动从不触碰它们。 ### 预定义任务队列 -The kernel provides a small set of preconfigured taskqueues for drivers that do not need a private one. They are declared in `/usr/src/sys/sys/taskqueue.h` with `TASKQUEUE_DECLARE`, which expands to an extern pointer. A driver uses them by name: +内核为不需要私有任务队列的驱动提供了一小组预配置任务队列。它们在 `/usr/src/sys/sys/taskqueue.h` 中用 `TASKQUEUE_DECLARE` 声明,展开为一个 extern 指针。驱动通过名称使用它们: ```c TASKQUEUE_DECLARE(thread); @@ -498,21 +498,21 @@ TASKQUEUE_DECLARE(fast); TASKQUEUE_DECLARE(bus); ``` -**`taskqueue_thread`** is the generic thread-context queue. One kernel thread, priority `PWAIT`. The thread's name shows up in `ps` as `thread taskq`. Safe for any task that wants a full thread context and does not need special properties. The easiest predefined queue to use; a very reasonable first choice if you are not sure which queue you need. +**`taskqueue_thread`** 是通用线程上下文队列。一个内核线程,优先级 `PWAIT`。线程名在 `ps` 中显示为 `thread taskq`。对任何想要完整线程上下文且不需要特殊属性的任务安全。最容易使用的预定义队列;如果你不确定需要哪个队列,这是一个非常合理的第一选择。 -**`taskqueue_swi`** is dispatched by a software interrupt handler, not a kernel thread. Tasks on this queue run with no driver mutex held but in SWI context, which still has restrictions (no sleeping). Useful for short non-sleeping work that wants to run promptly after an enqueue without the scheduling latency of waking a kernel thread. Driver use is uncommon. +**`taskqueue_swi`** 由软件中断处理程序调度,不是内核线程。此队列上的任务运行时没有驱动互斥锁持有但在 SWI 上下文中,仍有限制(不能睡眠)。适用于想要在入队后快速运行的非睡眠短工作,没有唤醒内核线程的调度延迟。驱动使用不常见。 -**`taskqueue_swi_giant`** is the same as `taskqueue_swi` but runs with the historical `Giant` lock held. Essentially never used in new code. Mentioned only for completeness. +**`taskqueue_swi_giant`** 与 `taskqueue_swi` 相同但运行时持有历史遗留的 `Giant` 锁。新代码中基本不使用。仅为完整性提及。 -**`taskqueue_fast`** is a spin-mutex-backed software-interrupt queue, used for tasks that must be enqueuable from contexts where a sleep mutex would be wrong (for example, from inside another spin mutex). The taskqueue itself uses a spin mutex for its internal list, so enqueue is legal from any context. The task callback, however, runs in SWI context, which still has the no-sleeping restriction. Driver use is rare; filter-interrupt contexts that need to enqueue work typically use `taskqueue_fast` or, more commonly today, a private `taskqueue_create_fast` queue. +**`taskqueue_fast`** 是自旋互斥锁支持的软件中断队列,用于必须从睡眠互斥锁会出错的上下文入队的任务(例如,从另一个自旋互斥锁内部)。任务队列本身使用自旋互斥锁作为其内部列表,因此入队在任何上下文中都合法。但任务回调运行在 SWI 上下文中,仍有禁止睡眠的限制。驱动使用罕见;需要入队工作的过滤器中断上下文通常使用 `taskqueue_fast` 或更常见地使用私有 `taskqueue_create_fast` 队列。 -**`taskqueue_bus`** is a dedicated queue for `newbus(9)` device events (hot-plug insertion, removal, child-bus notifications). Ordinary drivers do not enqueue onto this queue. +**`taskqueue_bus`** 是 `newbus(9)` 设备事件(热插拔插入、移除、子总线通知)的专用队列。普通驱动不在该队列上入队。 -For a driver like `myfirst`, the realistic choices are `taskqueue_thread` (the shared queue) or a private taskqueue you own and tear down at detach. Section 4 discusses the trade-off; Stage 1 of the refactor uses `taskqueue_thread` for simplicity and Stage 2 moves to a private queue. +对于像 `myfirst` 这样的驱动,现实的选择是 `taskqueue_thread`(共享队列)或你在分离时拥有并拆除的私有任务队列。第4节讨论权衡;重构的第1阶段为简单起见使用 `taskqueue_thread`,第2阶段转移到私有队列。 ### 任务队列与定时调用的比较 -A short side-by-side comparison, because a new reader asks this question first. +一个简短的并排比较,因为新读者最先问这个问题。 | Property | `callout(9)` | `taskqueue(9)` | |---|---|---| @@ -528,27 +528,27 @@ A short side-by-side comparison, because a new reader asks this question first. | Scheduled for the future | `callout_reset(co, ticks, ...)` | `taskqueue_enqueue_timeout(tq, tt, ticks)` | | Cost per firing | Microseconds | Microseconds plus thread wake (can be larger under load) | -The table illustrates the division. A callout is the right primitive when you need to fire at a particular moment and the work is safe for callout context. A taskqueue is the right primitive when you need thread-context work and are willing to accept whatever scheduling latency the taskqueue introduces. Many drivers use both together: a callout fires at the deadline, the callout enqueues a task, the task does the real work in thread context. +该表格说明了分工。当你需要在特定时刻触发且工作对 callout 上下文安全时,callout 是正确的原语。当你需要线程上下文工作并愿意接受任务队列引入的任何调度延迟时,任务队列是正确的原语。许多驱动两者一起使用:callout 在截止时间触发,callout 入队一个任务,任务在线程上下文中做真正的工作。 -### Comparing Taskqueues and a Private Kernel Thread +### 任务队列与私有内核线程的比较 -Another comparison the chapter owes you, because a reader asking "why not just make a kernel thread" deserves a straight answer. +本章欠你的另一个比较,因为问"为什么不直接创建一个内核线程"的读者值得一个直接的回答。 -A kernel thread created with `kproc_create(9)` is a full-fledged scheduled entity: its own stack (typically 16 KB on amd64), its own priority, its own `proc` entry, its own state. A driver that wants to run a loop "every second, do X" could create such a thread and have it `kproc_kthread_add` plus `cv_timedwait` its way through the loop. The code works, but it costs more than the job usually deserves. A taskqueue with one thread that sits idle most of the time and wakes on enqueue is cheaper per pending work item and easier to tear down. +用 `kproc_create(9)` 创建的内核线程是一个完整的调度实体:自己的栈(amd64 上通常 16 KB)、自己的优先级、自己的 `proc` 条目、自己的状态。想要运行"每秒做 X"循环的驱动可以创建这样的线程并用 `kproc_kthread_add` 加 `cv_timedwait` 来循环。代码可以工作,但成本超过工作通常应得的。一个有一个大部分时间空闲并在入队时唤醒的线程的任务队列,每个待处理工作项成本更低,也更容易拆除。 -There are legitimate cases for `kproc_create`. A long-running subsystem with its own tuning (priority, CPU affinity, process group) is one. A periodic job that genuinely needs a thread of its own for observability is another. A driver's deferred-work pattern almost never is. Use a taskqueue until a specific requirement forces you to do something else. +`kproc_create` 有合理的情况。一个有自己的调优(优先级、CPU 亲和性、进程组)的长运行子系统是一种。一个确实需要自己的线程以获得可观察性的周期性工作是另一种。驱动的延迟工作模式几乎从来不是。使用任务队列直到特定需求迫使你做其他事情。 ### 入队已待处理规则 -One rule worth calling out early, because it is the single most common source of surprise for newcomers to the API: a task cannot be pending twice. If you call `taskqueue_enqueue(tq, &sc->t)` while `sc->t` is already pending, the kernel increments `sc->t.ta_pending` and returns success without linking the task a second time. +一个值得提前指出的规则,因为它是 API 新手最常感到惊讶的来源:任务不能被待处理两次。如果你在 `sc->t` 已经待处理时调用 `taskqueue_enqueue(tq, &sc->t)`,内核递增 `sc->t.ta_pending` 并返回成功,不会第二次链接任务。 -This has two implications. First, your callback will run once, not twice, even if you enqueued twice. Second, the `pending` argument the callback receives is the number of times the task was enqueued before the callback got dispatched; your callback may use that count to batch accumulated work. +这有两个含义。首先,你的回调将运行一次,不是两次,即使你入队了两次。其次,回调接收的 `pending` 参数是回调被调度前任务被入队的次数;你的回调可以使用该计数来批量处理累积的工作。 -If you want to run the callback N times for N enqueues, a single task is the wrong model. Use N separate tasks, or enqueue a sentinel into a driver-owned queue and process each sentinel in the callback. Almost always the coalescing behaviour is what you want; Section 5 walks through how to exploit it deliberately. +如果你想让回调对 N 次入队运行 N 次,单个任务是错误的模型。使用 N 个独立任务,或向驱动拥有的队列中入队一个哨兵并在回调中处理每个哨兵。几乎总是合并行为是你想要的;第5节逐步讲解如何有意利用它。 ### 端到端最小示例 -A hello-world task, for concreteness. If you type this in a scratch module and load it, you will see the `device_printf` line in `dmesg`: +一个 hello-world 任务,为了具体。如果你在一个临时模块中输入并加载它,你将在 `dmesg` 中看到 `device_printf` 行: ```c #include @@ -592,17 +592,17 @@ DECLARE_MODULE(example_task, example_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(example_task, 1); ``` -The module does five things, each a single line. At load, `TASK_INIT` prepares the task structure. `taskqueue_enqueue` asks the shared `taskqueue_thread` to run the callback. The callback prints a message. At unload, `taskqueue_drain` waits for the callback to finish if it has not already. The whole lifecycle is compact. +该模块做了五件事,每件一行。加载时,`TASK_INIT` 准备任务结构。`taskqueue_enqueue` 请求共享的 `taskqueue_thread` 运行回调。回调打印一条消息。卸载时,`taskqueue_drain` 如果回调尚未完成则等待它完成。整个生命周期很紧凑。 -If you type this and load it, `dmesg` shows: +如果你输入并加载它,`dmesg` 显示: ```text example_task_fn: pending=1 ``` -The `pending=1` reflects the fact that the task was enqueued once before the callback fired. +`pending=1` 反映了任务在回调触发前被入队了一次。 -Now try a coalescing demonstration: change `MOD_LOAD` to enqueue the task five times in a row, then add a brief spin so the taskqueue thread gets a chance to wake up: +现在尝试一个合并演示:将 `MOD_LOAD` 改为连续入队任务五次,然后添加一个短暂暂停让任务队列线程有机会唤醒: ```c for (int i = 0; i < 5; i++) @@ -610,48 +610,48 @@ for (int i = 0; i < 5; i++) pause("example", hz / 10); ``` -Run it again and `dmesg` shows: +再次运行,`dmesg` 显示: ```text example_task_fn: pending=5 ``` -One invocation, pending of five. That is the coalescing rule, live. +一次调用,待处理为五。这就是合并规则的实际效果。 -That is enough shape to make the worked refactors in the next sections meaningful. The rest of this chapter scales the same structure up to the real `myfirst` driver, replaces the scratch module with four integration stages, adds the teardown, adds a private taskqueue, and walks through the debugging story. +这足以让下一节中实战重构变得有意义。本章的其余部分将相同结构扩展到真正的 `myfirst` 驱动,将临时模块替换为四个集成阶段,添加拆除、添加私有任务队列,并逐步讲解调试故事。 ### 第2节总结 -A `struct task` holds a callback and its context. A `struct taskqueue` manages a queue of such tasks and one or more threads (or an SWI context) that consume them. The API is small: create, start threads, enqueue (optionally with a delay), cancel, drain, free, block, unblock, quiesce. The kernel provides a handful of predefined queues that every driver can use without creating its own. The enqueue-already-pending rule folds redundant submissions into a coalesced invocation whose pending count is the final tally. +`struct task` 持有回调和其上下文。`struct taskqueue` 管理此类任务的队列和一个或多个消费它们的线程(或 SWI 上下文)。API 很小:创建、启动线程、入队(可选带延迟)、取消、排空、释放、阻塞、解阻塞、静默。内核提供了少数预定义队列,每个驱动都可以使用而不必创建自己的。入队已待处理规则将冗余提交合并为单次调用,其待处理计数是最终总计。 -Section 3 takes those tools to the `myfirst` driver and deposits the first task in the code, under the `tick_source` callout that has been quietly skipping `selwakeup`. The fix is small; the mental model is the important part. +第3节将这些工具带到 `myfirst` 驱动中,并在一直在静默跳过 `selwakeup` 的 `tick_source` callout 下放入第一个任务。修复很小;心智模型是重要的部分。 ## 第3节:从定时器或模拟中断延迟工作 -Chapter 13 left the `myfirst` driver with three callouts that all obeyed the callout contract strictly. None of them tried to do anything that does not belong in a callout callback. The `tick_source` callback in particular omitted the `selwakeup` call that a real driver would want to make when new bytes appear in the buffer, and the file even carried a comment saying so. Chapter 14 removes that omission. +第13章留给 `myfirst` 驱动三个都严格遵守 callout 契约的 callout。它们都没有尝试做不属于 callout 回调的事情。特别是 `tick_source` 回调省略了真实驱动在新字节出现在缓冲区时想要调用的 `selwakeup`,文件中甚至带有一条注释说明了这一点。第14章移除了这个省略。 -Section 3 is the first worked refactor. It introduces Stage 1 of the Chapter 14 driver: the driver gains one `struct task`, one task callback, an enqueue from `tick_source`, and a drain at detach. The private-taskqueue work is saved for Section 4; for Stage 1 we use the shared `taskqueue_thread`. Using the shared queue first keeps the first step small and isolates the change to the deferred-work pattern itself. +第3节是第一次实战重构。它引入第14章驱动的第1阶段:驱动获得一个 `struct task`、一个任务回调、一个从 `tick_source` 发出的入队,以及在分离时的排空。私有任务队列的工作留到第4节;第1阶段我们使用共享的 `taskqueue_thread`。先使用共享队列保持第一步小且将变更隔离到延迟工作模式本身。 ### 一句话概述变更 -When `tick_source` has just deposited a byte into the circular buffer, instead of silently omitting `selwakeup`, enqueue a task whose callback runs `selwakeup` in thread context. +当 `tick_source` 刚向循环缓冲区存入一个字节时,不再静默省略 `selwakeup`,而是入队一个任务,其回调在线程上下文中运行 `selwakeup`。 -That is the whole change. Everything else is the surrounding setup. +这就是全部更改。其他一切都是围绕的设置。 ### softc添加 -Add two members to `struct myfirst_softc`: +向 `struct myfirst_softc` 添加两个成员: ```c struct task selwake_task; int selwake_pending_drops; ``` -The `selwake_task` is the task we will enqueue. The `selwake_pending_drops` is a debug counter we will increment whenever the task coalesces two or more enqueues into one firing; the difference between "number of enqueue calls" and "number of callback invocations" tells us how often the tick source produced data faster than the taskqueue thread drained it. That is pure diagnostic; you can omit it if you prefer, but seeing a real coalescing count in action is valuable. +`selwake_task` 是我们将要入队的任务。`selwake_pending_drops` 是一个调试计数器,每当任务将两次或更多入队合并为一次触发时递增;"入队调用次数"与"回调调用次数"之间的差异告诉我们 tick 源产生数据的速度超过任务队列线程排空速度的频率。这纯粹是诊断性的;如果你愿意可以省略它,但看到实际合并计数在行动中是有价值的。 -Add a read-only sysctl so we can observe the counter from userspace without a debug build: +添加一个只读 sysctl 以便我们可以从用户空间观察计数器而无需调试构建: ```c SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), @@ -660,11 +660,11 @@ SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), "Times selwake_task coalesced two or more enqueues into one firing"); ``` -Placement matters only in the sense that it must come after `sc->sysctl_tree` has been created and before the function returns success; the Chapter 13 attach sequence already has the right structure, so the addition slots in naturally alongside the other stats. +放置位置仅在它必须在 `sc->sysctl_tree` 创建之后、函数返回成功之前才有意义;第13章的 attach 序列已经有正确的结构,因此添加自然地与其他统计数据放在一起。 ### 任务回调 -Add a function: +添加一个函数: ```c static void @@ -685,19 +685,19 @@ myfirst_selwake_task(void *arg, int pending) } ``` -Several things to notice. +有几件事值得注意。 -The callback takes the softc via the `arg` pointer, exactly like the callout callbacks do. It does not need `MYFIRST_ASSERT` at the top because the task callback does not run with any driver lock held; the taskqueue framework does not hold your lock for you. This is different from the callout lock-aware pattern from Chapter 13, and is worth pausing on. A callout initialised with `callout_init_mtx(&co, &sc->mtx, 0)` runs with `sc->mtx` held. A task never does. Inside the task callback, if you want to touch state that the mutex protects, you acquire the mutex yourself, do the work, release it, and continue. +回调通过 `arg` 指针获取 softc,与 callout 回调完全相同。它不需要在顶部使用 `MYFIRST_ASSERT`,因为任务回调运行时没有持有任何驱动锁;任务队列框架不会为你持有锁。这与第13章的 callout 锁感知模式不同,值得停下来思考。用 `callout_init_mtx(&co, &sc->mtx, 0)` 初始化的 callout 在 `sc->mtx` 持有的情况下运行。任务永远不会。在任务回调内部,如果你想触碰互斥锁保护的状态,你自行获取互斥锁,做工作,释放它,然后继续。 -The callback conditionally updates `selwake_pending_drops` under the mutex. The condition `pending > 1` means "this callback is handling at least two coalesced enqueues". Incrementing a counter under the mutex is fast and safe; doing it unconditionally would make the common case (pending == 1, no coalescing) pay the lock cost needlessly. +回调在互斥锁下有条件地更新 `selwake_pending_drops`。条件 `pending > 1` 意味着"此回调正在处理至少两个合并的入队"。在互斥锁下递增计数器是快速且安全的;无条件这样做会使常见情况(pending == 1,无合并)不必要地支付锁成本。 -The `selwakeup(&sc->rsel)` call itself is the reason we are here. It runs without any driver lock held, which is what `selwakeup` wants, and it runs in thread context, which is what `selwakeup` requires. The bug from Chapter 13 is fixed. +`selwakeup(&sc->rsel)` 调用本身就是我们在这里的原因。它在没有任何驱动锁持有的情况下运行,这正是 `selwakeup` 想要的,并且它在线程上下文中运行,这是 `selwakeup` 要求的。第13章的 bug 已修复。 -The callback does not check `is_attached`. It does not need to. The detach path drains the task before freeing the selinfo; by the time `is_attached` would be zero, the task callback is guaranteed not to be running, and `selwakeup` will see valid state. The drain ordering is what makes the omission safe, which is why we discuss the ordering so carefully in Section 4. +回调不检查 `is_attached`。它不需要。分离路径在释放 selinfo 之前排空任务;当 `is_attached` 为零时,任务回调保证不在运行,`selwakeup` 将看到有效状态。排空顺序是使省略安全的原因,这就是为什么我们在第4节中如此仔细地讨论顺序。 -### The `tick_source` Edit +### `tick_source` 的编辑 -Change the `tick_source` callback from: +将 `tick_source` 回调从: ```c static void @@ -729,7 +729,7 @@ myfirst_tick_source(void *arg) } ``` -To: +改为: ```c static void @@ -764,23 +764,23 @@ myfirst_tick_source(void *arg) } ``` -Two edits. A local `wake_sel` flag records whether a byte was written; the `taskqueue_enqueue` call happens after the cbuf work. The comment about "selwakeup omitted" becomes obsolete and is removed. +两处编辑。一个局部 `wake_sel` 标志记录是否写入了字节;`taskqueue_enqueue` 调用发生在 cbuf 工作之后。关于"selwakeup 省略"的注释变得过时并被移除。 -Why use a flag instead of calling `taskqueue_enqueue` inline in the `if (put > 0)` block? Because `taskqueue_enqueue` is safe to call while holding `sc->mtx` (it acquires its own internal mutex; there is no lock-order problem for the taskqueue's own mutex because it is not ordered against `sc->mtx`), but it is good hygiene to keep mutex-held sections tight and to name the reason for the enqueue with a local variable. The version with the flag is easier to read and easier to extend if later stages add more conditions that should trigger the wake. +为什么使用标志而不是在 `if (put > 0)` 块中内联调用 `taskqueue_enqueue`?因为 `taskqueue_enqueue` 在持有 `sc->mtx` 时是安全的(它获取自己的内部互斥锁;任务队列自己的互斥锁与 `sc->mtx` 之间没有锁序问题),但保持互斥锁持有段紧凑并用局部变量命名入队原因是良好的卫生习惯。带标志的版本更易读,如果后续阶段添加更多应触发唤醒的条件也更容易扩展。 -Is `taskqueue_enqueue` actually safe to call from a callout callback with `sc->mtx` held? Yes. The taskqueue uses its own internal mutex (`tq_mutex`) which is entirely separate from `sc->mtx`; no lock order between them is established, so `WITNESS` has nothing to complain about. We will verify this in the lab at the end of this section. For future reference, the relevant guarantee in `/usr/src/sys/kern/subr_taskqueue.c` is that `taskqueue_enqueue` acquires `TQ_LOCK(tq)` (a sleep mutex for `taskqueue_create`, a spin mutex for `taskqueue_create_fast`), performs the list manipulation, and releases the lock. No sleeping, no recursion into the caller's lock, no cross-lock dependency. +`taskqueue_enqueue` 在持有 `sc->mtx` 的 callout 回调中调用真的安全吗?是的。任务队列使用自己的内部互斥锁(`tq_mutex`),它完全独立于 `sc->mtx`;两者之间没有建立锁序,所以 `WITNESS` 没有什么可抱怨的。我们将在本节末尾的实验中验证这一点。供将来参考,`/usr/src/sys/kern/subr_taskqueue.c` 中的相关保证是 `taskqueue_enqueue` 获取 `TQ_LOCK(tq)`(对于 `taskqueue_create` 是睡眠互斥锁,对于 `taskqueue_create_fast` 是自旋互斥锁),执行列表操作,然后释放锁。不睡眠,不递归进入调用者的锁,无跨锁依赖。 ### 附加变更 -In `myfirst_attach`, add one line after the existing callout initialisations: +在 `myfirst_attach` 中,在现有 callout 初始化之后添加一行: ```c TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); ``` -Place it alongside the callout init calls. The conceptual grouping ("here is where we prepare the driver's deferred-work primitives") makes the file easier to scan. +把它放在 callout 初始化调用旁边。概念分组("这里是我们准备驱动延迟工作原语的地方")使文件更容易浏览。 -Initialise `selwake_pending_drops` to zero in the same block where other counters are zeroed: +在与其他计数器清零的同一代码块中将 `selwake_pending_drops` 初始化为零: ```c sc->selwake_pending_drops = 0; @@ -788,36 +788,36 @@ sc->selwake_pending_drops = 0; ### 分离变更 -This is the critical part of the stage. The Chapter 13 detach sequence, simplified, is: +这是阶段的关键部分。第13章的分离序列简化如下: -1. Refuse detach if `active_fhs > 0`. -2. Clear `is_attached`. -3. Broadcast `data_cv` and `room_cv`. -4. Drain `rsel` and `wsel` via `seldrain`. -5. Drain the three callouts. -6. Destroy devices, free sysctls, destroy cbuf, free counters, destroy cvs, destroy sx, destroy mtx. +1. 如果 `active_fhs > 0` 则拒绝 detach。 +2. 清除 `is_attached`。 +3. 广播 `data_cv` 和 `room_cv`。 +4. 通过 `seldrain` 排空 `rsel` 和 `wsel`。 +5. 排空三个 callout。 +6. 销毁设备、释放 sysctl、销毁 cbuf、释放计数器、销毁 cv、销毁 sx、销毁 mtx。 -Chapter 14 Stage 1 adds one step: drain `selwake_task` between the callout drains (step 5) and the `seldrain` calls (step 4). Actually, the ordering subtlety is more careful than that. Let's think through it. +第14章第1阶段添加一步:在 callout 排空(步骤5)和 `seldrain` 调用(步骤4)之间排空 `selwake_task`。实际上,排序的微妙之处比这更仔细。让我们仔细想想。 -The `selwake_task` callback calls `selwakeup(&sc->rsel)`. If `sc->rsel` is being drained concurrently, the callback could race. The rule is: ensure the task callback is guaranteed not to be running before calling `seldrain`. That means `taskqueue_drain(taskqueue_thread, &sc->selwake_task)` must happen before `seldrain(&sc->rsel)`. +`selwake_task` 回调调用 `selwakeup(&sc->rsel)`。如果 `sc->rsel` 正在被并发排空,回调可能产生竞争。规则是:确保在调用 `seldrain` 之前保证任务回调不在运行。这意味着 `taskqueue_drain(taskqueue_thread, &sc->selwake_task)` 必须在 `seldrain(&sc->rsel)` 之前发生。 -However, the task can still be enqueued by an in-flight callout callback until we have drained the callouts. If we drain the task first and then the callouts, an in-flight callout could re-enqueue the task after we drained it, and the re-enqueued task would then try to run after `seldrain`. +然而,在我们排空 callout 之前,任务仍然可以被进行中的 callout 回调入队。如果我们先排空任务再排空 callout,进行中的 callout 可能在我们排空它之后重新入队任务,重新入队的任务将尝试在 `seldrain` 之后运行。 -The only safe ordering is: drain callouts first (which guarantees no more enqueues will happen), then drain the task (which guarantees the last enqueue has completed), then call `seldrain`. But we also must clear `is_attached` before draining the callouts so an in-flight callback exits early instead of re-arming. +唯一安全的顺序是:先排空 callout(保证不会再有入队发生),然后排空任务(保证最后一次入队已完成),然后调用 `seldrain`。但我们也必须在排空 callout 之前清除 `is_attached`,以便进行中的回调提前退出而不是重新武装。 -Putting it all together, the Stage 1 detach ordering is: +综合起来,第1阶段的分离顺序是: -1. Refuse detach if `active_fhs > 0`. -2. Clear `is_attached` (under the mutex). -3. Broadcast `data_cv` and `room_cv` (release the mutex first). -4. Drain the three callouts (no mutex held; `callout_drain` may sleep). -5. Drain `selwake_task` (no mutex held; `taskqueue_drain` may sleep). -6. Drain `rsel` and `wsel` via `seldrain`. -7. Destroy devices, free sysctls, destroy cbuf, free counters, destroy cvs, destroy sx, destroy mtx. +1. 如果 `active_fhs > 0` 则拒绝 detach。 +2. 清除 `is_attached`(在互斥锁保护下)。 +3. 广播 `data_cv` 和 `room_cv`(先释放互斥锁)。 +4. 排空三个 callout(不持有互斥锁;`callout_drain` 可能睡眠)。 +5. 排空 `selwake_task`(不持有互斥锁;`taskqueue_drain` 可能睡眠)。 +6. 通过 `seldrain` 排空 `rsel` 和 `wsel`。 +7. 销毁设备、释放 sysctl、销毁 cbuf、释放计数器、销毁 cv、销毁 sx、销毁 mtx。 -Steps 4 and 5 are the new ordering constraint. Callouts first, tasks second, sel third. Violating that order on a debug kernel typically trips an assertion inside `seldrain`; on a production kernel it is a use-after-free waiting to happen. +步骤4和5是新的排序约束。先 callout,第二任务,第三 sel。在调试内核上违反此顺序通常会触发 `seldrain` 内部的断言;在生产内核上这是一个等待发生的释放后使用。 -The code in `myfirst_detach` becomes: +`myfirst_detach` 中的代码变为: ```c /* Chapter 13: drain every callout. No lock held; safe to sleep. */ @@ -832,24 +832,24 @@ seldrain(&sc->rsel); seldrain(&sc->wsel); ``` -Two lines of code plus a comment. The ordering is visible in the source. +两行代码加一条注释。排序在源码中可见。 -### The Makefile +### Makefile -No change. `bsd.kmod.mk` picks up the taskqueue API headers from the system tree; no additional source files are needed for Stage 1. +无更改。`bsd.kmod.mk` 从系统树中获取任务队列 API 头文件;第1阶段不需要额外的源文件。 ### 构建与加载 -At this point your working copy should have: +此时你的工作副本应该有: -- The two new softc members (`selwake_task`, `selwake_pending_drops`). -- The `myfirst_selwake_task` function. -- The edit to `myfirst_tick_source`. -- The `TASK_INIT` call and the counter zeroing in attach. -- The `taskqueue_drain` call in detach. -- The new `selwake_pending_drops` sysctl. +- 两个新的 softc 成员(`selwake_task`、`selwake_pending_drops`)。 +- `myfirst_selwake_task` 函数。 +- 对 `myfirst_tick_source` 的编辑。 +- attach 中的 `TASK_INIT` 调用和计数器清零。 +- detach 中的 `taskqueue_drain` 调用。 +- 新的 `selwake_pending_drops` sysctl。 -Build from the Stage 1 directory: +从第1阶段目录构建: ```text # cd /path/to/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task @@ -874,7 +874,7 @@ dev.myfirst.0.stats.selwake_pending_drops: 0 ### 观察修复效果 -To observe Stage 1 doing its job, start a `poll(2)` waiter on the device and have the tick source generate data. A simple poller lives under `examples/part-03/ch14-taskqueues-and-deferred-work/labs/poll_waiter.c`: +要观察第1阶段在做它的工作,在设备上启动一个 `poll(2)` 等待者并让 tick 源生成数据。一个简单的 poller 位于 `examples/part-03/ch14-taskqueues-and-deferred-work/labs/poll_waiter.c`: ```c #include @@ -912,122 +912,122 @@ main(int argc, char **argv) } ``` -Compile it with `cc poll_waiter.c -o poll_waiter` (no special libraries). Run it in one terminal: +用 `cc poll_waiter.c -o poll_waiter` 编译(无需特殊库)。在一个终端运行它: ```text # ./poll_waiter ``` -In a second terminal, enable the tick source at a slow pace to make the output easy to watch: +在第二个终端中,以较慢的节奏启用 tick 源使输出容易观察: ```text # sysctl dev.myfirst.0.tick_source_interval_ms=500 ``` -The Chapter 13 driver, without the Stage 1 fix, would leave `poll_waiter` stuck. The reader byte would accumulate in the buffer, but `poll(2)` would never return because `selwakeup` was never called. You would see nothing. +没有第1阶段修复的第13章驱动,会让 `poll_waiter` 卡住。读取字节会累积在缓冲区中,但 `poll(2)` 永远不会返回,因为 `selwakeup` 从未被调用。你什么也看不到。 -The Stage 1 driver does call `selwakeup`, via the task. You should see `t` characters appearing in the `poll_waiter` terminal every half second. When you stop the test, `poll_waiter` exits cleanly via `Ctrl-C`. +第1阶段驱动通过任务确实调用了 `selwakeup`。你应该看到 `t` 字符每半秒出现在 `poll_waiter` 终端中。当你停止测试时,`poll_waiter` 通过 `Ctrl-C` 干净退出。 -Now speed up the tick source to stress the taskqueue: +现在加速 tick 源来给任务队列施加压力: ```text # sysctl dev.myfirst.0.tick_source_interval_ms=1 ``` -You should see a continuous stream of `t` characters. Check the coalescing counter: +你应该看到 `t` 字符的连续流。检查合计计数器: ```text # sysctl dev.myfirst.0.stats.selwake_pending_drops dev.myfirst.0.stats.selwake_pending_drops: ``` -The number is the count of times the task callback handled a pending count greater than one. On a lightly loaded machine it may stay small (the taskqueue thread wakes quickly enough to handle each enqueue individually). Under contention the number grows, and you can watch the coalescing behaviour directly. +这个数字是任务回调处理了大于一的待处理计数的次数。在轻度负载的机器上它可能保持很小(任务队列线程足够快地醒来以单独处理每次入队)。在争用下数字会增长,你可以直接观察合并行为。 -If the counter stays at zero even under load, the machine is fast enough that every enqueue drains before the next one arrives. That is not a bug; it is a sign that the coalescing is present but not triggered. Section 5 introduces a deliberate workload that forces coalescing. +如果计数器即使在负载下也保持为零,说明机器足够快,每次入队在下一次到来之前就被排空了。这不是 bug;这表明合并存在但未触发。第5节引入一个故意的工作负载来强制合并。 ### 卸载 -Stop the tick source: +停止 tick 源: ```text # sysctl dev.myfirst.0.tick_source_interval_ms=0 ``` -Close the `poll_waiter` with `Ctrl-C`. Unload: +用 `Ctrl-C` 关闭 `poll_waiter`。卸载: ```text # kldunload myfirst ``` -The unload should be clean. If it fails with `EBUSY`, you still have an open descriptor somewhere; the close and the next `kldunload` should succeed. +卸载应该干净。如果以 `EBUSY` 失败,你仍然在某处有打开的描述符;关闭它然后下次 `kldunload` 应该成功。 -If the unload hangs, something in the detach path is blocked. The most likely cause is that the `taskqueue_drain` is waiting for a task that cannot complete. That would indicate a bug, and the debugging section (Section 7) shows how to identify it. For the normal flow, the unload completes in milliseconds. +如果卸载挂起,分离路径中的某样东西被阻塞。最可能的原因是 `taskqueue_drain` 在等待一个无法完成的任务。那将表明有 bug,调试部分(第7节)展示了如何识别它。对于正常流程,卸载在毫秒内完成。 ### 我们刚才做了什么 -A short summary before Section 4 scales up. +第4节扩展之前的简短总结。 -Stage 1 added one task to the driver, initialised it in attach, enqueued it from a callout callback, drained it in detach in the correct order, and observed coalescing in action. The task runs on the shared `taskqueue_thread`; it shares that queue with every other driver in the system that also uses it. For a low-rate workload that is entirely fine. For a driver that will eventually do substantial work in its tasks, or that wants to isolate its task-processing latency from whatever else the system is doing, a private taskqueue is the right answer. Section 4 takes that step. +第1阶段向驱动添加了一个任务,在 attach 中初始化它,从 callout 回调入队它,在分离时以正确顺序排空它,并观察了合并的实际效果。任务运行在共享的 `taskqueue_thread` 上;它与系统中其他也使用它的每个驱动共享该队列。对于低速率工作负载这完全没问题。对于最终会在任务中做大量工作的驱动,或想要将其任务处理延迟与系统正在做的其他事情隔离的驱动,私有任务队列是正确答案。第4节采取那一步。 ### 需要避免的常见错误 -A short list of mistakes that beginners make when writing their first task. Each has bitten real drivers; each has a simple rule that prevents it. +初学者在编写第一个任务时犯的错误简表。每个都咬过真实的驱动;每个都有一个简单的规则来防止它。 -**Forgetting to drain at detach.** If you enqueue tasks but do not drain them, an in-flight task may run after the softc is freed, and the kernel crashes in the task callback with a dereference of freed memory. Always drain every task your driver owns before freeing anything the task touches. +**忘记在分离时排空。** 如果你入队任务但不排空它们,进行中的任务可能在 softc 被释放后运行,内核在任务回调中对已释放内存的解引用时崩溃。总是在释放任务触碰的任何东西之前排空驱动拥有的每个任务。 -**Draining in the wrong order relative to the state the task uses.** The task-then-sel ordering we discussed above is a specific case. The general rule: drain every producer of enqueues, then drain the task, then free the state the task uses. Violating the order is a race, even if the race is rare. +**相对于任务使用的状态以错误顺序排空。** 我们上面讨论的任务然后 sel 的顺序是一个特定情况。通用规则:排空每个入队的生产者,然后排空任务,然后释放任务使用的状态。违反顺序是竞争,即使竞争很少见。 -**Assuming the task runs immediately after enqueue.** It does not. The taskqueue thread wakes on enqueue and then the scheduler decides when to run it. Under load this can be milliseconds. Drivers that assume zero latency break under load. +**假设任务在入队后立即运行。** 它不会。任务队列线程在入队时被唤醒,然后由调度器决定何时运行它。在负载下这可能是毫秒级。假设零延迟的驱动在负载下会出问题。 -**Assuming the task runs once per enqueue.** It does not. Coalescing folds redundant submissions. If you need "exactly once per event" semantics, you need per-event state inside the softc (a queue of work items, for example), not one task per event. +**假设任务每次入队运行一次。** 它不会。合并折叠冗余提交。如果你需要"每个事件恰好一次"语义,你需要 softc 内部的每事件状态(例如工作项队列),而不是每个事件一个任务。 -**Acquiring a driver lock in the wrong order in the task callback.** The task callback is ordinary thread-context code. It obeys your driver's established lock order. If the driver's order is `sc->mtx -> sc->cfg_sx`, the task callback must take the mutex before the sx. Violations of this order are `WITNESS` errors the same as they would be anywhere else. +**在任务回调中以错误顺序获取驱动锁。** 任务回调是普通的线程上下文代码。它遵守驱动已建立的锁序。如果驱动的顺序是 `sc->mtx -> sc->cfg_sx`,任务回调必须先获取互斥锁再获取 sx。违反此顺序与在其他任何地方一样是 `WITNESS` 错误。 -**Using `taskqueue_enqueue` from inside a filter-interrupt context without a fast taskqueue.** `taskqueue_enqueue(taskqueue_thread, ...)` acquires a sleep mutex on the taskqueue's internal lock. That is illegal from a filter-interrupt context. Filter interrupts must enqueue onto `taskqueue_fast` or a `taskqueue_create_fast` queue. Callout callbacks do not hit this restriction because they run in thread context; the issue is specific to filter interrupts. Part 4 revisits this when it introduces `bus_setup_intr`. +**从过滤器中断上下文内部在没有快速任务队列的情况下使用 `taskqueue_enqueue`。** `taskqueue_enqueue(taskqueue_thread, ...)` 获取任务队列内部锁上的睡眠互斥锁。这在过滤器中断上下文中是非法的。过滤器中断必须入队到 `taskqueue_fast` 或 `taskqueue_create_fast` 队列。callout 回调不触及此限制,因为它们在线程上下文中运行;这个问题是过滤器中断特有的。第四部分在引入 `bus_setup_intr` 时会重新讨论这一点。 -Each of those mistakes can be caught by a review, by `WITNESS`, or by a carefully written stress test. The first two in particular are the kind of bug that looks fine until the first detach under load. +这些错误中的每一个都可以通过审查、`WITNESS` 或精心编写的压力测试来捕获。前两个特别是那种在第一次负载下分离之前看起来都正常的 bug。 ### 第3节总结 -The `myfirst` driver now has one task. It uses the task to move `selwakeup` out of the callout callback and into thread context, fixing a real bug from Chapter 13. The task is initialised in attach, enqueued from the `tick_source` callback, and drained in detach in the correct order relative to the callouts and the selinfo drain. +`myfirst` 驱动现在有一个任务。它使用该任务将 `selwakeup` 从 callout 回调中移到线程上下文,修复了第13章的一个真实 bug。任务在 attach 中初始化,从 `tick_source` 回调入队,并在分离时以相对于 callout 和 selinfo 排空的正确顺序排空。 -The shared `taskqueue_thread` is the first taskqueue we used because it was already there. For a driver that is going to grow more tasks and more responsibility, a private taskqueue gives better isolation and a cleaner teardown story. Section 4 creates that private taskqueue. +共享的 `taskqueue_thread` 是我们使用的第一个任务队列,因为它已经存在。对于将要增长更多任务和更多职责的驱动,私有任务队列提供更好的隔离和更干净的拆除故事。第4节创建那个私有任务队列。 ## 第4节:任务队列设置与清理 -Stage 1 used the shared `taskqueue_thread`. That choice kept the first change small: one task, one enqueue, one drain, and a detach ordering to respect. Stage 2 creates a private taskqueue owned by the driver. The change is small in code terms, but it buys a handful of properties that become important once the driver grows. +第1阶段使用了共享的 `taskqueue_thread`。那个选择保持了第一次更改的小型化:一个任务、一个入队、一个排空,以及一个需要遵守的分离顺序。第2阶段创建一个由驱动拥有的私有任务队列。代码量的变更很小,但它带来了几个在驱动成长后变得重要的属性。 -This section teaches Stage 2 of the refactor, walks through the setup and teardown of a private taskqueue, audits the detach ordering carefully, and finishes with a pre-production checklist you can reuse on every taskqueue-using driver you write. +本节教授重构的第2阶段,逐步讲解私有任务队列的设置和拆除,仔细审计分离顺序,最后以一个你可以在编写的每个任务队列驱动上重用的投产前检查表结束。 ### 为什么使用私有任务队列 -Three reasons for a private taskqueue. +使用私有任务队列的三个原因。 -First, **isolation**. A private taskqueue's thread runs only your driver's tasks. If some other driver in the system misbehaves on `taskqueue_thread` (blocking for too long in its task callback, for example), your driver's tasks are not affected. Conversely, if your driver misbehaves, the misbehaviour is contained. +第一,**隔离**。私有任务队列的线程只运行你驱动的任务。如果系统中其他驱动在 `taskqueue_thread` 上行为不当(例如,在任务回调中阻塞太久),你驱动的任务不受影响。反之,如果你的驱动行为不当,不当行为被限制在范围内。 -Second, **observability**. `procstat -t` and `ps ax` show each taskqueue thread with a distinct name. A private queue is easy to spot: it shows up with the name you gave it (`myfirst taskq` by convention). The shared `taskqueue_thread` shows up just as `thread taskq`, which is shared with every other driver. +第二,**可观察性**。`procstat -t` 和 `ps ax` 显示每个任务队列线程及其独特的名称。私有队列很容易发现:它以你给它的名称(按约定是 `myfirst taskq`)出现。共享的 `taskqueue_thread` 仅显示为 `thread taskq`,与所有其他驱动共享。 -Third, **teardown is self-contained**. When you detach, you drain and free your own taskqueue. You do not have to reason about whether some other driver has a pending task that your drain might wait for. (You would not actually wait for another driver's task on the shared queue, but the mental model of "we own our teardown" is easier to reason about.) +第三,**拆除是自包含的**。当你分离时,你排空并释放自己的任务队列。你不必推理其他驱动是否有一个你的排空可能等待的待处理任务。(你实际上不会在共享队列上等待其他驱动的任务,但"我们拥有自己的拆除"的心智模型更容易推理。) -The cost is small. A taskqueue and one kernel thread, created at attach and torn down at detach. A few pages of memory and a couple of scheduler entries. Nothing measurable on any realistic system. +成本很小。一个任务队列和一个内核线程,在 attach 时创建,在分离时拆除。几页内存和几个调度器条目。在任何现实系统上都不可衡量。 -For a driver that will eventually have multiple tasks, a private taskqueue is the right default. For a driver with a single trivial task on a rare code path, the shared queue is fine. `myfirst` is the former: we already have one task, and the chapter will add more. +对于最终会有多个任务的驱动,私有任务队列是正确的默认选择。对于只有单个琐碎任务在罕见代码路径上的驱动,共享队列就可以了。`myfirst` 是前者:我们已有一个任务,本章还会添加更多。 ### softc添加 -Add one member to `struct myfirst_softc`: +向 `struct myfirst_softc` 添加一个成员: ```c struct taskqueue *tq; ``` -No other softc changes for Stage 2. +第2阶段没有其他 softc 更改。 -### Creating the Taskqueue in Attach +### 在 attach 中创建任务队列 -In `myfirst_attach`, between the mutex / cv / sx initialisations and the callout initialisations, add: +在 `myfirst_attach` 中,在互斥锁/cv/sx 初始化和 callout 初始化之间,添加: ```c sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, @@ -1042,37 +1042,37 @@ if (error != 0) goto fail_tq; ``` -The call reads as: create a taskqueue called "myfirst taskq", allocate with `M_WAITOK` so the allocation cannot fail (we are in attach, which is a sleepable context), use `taskqueue_thread_enqueue` as the dispatcher so the queue is serviced by kernel threads, and pass `&sc->tq` as the context so the dispatcher can find the queue. +该调用读作:创建一个名为 "myfirst taskq" 的任务队列,用 `M_WAITOK` 分配所以分配不会失败(我们在 attach 中,这是一个可睡眠上下文),使用 `taskqueue_thread_enqueue` 作为调度器以便队列由内核线程服务,并传递 `&sc->tq` 作为上下文以便调度器能找到队列。 -The name `"myfirst taskq"` is the human-readable label that shows up in `procstat -t`. The convention in the Chapter 14 examples is `" taskq"` for a driver with a single private queue; drivers with multiple queues should use more specific names like `"myfirst rx taskq"` and `"myfirst tx taskq"`. +名称 `"myfirst taskq"` 是在 `procstat -t` 中显示的可读标签。第14章示例中单队列驱动的约定是 `" taskq"`;有多个队列的驱动应使用更具体的名称如 `"myfirst rx taskq"` 和 `"myfirst tx taskq"`。 -`taskqueue_start_threads` creates the worker threads. The first argument is `&sc->tq`, a double pointer so the function can find the taskqueue. The second argument is the thread count; we use one thread for `myfirst`. A driver with heavy, parallelisable work might use more. The third argument is the priority; `PWAIT` is the ordinary choice and equivalent to what the predefined `taskqueue_thread` uses. The variadic name is a format string for each thread's name; `device_get_nameunit(dev)` gives a per-instance name so multiple `myfirst` instances have distinguishable threads. +`taskqueue_start_threads` 创建工作线程。第一个参数是 `&sc->tq`,一个双重指针以便函数能找到任务队列。第二个参数是线程数量;`myfirst` 使用一个线程。有大量、可并行工作的驱动可能使用更多。第三个参数是优先级;`PWAIT` 是普通选择,等同于预定义 `taskqueue_thread` 使用的优先级。可变名称是每个线程名称的格式字符串;`device_get_nameunit(dev)` 给出每实例名称,以便多个 `myfirst` 实例有可区分的线程。 -The failure paths deserve attention. If `taskqueue_create` returns NULL (it normally does not with `M_WAITOK`, but be defensive), we jump to `fail_sx`. If `taskqueue_start_threads` fails, we jump to `fail_tq`, which must call `taskqueue_free` before continuing with the other cleanup. The Chapter 14 Stage 2 source (see the examples tree) has the labels in the right order. +失败路径值得注意。如果 `taskqueue_create` 返回 NULL(用 `M_WAITOK` 通常不会,但要防御性处理),我们跳转到 `fail_sx`。如果 `taskqueue_start_threads` 失败,我们跳转到 `fail_tq`,它必须在继续其他清理之前调用 `taskqueue_free`。第14章第2阶段源码(见示例树)有正确顺序的标签。 -### Updating the Enqueue Call Sites +### 更新入队调用点 -Every `taskqueue_enqueue(taskqueue_thread, ...)` call becomes `taskqueue_enqueue(sc->tq, ...)`. Same for drains: `taskqueue_drain(taskqueue_thread, ...)` becomes `taskqueue_drain(sc->tq, ...)`. +每个 `taskqueue_enqueue(taskqueue_thread, ...)` 调用变为 `taskqueue_enqueue(sc->tq, ...)`。排空也一样:`taskqueue_drain(taskqueue_thread, ...)` 变为 `taskqueue_drain(sc->tq, ...)`。 -After Stage 1, the driver has two such call sites: the enqueue in `myfirst_tick_source` and the drain in `myfirst_detach`. Both change in a single search-and-replace pass. +第1阶段之后,驱动有两个这样的调用点:`myfirst_tick_source` 中的入队和 `myfirst_detach` 中的排空。两者都在一次搜索替换中更改。 -### The Teardown Sequence +### 拆除顺序 -The detach ordering grows by two lines. The full sequence for Stage 2 is: +分离顺序增加了两行。第2阶段的完整顺序是: -1. Refuse detach if `active_fhs > 0`. -2. Clear `is_attached` under the mutex, broadcast both cvs, release the mutex. -3. Drain the three callouts. -4. Drain `selwake_task` on the private taskqueue. -5. Drain `rsel` and `wsel` via `seldrain`. -6. Free the private taskqueue with `taskqueue_free`. -7. Destroy devices, free sysctls, destroy cbuf, free counters, destroy cvs, destroy sx, destroy mtx. +1. 如果 `active_fhs > 0` 则拒绝分离。 +2. 在互斥锁下清除 `is_attached`,广播两个 cv,释放互斥锁。 +3. 排空三个 callout。 +4. 在私有任务队列上排空 `selwake_task`。 +5. 通过 `seldrain` 排空 `rsel` 和 `wsel`。 +6. 用 `taskqueue_free` 释放私有任务队列。 +7. 销毁设备,释放 sysctl,销毁 cbuf,释放计数器,销毁 cv,销毁 sx,销毁互斥锁。 -The new steps are 4 (which already existed in Stage 1, now targeting `sc->tq`) and 6 (which is new in Stage 2). +新步骤是 4(在第1阶段已存在,现在指向 `sc->tq`)和 6(在第2阶段新增)。 -A natural question: do we need the explicit `taskqueue_drain` at step 4 if step 6 is going to drain everything anyway? Technically no. `taskqueue_free` drains all pending tasks before destroying the queue. But keeping the explicit drain has two benefits. First, it makes the ordering explicit: you see that the task drain happens before `seldrain`, which is the ordering we care about. Second, it separates the "wait for this specific task to finish" question from the "tear down the whole queue" question. If later stages add more tasks on the same queue, each gets its own explicit drain, and the code tells the reader what is happening. +一个自然的问题:如果步骤 6 会排空一切,我们还需要步骤 4 的显式 `taskqueue_drain` 吗?技术上不需要。`taskqueue_free` 在销毁队列之前排空所有待处理任务。但保留显式排空有两个好处。第一,它使顺序显式:你看到任务排空发生在 `seldrain` 之前,这是我们关心的顺序。第二,它将"等待此特定任务完成"的问题与"拆除整个队列"的问题分开。如果后续阶段在同一队列上添加更多任务,每个都有自己的显式排空,代码告诉读者正在发生什么。 -The relevant code in `myfirst_detach`: +`myfirst_detach` 中的相关代码: ```c /* Chapter 13: drain every callout. No lock held; safe to sleep. */ @@ -1091,11 +1091,11 @@ taskqueue_free(sc->tq); sc->tq = NULL; ``` -Setting `sc->tq` to `NULL` after freeing is defensive: a later bug that tries to use a pointer after free will dereference `NULL` and panic at the call site, rather than corrupt unrelated memory. It costs nothing and occasionally saves an afternoon of debugging. +释放后将 `sc->tq` 设为 `NULL` 是防御性的:后来尝试使用已释放指针的 bug 会在调用点解引用 `NULL` 并崩溃,而不是损坏无关内存。它不花任何代价,偶尔能省下一个下午的调试。 -### The Attach Failure Path +### attach 失败路径 -Walk through the attach failure path carefully. The Chapter 13 attach had labels for the cbuf and mutex failure paths. Stage 2 adds taskqueue-related labels: +仔细遍历 attach 失败路径。第13章的 attach 有 cbuf 和互斥锁失败路径的标签。第2阶段添加任务队列相关标签: ```c static int @@ -1149,17 +1149,17 @@ fail_sx: } ``` -The failure labels chain: `fail_cb` calls `cbuf_destroy` then falls through to `fail_tq` which calls `taskqueue_free` then falls through to `fail_sx` which destroys the cvs, the sx, and the mutex. Each label undoes everything up to the point the corresponding init call succeeded. If `taskqueue_start_threads` fails, we go straight to `fail_tq` (the taskqueue was allocated but has no threads; `taskqueue_free` still handles that correctly because a just-created-and-not-started taskqueue has zero threads to reap). +失败标签链式:`fail_cb` 调用 `cbuf_destroy` 然后落入 `fail_tq`,它调用 `taskqueue_free` 然后落入 `fail_sx`,后者销毁 cv、sx 和互斥锁。每个标签撤销到对应初始化调用成功点为止的所有内容。如果 `taskqueue_start_threads` 失败,我们直接跳转到 `fail_tq`(任务队列已分配但没有线程;`taskqueue_free` 仍然正确处理,因为刚创建且未启动的任务队列没有线程需要回收)。 -Note also: `TASK_INIT` does not have a failure mode (it is a macro that sets fields), and does not need a destroy counterpart. The task becomes idle once `taskqueue_drain` has been called on it, and the storage is simply reclaimed with the softc. +还要注意:`TASK_INIT` 没有失败模式(它是一个设置字段的宏),也不需要对应的销毁。任务在 `taskqueue_drain` 被调用后变为空闲,其存储随 softc 一起回收。 ### 线程命名约定 -`taskqueue_start_threads` takes a format string and a variable argument list, so each thread gets its own name. The naming convention has a real effect on debuggability, so a short paragraph about conventions is worth it. +`taskqueue_start_threads` 接受一个格式字符串和可变参数列表,因此每个线程都有自己的名称。命名约定对可调试性有实际影响,所以一段简短的约定说明是值得的。 -The format string we use is `"%s taskq"` with `device_get_nameunit(dev)` as the argument. For a first `myfirst` instance the thread shows up as `myfirst0 taskq`. For a second instance it shows up as `myfirst1 taskq`. That makes the thread identifiable in `procstat -t` and `ps ax`. +我们使用的格式字符串是 `"%s taskq"`,参数为 `device_get_nameunit(dev)`。对于第一个 `myfirst` 实例,线程显示为 `myfirst0 taskq`。对于第二个实例显示为 `myfirst1 taskq`。这使线程在 `procstat -t` 和 `ps ax` 中可识别。 -A driver with multiple private queues should pick names that distinguish the queues: +有多个私有队列的驱动应选择区分队列的名称: ```c taskqueue_start_threads(&sc->tx_tq, 1, PWAIT, @@ -1168,32 +1168,32 @@ taskqueue_start_threads(&sc->rx_tq, 1, PWAIT, "%s rx", device_get_nameunit(dev)); ``` -Network drivers often name per-queue threads more specifically still (`"%s tx%d"` with the queue index) so that `procstat -t` shows every hardware queue's dedicated worker. +网络驱动通常更具体地命名每队列线程(`"%s tx%d"` 加队列索引),以便 `procstat -t` 显示每个硬件队列的专用工作线程。 ### 选择线程数量 -Most drivers create a single-threaded private taskqueue. One worker means tasks run sequentially, which simplifies the locking story: inside the task callback you can assume no other invocation of the same callback is running concurrently, without any explicit exclusion. +大多数驱动创建单线程私有任务队列。一个工作线程意味着任务顺序运行,这简化了锁定故事:在任务回调内部,你可以假设同一回调没有其他调用在并发运行,无需任何显式排他。 -A driver with multiple hardware channels that need parallel processing might create multiple worker threads on the same taskqueue. The taskqueue guarantees that a single task is running on at most one thread at a time (that is what `tq_active` tracks), but different tasks on the same queue can run in parallel on different threads. For `myfirst` the single-threaded configuration is correct. +有多个硬件通道需要并行处理的驱动可能在同一任务队列上创建多个工作线程。任务队列保证单个任务最多在一个线程上同时运行(这就是 `tq_active` 跟踪的),但同一队列上的不同任务可以在不同线程上并行运行。对于 `myfirst`,单线程配置是正确的。 -Multi-threaded taskqueues have implications for lock contention: two workers on the same queue, each running a different task, may contend for the same driver mutex. If the workload is naturally parallelisable, a multi-threaded queue speeds things up. If the workload is serialised anyway on the driver mutex, multiple threads add complexity without benefit. For a first taskqueue, single-threaded is the right default. +多线程任务队列对锁争用有影响:同一队列上的两个工作线程,各自运行不同的任务,可能争用同一驱动互斥锁。如果工作负载天然可并行,多线程队列可以加速。如果工作负载无论如何都在驱动互斥锁上串行化,多线程只增加复杂性而无收益。对于第一个任务队列,单线程是正确的默认选择。 ### 选择线程优先级 -The `pri` argument to `taskqueue_start_threads` is the thread's scheduling priority. We use `PWAIT` in the Chapter 14 examples. The options in practice are: +`taskqueue_start_threads` 的 `pri` 参数是线程的调度优先级。在第14章的示例中我们使用 `PWAIT`。实践中的选项有: -- `PWAIT` (numerically 76): ordinary driver priority, equivalent to the priority of `taskqueue_thread`. -- `PI_NET` (numerically 4): network-adjacent priority, used by many ethernet drivers. -- `PI_DISK`: historical constant; `PRI_MIN_KERN` territory. Used by storage drivers. -- `PRI_MIN_KERN` (numerically 48): generic kernel-thread priority, used when the above constants do not fit. +- `PWAIT`(数值 76):普通驱动优先级,等同于 `taskqueue_thread` 的优先级。 +- `PI_NET`(数值 4):网络相关优先级,被许多以太网驱动使用。 +- `PI_DISK`:历史常量;属于 `PRI_MIN_KERN` 范围。被存储驱动使用。 +- `PRI_MIN_KERN`(数值 48):通用内核线程优先级,当以上常量都不适用时使用。 -For a driver whose task work is not latency-sensitive, `PWAIT` is fine. For a driver that must run its task callbacks promptly even under load, raising the priority closer to the interrupt threads is sometimes justified. `myfirst` uses `PWAIT`. +对于任务工作不对延迟敏感的驱动,`PWAIT` 就够了。对于即使在负载下也必须及时运行任务回调的驱动,有时将优先级提高到接近中断线程是合理的。`myfirst` 使用 `PWAIT`。 -If you are writing a driver and are not sure what priority the convention expects, look at drivers of the same kind in `/usr/src/sys/dev/`. A storage driver that uses taskqueues probably uses `PRI_MIN_KERN` or `PI_DISK`; a network driver probably uses `PI_NET`. Pattern-matching on existing drivers is better than making up a priority. +如果你正在编写驱动但不确定约定期望什么优先级,可以查看 `/usr/src/sys/dev/` 中同类驱动的做法。使用 taskqueue 的存储驱动可能使用 `PRI_MIN_KERN` 或 `PI_DISK`;网络驱动可能使用 `PI_NET`。对现有驱动进行模式匹配比自己编造优先级更好。 -### A Worked Source Excerpt: `ale(4)` +### 实例源码阅读:`ale(4)` -A real driver using the exact pattern this section teaches. From `/usr/src/sys/dev/ale/if_ale.c`: +一个使用本节所授确切模式的真实驱动。来自 `/usr/src/sys/dev/ale/if_ale.c`: ```c /* Create local taskq. */ @@ -1203,9 +1203,9 @@ taskqueue_start_threads(&sc->ale_tq, 1, PI_NET, "%s taskq", device_get_nameunit(sc->ale_dev)); ``` -The `ale` ethernet driver creates a fast taskqueue (`taskqueue_create_fast`) with a spin mutex, because it wants to be able to enqueue from its filter interrupt handler. It runs one thread at `PI_NET` priority, with the per-unit name convention. The shape is exactly what we use in `myfirst`, with the choice of fast vs. regular and the priority reflecting the driver's context. +`ale` 以太网驱动创建了一个快速 taskqueue(`taskqueue_create_fast`),使用自旋互斥锁,因为它需要能从过滤器中断处理程序中入队。它以 `PI_NET` 优先级运行一个线程,使用每单元命名约定。其形状与我们在 `myfirst` 中使用的完全相同,只是快速 vs 普通的选择和优先级反映了驱动的上下文。 -From the same file, the matching teardown path: +同一文件中匹配的拆卸路径: ```c taskqueue_drain(sc->ale_tq, &sc->ale_int_task); @@ -1213,33 +1213,33 @@ taskqueue_drain(sc->ale_tq, &sc->ale_int_task); taskqueue_free(sc->ale_tq); ``` -`taskqueue_drain` on the specific task, then `taskqueue_free` on the queue. The same idiom we use. +对特定任务调用 `taskqueue_drain`,然后对队列调用 `taskqueue_free`。与我们使用的惯用法相同。 -Reading `ale(4)`'s setup and teardown once is worthwhile. It is a real driver, doing real work, using the pattern you are about to write in your own driver. Every driver under `/usr/src/sys/dev/` that uses taskqueues has very similar shape. +阅读 `ale(4)` 的设置和拆卸一次是值得的。它是一个真实的驱动,做真实的工作,使用你即将在自己驱动中编写的模式。`/usr/src/sys/dev/` 下每个使用 taskqueue 的驱动都有非常相似的形状。 -### Regressing Chapter 13 Behaviour +### 回归测试第13章行为 -Stage 2 must not break anything Chapter 13 established. Before proceeding, rerun the Chapter 13 stress kit with the Stage 2 driver loaded: +第2阶段不能破坏第13章建立的任何东西。在继续之前,用加载了第2阶段驱动的系统重新运行第13章的压力测试套件: ```text # cd /path/to/examples/part-03/ch13-timers-and-delayed-work/stage4-final # ./test-all.sh ``` -The test should pass exactly as it did at the end of Chapter 13. If it does not, the regression is in something Stage 2 changed; roll back to the pre-Stage-2 source and find the difference. The common cause is a missed enqueue-call-site update (an enqueue still targets `taskqueue_thread` instead of `sc->tq`). Those compile fine because the API is the same; they produce unrelated bugs at runtime. +测试应该像第13章结束时那样完全通过。如果不通过,回归出在第2阶段更改的某处;回滚到第2阶段之前的源码并找出差异。常见原因是遗漏了入队调用点的更新(某个入队仍指向 `taskqueue_thread` 而非 `sc->tq`)。这些代码编译没问题因为 API 相同;但会在运行时产生无关的 bug。 -### Observing the Private Taskqueue +### 观察私有任务队列 -With the Stage 2 driver loaded, `procstat -t` shows the new thread: +加载第2阶段驱动后,`procstat -t` 显示新线程: ```text # procstat -t | grep myfirst 0 100 myfirst0 taskq sleep - - 0:00 ``` -The name `myfirst0 taskq` is the per-instance thread name we asked for in `taskqueue_start_threads`. The state is `sleep` because the thread is blocked waiting for a task. The wchan is empty because the thread is sleeping on its own cv, which `procstat` may show differently across releases. +名称 `myfirst0 taskq` 是我们在 `taskqueue_start_threads` 中请求的每实例线程名。状态为 `sleep` 是因为线程在等待任务时被阻塞。wchan 为空是因为线程在自己的条件变量上睡眠,`procstat` 在不同版本中可能显示不同。 -Enable the tick source and watch again: +启用 tick 源并再次观察: ```text # sysctl dev.myfirst.0.tick_source_interval_ms=100 @@ -1247,75 +1247,75 @@ Enable the tick source and watch again: 0 100 myfirst0 taskq run - - 0:00 ``` -Briefly you may catch the thread in `run` state as it processes a task. Most of the time it sits in `sleep`. Both are expected. +偶尔你可能捕捉到线程在 `run` 状态处理任务。大部分时间它处于 `sleep`。两种状态都是正常的。 -`ps ax` shows the same thread: +`ps ax` 显示同样的线程: ```text # ps ax | grep 'myfirst.*taskq' 50 - IL 0:00.00 [myfirst0 taskq] ``` -The brackets indicate a kernel thread. The thread is always there while the driver is attached; it goes away at detach. +方括号表示这是一个内核线程。该线程在驱动 attach 期间始终存在;在 detach 时消失。 -### The Pre-Production Checklist for Stage 2 +### 第2阶段的预生产检查清单 -A short checklist to run through before declaring Stage 2 done. Each item is a question; each should be answerable with confidence. +一份简短的检查清单,在宣布第2阶段完成之前逐一过一遍。每一项都是一个问题;每一项都应该有信心地回答。 -- [ ] Does `attach` create the taskqueue before any code that might enqueue onto it? -- [ ] Does `attach` start at least one worker thread on the taskqueue before any code that expects a task to actually run? -- [ ] Does `attach` have failure labels that `taskqueue_free` the queue if a subsequent init fails? -- [ ] Does `detach` drain every task the driver owns before freeing any state those tasks touch? -- [ ] Does `detach` call `taskqueue_free` after every task drain and before destroying the mutex? -- [ ] Does `detach` set `sc->tq = NULL` after free, for defensive clarity? -- [ ] Is the taskqueue's thread priority chosen deliberately, with a rationale that matches the driver's kind? -- [ ] Is the taskqueue's thread name informative enough that `procstat -t` output is useful? -- [ ] Does every `taskqueue_enqueue` call target `sc->tq`, not `taskqueue_thread` (unless the enqueue is on a genuinely shared path for a specific reason)? -- [ ] Does every `taskqueue_drain` call match a `taskqueue_enqueue` on the same queue with the same task? +- [ ] `attach` 是否在任何可能入队的代码之前创建 taskqueue? +- [ ] `attach` 是否在任何期望任务实际运行的代码之前启动至少一个工作线程? +- [ ] `attach` 是否有失败标签,在后续初始化失败时 `taskqueue_free` 队列? +- [ ] `detach` 是否在释放任务触及的任何状态之前排空驱动拥有的每个任务? +- [ ] `detach` 是否在每个任务排空之后、销毁互斥锁之前调用 `taskqueue_free`? +- [ ] `detach` 是否在 free 之后设置 `sc->tq = NULL`,以保持防御性清晰? +- [ ] taskqueue 的线程优先级是否经过有意选择,理由与驱动的类型匹配? +- [ ] taskqueue 的线程名称是否足够有信息量,使 `procstat -t` 输出有用? +- [ ] 每个 `taskqueue_enqueue` 调用是否指向 `sc->tq`,而非 `taskqueue_thread`(除非入队因特定原因确实在共享路径上)? +- [ ] 每个 `taskqueue_drain` 调用是否在同一队列上用同一任务匹配一个 `taskqueue_enqueue`? -A driver that answers every item cleanly is a driver that handles its private taskqueue correctly. A driver that cannot is probably one step from a use-after-free at detach. +能干净地回答每一项的驱动就是一个正确处理其私有 taskqueue 的驱动。无法回答的驱动可能离 detach 时的释放后使用只有一步之遥。 ### 第2阶段的常见错误 -Three mistakes that beginners make when adding a private taskqueue. Each is preventable with a habit. +初学者在添加私有 taskqueue 时常犯的三个错误。每一个都可以通过一个好习惯来避免。 -**Creating the taskqueue after something that enqueues.** If the enqueue happens before `taskqueue_create` has returned, the enqueue dereferences a `NULL` pointer. Always put `taskqueue_create` early in attach, before any code that can trigger an enqueue. +**在入队代码之后创建 taskqueue。** 如果入队发生在 `taskqueue_create` 返回之前,入队会解引用一个 `NULL` 指针。始终将 `taskqueue_create` 放在 attach 的早期,在任何可能触发入队的代码之前。 -**Forgetting `taskqueue_start_threads`.** A taskqueue without worker threads is a queue that accepts enqueues but never runs the callbacks. Tasks pile up silently. If you think "my task never fires", check that you called `taskqueue_start_threads`. +**忘记 `taskqueue_start_threads`。** 一个没有工作线程的 taskqueue 是一个接受入队但从不运行回调的队列。任务会静默堆积。如果你觉得"我的任务从不触发",检查你是否调用了 `taskqueue_start_threads`。 -**Calling `taskqueue_free` without first having cleared `is_attached`.** If the taskqueue is freed while a callout callback is still running and could enqueue, the callout's enqueue will crash on the freed taskqueue. Always clear `is_attached`, drain callouts, drain the task, then free. The ordering is what makes it safe. +**在未清除 `is_attached` 的情况下调用 `taskqueue_free`。** 如果 taskqueue 在 callout 回调仍在运行且可能入队时被释放,callout 的入队会在已释放的 taskqueue 上崩溃。始终先清除 `is_attached`,排空 callout,排空任务,然后释放。顺序正是使其安全的关键。 -Section 7 will walk through each of these mistakes live, with a break-and-fix on a deliberately-misordered driver. For now the rule is: follow the ordering in this section, and the taskqueue lifecycle will be correct. +第7节将在一个故意错误排序的驱动上实时演练这些错误。目前的规则是:遵循本节的顺序,taskqueue 生命周期就会正确。 ### 第4节总结 -The driver now owns its own taskqueue. One thread, one name, one lifetime. Attach creates it and starts a worker; detach drains the task, frees the taskqueue, and unwinds. The ordering relative to callouts and selinfo is respected. `procstat -t` shows the thread by a recognisable name. The driver is self-contained in its deferred-work story. +驱动现在拥有自己的 taskqueue。一个线程,一个名称,一个生命周期。Attach 创建它并启动工作线程;detach 排空任务、释放 taskqueue 并回滚。相对于 callout 和 selinfo 的顺序得到了遵守。`procstat -t` 以可识别的名称显示线程。驱动在其延迟工作的故事中是自包含的。 -Section 5 takes the next step: we exploit the coalescing behaviour deliberately for batching, introduce the `timeout_task` variant for scheduled tasks, and discuss how priority applies when a queue holds multiple task kinds. +第5节将迈出下一步:我们有意识地利用合并行为进行批处理,引入 `timeout_task` 变体用于计划任务,并讨论当队列持有多种任务类型时优先级如何适用。 ## 第5节:工作的优先级与合并 -Every task your driver owns enters a queue. The queue has a policy for deciding the order in which tasks run and what happens when the same task is enqueued twice. Section 5 makes that policy explicit, then shows how to use the coalescing contract deliberately to batch work, and finally introduces `timeout_task` as the taskqueue-side analogue of the callout. +你驱动的每个任务都进入一个队列。队列有一个决定任务运行顺序和同一任务入队两次时发生什么的策略。第5节使该策略显式化,然后展示如何有意利用合并契约进行批处理,最后引入 `timeout_task` 作为任务队列侧的 callout 对应物。 -This section is dense in ideas but short in code. The two driver changes for Stage 3 are a new task on the same taskqueue and a timeout task that drives a periodic batched write. The value is in the rules you internalise. +本节思想密集但代码短小。第3阶段的两个驱动更改是同一任务队列上的一个新任务和一个驱动周期性批量写入的超时任务。价值在于你内化的规则。 ### 优先级排序规则 -The `ta_priority` field in `struct task` orders tasks inside a single queue. Higher priority tasks run before lower priority tasks. A task with priority 5 that is enqueued after a task with priority 0 runs before the priority-0 task, even if the priority-0 task was enqueued first. +`struct task` 中的 `ta_priority` 字段在单个队列内排序任务。更高优先级的任务在更低优先级的任务之前运行。优先级为 5 的任务在优先级为 0 的任务之后入队但在优先级为 0 的任务之前运行,即使优先级为 0 的任务先入队。 -Priority is a small unsigned integer (`uint8_t`, so range 0-255). Most drivers use priority 0 for everything, in which case the queue is effectively FIFO. A driver with genuinely different urgencies for different tasks can assign different priorities and let the taskqueue reorder. +优先级是一个小无符号整数(`uint8_t`,范围 0-255)。大多数驱动所有任务使用优先级 0,此时队列实际上是 FIFO。有真正不同紧急程度任务的驱动可以分配不同优先级让任务队列重排序。 -A quick example. Suppose a driver has two tasks: a `reset_task` that recovers from a hardware error, and a `stats_task` that rolls up accumulated statistics. If both are enqueued in a short window, the reset should run first. Giving `reset_task` priority 10 and `stats_task` priority 0 achieves that. The reset task runs first even if it was enqueued last. +一个快速示例。假设驱动有两个任务:从硬件错误恢复的 `reset_task` 和汇总累积统计的 `stats_task`。如果两者在短窗口内被入队,重置应先运行。给 `reset_task` 优先级 10 和 `stats_task` 优先级 0 即可实现。重置任务即使最后入队也先运行。 -Use priorities sparingly. A driver with ten different task kinds and ten different priorities is harder to reason about than a driver with ten task kinds that all run in enqueue order. Priorities exist for real differentiation, not for aesthetic ordering. +谨慎使用优先级。有十种不同任务和十个不同优先级的驱动比有十种任务都以入队顺序运行的驱动更难推理。优先级用于真正的差异化,不是为了美观排序。 ### 重述合并规则 -From Section 2, and worth saying again: if a task is enqueued while it is already pending, the kernel increments `ta_pending` and does not link the task a second time. The callback runs once, with the pending count in the second argument. +从第2节回顾,值得再说一次:如果任务在已经待处理时被入队,内核递增 `ta_pending` 并且不会第二次链接任务。回调运行一次,第二个参数中有待处理计数。 -The precise code, from `/usr/src/sys/kern/subr_taskqueue.c`: +精确代码,来自 `/usr/src/sys/kern/subr_taskqueue.c`: ```c if (task->ta_pending) { @@ -1330,30 +1330,30 @@ if (task->ta_pending) { } ``` -The counter saturates at `USHRT_MAX` (65535), which is a hard cap on how high the coalescing count can go. Past that, repeated enqueues are lost from the counter's perspective, though they still return success. In practice nobody hits that cap, because a task that backs up 65535 times has deeper problems. +计数器在 `USHRT_MAX`(65535)处饱和,这是合计计数可以达到的硬上限。超过它后,重复入队从计数器的角度看会丢失,尽管它们仍然返回成功。实际上没人会触及那个上限,因为积压 65535 次的任务有更深层次的问题。 -The coalescing rule has three consequences you design around. +合并规则有三个你在设计中需要考虑的后果。 -First, **a task handles at most "one run per scheduler wakeup"**. If your work model needs "one callback per event", a single task is wrong. You need per-event state. +第一,**一个任务最多处理"每次调度器唤醒一次运行"**。如果你的工作模型需要"每个事件一次回调",单个任务是错误的。你需要每事件状态。 -Second, **the callback must be able to handle multiple events in one firing**. Writing the callback as if `pending` is always 1 is a bug that only shows up under load. Use the pending argument deliberately, or structure the callback so it processes whatever is in a driver-owned queue until the queue is empty. +第二,**回调必须能够在一次触发中处理多个事件**。将回调写成 `pending` 总是 1 是一个只在负载下才显现的 bug。有意使用 pending 参数,或者构建回调使其处理驱动拥有队列中的内容直到队列为空。 -Third, **you can exploit coalescing for batching**. If a producer enqueues a task once per event and the consumer drains a batch per firing, the system naturally converges on the rate the consumer can sustain. Under light load the coalescing never triggers (one event, one firing). Under heavy load the coalescing folds bursts into single firings with larger batches. The behaviour is self-tuning. +第三,**你可以利用合并进行批处理**。如果生产者每次事件入队任务一次,消费者每次触发排空一批,系统自然收敛到消费者能维持的速率。在轻负载下合并从不触发(一个事件,一次触发)。在重负载下合并将突发折叠为带有更大批次的单次触发。行为是自调节的。 -### A Deliberate Batching Pattern: Stage 3 +### 一个有意的批处理模式:第3阶段 -Stage 3 adds a second task to the driver: a `bulk_writer_task` that writes a fixed number of tick bytes to the buffer in a single firing, driven by a callout that enqueues the task periodically. The pattern is contrived (the real driver would just use a faster tick source), but it is the simplest demonstration of deliberate batching. +第3阶段向驱动添加第二个任务:一个 `bulk_writer_task`,在单次触发中写入固定数量的 tick 字节到缓冲区,由定期入队任务的 callout 驱动。这种模式是人为的(真正的驱动只会用更快的 tick 源),但它是有意批处理的最简单演示。 -The softc addition: +softc 添加: ```c struct task bulk_writer_task; int bulk_writer_batch; /* bytes per firing */ ``` -The default `bulk_writer_batch` is zero (disabled). A sysctl exposes it for tuning. +默认 `bulk_writer_batch` 为零(禁用)。一个 sysctl 暴露它以便调优。 -The callback: +回调: ```c static void @@ -1386,17 +1386,17 @@ myfirst_bulk_writer_task(void *arg, int pending) } ``` -A few remarks. +几点说明。 -The callback acquires `sc->mtx`, reads the batch size, releases. Acquiring and releasing twice is fine; the work in between (memset) does not need the lock. The second acquisition wraps the actual cbuf operation and the counter update. The selwakeup happens with no lock held, as always. +回调获取 `sc->mtx`,读取批次大小,释放。获取和释放两次没问题;中间的工作(memset)不需要锁。第二次获取包装实际的 cbuf 操作和计数器更新。selwakeup 在没有锁持有的情况下发生,一如既往。 -The `pending` argument is unused in this simple callback. For a different batching design, `pending` would tell the callback how many times the task was enqueued and therefore how much work accumulated. Here the batching policy is "always write exactly `bulk_writer_batch` bytes per firing, no matter how many times enqueued", so `pending` does not come into it. +`pending` 参数在此简单回调中未使用。对于不同的批处理设计,`pending` 会告诉回调任务被入队了多少次因此累积了多少工作。这里的批处理策略是"每次触发总是精确写入 `bulk_writer_batch` 字节,不管入队多少次",所以 `pending` 不参与。 -The callback does not check `is_attached`. It does not need to. The detach drains the task before freeing anything the task touches, and `sc->mtx` protects `sc->cb` until the drain completes. +回调不检查 `is_attached`。它不需要。分离在释放任务触碰的任何东西之前排空任务,`sc->mtx` 保护 `sc->cb` 直到排空完成。 -### The Coalescing in Action +### 实际合并的效果 -To demonstrate coalescing deliberately, Stage 3 adds a sysctl `bulk_writer_flood` whose writer attempts to enqueue `bulk_writer_task` a thousand times in a tight loop: +为了有意演示合并,第3阶段添加一个 sysctl `bulk_writer_flood`,其写入者尝试在紧密循环中入队 `bulk_writer_task` 一千次: ```c static int @@ -1418,20 +1418,20 @@ myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) } ``` -Run it: +运行它: ```text # sysctl dev.myfirst.0.bulk_writer_batch=32 # sysctl dev.myfirst.0.bulk_writer_flood=1000 ``` -Immediately after, observe the byte count. Without coalescing, a thousand enqueues at 32 bytes each would produce 32000 bytes. With coalescing, the actual number is one firing of 32 bytes, because the thousand enqueues collapsed into a single pending task. The driver's `bytes_written` counter should increase by 32, not 32000. +紧接着观察字节计数。没有合并的话,一千次入队每次 32 字节会产生 32000 字节。有了合并,实际数字是一次 32 字节的触发,因为一千次入队折叠为一个待处理任务。驱动的 `bytes_written` 计数器应增加 32,不是 32000。 -This is the coalescing contract working as designed. The producer asked for a thousand task runs; the taskqueue delivered one. The callback's single firing reflected all thousand requests but did the fixed amount of work the batching policy specified. +这就是合并契约按设计工作的效果。生产者请求一千次任务运行;任务队列只交付了一次。回调的单次触发反映了所有一千个请求,但执行了批处理策略指定的固定工作量。 -### Using `pending` for Adaptive Batching +### 使用 `pending` 进行自适应批处理 -A more sophisticated pattern uses the `pending` argument to adapt batch size to queue depth. Suppose a driver wants to write `pending` bytes per firing: one byte per enqueue, folded into coalesced runs. The callback becomes: +一个更复杂的模式使用 `pending` 参数来适应批处理大小到队列深度。假设驱动想要每次触发写入 `pending` 字节:每次入队一个字节,折叠为合并运行。回调变为: ```c static void @@ -1454,30 +1454,30 @@ myfirst_adaptive_task(void *arg, int pending) } ``` -The callback writes `pending` bytes (up to the buffer size). At low load, `pending` is 1 and the callback writes one byte. At high load, `pending` is the queue depth at the moment the callback started, and the callback writes that many bytes in a single pass. The batching naturally scales with load. +回调写入 `pending` 字节(上限缓冲区大小)。在低负载时,`pending` 为 1,回调写入一个字节。在高负载时,`pending` 是回调开始时刻的队列深度,回调在一次遍历中写入那么多字节。批处理随负载自然缩放。 -This design is useful when each enqueue corresponds to a real event that wants one unit of work, and the batching is a performance optimisation rather than a semantic change. A network driver's "transmit completion" handler is a classic example: each transmitted packet generates an interrupt that enqueues a task; the task's job is to reclaim completed descriptors; at high packet rates, many interrupts fold into a single task firing that reclaims many descriptors at once. +这种设计在每次入队对应一个想要一个工作单元的真实事件、且批处理是性能优化而非语义变更时有用。网络驱动的"发送完成"处理程序是经典例子:每个发送的包产生一个入队任务的中断;任务的工作是回收已完成的描述符;在高包速率下,多个中断折叠为单次任务触发,一次回收多个描述符。 -We will not add the adaptive-batching task to `myfirst` in Stage 3, because the fixed-batch version already demonstrates coalescing. The adaptive pattern is worth keeping in mind for real driver work; the real FreeBSD drivers you will read use it often. +我们不会在第3阶段的 `myfirst` 中添加自适应批处理任务,因为固定批次版本已经演示了合并。自适应模式值得在实际驱动工作中记住;你将读到的真实 FreeBSD 驱动经常使用它。 -### The Enqueue Flags +### 入队标志 -`taskqueue_enqueue_flags` extends `taskqueue_enqueue` with two flag bits: +`taskqueue_enqueue_flags` 用两个标志位扩展 `taskqueue_enqueue`: -- `TASKQUEUE_FAIL_IF_PENDING`: if the task is already pending, return `EEXIST` instead of coalescing. -- `TASKQUEUE_FAIL_IF_CANCELING`: if the task is currently being cancelled, return `EAGAIN` instead of waiting. +- `TASKQUEUE_FAIL_IF_PENDING`:如果任务已经待处理,返回 `EEXIST` 而不是合并。 +- `TASKQUEUE_FAIL_IF_CANCELING`:如果任务当前正在被取消,返回 `EAGAIN` 而不是等待。 -`TASKQUEUE_FAIL_IF_PENDING` is useful when you want to know whether the enqueue actually produced a new pending state, for accounting or debugging. A driver that counts "how many times was this task enqueued" can use the flag, get `EEXIST` on the redundant calls, and count only the non-redundant enqueues. +`TASKQUEUE_FAIL_IF_PENDING` 在你想知道入队是否实际产生了新的待处理状态时有用,用于记账或调试。计算"此任务被入队了多少次"的驱动可以使用该标志,在冗余调用上得到 `EEXIST`,只计算非冗余入队。 -`TASKQUEUE_FAIL_IF_CANCELING` is useful during shutdown. If you are tearing the driver down and some code path would enqueue a task, you can pass the flag and check for `EAGAIN` to avoid re-adding a task that is in the middle of being cancelled. Most drivers do not need this in practice; the `is_attached` check usually handles the equivalent condition. +`TASKQUEUE_FAIL_IF_CANCELING` 在关闭期间有用。如果你正在拆除驱动且某个代码路径会入队任务,你可以传递该标志并检查 `EAGAIN` 以避免重新添加正在取消过程中的任务。大多数驱动在实践中不需要这个;`is_attached` 检查通常处理等效条件。 -Neither flag is used in `myfirst`. Both exist, and a driver with specific needs can reach for them. For ordinary work, the plain `taskqueue_enqueue` is correct. +`myfirst` 中没有使用任何一个标志。两者都存在,有特定需求的驱动可以使用它们。对于普通工作,普通的 `taskqueue_enqueue` 是正确的。 -### The `timeout_task` Variant +### `timeout_task` 变体 -Sometimes you want a task to fire after a specific delay. The callout would be the natural primitive for that, but if the work the delayed callback wants to do requires thread context, you need the task's context, not the callout's. The kernel offers `struct timeout_task` for exactly this case. +有时你想要一个任务在特定延迟后触发。callout 是自然的首选原语,但如果延迟回调想要做的工作需要线程上下文,你需要任务的上下文而不是 callout 的。内核为这种情况提供了 `struct timeout_task`。 -`timeout_task` is defined in `/usr/src/sys/sys/_task.h`: +`timeout_task` 定义在 `/usr/src/sys/sys/_task.h`: ```c struct timeout_task { @@ -1488,48 +1488,48 @@ struct timeout_task { }; ``` -The structure wraps a `struct task`, a `struct callout`, and an internal flag. When you schedule a timeout task with `taskqueue_enqueue_timeout`, the kernel starts the callout; when the callout fires, its callback enqueues the underlying task on the taskqueue. The task then runs in thread context, with all the usual guarantees. +该结构包装了一个 `struct task`、一个 `struct callout` 和一个内部标志。当你用 `taskqueue_enqueue_timeout` 调度超时任务时,内核启动 callout;当 callout 触发时,其回调将底层任务入队到任务队列。任务随后在线程上下文中运行,拥有所有常规保证。 -The initialisation uses `TIMEOUT_TASK_INIT`: +初始化使用 `TIMEOUT_TASK_INIT`: ```c TIMEOUT_TASK_INIT(queue, timeout_task, priority, func, context); ``` -The macro expands to a function call `_timeout_task_init` that initialises both the task and the callout with appropriate linkage. You must pass the taskqueue at init time because the callout is set up to enqueue on that specific queue. +该宏展开为函数调用 `_timeout_task_init`,它用适当的链接初始化任务和 callout。你必须在初始化时传递任务队列,因为 callout 被设置为在特定的队列上入队。 -Scheduling uses `taskqueue_enqueue_timeout(tq, &tt, ticks)`: +调度使用 `taskqueue_enqueue_timeout(tq, &tt, ticks)`: ```c int taskqueue_enqueue_timeout(struct taskqueue *queue, struct timeout_task *timeout_task, int ticks); ``` -The `ticks` argument is the same convention as `callout_reset`: `hz` ticks equals one second. +`ticks` 参数与 `callout_reset` 使用相同约定:`hz` tick 等于一秒。 -Draining uses `taskqueue_drain_timeout(tq, &tt)`, which waits for the callout to expire (or cancels it if still pending) and then waits for the underlying task to complete. The drain is a single call, but it handles both the callout and the task phases. +排空使用 `taskqueue_drain_timeout(tq, &tt)`,它等待 callout 到期(或如果仍待处理则取消它),然后等待底层任务完成。排空是一次调用,但它处理 callout 和任务两个阶段。 -Cancelling uses `taskqueue_cancel_timeout(tq, &tt, &pendp)`: +取消使用 `taskqueue_cancel_timeout(tq, &tt, &pendp)`: ```c int taskqueue_cancel_timeout(struct taskqueue *queue, struct timeout_task *timeout_task, u_int *pendp); ``` -Returns zero if the timeout was cancelled cleanly, or `EBUSY` if the task is currently running. In the `EBUSY` case you typically follow up with `taskqueue_drain_timeout`. +如果超时被干净取消则返回零,如果任务当前正在运行则返回 `EBUSY`。在 `EBUSY` 情况下,你通常需要跟进 `taskqueue_drain_timeout`。 -### A Stage 3 Timeout Task: Delayed Reset +### 第3阶段的超时任务:延迟重置 -Stage 3 adds a timeout task to the driver: a delayed reset that fires `reset_delay_ms` milliseconds after the reset sysctl is written. The existing reset sysctl runs synchronously; the delayed variant schedules the reset for later. Useful for testing and for situations where the reset should not happen until after the current IO drains. +第3阶段向驱动添加一个超时任务:一个延迟重置,在重置 sysctl 被写入 `reset_delay_ms` 毫秒后触发。现有重置 sysctl 同步运行;延迟变体将重置调度到稍后。对测试和重置不应该在当前 IO 排空之前发生的情况有用。 -The softc addition: +softc 添加: ```c struct timeout_task reset_delayed_task; int reset_delay_ms; ``` -The initialisation in attach: +attach 中的初始化: ```c TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, @@ -1537,9 +1537,9 @@ TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, sc->reset_delay_ms = 0; ``` -`TIMEOUT_TASK_INIT` takes the taskqueue as its first argument because the callout inside the timeout_task needs to know which queue to enqueue onto when it fires. +`TIMEOUT_TASK_INIT` 以任务队列作为第一个参数,因为 timeout_task 内部的 callout 需要知道触发时在哪个队列上入队。 -The callback: +回调: ```c static void @@ -1563,9 +1563,9 @@ myfirst_reset_delayed_task(void *arg, int pending) } ``` -Same logic as the synchronous reset from Chapter 13, but in task context. It can acquire the sleepable `cfg_sx` without the complications a callout would face. The `pending` count is logged for diagnostic purposes. +与第13章的同步重置逻辑相同,但在任务上下文中。它可以获取可睡眠的 `cfg_sx` 而没有 callout 会面临的复杂性。`pending` 计数用于诊断目的被记录。 -The sysctl handler that arms the delayed reset: +武装延迟重置的 sysctl 处理程序: ```c static int @@ -1593,31 +1593,31 @@ myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) } ``` -A zero writes cancel the pending delayed reset. Any positive value schedules the task to fire after the given number of milliseconds. The tick conversion `(ms * hz + 999) / 1000` is the same ceiling conversion we use for callouts. +写入零取消待处理的延迟重置。任何正值调度任务在给定毫秒数后触发。tick 转换 `(ms * hz + 999) / 1000` 与我们用于 callout 的相同向上取整转换。 -The detach path drains the timeout task: +分离路径排空超时任务: ```c taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); ``` -Placement of the drain is the same as the plain task drain: after the callouts are drained, after `is_attached` is clear, before `seldrain` and before `taskqueue_free`. +排空的位置与普通任务排空相同:在 callout 排空之后,`is_attached` 清除之后,`seldrain` 之前和 `taskqueue_free` 之前。 -### Observing the Delayed Reset +### 观察延迟重置 -With Stage 3 loaded, arm the delayed reset for three seconds in the future: +加载第3阶段后,将延迟重置武装为未来三秒: ```text # sysctl dev.myfirst.0.reset_delayed=3000 ``` -Three seconds later `dmesg` shows: +三秒后 `dmesg` 显示: ```text myfirst0: delayed reset fired (pending=1) ``` -The `pending=1` confirms that the timeout task fired once. Now arm it multiple times in rapid succession: +`pending=1` 确认超时任务触发了一次。现在快速连续地武装它多次: ```text # sysctl dev.myfirst.0.reset_delayed=1000 @@ -1625,19 +1625,19 @@ The `pending=1` confirms that the timeout task fired once. Now arm it multiple t # sysctl dev.myfirst.0.reset_delayed=1000 ``` -One second later, only one reset fires. `dmesg` shows: +一秒后,只有一个重置触发。`dmesg` 显示: ```text myfirst0: delayed reset fired (pending=1) ``` -Why only one firing? Because `taskqueue_enqueue_timeout` behaves consistently with `callout_reset`: arming a pending timeout task replaces the previous deadline. The three successive arms produce one scheduled firing. The same behaviour would apply if we used `callout_reset` on a plain callout. +为什么只有一次触发?因为 `taskqueue_enqueue_timeout` 的行为与 `callout_reset` 一致:武装一个待处理的超时任务替换之前的截止时间。三次连续武装产生一次调度触发。如果我们使用 `callout_reset` 对普通 callout 做同样的事情,行为相同。 -### When to Use `timeout_task` vs. Callout Plus Task +### 何时使用 `timeout_task` 与 callout 加任务 -A timeout task is the right primitive when you want a delayed action in thread context and the delay is the primary parameter. A plain callout with a task enqueue is the right primitive when you want a delayed action and the delay is an implementation detail: for example, when the delay is recomputed dynamically each time. Both work. +当你想要线程上下文中的延迟操作且延迟是主要参数时,超时任务是正确的原语。当你想要延迟操作且延迟是实现细节时(例如,延迟每次动态重新计算),普通 callout 加任务入队是正确的原语。两者都可以工作。 -The two patterns have slightly different shapes in the source: +两种模式在源码中有稍微不同的形态: ```c /* timeout_task pattern */ @@ -1660,58 +1660,58 @@ callout_drain(&co); taskqueue_drain(tq, &t); ``` -The timeout_task version is shorter because the kernel has bundled the pattern for you. The callout+task version is more flexible because the callout callback can decide dynamically whether to enqueue the task (for example, based on state conditions that do not exist at schedule time). +timeout_task 版本更短因为内核已经为你打包了模式。callout+任务版本更灵活因为 callout 回调可以动态决定是否入队任务(例如,基于调度时不存在的状态条件)。 -For `myfirst`'s delayed reset, the timeout_task is the right choice because the decision to fire is taken at schedule time (the sysctl writer requested it) and nothing in between changes that decision. +对于 `myfirst` 的延迟重置,timeout_task 是正确选择,因为触发决策在调度时做出(sysctl 写入者请求了它)且中间没有任何东西改变那个决策。 -### Priority Ordering Across Task Kinds +### 跨任务种类的优先级排序 -A driver with multiple tasks on the same taskqueue can use priorities to order them. For `myfirst` we do not need this; all tasks are equal-priority. But the pattern is worth understanding for when you do. +在同一任务队列上有多个任务的驱动可以使用优先级来排序它们。对于 `myfirst` 我们不需要这个;所有任务优先级相同。但当需要时这个模式值得理解。 -Suppose we had a `high_priority_reset_task` that must run ahead of any other pending tasks. We would initialise it with a priority greater than zero: +假设我们有一个必须排在其他待处理任务之前的 `high_priority_reset_task`。我们会用大于零的优先级初始化它: ```c TASK_INIT(&sc->high_priority_reset_task, 10, myfirst_high_priority_reset_task, sc); ``` -And enqueue it normally: +并正常入队: ```c taskqueue_enqueue(sc->tq, &sc->high_priority_reset_task); ``` -If the queue has several tasks pending, including the new one and several priority-0 tasks, the new one runs first because of its higher priority. Priority is a property of the task (set at init), not of the enqueue (set at each call); if a task should sometimes be urgent and sometimes not, you need two task structures with two priorities, not one task you retune. +如果队列有几个待处理任务,包括新的和几个优先级为 0 的任务,新的会因其更高优先级而先运行。优先级是任务的属性(在初始化时设置),不是入队的属性(在每次调用时设置);如果一个任务有时紧急有时不紧急,你需要两个不同优先级的两个任务结构,而不是一个你重新调整的任务。 -### A Note on Fairness +### 关于公平性的说明 -A taskqueue with a single worker thread runs tasks strictly in priority order, with ties broken by enqueue order. A taskqueue with multiple worker threads can run several tasks in parallel; priority still orders the list, but the parallel workers may dispatch tasks out of strict order at the margin. For most drivers this does not matter. +有单个工作线程的任务队列严格按优先级顺序运行任务,平局按入队顺序打破。有多个工作线程的任务队列可以并行运行多个任务;优先级仍然排序列表,但并行工作线程在边际可能不按严格顺序分派任务。对大多数驱动这不重要。 -If strict fairness or strict priority ordering is required, a single worker is the right choice. If throughput at the cost of occasional reordering is acceptable, multiple workers are fine. `myfirst` uses a single worker. +如果需要严格公平性或严格优先级排序,单个工作线程是正确选择。如果以偶尔乱序为代价的吞吐量可接受,多个工作线程没问题。`myfirst` 使用单个工作线程。 ### 第5节总结 -Stage 3 added a deliberate batching task and a timeout task. The batching task demonstrates coalescing by collapsing a thousand enqueues into a single firing; the timeout task demonstrates delayed execution in thread context. Both share the private taskqueue from Stage 2, both are drained at detach in the established order, and both obey the locking discipline the rest of the driver uses. +第3阶段添加了一个有意的批处理任务和一个超时任务。批处理任务通过将一千次入队折叠为单次触发来演示合并;超时任务演示了线程上下文中的延迟执行。两者共享第2阶段的私有任务队列,两者在分离时以既定顺序排空,两者都遵守驱动其余部分使用的锁定纪律。 -The priority and coalescing rules are now explicit. A task's priority orders it inside the queue; a task's `ta_pending` counter folds redundant enqueues into a single firing whose `pending` argument carries the tally. +优先级和合并规则现在已显式化。任务的优先级在队列内对其排序;任务的 `ta_pending` 计数器将冗余入队折叠为单次触发,其 `pending` 参数携带总计。 -Section 6 steps back from the `myfirst` refactor to survey the patterns that show up in real FreeBSD drivers. The mental models accumulate; the driver does not change again until Section 8. +第6节从 `myfirst` 重构中退后,审视在真实 FreeBSD 驱动中出现的模式。心智模型在积累;驱动直到第8节才再次更改。 ## 第6节:使用任务队列的实际模式 -Up to now Chapter 14 has developed a single driver through three stages. Real FreeBSD drivers use taskqueues in a handful of recurring shapes. This section catalogs the patterns, shows where each one appears in `/usr/src/sys/dev/`, and explains when to reach for which. Recognising the patterns turns reading driver source from a puzzle into a vocabulary exercise. +到目前为止,第14章通过三个阶段开发了一个单一驱动。真实的 FreeBSD 驱动以少数几种重复形态使用任务队列。本节编目这些模式,展示每种模式在 `/usr/src/sys/dev/` 中出现的位置,并解释何时使用哪种。识别这些模式将阅读驱动源码从猜谜变成词汇练习。 -Each pattern is presented as a short recipe: the problem, the taskqueue shape that solves it, a code sketch, and a real-driver reference you can read for the production version. +每种模式以一个小方案呈现:问题、解决它的任务队列形态、代码草图,以及你可以阅读生产版本的真实驱动参考。 -### Pattern 1: Deferred Logging or Notification From an Edge Context +### 模式1:从边缘上下文延迟日志或通知 -**Problem.** An edge-context callback (callout, interrupt filter, epoch section) detects a condition that should produce a log message or a notification to user-space. The logging call is too heavy for the edge context: `selwakeup`, `log(9)`, `kqueue_user_event`, or a multi-line `printf` that holds a lock the edge context cannot afford. +**问题。** 一个边缘上下文回调(callout、中断过滤器、epoch 段)检测到一个应该产生日志消息或通知用户空间的情况。日志调用对边缘上下文太重:`selwakeup`、`log(9)`、`kqueue_user_event`,或一个持有边缘上下文不能承受的锁的多行 `printf`。 -**Solution.** One `struct task` per condition, initialised in attach with a callback that performs the heavy call in thread context. The edge-context callback records the condition in softc state (a flag, a counter, a small piece of data), enqueues the task, and returns. The task runs in thread context, reads the condition from softc state, performs the call, clears the condition. +**解决方案。** 每种情况一个 `struct task`,在 attach 中初始化,回调在线程上下文中执行重调用。边缘上下文回调在 softc 状态中记录情况(一个标志、一个计数器、一小块数据),入队任务,然后返回。任务在线程上下文中运行,从 softc 状态读取情况,执行调用,清除情况。 -**Code sketch.** +**代码草图。** ```c struct my_softc { @@ -1750,27 +1750,27 @@ if (some_condition) { } ``` -The flags field lets the edge context accumulate multiple distinct conditions before the task runs. When the task fires, it snapshots the flags, clears them, and emits one log line per condition. Coalescing folds repeated-same-condition enqueues into one callback invocation, which is what you want for log-spam prevention. +标志字段让边缘上下文在任务运行前累积多个不同情况。当任务触发时,它快照标志,清除它们,并按情况发出一行日志。合并将重复相同情况的入队折叠为一次回调调用,这正是你想要的日志垃圾防护。 -**Real example.** `/usr/src/sys/dev/ale/if_ale.c` uses an interrupt task (`sc->ale_int_task`) to handle deferred work from the filter interrupt, including conditions that want to log or notify. +**真实示例。** `/usr/src/sys/dev/ale/if_ale.c` 使用中断任务(`sc->ale_int_task`)处理过滤器中断的延迟工作,包括想要记录或通知的情况。 -### Pattern 2: Delayed Reset or Reconfiguration +### 模式2:延迟重置或重新配置 -**Problem.** The driver detects a condition that calls for a hardware reset or a configuration change, but the reset should not happen immediately. Reasons for the delay include "give in-flight IO a chance to complete", "batch multiple causes into one reset", or "throttle resets to avoid a reset storm". +**问题。** 驱动检测到需要硬件重置或配置更改的情况,但重置不应该立即发生。延迟的原因包括"给进行中的 IO 一个完成的机会"、"将多个原因合并为一次重置"或"限制重置以避免重置风暴"。 -**Solution.** A `struct timeout_task` (or a `struct callout` paired with a `struct task`). The detector enqueues the timeout task with the chosen delay. If the condition clears before the delay elapses, the detector cancels the timeout task. If the condition persists, the task fires in thread context and performs the reset. +**解决方案。** 一个 `struct timeout_task`(或一个 `struct callout` 配对一个 `struct task`)。检测器以选定的延迟入队超时任务。如果情况在延迟到期前清除,检测器取消超时任务。如果情况持续,任务在线程上下文中触发并执行重置。 -**Code sketch.** Same shape as the `myfirst` Stage 3 delayed-reset task. The only variation is that the detector typically cancels the pending task whenever the "need to reset" state changes, so the reset happens only when the condition has persisted for the full delay. +**代码草图。** 与 `myfirst` 第3阶段延迟重置任务形态相同。唯一的变体是检测器通常在"需要重置"状态改变时取消待处理任务,因此重置只在情况持续了完整延迟后才发生。 -**Real example.** Many storage and network drivers use this pattern for recovery. The `/usr/src/sys/dev/bge/if_bge.c` Broadcom driver uses timeout tasks for link-state re-evaluation after a physical-layer event. +**真实示例。** 许多存储和网络驱动使用此模式进行恢复。`/usr/src/sys/dev/bge/if_bge.c` Broadcom 驱动在物理层事件后使用超时任务进行链路状态重新评估。 -### Pattern 3: Post-Interrupt Processing (the Filter + Task Split) +### 模式3:中断后处理(过滤器加任务分割) -**Problem.** A hardware interrupt arrives. The interrupt filter's job is to decide "is this our interrupt and did the hardware really need attention". The filter must run quickly and must not sleep. The actual processing (read registers, service completion queues, possibly `copyout` results to user-space) does not belong in the filter. +**问题。** 硬件中断到达。中断过滤器的工作是判断"这是我们的中断吗,硬件真的需要关注吗"。过滤器必须快速运行且不能睡眠。实际处理(读寄存器、服务完成队列、可能 `copyout` 结果到用户空间)不属于过滤器。 -**Solution.** A two-level split. The filter handler runs synchronously, reads a status register, decides whether the interrupt belongs to us, and if so enqueues a task. The task runs in thread context and performs the real work. This is the standard filter-plus-ithread split that `bus_setup_intr(9)` supports natively, but the taskqueue variant is useful when the driver wants more control over the deferred context than ithread provides. +**解决方案。** 两级分割。过滤器处理程序同步运行,读取状态寄存器,判断中断是否属于我们,如果是则入队一个任务。任务在线程上下文中运行并执行真正的工作。这是 `bus_setup_intr(9)` 原生支持的标准过滤器加 ithread 分割,但任务队列变体在驱动想要对延迟上下文有更多控制时有用。 -**Code sketch.** +**代码草图。** ```c static int @@ -1804,17 +1804,17 @@ my_intr_task(void *arg, int pending) } ``` -Several subtleties. The filter masks the interrupt at the hardware level before enqueuing the task, so the hardware does not keep firing while the task is pending. The task runs in thread context, processes completions, and re-enables interrupts at the end. Coalescing folds multiple interrupts into a single task firing; the masking prevents the hardware from firing unboundedly. Part 4 will walk through real interrupt setup; the pattern shown here is the shape the chapter prepares you for. +几个微妙之处。过滤器在入队任务之前在硬件层面屏蔽中断,因此硬件在任务待处理时不会持续触发。任务在线程上下文中运行,处理完成,并在最后重新启用中断。合并将多个中断折叠为单次任务触发;屏蔽防止硬件无限制触发。第四部分将逐步讲解真实中断设置;这里展示的模式是该章为你准备的形态。 -**Real example.** `/usr/src/sys/dev/ale/if_ale.c`, `/usr/src/sys/dev/age/if_age.c`, and most Ethernet drivers use this pattern or a close variant. +**真实示例。** `/usr/src/sys/dev/ale/if_ale.c`、`/usr/src/sys/dev/age/if_age.c` 和大多数以太网驱动使用此模式或其接近变体。 -### Pattern 4: Async `copyin`/`copyout` After Hardware Completion +### 模式4:硬件完成后的异步 `copyin`/`copyout` -**Problem.** The driver has a queued user-space request that supplied addresses for input or output data. Hardware completion arrives as an interrupt. The driver must copy the data between user-space and kernel buffers to finalise the request. `copyin` and `copyout` sleep on their slow path, so they cannot run in interrupt context. +**问题。** 驱动有一个排队的用户空间请求,提供了输入或输出数据的地址。硬件完成以中断到达。驱动必须在用户空间和内核缓冲区之间复制数据来完成请求。`copyin` 和 `copyout` 在慢路径上睡眠,所以它们不能在中断上下文中运行。 -**Solution.** The interrupt path records the request identifier and enqueues a task. The task runs in thread context, identifies the user-space addresses from the stored request state, performs the `copyin` or `copyout`, and wakes the waiting user thread. +**解决方案。** 中断路径记录请求标识符并入队一个任务。任务在线程上下文中运行,从存储的请求状态中识别用户空间地址,执行 `copyin` 或 `copyout`,并唤醒等待的用户线程。 -**Code sketch.** +**代码草图。** ```c struct my_request { @@ -1845,17 +1845,17 @@ my_finish_task(void *arg, int pending) taskqueue_enqueue(sc->tq, &req->finish_task); ``` -The user-space thread waits on `req->cv` after submitting the request; it wakes when the task marks `done` and broadcasts. +用户空间线程在提交请求后等待 `req->cv`;当任务标记 `done` 并广播时它醒来。 -**Real example.** Character-device drivers that implement ioctls with large data transfers sometimes use this pattern. USB bulk-transfer completion in `/usr/src/sys/dev/usb/` frequently defers the user-space data copy via tasks. +**真实示例。** 实现带有大数据传输 ioctl 的字符设备驱动有时使用此模式。`/usr/src/sys/dev/usb/` 中的 USB 批量传输完成频繁通过任务延迟用户空间数据复制。 -### Pattern 5: Retry-With-Backoff After Transient Failure +### 模式5:瞬态失败后的退避重试 -**Problem.** A hardware operation failed, but the failure is known to be transient. The driver wants to retry after a backoff interval, with increasing backoff on repeated failures. +**问题。** 硬件操作失败,但失败已知是瞬态的。驱动想在退避间隔后重试,重复失败时增加退避。 -**Solution.** A `struct timeout_task` that is rearmed with increasing delay on each failure. The task callback performs the retry; on success the driver clears the backoff; on failure the task re-enqueues with a larger delay. +**解决方案。** 一个 `struct timeout_task`,在每次失败时用增加的延迟重新武装。任务回调执行重试;成功时驱动清除退避;失败时任务用更大的延迟重新入队。 -**Code sketch.** +**代码草图。** ```c struct my_softc { @@ -1891,19 +1891,19 @@ my_retry_task(void *arg, int pending) } ``` -The initial interval is 10 ms, doubling on each failure, capped at 5 seconds, with a maximum attempt count. The retry keeps firing until success or giveup. A separate code path can cancel the retry (with `taskqueue_cancel_timeout`) if the conditions that motivated it change. +初始间隔为 10 毫秒,每次失败翻倍,上限 5 秒,有最大尝试次数。重试持续触发直到成功或放弃。单独的代码路径可以在激励它的条件改变时取消重试(用 `taskqueue_cancel_timeout`)。 -**Real example.** `/usr/src/sys/dev/iwm/if_iwm.c` and other wireless drivers use timeout tasks for firmware-load retries and link recalibration. +**真实示例。** `/usr/src/sys/dev/iwm/if_iwm.c` 和其他无线驱动使用超时任务进行固件加载重试和链路重新校准。 -### Pattern 6: Deferred Teardown +### 模式6:延迟拆除 -**Problem.** An object inside the driver must be freed, but some other code path may still hold a reference. Freeing immediately would be a use-after-free. The driver needs to free later, after the references are known to be gone. +**问题。** 驱动内部的一个对象必须被释放,但其他代码路径可能仍然持有引用。立即释放会是释放后使用。驱动需要稍后释放,在引用已知消失后。 -**Solution.** A `struct task` whose callback frees the object. The code path that wants to free the object enqueues the task; the task runs in thread context, after any outstanding references have had a chance to complete. +**解决方案。** 一个 `struct task`,其回调释放对象。想要释放对象的代码路径入队该任务;任务在线程上下文中运行,在任何未完成引用都有机会完成后。 -In more elaborate forms, the pattern uses reference counting: the task decrements a reference count and frees the object only when the count reaches zero. In simpler forms, the taskqueue's FIFO ordering is enough: all earlier-enqueued tasks complete before the teardown task runs, so if references are always taken inside tasks, they are all gone by the time the teardown task fires. +在更复杂的形式中,该模式使用引用计数:任务递减引用计数,只在计数归零时释放对象。在更简单的形式中,任务队列的 FIFO 排序足够了:所有更早入队的任务在拆除任务运行前完成,因此如果引用总是在任务内获取,它们在拆除任务触发时都已消失。 -**Code sketch.** +**代码草图。** ```c static void @@ -1921,19 +1921,19 @@ TASK_INIT(&free_task, 0, my_free_task, obj); taskqueue_enqueue(sc->tq, &free_task); ``` -Caveat: the `struct task` itself must live until the callback fires, which means either embedding it in the object (and freeing the containing structure) or allocating it separately. +注意:`struct task` 本身必须存活到回调触发,这意味着要么将其嵌入对象中(并释放包含结构),要么单独分配它。 -**Real example.** `/usr/src/sys/dev/usb/usb_hub.c` uses deferred teardown when a USB device is removed while still being used by a driver further up the stack. +**真实示例。** `/usr/src/sys/dev/usb/usb_hub.c` 在 USB 设备被移除但仍被上层栈驱动使用时使用延迟拆除。 -### Pattern 7: Scheduled Statistics Rollover +### 模式7:定时统计滚动 -**Problem.** The driver keeps accumulated statistics that must be rolled into a rate-per-interval at regular boundaries. The rollover involves snapshotting counters, computing the delta, and storing the result in a ring buffer. This can be done in a timer callback, but the computation touches data structures protected by a sleepable lock. +**问题。** 驱动维护必须在定期边界滚动为每间隔速率的累积统计。滚动涉及快照计数器、计算增量并将结果存储在环形缓冲区中。这可以在定时器回调中完成,但计算触碰由可睡眠锁保护的数据结构。 -**Solution.** A periodic `timeout_task` that handles the rollover in thread context. The task re-enqueues itself at the end of each firing for the next interval. +**解决方案。** 一个周期性 `timeout_task` 在线程上下文中处理滚动。任务在每次触发结束时重新入队自己以备下一个间隔。 -This is, in effect, a "taskqueue-based callout". It is slightly heavier than a plain callout because it rides a callout-plus-task combo, but it can do things a plain callout cannot. Useful only when the callout alone would not suffice. +这实际上是"基于任务队列的 callout"。它比普通 callout 稍重因为它搭载了一个 callout 加任务组合,但它可以做普通 callout 不能做的事情。只在单独的 callout 不够时才有用。 -**Code sketch.** +**代码草图。** ```c static void @@ -1949,17 +1949,17 @@ my_stats_rollover_task(void *arg, int pending) } ``` -The self-reenqueue at the end keeps the task firing once per second. A control path that wants to stop the rollover cancels the timeout task. +末尾的自重新入队保持任务每秒触发一次。想要停止滚动的控制路径取消超时任务。 -**Real example.** Several network drivers use this pattern for watchdog-adjacent timers whose work needs a sleepable lock. +**真实示例。** 几个网络驱动对工作需要可睡眠锁的看门狗邻近定时器使用此模式。 -### Pattern 8: `taskqueue_block` During Delicate Configuration +### 模式8:精细配置期间的 `taskqueue_block` -**Problem.** The driver is performing a configuration change that must not be interrupted by task execution. A task firing in the middle of the configuration could observe inconsistent state. +**问题。** 驱动正在执行不能被任务执行中断的配置更改。在配置中间触发的任务可能观察到不一致的状态。 -**Solution.** `taskqueue_block(sc->tq)` before the configuration change; `taskqueue_unblock(sc->tq)` after. While blocked, new enqueues accumulate but no tasks are dispatched. The already-running task (if any) completes naturally before the block takes effect. +**解决方案。** 在配置更改前 `taskqueue_block(sc->tq)`;配置更改后 `taskqueue_unblock(sc->tq)`。被阻塞时,新入队累积但不分派任务。已运行的任务(如果有)在阻塞生效前自然完成。 -**Code sketch.** +**代码草图。** ```c taskqueue_block(sc->tq); @@ -1967,7 +1967,7 @@ taskqueue_block(sc->tq); taskqueue_unblock(sc->tq); ``` -`taskqueue_block` is fast. It does not drain running tasks; it only prevents dispatch of new ones. For a guarantee that no task is currently running you combine it with `taskqueue_quiesce`: +`taskqueue_block` 很快。它不排空运行中的任务;它只阻止新任务的分派。为了获得没有任务正在运行的保证,你将它与 `taskqueue_quiesce` 结合使用: ```c taskqueue_block(sc->tq); @@ -1976,101 +1976,101 @@ taskqueue_quiesce(sc->tq); taskqueue_unblock(sc->tq); ``` -`taskqueue_quiesce` waits for the currently-running task to finish and for the pending queue to drain. Combined with `block`, you have a guarantee that no task is running and no task will start until you unblock. +`taskqueue_quiesce` 等待当前运行的任务完成并等待待处理队列为空。与 `block` 结合,你获得了没有任务在运行且没有任务会启动的保证,直到你解除阻塞。 -**Real example.** Some Ethernet drivers use this pattern during interface state transitions (link up, link down, media change). +**真实示例。** 一些以太网驱动在接口状态转换(链路启动、链路断开、媒体更改)期间使用此模式。 -### Pattern 9: `taskqueue_drain_all` at a Subsystem Boundary +### 模式9:子系统边界的 `taskqueue_drain_all` -**Problem.** A complex subsystem wants to be fully quiet at a specific point. All its pending tasks, including ones that may have been enqueued by other pending tasks, must complete before the subsystem proceeds. +**问题。** 复杂子系统想要在特定点完全安静。所有待处理任务,包括可能被其他待处理任务入队的任务,必须在子系统继续之前完成。 -**Solution.** `taskqueue_drain_all(tq)` drains every task on the queue, waits for every in-flight task to complete, and returns when the queue is quiet. +**解决方案。** `taskqueue_drain_all(tq)` 排空队列中的每个任务,等待每个进行中的任务完成,在队列安静时返回。 -`taskqueue_drain_all` is not a substitute for per-task `taskqueue_drain` at detach (because the queue might have tasks from other paths that should not be drained), but it is useful for internal synchronisation points where you want "everything is done, full stop". +`taskqueue_drain_all` 不是分离时每任务 `taskqueue_drain` 的替代品(因为队列可能有来自其他路径不应被排空的任务),但对于你想要"一切都完成了,句号"的内部同步点很有用。 -**Real example.** `/usr/src/sys/dev/wg/if_wg.c` uses `taskqueue_drain_all` on its per-peer taskqueue during peer cleanup. +**真实示例。** `/usr/src/sys/dev/wg/if_wg.c` 在对等端清理期间在其每对等任务队列上使用 `taskqueue_drain_all`。 -### Pattern 10: Simulation-Grade Synthetic Event Generation +### 模式10:仿真级合成事件生成 -**Problem.** During testing, the driver wants to generate synthetic events that exercise the full event-processing path. A direct function call would bypass the scheduler, miss the race conditions, and not stress the taskqueue mechanism. A real hardware event is of course unavailable in a test rig. +**问题。** 在测试期间,驱动想要生成演练完整事件处理路径的合成事件。直接函数调用会绕过调度器、错过竞争条件,并且不会给任务队列机制施加压力。真实硬件事件在测试台上当然不可用。 -**Solution.** A sysctl handler that enqueues a task. The task callback invokes the same driver routine a real event would have invoked. Because the task goes through the taskqueue, the synthetic event has the same execution shape as a real one: it runs in thread context, observes the same locking, and passes through the same coalescing. +**解决方案。** 一个入队任务的 sysctl 处理程序。任务回调调用真实事件会调用的相同驱动例程。因为任务通过任务队列,合成事件具有与真实事件相同的执行形态:它在线程上下文中运行,观察相同的锁定,并通过相同的合并。 -This is exactly what `myfirst`'s `bulk_writer_flood` sysctl does. The pattern transfers to any driver that wants to self-test its deferred-work paths without needing real hardware to generate the triggering event. +这正是 `myfirst` 的 `bulk_writer_flood` sysctl 做的。该模式可以转移到任何想要自测延迟工作路径而无需真实硬件生成触发事件的驱动。 -### A Selection From Real Drivers +### 真实驱动精选 -The patterns above are not invented for the chapter. A short tour of `/usr/src/sys/dev/` that you should explore for yourself, with a suggested order: +上述模式不是为本章发明的。`/usr/src/sys/dev/` 的简短之旅,你应该自己探索,建议顺序: -- **`/usr/src/sys/dev/ale/if_ale.c`**: A small, readable Ethernet driver that uses a private taskqueue, a filter-plus-task split, and a single interrupt task. Good first reading. -- **`/usr/src/sys/dev/age/if_age.c`**: Similar pattern, slightly different driver family. Reading both reinforces the pattern. -- **`/usr/src/sys/dev/bge/if_bge.c`**: A larger Ethernet driver with multiple tasks (interrupt task, link task, reset task). Shows how multiple tasks compose on one queue. -- **`/usr/src/sys/dev/usb/usb_process.c`**: USB's dedicated per-device process queue (`usb_proc_*`). Demonstrates how a subsystem wraps task-style deferred work for its own domain. -- **`/usr/src/sys/dev/wg/if_wg.c`**: WireGuard uses grouptaskqueues for per-peer encryption. Advanced reading, but useful once the basic patterns click. -- **`/usr/src/sys/dev/iwm/if_iwm.c`**: Wireless driver with multiple timeout tasks for calibration, scanning, and firmware management. -- **`/usr/src/sys/kern/subr_taskqueue.c`**: The implementation itself. Reading `taskqueue_run_locked` once makes everything else concrete. +- **`/usr/src/sys/dev/ale/if_ale.c`**:一个小型、可读的以太网驱动,使用私有任务队列、过滤器加任务分割和单个中断任务。好的第一阅读。 +- **`/usr/src/sys/dev/age/if_age.c`**:类似模式,略有不同的驱动系列。两者都阅读可以强化模式。 +- **`/usr/src/sys/dev/bge/if_bge.c`**:更大的以太网驱动,有多个任务(中断任务、链路任务、重置任务)。展示多个任务如何在一个队列上组合。 +- **`/usr/src/sys/dev/usb/usb_process.c`**:USB 的专用每设备进程队列(`usb_proc_*`)。演示子系统如何为自己的领域包装任务风格的延迟工作。 +- **`/usr/src/sys/dev/wg/if_wg.c`**:WireGuard 使用组任务队列进行每对等端加密。进阶阅读,但在基本模式理解后有用。 +- **`/usr/src/sys/dev/iwm/if_iwm.c`**:带有多个超时任务用于校准、扫描和固件管理的无线驱动。 +- **`/usr/src/sys/kern/subr_taskqueue.c`**:实现本身。阅读 `taskqueue_run_locked` 一次让其他一切变得具体。 -Twenty minutes with any of those files is an hour of chapter explanations you can skip. The patterns are visible at a glance once you know what to look for. +花二十分钟阅读其中任何一个文件相当于省去一小时的章节解释。一旦你知道要寻找什么,模式一眼就能看出来。 ### 第6节总结 -The same small API composes into a large family of patterns. Deferred logging, filter-plus-task interrupts, async `copyin`/`copyout`, retry-with-backoff, deferred teardown, statistics rollover, `block` during reconfiguration, `drain_all` at subsystem boundaries, synthetic event generation: each pattern is a variation on "edge detects, task acts", and each is productive whenever the driver you are writing or reading fits the shape. +同一个小型 API 组合成一个大型模式家族。延迟日志、过滤器加任务中断分割、异步 `copyin`/`copyout`、退避重试、延迟拆除、统计滚动、重配置期间阻塞、子系统边界排空所有、合成事件生成:每种模式都是"边缘检测、任务行动"的变体,每当你在编写或阅读的驱动符合该形态时都很有用。 -Section 7 turns to the other side of the same coin: when the pattern goes wrong, how do you see it? What tools does FreeBSD provide for inspecting a taskqueue's state, and what are the common bugs that those tools help you diagnose? +第7节转向同一硬币的另一面:当模式出错时,你如何看到?FreeBSD 提供了哪些工具来检查任务队列状态,这些工具帮助你诊断哪些常见 bug? ## 第7节:调试任务队列 -Most taskqueue code is short. The common bugs are not subtle: tasks that never fire, tasks that fire too often, tasks that fire after the softc is freed, deadlocks against the driver mutex, and draining at the wrong point in the detach sequence. This section names the bugs, shows how to observe them, and walks through a deliberate break-and-fix on `myfirst` so you can practise the debugging workflow with something in front of you. +大多数任务队列代码很短。常见 bug 并不微妙:从不触发的任务、触发太频繁的任务、softc 释放后触发的任务、与驱动互斥锁的死锁、以及在分离序列中错误位置的排空。本节命名这些 bug,展示如何观察它们,并在 `myfirst` 上逐步进行一个故意的破坏-修复以便你可以在面前有东西的情况下练习调试工作流程。 -### The Tools +### 工具 -A short survey of the tools you will reach for. +你将使用的工具简短概述。 -**`procstat -t`**: lists every kernel thread with its name, priority, state, and wait-channel. A private taskqueue's worker thread shows up as ` taskq`, where `` is what you passed to `taskqueue_start_threads`. A thread stuck in a non-trivial wait channel is a clue: the name of the channel often tells you what the thread is waiting for. +**`procstat -t`**:列出每个内核线程及其名称、优先级、状态和等待通道。私有任务队列的工作线程显示为 ` taskq`,其中 `` 是你传递给 `taskqueue_start_threads` 的名称。卡在非平凡等待通道中的线程是线索:通道名称通常告诉你线程在等待什么。 -**`ps ax`**: equivalent for most of what `procstat -t` shows, with a less taskqueue-specific output. The kernel thread name appears in brackets. +**`ps ax`**:等同于 `procstat -t` 显示的大多数内容,输出不太针对任务队列。内核线程名出现在方括号中。 -**`sysctl dev.`**: the driver's own sysctl tree. If you added a counter like `selwake_pending_drops`, its value is visible here. Diagnostic sysctls are the cheapest form of observability; add them whenever the question "how often does this path fire" might matter later. +**`sysctl dev.`**:驱动自己的 sysctl 树。如果你添加了像 `selwake_pending_drops` 这样的计数器,其值在这里可见。诊断 sysctl 是最便宜的可观察性形式;在"此路径触发频率是否重要"可能重要时随时添加它们。 -**`dtrace(1)`**: the kernel tracing framework. Taskqueue activity is traceable via FBT (function boundary tracing) probes on `taskqueue_enqueue` and `taskqueue_run_locked`. A short D script can count enqueues, measure delays between enqueue and dispatch, and so on. +**`dtrace(1)`**:内核跟踪框架。任务队列活动可通过 `taskqueue_enqueue` 和 `taskqueue_run_locked` 上的 FBT(函数边界跟踪)探测来跟踪。一个简短的 D 脚本可以计数入队、测量入队到调度之间的延迟等。 -**`ktr(4)`**: the kernel event tracer. Compile-time enabled in debug kernels, provides a ring buffer of kernel events that can be dumped after a crash or inspected live. Useful for post-mortem analysis. +**`ktr(4)`**:内核事件跟踪器。在调试内核中编译时启用,提供可在崩溃后转储或实时检查的内核事件环形缓冲区。对事后分析有用。 -**`ddb(4)`**: the in-kernel debugger. Breakpoints, stack traces, memory inspection. Reachable via `kgdb` after a kernel panic, or interactively after a `sysctl debug.kdb.enter=1` if you built a kernel with KDB enabled. +**`ddb(4)`**:内核内调试器。断点、栈跟踪、内存检查。通过 `kgdb` 在内核崩溃后可达,或在构建了 KDB 的内核上通过 `sysctl debug.kdb.enter=1` 交互式可达。 -**`INVARIANTS` and `WITNESS`**: compile-time assertions and lock-order checker. Not tools you invoke, but the first line of defence. A debug kernel catches most taskqueue bugs the first time you hit them. +**`INVARIANTS` 和 `WITNESS`**:编译时断言和锁序检查器。不是你调用的工具,而是第一道防线。调试内核在你第一次命中时就捕获大多数任务队列 bug。 -The Chapter 14 labs exercise `procstat -t`, `sysctl`, and `dtrace` explicitly. `ktr` and `ddb` are mentioned for completeness. +第14章实验明确练习 `procstat -t`、`sysctl` 和 `dtrace`。`ktr` 和 `ddb` 为完整性提及。 -### Common Bug 1: The Task Never Runs +### 常见Bug 1:任务从不运行 -**Symptoms.** You enqueue a task from a sysctl handler or callout callback; the task callback's `device_printf` never appears; the driver otherwise seems to work. +**症状。** 你从 sysctl 处理程序或 callout 回调入队任务;任务回调的 `device_printf` 从不出现;驱动其他方面似乎工作正常。 -**Likely cause.** `taskqueue_start_threads` was not called, or the taskqueue pointer you enqueued onto is `NULL`. +**可能原因。** `taskqueue_start_threads` 未被调用,或你入队到的任务队列指针为 `NULL`。 -**How to check.** +**如何检查。** ```text # procstat -t | grep myfirst ``` -If no `myfirst taskq` thread is listed, the taskqueue either does not exist or has no threads. Check the attach path: is `taskqueue_create` called? Is its return value stored? Is `taskqueue_start_threads` called after? +如果没有 `myfirst taskq` 线程列出,任务队列要么不存在,要么没有线程。检查 attach 路径:`taskqueue_create` 是否被调用了?它的返回值是否被存储了?之后是否调用了 `taskqueue_start_threads`? ```text # dtrace -n 'fbt::taskqueue_enqueue:entry /arg0 != 0/ { @[stack()] = count(); }' ``` -If the stack trace shows enqueues onto the driver's taskqueue, the task is being submitted. If nothing shows, the code path that should enqueue is not being reached. Trace back and find why. +如果栈跟踪显示在驱动的任务队列上入队,任务正在被提交。如果什么也没显示,应该入队的代码路径没有到达。回溯并找出原因。 -### Common Bug 2: The Task Runs Too Often +### 常见Bug 2:任务运行太频繁 -**Symptoms.** The task callback does more work than expected, or the driver logs a strange count. +**症状。** 任务回调做的工作比预期多,或驱动记录了奇怪的计数。 -**Likely cause.** The callback does not respect the `pending` argument, or the callback self-enqueues without a condition, so once started it loops forever. +**可能原因。** 回调不遵守 `pending` 参数,或回调无条件地自入队,所以一旦启动就永远循环。 -**How to check.** Add a counter to the callback: +**如何检查。** 在回调中添加计数器: ```c static void @@ -2086,85 +2086,85 @@ myfirst_task(void *arg, int pending) } ``` -If the counter grows faster than the expected trigger rate, the task is self-looping or coalescing is not happening. Inspect the enqueue call sites. +如果计数器增长快于预期触发率,任务正在自循环或合并没有发生。检查入队调用点。 -### Common Bug 3: Use-After-Free In the Task Callback +### 常见Bug 3:任务回调中的释放后使用 -**Symptoms.** Kernel panic with a stack trace ending in your task callback, at a location that accesses softc state. The panic may happen during or shortly after detach. +**症状。** 内核崩溃,栈跟踪结束于你的任务回调中访问 softc 状态的位置。崩溃可能在分离期间或之后不久发生。 -**Likely cause.** The detach path freed the softc (or something the task touches) before draining the task. A trailing enqueue from a callout or other edge context fired after the drain, and the task ran against freed state. +**可能原因。** 分离路径在排空任务之前释放了 softc(或任务触碰的某些东西)。来自 callout 或其他边缘上下文的尾随入队在排空后触发,任务对已释放状态运行。 -**How to check.** Review the detach path against the ordering from Section 4. Specifically: +**如何检查。** 根据第4节的顺序审查分离路径。具体地: -1. `is_attached` must be cleared before callouts are drained, so callout callbacks exit without re-enqueueing. -2. Callouts must be drained before tasks are drained, so no more enqueues can happen after the task drain. -3. Tasks must be drained before the state they touch is freed. -4. `taskqueue_free` must be called after all tasks on the queue are drained. +1. `is_attached` 必须在 callout 排空前清除,以便 callout 回调提前退出而不再入队。 +2. callout 必须在任务排空前排空,以便排空任务后不再有入队发生。 +3. 任务必须在它们触碰的状态被释放前排空。 +4. `taskqueue_free` 必须在队列上所有任务排空后调用。 -A mismatch in any of those is a potential use-after-free. +其中任何不匹配都是潜在的释放后使用。 -The debug kernel catches many of these cases via `INVARIANTS` assertions in `cbuf_*`, `cv_*`, and `mtx_*` routines. Run the detach path under load with `WITNESS` enabled; a bug often surfaces immediately. +调试内核通过 `cbuf_*`、`cv_*` 和 `mtx_*` 例程中的 `INVARIANTS` 断言捕获许多此类情况。在启用 `WITNESS` 的情况下在负载下运行分离路径;bug 通常会立即浮出。 -### Common Bug 4: Deadlock Between Task and Driver Mutex +### 常见Bug 4:任务与驱动互斥锁间的死锁 -**Symptoms.** A `read(2)` or `write(2)` to the device hangs forever. The task callback sits in a lock wait. The driver mutex is held by a different thread. +**症状。** 对设备的 `read(2)` 或 `write(2)` 永远挂起。任务回调卡在锁等待中。驱动互斥锁由不同线程持有。 -**Likely cause.** The task callback tries to acquire a lock that the thread enqueuing the task already holds, creating a cycle. For example: +**可能原因。** 任务回调尝试获取入队任务的线程已持有的锁,创建了循环。例如: -- Thread A holds `sc->mtx` and calls a function that enqueues a task. -- The task callback acquires `sc->mtx` before doing its work. -- The task cannot proceed because Thread A still holds the mutex. -- Thread A waits for the task to complete. +- 线程 A 持有 `sc->mtx` 并调用一个入队任务的函数。 +- 任务回调在做其工作前获取 `sc->mtx`。 +- 任务无法继续因为线程 A 仍持有互斥锁。 +- 线程 A 等待任务完成。 -The "Thread A waits for the task to complete" part does not fit the `myfirst` architecture (the driver does not explicitly wait for tasks from inside mutex-held paths), but it is a common shape in other drivers. Avoid it by not draining tasks while holding a lock they need. +"线程 A 等待任务完成"部分不符合 `myfirst` 架构(驱动不从互斥锁持有路径内部显式等待任务),但它是其他驱动中的常见形态。通过不在持有它们需要的锁时排空任务来避免它。 -**How to check.** +**如何检查。** ```text # procstat -kk # procstat -kk ``` -Compare the stack traces. If one shows `mtx_lock`/`sx_xlock` in the task callback and the other shows `msleep_sbt`/`sleepqueue` at a point that holds the same lock, you have a deadlock. +比较栈跟踪。如果一个在任务回调中显示 `mtx_lock`/`sx_xlock`,另一个在持有同一锁的位置显示 `msleep_sbt`/`sleepqueue`,你就有死锁。 -### Common Bug 5: Drain Hangs Forever +### 常见Bug 5:排空永远挂起 -**Symptoms.** Detach hangs, `kldunload` does not return. The taskqueue thread is stuck somewhere. +**症状。** 分离挂起,`kldunload` 不返回。任务队列线程卡在某处。 -**Likely cause.** The task callback is waiting on a condition that cannot be satisfied because the drain path is blocking the producer. Or the task callback is waiting on a lock that the detach path holds. +**可能原因。** 任务回调在等待一个无法满足的条件因为排空路径阻塞了生产者。或者任务回调在等待分离路径持有的锁。 -**How to check.** +**如何检查。** ```text # procstat -kk # procstat -kk ``` -The drain is in `taskqueue_drain`, which is in `msleep`. The task is in some wait. Identify the wait channel; the name often tells you what the task is blocked on. If the task is blocked on something the detach path is holding, the design has a cycle. +排空在 `taskqueue_drain` 中,处于 `msleep`。任务在某个等待中。识别等待通道;名称通常告诉你任务阻塞在什么上。如果任务阻塞在分离路径持有的东西上,设计有循环。 -A common specific case: the task callback calls `seldrain`, the detach path also calls `seldrain`, and the two collide. Avoid by ensuring `seldrain` is called exactly once, in the detach path, after the task drain. +一个常见的具体情况:任务回调调用 `seldrain`,分离路径也调用 `seldrain`,两者冲突。通过确保 `seldrain` 在分离路径中只调用一次、在任务排空之后来避免。 -### The Break-and-Fix Exercise +### 破坏-修复练习 -A deliberate bug-and-fix walkthrough. The Stage 1 driver is correct; we modify it to introduce each of the bugs above, observe the symptom, and fix it. +一个故意的 bug 和修复演练。第1阶段驱动是正确的;我们修改它以引入上述每个 bug,观察症状,然后修复它。 -#### Broken variant 1: missing `taskqueue_start_threads` +#### 损坏变体1:缺少 `taskqueue_start_threads` -Remove the `taskqueue_start_threads` call from attach. Rebuild, load, enable the tick source, and run the `poll_waiter`. You will observe: no data appears in `poll_waiter`, even though `sysctl dev.myfirst.0.tick_source_interval_ms` is set. +从 attach 中移除 `taskqueue_start_threads` 调用。重新构建、加载、启用 tick 源,并运行 `poll_waiter`。你会观察到:`poll_waiter` 中没有数据出现,即使 `sysctl dev.myfirst.0.tick_source_interval_ms` 已设置。 -Check `procstat -t`: +检查 `procstat -t`: ```text # procstat -t | grep myfirst ``` -No `myfirst taskq` thread appears. The taskqueue exists (you created it) but has no workers. The enqueued `selwake_task` sits on the queue forever. +没有 `myfirst taskq` 线程出现。任务队列存在(你创建了它)但没有工作线程。入队的 `selwake_task` 永远停在队列上。 -Fix: put the `taskqueue_start_threads` call back. Rebuild. Confirm the thread appears in `procstat -t` and the `poll_waiter` sees data. +修复:把 `taskqueue_start_threads` 调用放回去。重新构建。确认线程出现在 `procstat -t` 中且 `poll_waiter` 看到数据。 -#### Broken variant 2: draining in the wrong order +#### 损坏变体2:以错误顺序排空 -Move the `taskqueue_drain` call in detach to happen before the callout drains: +将 detach 中的 `taskqueue_drain` 调用移到 callout 排空之前: ```c /* WRONG ORDER: */ @@ -2176,15 +2176,15 @@ seldrain(&sc->rsel); seldrain(&sc->wsel); ``` -Rebuild, load, enable the tick source at a high rate, let data flow for a few seconds, then unload. Most times the unload works. Occasionally, the unload panics with a stack in `selwakeup` being called after `seldrain`. The race is rare but real. +重新构建、加载、以高速率启用 tick 源,让数据流几秒钟,然后卸载。大多数时候卸载成功。偶尔,卸载会在 `selwakeup` 被调用时崩溃,在 `seldrain` 之后。竞争很少但真实存在。 -The issue: `taskqueue_drain` returned, but then an in-flight `tick_source` callout fired (it had not been drained yet) and re-enqueued the task. The new task fired after `seldrain` had run, and tried to `selwakeup` on a drained selinfo. +问题:`taskqueue_drain` 返回了,但随后一个进行中的 `tick_source` callout 触发了(它还没被排空)并重新入队了任务。新任务在 `seldrain` 运行后触发,并尝试对一个已排空的 selinfo 调用 `selwakeup`。 -Fix: restore the correct order (callouts first, then tasks, then `seldrain`). Rebuild, verify the race is gone under the same stress. +修复:恢复正确顺序(先 callout,然后任务,然后 `seldrain`)。重新构建,验证竞争在相同压力下消失。 -#### Broken variant 3: task callback holds the mutex too long +#### 损坏变体3:任务回调持有互斥锁太久 -Change `myfirst_selwake_task` to hold the mutex across `selwakeup`: +将 `myfirst_selwake_task` 改为在 `selwakeup` 期间持有互斥锁: ```c static void @@ -2198,23 +2198,23 @@ myfirst_selwake_task(void *arg, int pending) } ``` -Rebuild. Load under a debug kernel. Enable the tick source. Within seconds the kernel panics with a `WITNESS` complaint about locking order (or in some configurations with an assertion failure in `selwakeup` itself). +重新构建。在调试内核下加载。启用 tick 源。几秒内内核崩溃,`WITNESS` 抱怨锁序(或某些配置中 `selwakeup` 本身的断言失败)。 -The issue: `selwakeup` acquires a lock that is not in the driver's documented lock order. `WITNESS` notices and complains. +问题:`selwakeup` 获取一个不在驱动文档记录锁序中的锁。`WITNESS` 注意到并抱怨。 -Fix: the correct `myfirst_selwake_task` calls `selwakeup` with no driver mutex held. Restore that, rebuild, verify no WITNESS warnings. +修复:正确的 `myfirst_selwake_task` 在没有驱动互斥锁持有的情况下调用 `selwakeup`。恢复它,重新构建,验证没有 WITNESS 警告。 -#### Broken variant 4: forget to drain the task in detach +#### 损坏变体4:忘记在 detach 中排空任务 -Remove the `taskqueue_drain(sc->tq, &sc->selwake_task)` line from detach. Rebuild. Load, enable the tick source at a high rate, run the `poll_waiter`, and immediately unload the driver. +从 detach 中移除 `taskqueue_drain(sc->tq, &sc->selwake_task)` 行。重新构建。加载,以高速率启用 tick 源,运行 `poll_waiter`,然后立即卸载驱动。 -Most times the unload completes. Occasionally, a task that was in flight at unload time runs against a softc whose selinfo has been drained and freed. The symptom is usually a kernel panic or a memory corruption that shows up later as an unrelated crash. +大多数时候卸载完成。偶尔,卸载时进行中的任务对 selinfo 已被排空和释放的 softc 运行。症状通常是内核崩溃或后来作为不相关崩溃出现的内存损坏。 -Fix: restore the drain. Rebuild, verify that repeated load-and-unload under load is stable. +修复:恢复排空。重新构建,验证在负载下重复加载-卸载是稳定的。 -#### Broken variant 5: wrong taskqueue pointer +#### 损坏变体5:错误的任务队列指针 -A subtle Stage-2 bug. After moving to the private taskqueue, forget to update the `taskqueue_drain` call in detach. It still targets `taskqueue_thread`: +一个微妙的第2阶段 bug。转移到私有任务队列后,忘记更新 detach 中的 `taskqueue_drain` 调用。它仍然指向 `taskqueue_thread`: ```c /* WRONG: enqueue on sc->tq but drain on taskqueue_thread */ @@ -2223,13 +2223,13 @@ taskqueue_enqueue(sc->tq, &sc->selwake_task); taskqueue_drain(taskqueue_thread, &sc->selwake_task); ``` -Rebuild. Load, enable the tick source, run the waiter, unload. The unload typically completes without error, but `taskqueue_drain(taskqueue_thread, ...)` does not actually wait for the task that is running on `sc->tq`. If the task is in flight when detach proceeds, use-after-free. +重新构建。加载,启用 tick 源,运行等待者,卸载。卸载通常无错完成,但 `taskqueue_drain(taskqueue_thread, ...)` 实际上不会等待运行在 `sc->tq` 上的任务。如果任务在 detach 继续时进行中,就会发生释放后使用。 -Fix: match enqueue and drain on the same taskqueue pointer. Rebuild, test. +修复:在同一任务队列指针上匹配入队和排空。重新构建,测试。 -### A DTrace One-Liner +### 一个 DTrace 单行命令 -A useful one-liner for any taskqueue-using driver. It measures the time between enqueue and dispatch for every task on the system: +对任何使用任务队列的驱动有用的单行命令。它测量系统上每个任务的入队到调度延迟: ```text # dtrace -n ' @@ -2241,9 +2241,9 @@ A useful one-liner for any taskqueue-using driver. It measures the time between ' ``` -The output is a distribution of enqueue-to-dispatch latency per process. Run it while your driver is producing tasks, then hit Ctrl-C to see the quantised histogram. Typical results on a lightly-loaded machine: tens of microseconds. Under load: milliseconds. If you see seconds, something is wrong. +输出是每个进程的入队到调度延迟分布。在你的驱动产生任务时运行它,然后按 Ctrl-C 查看量化直方图。轻度负载机器上的典型结果:几十微秒。在负载下:毫秒级。如果你看到秒级,说明有问题。 -A second useful one-liner measures task callback duration: +第二个有用的单行命令测量任务回调持续时间: ```text # dtrace -n ' @@ -2255,11 +2255,11 @@ A second useful one-liner measures task callback duration: ' ``` -Same structure, different timing. Tells you how long each `taskqueue_run_locked` invocation takes (which is the callback duration plus a small constant overhead). +相同结构,不同计时。告诉你每次 `taskqueue_run_locked` 调用花费多长时间(即回调持续时间加上一个小的固定开销)。 -### Diagnostic Sysctls to Add +### 要添加的诊断 Sysctl -Useful counters to add to any taskqueue-using driver, with minimal cost and high diagnostic value. +对任何使用任务队列的驱动有用的计数器,成本最小,诊断价值高。 ```c int enqueues; /* Total enqueues attempted. */ @@ -2268,7 +2268,7 @@ int callback_runs; /* Total callback invocations. */ int largest_pending; /* Peak pending count observed. */ ``` -Update the counters in the enqueue path and the callback: +在入队路径和回调中更新计数器: ```c static void @@ -2289,56 +2289,56 @@ sc->enqueues++; taskqueue_enqueue(sc->tq, &sc->task); ``` -Expose each as a read-only sysctl. Under normal load, `enqueues == callback_runs + pending_drops`. `largest_pending` tells you the worst coalescing moment; if it grows, the taskqueue is falling behind the producer. +将每个暴露为只读 sysctl。正常负载下,`enqueues == callback_runs + pending_drops`。`largest_pending` 告诉你最糟糕的合并时刻;如果它增长,任务队列正在落后于生产者。 -These counters cost a few atomic adds per enqueue. On any realistic workload the cost is unmeasurable. The diagnostic value is substantial. +这些计数器每次入队花费少量原子添加。在任何现实工作负载上成本不可衡量。诊断价值是实质性的。 -### The Debug-Kernel Obligation +### 调试内核义务 -A reminder worth repeating: run every Chapter 14 change under a kernel with `INVARIANTS`, `WITNESS`, `WITNESS_SKIPSPIN`, `DDB`, `KDB`, and `KDB_UNATTENDED`. Most taskqueue bugs that are hard to find on a production kernel are caught instantly on a debug kernel. The cost of running a debug kernel is a small performance hit and a slightly larger build; the cost of not running one is an afternoon of debugging whenever anything goes wrong. +值得重复的提醒:在启用了 `INVARIANTS`、`WITNESS`、`WITNESS_SKIPSPIN`、`DDB`、`KDB` 和 `KDB_UNATTENDED` 的内核下运行第14章的每一次更改。大多数在生产内核上难以找到的任务队列 bug 在调试内核上立即被捕获。运行调试内核的成本是小的性能损失和稍大的构建;不运行的成本是每当出问题时的一个下午的调试。 ### 第7节总结 -Debugging taskqueues is a small skill that composes with the tools you already have for debugging callouts, mutexes, and cvs. `procstat -t` and `ps ax` show the thread. `sysctl` exposes diagnostic counters. `dtrace` measures enqueue-to-dispatch latency and callback duration. `WITNESS` catches locking-order violations at runtime. The common bugs (task never runs, wrong drain order, wrong lock discipline in callback, forgotten drain) are each catchable with a checklist and a debug kernel. +调试任务队列是一项小技能,与你已有的调试 callout、互斥锁和 cv 的工具组合。`procstat -t` 和 `ps ax` 显示线程。`sysctl` 暴露诊断计数器。`dtrace` 测量入队到调度延迟和回调持续时间。`WITNESS` 在运行时捕获锁序违规。常见 bug(任务从不运行、错误排空顺序、回调中错误锁纪律、遗忘排空)每一个都可以通过检查表和调试内核捕获。 -Section 8 consolidates the Chapter 14 work into Stage 4, the final driver. We extend `LOCKING.md`, bump the version string, and audit the driver against a full stress pass. +第8节将第14章的工作整合到第4阶段,最终驱动中。我们扩展 `LOCKING.md`,提升版本字符串,并根据完整的压力测试审计驱动。 ## 第8节:重构任务队列驱动程序并更新版本 -Stage 4 is the consolidation stage. It does not add new functionality beyond what Stage 3 established; it sharpens the organisation of the code, updates the documentation, bumps the version, and runs the full regression sweep. If Stages 1 through 3 are where you built the driver, Stage 4 is where you ship it. +第4阶段是整合阶段。它不添加超出第3阶段建立的新功能;它锐化代码组织,更新文档,提升版本,并运行完整的回归扫描。如果第1到第3阶段是你构建驱动的阶段,第4阶段是你交付的阶段。 -This section walks through the consolidation. The driver source is unified into a single, well-structured file; `LOCKING.md` gains a Tasks section; the version string advances to `0.8-taskqueues`; and the final regression pass confirms that every Chapter 12 and Chapter 13 behaviour still works correctly alongside the new Chapter 14 additions. +本节逐步讲解整合过程。驱动源码被统一为单一的、结构良好的文件;`LOCKING.md` 获得一个 Tasks 节;版本字符串提升到 `0.8-taskqueues`;最终回归通过确认每个第12章和第13章行为在新的第14章添加旁仍然正确工作。 -### File Organisation +### 文件组织 -The chapter does not split the driver into multiple `.c` files. `myfirst.c` stays as the single translation unit, with one added responsibility (the tasks) grouped next to the corresponding callouts. If the driver grew much larger, a natural split would be `myfirst_timers.c` for callout code and `myfirst_tasks.c` for task code, with shared declarations in `myfirst.h`. For the current size the single file is easier to read. +本章不将驱动拆分为多个 `.c` 文件。`myfirst.c` 保持为单一翻译单元,增加一项责任(任务)分组在相应 callout 旁边。如果驱动变得大得多,自然的拆分将是 `myfirst_timers.c` 用于 callout 代码和 `myfirst_tasks.c` 用于任务代码,共享声明在 `myfirst.h` 中。对于当前大小,单文件更容易阅读。 -Inside `myfirst.c`, the Stage 4 organisation is: +在 `myfirst.c` 内部,第4阶段的组织是: -1. Includes and global macros. -2. Softc structure. -3. File-handle structure. -4. cdevsw declaration. -5. Buffer helpers. -6. Condition-variable wait helpers. -7. Sysctl handlers, grouped: - - Configuration sysctls (debug level, soft byte limit, nickname). - - Timer interval sysctls (heartbeat, watchdog, tick source). - - Task sysctls (reset delayed, bulk writer batch, bulk writer flood). - - Read-only stats sysctls. -8. Callout callbacks. -9. Task callbacks. -10. Cdev handlers (open, close, read, write, poll, handle destructor). -11. Device methods (identify, probe, attach, detach). -12. Module glue (driver, `DRIVER_MODULE`, version). +1. 头文件和全局宏。 +2. Softc 结构。 +3. 文件句柄结构。 +4. cdevsw 声明。 +5. 缓冲区辅助函数。 +6. 条件变量等待辅助函数。 +7. Sysctl 处理函数,分组: + - 配置 sysctl(调试级别、软字节限制、昵称)。 + - 定时器间隔 sysctl(心跳、看门狗、tick 源)。 + - 任务 sysctl(延迟重置、批量写入批次、批量写入洪泛)。 + - 只读统计 sysctl。 +8. Callout 回调。 +9. 任务回调。 +10. Cdev 处理函数(open、close、read、write、poll、句柄析构函数)。 +11. 设备方法(identify、probe、attach、detach)。 +12. 模块胶水代码(驱动、`DRIVER_MODULE`、版本)。 -A block comment at the top of the file lists the major sections, so a new reader can jump to the right area without grep. Inside each section, the order is established-first: heartbeat before watchdog before tick source, for the callouts that share that order in the outline. +文件顶部的一块注释列出主要节,以便新读者可以不用 grep 就跳到正确区域。每个节内部,顺序是先建立的:心跳在 watchdog 之前,watchdog 在 tick 源之前,对于大纲中共享该顺序的 callout。 -### The `LOCKING.md` Update +### `LOCKING.md` 更新 -The Chapter 13 `LOCKING.md` had sections for the mutex, the cvs, the sx, and the callouts. Chapter 14 adds a Tasks section. +第13章的 `LOCKING.md` 有互斥锁、cv、sx 和 callout 的节。第14章添加一个 Tasks 节。 ```markdown ## Tasks @@ -2392,99 +2392,99 @@ accesses after drain, or taskqueue teardown while a task is still running. ``` -The update is explicit about the ordering because the ordering is the main thing that can go wrong. A reader who inherits the driver from you and wants to add a new task has the existing discipline spelled out. +更新明确说明了排序因为排序是可能出错的主要地方。一个从你那里继承驱动并想要添加新任务的读者会发现现有的纪律已被清楚写明。 -### The Version Bump +### 版本提升 -The version string in the source moves from `0.7-timers` to `0.8-taskqueues`: +源码中的版本字符串从 `0.7-timers` 移到 `0.8-taskqueues`: ```c #define MYFIRST_VERSION "0.8-taskqueues" ``` -And the driver's probe string updates: +驱动的探测字符串更新: ```c device_set_desc(dev, "My First FreeBSD Driver (Chapter 14 Stage 4)"); ``` -The version is visible via the `hw.myfirst.version` sysctl, which was established in Chapter 12. +版本通过 `hw.myfirst.version` sysctl 可见,这在第12章中建立。 -### The Final Regression Pass +### 最终回归通过 -Stage 4 must pass every test that Stages 1 through 3 passed, plus the Chapter 12 and Chapter 13 test suites. A compact pass order: +第4阶段必须通过第1到第3阶段通过的每个测试,加上第12章和第13章的测试套件。一个紧凑的通过顺序: -1. **Build cleanly** under the debug kernel (`make clean && make`). -2. **Load** with `kldload ./myfirst.ko`. -3. **Chapter 11 unit tests**: basic read, write, open, close, reset. -4. **Chapter 12 synchronisation tests**: bounded blocking reads, bounded blocking writes, timeout reads, sx-protected configuration, cv broadcasts at detach. -5. **Chapter 13 timer tests**: heartbeat fires at configured rate, watchdog detects stalled drainage, tick source injects bytes. -6. **Chapter 14 task tests**: - - `poll_waiter` sees data when tick source is active. - - `selwake_pending_drops` counter grows under load. - - `bulk_writer_flood` triggers coalescing into a single callback. - - `reset_delayed` fires after the configured delay. - - Re-arming `reset_delayed` replaces the deadline (only one fire). -7. **Detach under load**: tick source at 1 ms, `poll_waiter` running, `bulk_writer_flood` issuing floods, then immediate unload. Should be clean. -8. **WITNESS pass**: every test above, with no `WITNESS` warnings in `dmesg`. -9. **lockstat pass**: run the test suite under `lockstat -s 5` to measure lock contention. The taskqueue's internal mutex should show up only briefly. +1. **干净构建** 在调试内核下(`make clean && make`)。 +2. **加载** 用 `kldload ./myfirst.ko`。 +3. **第11章单元测试**:基本读、写、打开、关闭、重置。 +4. **第12章同步测试**:有界阻塞读、有界阻塞写、超时读、sx 保护的配置、分离时 cv 广播。 +5. **第13章定时器测试**:心跳以配置速率触发、看门狗检测排放停滞、tick 源注入字节。 +6. **第14章任务测试**: + - `poll_waiter` 在 tick 源活跃时看到数据。 + - `selwake_pending_drops` 计数器在负载下增长。 + - `bulk_writer_flood` 触发合并为单次回调。 + - `reset_delayed` 在配置的延迟后触发。 + - 重新武装 `reset_delayed` 替换截止时间(只触发一次)。 +7. **负载下分离**:tick 源设为 1 ms,`poll_waiter` 运行中,`bulk_writer_flood` 发出洪水,然后立即卸载。应该干净。 +8. **WITNESS 通过**:以上每个测试,`dmesg` 中没有 `WITNESS` 警告。 +9. **lockstat 通过**:在 `lockstat -s 5` 下运行测试套件来测量锁争用。任务队列的内部互斥锁应该只短暂出现。 -Every test should pass. If any fails, the cause is almost certainly a regression introduced between Stage 3 and Stage 4, not a pre-existing issue; Stages 1-3 are each validated independently before Stage 4 starts. +每个测试应该通过。如果任何失败,原因几乎肯定是第3阶段和第4阶段之间引入的回归,不是预先存在的问题;第1-3阶段在开始第4阶段之前各自独立验证。 -### Keeping Documentation in Sync +### 保持文档同步 -Three places where documentation should reflect Chapter 14: +第14章应反映在三个地方: -- The top-of-file comment in `myfirst.c`. Update the "locking strategy" block to mention the taskqueue. -- `LOCKING.md`. Update per the earlier subsection. -- Any per-chapter `README.md` under `examples/part-03/ch14-taskqueues-and-deferred-work/`. Describe each stage's deliverables and how to build them. +- `myfirst.c` 的文件顶部注释。更新"锁定策略"块以提及任务队列。 +- `LOCKING.md`。按前一小节更新。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/` 下的每章 `README.md`。描述每个阶段的交付物及如何构建它们。 -Updating documentation feels like overhead. It is not. Next year's reader (often your future self) depends on the documentation to reconstruct the design. Writing it now, while the design is fresh, is an order of magnitude cheaper than writing it later. +更新文档感觉像是开销。它不是。明年的读者(通常是你未来的自己)依赖文档来重建设计。现在写,当设计还清晰时,比以后写成本低一个数量级。 -### A Final Audit +### 最终审计 -Before closing Stage 4, run through a short audit. +在关闭第4阶段之前,运行一个简短的审计。 -- [ ] Does every callout drain happen before every task drain in detach? -- [ ] Does every task drain happen before `seldrain`? -- [ ] Does `taskqueue_free` happen after all tasks are drained? -- [ ] Does the attach failure path `taskqueue_free` the queue if a subsequent init step fails? -- [ ] Is every enqueue call site targeting the right taskqueue pointer (private, not shared)? -- [ ] Is every drain call site matched with its enqueue call site (same taskqueue, same task)? -- [ ] Is every task callback free of assumptions that "I run exactly once per enqueue"? -- [ ] Is every task callback free of assumptions that "I hold a driver lock on entry"? -- [ ] Does `LOCKING.md` list every task and its callback, lifetime, and enqueue paths? -- [ ] Does the version string reflect the new stage? +- [ ] 每个调用排空是否在 每个 任务排空之前发生? +- [ ] 每个任务排空是否在 `seldrain` 之前发生? +- [ ] `taskqueue_free` 是否在所有任务排空之后发生? +- [ ] attach 失败路径是否在后续初始化步骤失败时 `taskqueue_free` 队列? +- [ ] 每个入队调用点是否指向正确的 taskqueue 指针(私有的,而非共享的)? +- [ ] 每个排空调用点是否与其入队调用点匹配(同一 taskqueue、同一任务)? +- [ ] 每个任务回调是否不包含"我每次入队恰好运行一次"的假设? +- [ ] 每个任务回调是否不包含"我进入时持有驱动锁"的假设? +- [ ] `LOCKING.md` 是否列出了每个任务及其回调、生命周期和入队路径? +- [ ] 版本字符串是否反映了新阶段? -A driver that passes this audit, plus Chapter 13's audit from Section 7 of that chapter, is a driver you can hand to another engineer with confidence. +通过此审计的驱动,加上第13章第7节的审计,是一个你可以有信心交给其他工程师的驱动。 ### 第8节总结 -Stage 4 is the consolidation. The driver code is organised. `LOCKING.md` is current. The version string reflects the new capability. The full regression suite passes under a debug kernel. The audit checklist is clean. +第4阶段是整合。驱动代码被组织好了。`LOCKING.md` 是最新的。版本字符串反映了新能力。完整的回归套件在调试内核下通过。审计检查表是干净的。 -The `myfirst` driver has come a long way. It started Chapter 10 as a single-open character device that moved bytes through a circular buffer. Chapter 11 gave it concurrent access. Chapter 12 gave it bounded blocking, cv channels, and sx-protected configuration. Chapter 13 gave it callouts for periodic and watchdog work. Chapter 14 gives it deferred work, which is the bridge between edge contexts and thread context and the missing piece for a driver that will eventually face real hardware interrupts. +`myfirst` 驱动走了很长的路。它在第10章开始时是一个单次打开的字符设备,通过循环缓冲区移动字节。第11章给了它并发访问。第12章给了它有界阻塞、cv 通道和 sx 保护的配置。第13章给了它 callout 用于周期性和看门狗工作。第14章给了它延迟工作,这是边缘上下文和线程上下文之间的桥梁,也是驱动最终将面对真实硬件中断所缺少的那一块。 -The rest of this chapter expands the view slightly. The additional topics section introduces `epoch(9)`, grouptaskqueues, and per-CPU taskqueues at an introductory level. Hands-on labs consolidate the Section 3 through Section 8 material. Challenge exercises stretch the reader. A troubleshooting reference gathers the common issues into one place. Then the wrapping-up and the bridge to Chapter 15. +本章的其余部分稍微扩展了视野。附加主题节以介绍级别介绍了 `epoch(9)`、组任务队列和每 CPU 任务队列。动手实验整合了第3节到第8节的材料。挑战练习延伸读者。故障排除参考将常见问题汇集在一个地方。然后是收尾和通往第15章的桥梁。 ## Additional Topics: `epoch(9)`, Grouptaskqueues, and Per-CPU Taskqueues -The main body of Chapter 14 taught the `taskqueue(9)` patterns a typical driver needs. Three adjacent topics deserve a mention for readers who will eventually write or read network drivers, or whose drivers grow to a scale where the simple private taskqueue is not enough. Each topic is introduced at the "know when to reach for it" level. The full mechanics belong to later chapters, especially those covering network drivers in Part 6 (Chapter 28). +第14章的主体教授了典型驱动需要的 `taskqueue(9)` 模式。三个相邻主题值得为最终会编写或阅读网络驱动的读者提及,或驱动规模增长到简单私有任务队列不够时。每个主题在"知道何时使用它"的级别介绍。完整的机制属于后续章节,特别是第六部分覆盖网络驱动的章节(第28章)。 -### `epoch(9)` in One Page +### `epoch(9)` 一页概述 -`epoch(9)` is a lockless read-synchronisation mechanism. Its purpose is to allow many readers to walk a shared data structure concurrently, without acquiring any exclusive lock, while guaranteeing that the data structure will not disappear underneath them. +`epoch(9)` 是一种无锁读同步机制。其目的是允许多个读者并发遍历共享数据结构,无需获取任何排他锁,同时保证数据结构不会在它们脚下消失。 -The shape is this. Code that reads shared data enters an "epoch section" with `epoch_enter(epoch)` and leaves it with `epoch_exit(epoch)`. Inside the section, readers can dereference pointers freely. Writers who want to change or free a shared object do not do so directly; instead, they either call `epoch_wait(epoch)` to block until every current reader has left the epoch section, or they register a callback via `epoch_call(epoch, cb, ctx)` that runs asynchronously after all current readers have left. +其形态是这样的。读取共享数据的代码用 `epoch_enter(epoch)` 进入一个 "epoch 段",用 `epoch_exit(epoch)` 离开。在段内部,读者可以自由解引用指针。想要更改或释放共享对象的写入者不直接这样做;相反,它们要么调用 `epoch_wait(epoch)` 阻塞直到所有当前读者离开了 epoch 段,要么通过 `epoch_call(epoch, cb, ctx)` 注册一个回调,在所有当前读者离开后异步运行。 -The benefit is scalability. Readers pay no atomic-operation cost; they simply record thread-local state on entry and exit. Writers pay the synchronisation cost, but writes are rare compared to reads, so the amortised cost is low. For data structures that are walked by many threads and changed only occasionally, `epoch(9)` beats reader-writer locks substantially. +好处是可扩展性。读者不支付原子操作成本;它们只在进入和退出时记录线程本地状态。写入者支付同步成本,但写入相比读取很少,所以分摊成本很低。对于被多个线程遍历且偶尔更改的数据结构,`epoch(9)` 大幅优于读写锁。 -The cost is discipline. Code inside an epoch section must not sleep, must not acquire sleepable locks, and must not call functions that might do either. Writers who use `epoch_wait` block until every current reader has left, which means the writer is waiting for potentially a lot of readers. +代价是纪律。epoch 段内部的代码不能睡眠、不能获取可睡眠锁、不能调用可能做这两者的函数。使用 `epoch_wait` 的写入者阻塞直到所有当前读者离开,这意味着写入者可能在等待很多读者。 -Network drivers use `epoch(9)` heavily. The `net_epoch_preempt` epoch protects reads of network state (ifnet lists, routing entries, interface flags). A packet-input path enters the epoch, walks the state, exits the epoch. A writer who wants to remove an interface defers the free via `NET_EPOCH_CALL` and the free happens on a taskqueue-like mechanism once every reader has finished. +网络驱动大量使用 `epoch(9)`。`net_epoch_preempt` epoch 保护网络状态的读取(ifnet 列表、路由条目、接口标志)。包输入路径进入 epoch、遍历状态、退出 epoch。想要移除接口的写入者通过 `NET_EPOCH_CALL` 延迟释放,释放在类似任务队列的机制上在每个读者完成后发生。 -For the taskqueue connection: when a task is initialised with `NET_TASK_INIT` instead of `TASK_INIT`, the taskqueue runs the callback inside the `net_epoch_preempt` epoch. The task callback can therefore walk network state without entering the epoch explicitly. From the implementation in `/usr/src/sys/kern/subr_taskqueue.c`: +对于任务队列的连接:当任务用 `NET_TASK_INIT` 而不是 `TASK_INIT` 初始化时,任务队列在 `net_epoch_preempt` epoch 内运行回调。任务回调因此可以遍历网络状态而无需显式进入 epoch。来自 `/usr/src/sys/kern/subr_taskqueue.c` 的实现: ```c if (!in_net_epoch && TASK_IS_NET(task)) { @@ -2497,15 +2497,15 @@ if (!in_net_epoch && TASK_IS_NET(task)) { task->ta_func(task->ta_context, pending); ``` -The taskqueue dispatcher notices the `TASK_NETWORK` flag and enters or exits the epoch around the callback as needed. Consecutive network tasks share a single epoch entry, which is a small optimisation the framework does for free. +taskqueue 分发器注意到 `TASK_NETWORK` 标志并根据需要在回调周围进入或退出 epoch。连续的网络任务共享单个 epoch 进入,这是框架免费提供的一个小优化。 -For `myfirst`, this is not relevant. The driver does not touch network state. But if you later write a network driver or read network driver code, `NET_TASK_INIT` and `TASK_IS_NET` are the macros that tell you a task is epoch-aware. +对于 `myfirst`,这不相关。驱动不触碰网络状态。但如果你后来编写网络驱动或阅读网络驱动代码,`NET_TASK_INIT` 和 `TASK_IS_NET` 是告诉你任务感知 epoch 的宏。 -### Grouptaskqueues in One Page +### 组任务队列一页概述 -A grouptaskqueue is a scalable generalisation of a taskqueue. The basic idea: instead of a single queue with a single (or small) pool of workers, distribute tasks across many per-CPU queues, each serviced by its own worker thread. A "grouptask" is a task that binds to one of those queues. +组任务队列是任务队列的可扩展泛化。基本想法:不是单一队列配单一(或小型)工作线程池,而是将任务分配到许多每 CPU 队列,每个由自己的工作线程服务。"组任务"是绑定到其中一个队列的任务。 -The header is `/usr/src/sys/sys/gtaskqueue.h`: +头文件是 `/usr/src/sys/sys/gtaskqueue.h`: ```c #define GROUPTASK_INIT(gtask, priority, func, context) \ @@ -2523,37 +2523,37 @@ int taskqgroup_attach_cpu(struct taskqgroup *qgroup, void taskqgroup_detach(struct taskqgroup *qgroup, struct grouptask *gtask); ``` -A driver that uses grouptasks does the following at attach: +使用组任务的驱动在 attach 时做以下事情: -1. Initialise each grouptask with `GROUPTASK_INIT`. -2. Attach each grouptask to a `taskqgroup` with `taskqgroup_attach` or `taskqgroup_attach_cpu`. The attachment assigns the grouptask to a specific per-CPU queue and worker. -3. At event time, enqueue with `GROUPTASK_ENQUEUE`. -4. At detach, `taskqgroup_detach` disassociates the grouptask. +1. 用 `GROUPTASK_INIT` 初始化每个组任务。 +2. 用 `taskqgroup_attach` 或 `taskqgroup_attach_cpu` 将每个组任务附加到 `taskqgroup`。附加将组任务分配到特定的每 CPU 队列和工作线程。 +3. 在事件时,用 `GROUPTASK_ENQUEUE` 入队。 +4. 在分离时,`taskqgroup_detach` 解除组任务的关联。 -Why use grouptasks instead of plain tasks? Two reasons. +为什么使用组任务而不是普通任务?两个原因。 -First, **scalability with CPU count**. A single-threaded taskqueue is a bottleneck when many producers on different CPUs enqueue concurrently. The taskqueue's internal mutex becomes contended. A grouptaskqueue with per-CPU queues lets each CPU enqueue onto its own queue with no cross-CPU contention. +第一,**随 CPU 数量的可扩展性**。单线程任务队列在多个 CPU 上并发入队时是瓶颈。任务队列的内部互斥锁成为争用点。有每 CPU 队列的组任务队列让每个 CPU 在自己的队列上入队而无跨 CPU 争用。 -Second, **cache locality**. When an interrupt fires on CPU N and enqueues a grouptask that is bound to CPU N, the task runs on the same CPU that saw the interrupt. The task's data is already in that CPU's caches. For high-rate network drivers this is a substantial performance win. +第二,**缓存局部性**。当中断在 CPU N 上触发并将在 CPU N 上绑定的组任务入队时,任务在看到中断的同一 CPU 上运行。任务的数据已经在那个 CPU 的缓存中。对于高速率网络驱动这是实质性的性能提升。 -The cost is complexity. Grouptaskqueues require more setup, more teardown, and more thinking about which queue a task belongs to. For most drivers this cost is not justified. For a high-end Ethernet driver that processes millions of packets per second, the cost pays for itself. +代价是复杂性。组任务队列需要更多设置、更多拆除、更多考虑任务属于哪个队列。对大多数驱动这个代价不值得。对于每秒处理数百万包的高端以太网驱动,代价物有所值。 -`myfirst` does not use grouptasks. It would not benefit. We mention them so that when you read a driver like `/usr/src/sys/dev/wg/if_wg.c` or `/usr/src/sys/net/iflib.c`, the macros look familiar. +`myfirst` 不使用组任务。它不会受益。我们提到它们以便当你阅读 `/usr/src/sys/dev/wg/if_wg.c` 或 `/usr/src/sys/net/iflib.c` 这样的驱动时,宏看起来很熟悉。 -### Per-CPU Taskqueues in One Page +### 每 CPU 任务队列一页概述 -A per-CPU taskqueue is the simple version of the grouptaskqueue idea: one taskqueue per CPU, each with its own worker thread. The driver creates N taskqueues (one per CPU), binds each to a specific CPU with `taskqueue_start_threads_cpuset`, and dispatches tasks to the appropriate queue based on whatever locality rule the driver wants. +每 CPU 任务队列是组任务队列想法的简单版本:每个 CPU 一个任务队列,每个有自己的工作线程。驱动创建 N 个任务队列(每个 CPU 一个),用 `taskqueue_start_threads_cpuset` 将每个绑定到特定 CPU,并根据驱动想要的任何局部性规则将任务分派到适当的队列。 -The key primitive is `taskqueue_start_threads_cpuset`: +关键原语是 `taskqueue_start_threads_cpuset`: ```c int taskqueue_start_threads_cpuset(struct taskqueue **tqp, int count, int pri, cpuset_t *mask, const char *name, ...); ``` -It is like `taskqueue_start_threads` but with a `cpuset_t` describing which CPUs the threads may run on. For a single-CPU binding the mask has exactly one bit set. For multi-CPU flexibility the mask has multiple bits. +它类似于 `taskqueue_start_threads` 但有一个描述线程可以运行在哪些 CPU 上的 `cpuset_t`。对于单 CPU 绑定,掩码恰好设置一位。对于多 CPU 灵活性,掩码有多个位。 -A driver that uses per-CPU taskqueues typically keeps an array of taskqueue pointers indexed by CPU: +使用每 CPU 任务队列的驱动通常维护一个按 CPU 索引的任务队列指针数组: ```c struct my_softc { @@ -2570,28 +2570,28 @@ for (int i = 0; i < mp_ncpus; i++) { } ``` -And at enqueue time, pick the queue corresponding to the current CPU: +在入队时,选择对应当前 CPU 的队列: ```c int cpu = curcpu; taskqueue_enqueue(sc->per_cpu_tq[cpu], &task); ``` -The benefits are the same as grouptasks, without the grouptask framework: work stays on the CPU it was produced on, CPU-local contention is eliminated, caches stay warm. The cost is that the driver manages its own per-CPU data structure. +好处与组任务相同,没有组任务框架:工作留在产生它的 CPU 上,CPU 本地争用被消除,缓存保持热。代价是驱动管理自己的每 CPU 数据结构。 -For `myfirst` this is overkill. For a driver whose event rate exceeds tens of thousands of events per second, per-CPU taskqueues are worth considering. Grouptaskqueues are more general and usually preferred when the scalability story matters; per-CPU taskqueues are the lighter-weight alternative. +对于 `myfirst` 这是过度杀伤。对于事件率超过每秒数万个事件的驱动,每 CPU 任务队列值得考虑。组任务队列更通用,通常在可扩展性故事重要时更受青睐;每 CPU 任务队列是更轻量的替代方案。 ### 何时使用哪种工具 -A short decision tree. +一个简短的决策树。 -- **Low-rate, thread-context, shared-queue is fine**: use `taskqueue_thread`. Easiest. -- **Low-rate, thread-context, isolation matters**: private taskqueue with `taskqueue_create` and `taskqueue_start_threads`. What `myfirst` uses. -- **High-rate, contention is the bottleneck**: per-CPU taskqueues or grouptaskqueues. Start with per-CPU; reach for grouptasks if you need the extra scalability features. -- **Network-path data**: `NET_TASK_INIT` and grouptaskqueues, following the patterns in network drivers. -- **Filter-interrupt context, must enqueue without sleeping**: `taskqueue_create_fast` or `taskqueue_fast`, since filter interrupts cannot use a sleep mutex. +- **低速率,线程上下文,共享队列即可**:使用 `taskqueue_thread`。最简单。 +- **低速率,线程上下文,隔离重要**:私有任务队列,用 `taskqueue_create` 和 `taskqueue_start_threads`。`myfirst` 使用的。 +- **高速率,争用是瓶颈**:每 CPU 任务队列或组任务队列。从每 CPU 开始;如果需要额外可扩展性特性则使用组任务。 +- **网络路径数据**:`NET_TASK_INIT` 和组任务队列,遵循网络驱动中的模式。 +- **过滤器中断上下文,必须不睡眠入队**:`taskqueue_create_fast` 或 `taskqueue_fast`,因为过滤器中断不能使用睡眠互斥锁。 -Most drivers you write or read will fit one of the first two lines. The remainder are specialised cases that their chapters will walk through. +你编写或阅读的大多数驱动将适合前两行之一。其余是需要其章节逐步讲解的专门情况。 ### 附加主题总结 @@ -2968,102 +2968,102 @@ Most drivers you write or read will fit one of the first two lines. The remainde 那就是工艺。本书其余部分带你通过它。 -## Reference: Pre-Production Taskqueue Audit +## 参考:预生产任务队列审计 -A short audit to perform before promoting a taskqueue-using driver from development to production. Each item is a question; each should be answerable with confidence. +在将使用任务队列的驱动从开发提升到生产之前要执行的简短审计。每个项目是一个问题;每个应该能够自信地回答。 -### Task Inventory +### 任务清单 -- [ ] Have I listed every task the driver owns in `LOCKING.md`? -- [ ] For each task, have I named its callback function? -- [ ] For each task, have I documented its lifetime (init in attach, drain in detach)? -- [ ] For each task, have I documented its trigger (what causes it to be enqueued)? -- [ ] For each task, have I documented whether it self-reenqueues or runs once per external trigger? -- [ ] For each timeout task, have I named the interval it is scheduled for and the cancellation path? +- [ ] 我是否在 `LOCKING.md` 中列出了驱动拥有的每个任务? +- [ ] 对于每个任务,我是否命名了其回调函数? +- [ ] 对于每个任务,我是否文档记录了其生命周期(attach 中初始化,分离中排空)? +- [ ] 对于每个任务,我是否文档记录了其触发器(什么导致它被入队)? +- [ ] 对于每个任务,我是否文档记录了它是自重新入队还是每次外部触发运行一次? +- [ ] 对于每个超时任务,我是否命名了它被调度的间隔和取消路径? -### Taskqueue Inventory +### 任务队列清单 -- [ ] Is the taskqueue a private queue or a predefined one? Is the choice justified? -- [ ] If private, does attach call `taskqueue_create` (or `taskqueue_create_fast`) before any code that could enqueue? -- [ ] If private, does attach call `taskqueue_start_threads` before any code that expects a callback to fire? -- [ ] Is the worker thread count appropriate for the workload? -- [ ] Is the worker thread priority appropriate for the workload? -- [ ] Is the worker thread name informative enough that `procstat -t` output is useful? +- [ ] 任务队列是私有队列还是预定义的?选择是否有理由? +- [ ] 如果是私有的,attach 是否在任何可能入队的代码之前调用 `taskqueue_create`(或 `taskqueue_create_fast`)? +- [ ] 如果是私有的,attach 是否在任何期望回调触发的代码之前调用 `taskqueue_start_threads`? +- [ ] 工作线程数量是否适合工作负载? +- [ ] 工作线程优先级是否适合工作负载? +- [ ] 工作线程名称是否足够信息丰富使 `procstat -t` 输出有用? -### Initialisation +### 初始化 -- [ ] Does every `TASK_INIT` happen after the softc is zeroed and before the task can be enqueued? -- [ ] Does every `TIMEOUT_TASK_INIT` reference the correct taskqueue and a valid callback? -- [ ] Does attach handle `taskqueue_create` failure by unwinding earlier initialisations? -- [ ] Does attach handle `taskqueue_start_threads` failure by freeing the taskqueue? +- [ ] 每个 `TASK_INIT` 是否在 softc 清零后、任务可以被入队前发生? +- [ ] 每个 `TIMEOUT_TASK_INIT` 是否引用了正确的任务队列和有效的回调? +- [ ] attach 是否通过回退较早初始化来处理 `taskqueue_create` 失败? +- [ ] attach 是否通过释放任务队列来处理 `taskqueue_start_threads` 失败? -### Enqueue Sites +### 入队点 -- [ ] Does every enqueue site target the right taskqueue pointer? -- [ ] Does every enqueue from an edge context (callout, interrupt filter) confirm the taskqueue exists before enqueuing? -- [ ] Is the enqueue call safe in the context it happens from (not inside a spin mutex if the taskqueue is `taskqueue_create`, for example)? -- [ ] Is the coalescing behaviour intentional at every enqueue site? +- [ ] 每个入队点是否指向正确的任务队列指针? +- [ ] 从边缘上下文(callout、中断过滤器)的每次入队是否在入队前确认任务队列存在? +- [ ] 入队调用在它发生的上下文中是否安全(例如,不是在自旋互斥锁内部如果任务队列是 `taskqueue_create`)? +- [ ] 合并行为在每个入队点是否是有意的? -### Callback Hygiene +### 回调卫生 -- [ ] Does every callback have the correct signature `(void *context, int pending)`? -- [ ] Does every callback acquire driver locks explicitly where needed? -- [ ] Does every callback release driver locks before calling `selwakeup`, `log`, or other functions that acquire unrelated locks? -- [ ] Does every callback avoid `M_NOWAIT` allocations where `M_WAITOK` is safe? -- [ ] Is the callback's total work time bounded? +- [ ] 每个回调是否有正确的签名 `(void *context, int pending)`? +- [ ] 每个回调是否在需要的地方显式获取驱动锁? +- [ ] 每个回调是否在调用 `selwakeup`、`log` 或其他获取无关锁的函数之前释放驱动锁? +- [ ] 每个回调是否在 `M_WAITOK` 安全的地方避免 `M_NOWAIT` 分配? +- [ ] 回调的总工作时间是否有界? -### Cancellation +### 取消 -- [ ] Does every `taskqueue_cancel` / `taskqueue_cancel_timeout` call happen under the right mutex if the cancellation race matters? -- [ ] Are the cases where cancel returns `EBUSY` handled (usually by a follow-up drain)? +- [ ] 每个 `taskqueue_cancel` / `taskqueue_cancel_timeout` 调用是否在取消竞争重要时在正确的互斥锁下发生? +- [ ] 取消返回 `EBUSY` 的情况是否被处理(通常通过后续排空)? -### Detach +### 分离 -- [ ] Does detach clear `is_attached` before draining callouts? -- [ ] Does detach drain every callout before draining any task? -- [ ] Does detach drain every task before calling `seldrain`? -- [ ] Does detach call `seldrain` before `taskqueue_free`? -- [ ] Does detach call `taskqueue_free` before destroying the mutex? -- [ ] Does detach set `sc->tq = NULL` after free? +- [ ] 分离是否在排空 callout 前清除 `is_attached`? +- [ ] 分离是否在排空任何任务前排空每个 callout? +- [ ] 分离是否在调用 `seldrain` 前排空每个任务? +- [ ] 分离是否在 `taskqueue_free` 前调用 `seldrain`? +- [ ] 分离是否在销毁互斥锁前调用 `taskqueue_free`? +- [ ] 分离是否在释放后将 `sc->tq` 设为 `NULL`? -### Documentation +### 文档 -- [ ] Is every task documented in `LOCKING.md`? -- [ ] Are the discipline rules (enqueue-safe, callback-lock, drain-order) documented? -- [ ] Is the taskqueue subsystem mentioned in the README? -- [ ] Are there sysctls exposed that let users observe the behaviour? +- [ ] 每个任务是否文档记录在 `LOCKING.md` 中? +- [ ] 纪律规则(入队安全、回调锁定、排空顺序)是否被文档记录? +- [ ] 任务队列子系统是否在 README 中提及? +- [ ] 是否有暴露的 sysctl 让用户观察行为? -### Testing +### 测试 -- [ ] Have I run the regression suite with `WITNESS` enabled? -- [ ] Have I tested detach with all tasks in flight? -- [ ] Have I run a long-duration stress test with high enqueue rates? -- [ ] Have I used `dtrace` to verify the enqueue-to-dispatch latency is within expectations? -- [ ] Have I used `procstat -kk` under load to confirm the taskqueue thread is not stuck? +- [ ] 我是否在启用 `WITNESS` 的情况下运行了回归套件? +- [ ] 我是否在所有任务进行中时测试了分离? +- [ ] 我是否在高入队率下运行了长持续时间压力测试? +- [ ] 我是否用 `dtrace` 验证了入队到调度延迟在预期范围内? +- [ ] 我是否在负载下用 `procstat -kk` 确认任务队列线程没有卡住? -A driver that passes this audit is a driver you can trust under load. +通过此审计的驱动是你在负载下可以信任的驱动。 -## Reference: Standardising Tasks Across a Driver +## 参考:在驱动中标准化任务 -For a driver with several tasks, consistency matters more than cleverness. A short discipline. +对于有几个任务的驱动,一致性比巧妙更重要。一个简短的纪律。 -### One Naming Convention +### 一个命名约定 -Pick a convention and follow it. The chapter's convention: +选择一个约定并遵循它。本章的约定: -- The task struct is named `_task` (e.g., `selwake_task`, `bulk_writer_task`). -- The timeout-task struct is named `_delayed_task` (e.g., `reset_delayed_task`). -- The callback is named `myfirst__task` (e.g., `myfirst_selwake_task`, `myfirst_bulk_writer_task`). -- The sysctl that enqueues the task (if one exists) is named `_enqueue` or `_flood` for bulk variants. -- The sysctl that configures the task (if one exists) is named `_` (e.g., `bulk_writer_batch`). +- 任务结构命名为 `_task`(例如,`selwake_task`、`bulk_writer_task`)。 +- 超时任务结构命名为 `_delayed_task`(例如,`reset_delayed_task`)。 +- 回调命名为 `myfirst__task`(例如,`myfirst_selwake_task`、`myfirst_bulk_writer_task`)。 +- 入队任务的 sysctl(如果有)命名为 `_enqueue` 或批量变体的 `_flood`。 +- 配置任务的 sysctl(如果有)命名为 `_`(例如,`bulk_writer_batch`)。 -A new maintainer can add a new task following the convention without thinking about names. Conversely, a code review immediately catches deviations. +新的维护者可以按照约定添加新任务而不用想名字。反之,代码审查立即捕获偏差。 -### One Init/Drain Pattern +### 一个初始化/排空模式 -Every task uses the same initialisation and drain: +每个任务使用相同的初始化和排空: ```c /* In attach, after taskqueue_start_threads: */ @@ -3073,7 +3073,7 @@ TASK_INIT(&sc->_task, 0, myfirst__task, sc); taskqueue_drain(sc->tq, &sc->_task); ``` -For timeout tasks: +对于超时任务: ```c /* In attach: */ @@ -3084,11 +3084,11 @@ TIMEOUT_TASK_INIT(sc->tq, &sc->_delayed_task, 0, taskqueue_drain_timeout(sc->tq, &sc->_delayed_task); ``` -The call sites are short and uniform. A reviewer can scan for the pattern and flag deviations instantly. +调用点简短且统一。审查者可以扫描模式并立即标记偏差。 -### One Callback Pattern +### 一个回调模式 -Every task callback follows the same structure: +每个任务回调遵循相同结构: ```c static void @@ -3107,189 +3107,189 @@ myfirst__task(void *arg, int pending) } ``` -The optional coalescing record makes the coalescing behaviour visible through sysctls. Drop it if the task rarely coalesces or if the counter would not be useful. +可选的合并记录通过 sysctl 使合并行为可见。如果任务很少合并或计数器没有用,可以去掉它。 -### One Documentation Pattern +### 一个文档模式 -Every task is documented in `LOCKING.md` with the same fields: +每个任务在 `LOCKING.md` 中以相同字段文档记录: -- Task name and kind (plain or timeout_task). -- Callback function. -- Which code paths enqueue it. -- Which code paths cancel it (if any). -- Where it is drained at detach. -- What lock, if any, the callback acquires. -- Why this task is deferred (i.e., why it cannot run in the enqueue context). +- 任务名称和种类(普通或 timeout_task)。 +- 回调函数。 +- 哪些代码路径入队它。 +- 哪些代码路径取消它(如果有)。 +- 在分离时在哪里排空它。 +- 回调获取什么锁(如果有)。 +- 为什么此工作被延迟(即,为什么它不能在入队上下文中运行)。 -A new task's documentation is mechanical. A code review can verify the documentation against the code. +新任务的文档是机械的。代码审查可以对照代码验证文档。 -### Why Standardise +### 为什么要标准化 -Standardisation has costs: a new contributor must learn the conventions; deviations require a special reason. The benefits are larger: +标准化有成本:新贡献者必须学习约定;偏差需要特殊理由。但好处更大: -- Reduced cognitive load. A reader who knows the pattern instantly understands every task. -- Fewer mistakes. The standard pattern handles the common cases (init in attach, drain in detach, drop lock before selwakeup) correctly; a deviation is more likely to be wrong. -- Easier review. Reviewers can scan for shape rather than reading every line. -- Easier handoff. A maintainer who has not seen the driver can add a new task following the existing template. +- 减少认知负担。了解模式的读者立即理解每个任务。 +- 更少错误。标准模式正确处理常见情况(attach 中初始化、分离中排空、selwakeup 前释放锁);偏差更可能是错误的。 +- 更容易审查。审查者可以扫描形态而不是逐行阅读。 +- 更容易交接。未见过驱动的维护者可以按照现有模板添加新任务。 -The cost of standardisation is paid once at design time. The benefits accrue forever. Always worth it. +标准化的成本在设计时支付一次。好处永远累积。总是值得的。 ## Reference: Further Reading on Taskqueues -For readers who want to go deeper. +供希望深入学习的读者参考。 -### Manual Pages +### 手册页 -- `taskqueue(9)`: the canonical API reference. -- `epoch(9)`: the epoch synchronisation framework, relevant for network tasks. -- `callout(9)`: the companion primitive; timeout_task is built on top of it. -- `swi_add(9)`: the software-interrupt registration used by `taskqueue_swi` and friends. -- `kproc(9)`, `kthread(9)`: direct kernel-thread creation, for when a taskqueue is not enough. +- `taskqueue(9)`:权威 API 参考。 +- `epoch(9)`:epoch 同步框架,与网络任务相关。 +- `callout(9)`:相伴原语;`timeout_task` 建立在它之上。 +- `swi_add(9)`:`taskqueue_swi` 及相关队列使用的软件中断注册接口。 +- `kproc(9)`、`kthread(9)`:直接创建内核线程的接口,适用于 taskqueue 不够用的场景。 -### Source Files +### 源代码文件 -- `/usr/src/sys/kern/subr_taskqueue.c`: the taskqueue implementation. Read `taskqueue_run_locked` carefully; it is the heart of the subsystem. -- `/usr/src/sys/sys/taskqueue.h`, `/usr/src/sys/sys/_task.h`: the public API and structures. -- `/usr/src/sys/kern/subr_gtaskqueue.c`, `/usr/src/sys/sys/gtaskqueue.h`: the grouptaskqueue layer. -- `/usr/src/sys/sys/epoch.h`, `/usr/src/sys/kern/subr_epoch.c`: the epoch framework. -- `/usr/src/sys/dev/ale/if_ale.c`: a clean Ethernet driver using taskqueues. -- `/usr/src/sys/dev/bge/if_bge.c`: a larger Ethernet driver with multiple tasks. -- `/usr/src/sys/dev/wg/if_wg.c`: WireGuard's grouptaskqueue usage. -- `/usr/src/sys/dev/iwm/if_iwm.c`: a wireless driver with timeout tasks. -- `/usr/src/sys/dev/usb/usb_process.c`: USB's dedicated per-device process queue (`usb_proc_*`). +- `/usr/src/sys/kern/subr_taskqueue.c`:taskqueue 的实现。仔细阅读 `taskqueue_run_locked`;它是该子系统的核心。 +- `/usr/src/sys/sys/taskqueue.h`、`/usr/src/sys/sys/_task.h`:公共 API 和数据结构。 +- `/usr/src/sys/kern/subr_gtaskqueue.c`、`/usr/src/sys/sys/gtaskqueue.h`:grouptaskqueue 层。 +- `/usr/src/sys/sys/epoch.h`、`/usr/src/sys/kern/subr_epoch.c`:epoch 框架。 +- `/usr/src/sys/dev/ale/if_ale.c`:一个使用 taskqueue 的简洁以太网驱动。 +- `/usr/src/sys/dev/bge/if_bge.c`:一个使用多个任务的较大以太网驱动。 +- `/usr/src/sys/dev/wg/if_wg.c`:WireGuard 的 grouptaskqueue 用法。 +- `/usr/src/sys/dev/iwm/if_iwm.c`:一个使用 timeout task 的无线驱动。 +- `/usr/src/sys/dev/usb/usb_process.c`:USB 专用的每设备进程队列(`usb_proc_*`)。 -### Manual Pages To Read in Order +### 手册页阅读顺序 -For a reader new to FreeBSD's deferred-work subsystem: +对于初学 FreeBSD 延迟工作子系统的读者: -1. `taskqueue(9)`: the canonical API. -2. `epoch(9)`: the lockless read-synchronisation framework. -3. `callout(9)`: the sibling timed-execution primitive. -4. `swi_add(9)`: the software-interrupt layer beneath some taskqueues. -5. `kthread(9)`: the direct-thread-creation alternative. +1. `taskqueue(9)`:权威 API。 +2. `epoch(9)`:无锁读同步框架。 +3. `callout(9)`:兄弟定时执行原语。 +4. `swi_add(9)`:部分 taskqueue 底层的软件中断层。 +5. `kthread(9)`:直接创建线程的替代方案。 -Each builds on the previous; reading in order takes a couple of hours and gives you a solid mental model of the kernel's deferred-work infrastructure. +每个手册页都建立在前一个的基础之上;按顺序阅读只需几个小时,就能对内核的延迟工作基础设施建立扎实的心智模型。 -### External Material +### 外部资料 -The chapter on synchronization in *The Design and Implementation of the FreeBSD Operating System* (McKusick et al.) covers the historical evolution of deferred-work subsystems. Useful as context; not required. +*The Design and Implementation of the FreeBSD Operating System*(McKusick 等著)中关于同步的章节涵盖了延迟工作子系统的历史演变。作为背景阅读很有用,但非必需。 -The FreeBSD developers' mailing list (`freebsd-hackers@`) occasionally discusses taskqueue improvements and edge cases. Searching the archive for "taskqueue" returns relevant historical context. +FreeBSD 开发者邮件列表(`freebsd-hackers@`)偶尔会讨论 taskqueue 的改进和边缘情况。在归档中搜索 "taskqueue" 可以找到相关的历史背景。 -For deeper understanding of the network stack's use of `epoch(9)` and grouptaskqueues, the `iflib(9)` framework documentation and the source under `/usr/src/sys/net/iflib.c` are worth a read. They are beyond the level of this chapter, but they explain why modern network drivers are structured the way they are. +若要深入理解网络栈对 `epoch(9)` 和 grouptaskqueue 的使用,`iflib(9)` 框架文档和 `/usr/src/sys/net/iflib.c` 下的源代码值得一读。它们超出了本章的范围,但解释了现代网络驱动之所以如此架构的原因。 -Finally, real driver source. Pick any driver in `/usr/src/sys/dev/` that uses taskqueues (most do), read its taskqueue-related code, and compare it to the patterns in this chapter. The translation is direct; you will recognize the shapes immediately. That kind of reading turns the chapter's abstractions into working knowledge. +最后,真实的驱动源代码。在 `/usr/src/sys/dev/` 中挑选任何使用 taskqueue 的驱动(大多数都使用),阅读其 taskqueue 相关代码,并与本章的模式进行比较。这种对应是直接的;你会立刻认出那些模式。这种阅读能将本章的抽象概念转化为实际的工作知识。 ## Reference: Taskqueue Cost Analysis -A short discussion of what taskqueues actually cost, useful when deciding whether to defer or whether to create a private queue. +简要讨论 taskqueue 的实际开销,有助于决定是否延迟执行或是否创建私有队列。 -### Cost At Rest +### 静态开销 -A `struct task` that has not been enqueued costs nothing beyond the sizeof the structure (32 bytes on amd64). The kernel does not know about it. It sits in your softc, doing nothing. +一个未入队的 `struct task` 除了结构体本身的大小(amd64 上为 32 字节)之外没有额外开销。内核并不感知它的存在。它静静地待在你的 softc 中,什么也不做。 -A `struct taskqueue` allocated and idle costs: -- The taskqueue structure itself (a few hundred bytes). -- One or more worker threads (16 KB stack each on amd64, plus scheduler state). -- No per-enqueue cost at rest. +一个已分配但空闲的 `struct taskqueue` 的开销: +- taskqueue 结构体本身(几百字节)。 +- 一个或多个工作线程(amd64 上每个 16 KB 栈,外加调度器状态)。 +- 空闲时没有每次入队的开销。 -### Cost Per Enqueue +### 每次入队的开销 -When you call `taskqueue_enqueue(tq, &task)`, the kernel does: +当你调用 `taskqueue_enqueue(tq, &task)` 时,内核执行以下操作: -1. Acquire the taskqueue's internal mutex. Microseconds. -2. Check whether the task is already pending. Constant time. -3. If not pending, link into the list and wake the worker (via `wakeup` on the queue). Constant time plus a scheduler event. -4. If already pending, increment `ta_pending`. Single arithmetic. -5. Release the mutex. +1. 获取 taskqueue 的内部互斥锁。微秒级。 +2. 检查任务是否已处于待处理状态。常数时间。 +3. 如果未待处理,链接到列表中并唤醒工作线程(通过 `wakeup`)。常数时间加一个调度事件。 +4. 如果已待处理,递增 `ta_pending`。单次算术运算。 +5. 释放互斥锁。 -The total cost is microseconds on an uncontended queue. Under contention the mutex acquisition can take longer, but the framework uses a padalign mutex to minimise false sharing, and the mutex is rarely held for more than a few instructions. +在无竞争的队列上,总开销为微秒级。在存在竞争时,互斥锁获取可能需要更长时间,但框架使用填充对齐的互斥锁来最小化伪共享,且互斥锁很少被持有超过几条指令的时间。 -### Cost Per Dispatch +### 每次分发的开销 -When the worker thread wakes and runs `taskqueue_run_locked`, the per-task cost is: +当工作线程被唤醒并运行 `taskqueue_run_locked` 时,每个任务的开销为: -1. Walk to the head of the queue. Constant time. -2. Pull the task off. Constant time. -3. Record the pending count, reset it. Constant time. -4. Drop the mutex. -5. Enter any required epoch (for network tasks). -6. Call the callback. Cost depends on the callback. -7. Exit epoch if entered. -8. Re-acquire the mutex for the next iteration. +1. 步进到队列头部。常数时间。 +2. 取下任务。常数时间。 +3. 记录待处理计数,重置它。常数时间。 +4. 释放互斥锁。 +5. 进入所需的 epoch(对于网络任务)。 +6. 调用回调函数。开销取决于回调。 +7. 如果进入了 epoch 则退出。 +8. 为下一次迭代重新获取互斥锁。 -For a typical short callback (microseconds of work), the per-dispatch overhead is dominated by the callback itself plus one mutex round-trip and one wakeup round-trip. +对于一个典型的短回调(微秒级的工作),每次分发的开销主要由回调本身加上一次互斥锁往返和一次唤醒往返构成。 -### Cost At Cancel/Drain +### 取消/排空时的开销 -`taskqueue_cancel` is fast: mutex acquisition, list removal if pending, mutex release. Microseconds. +`taskqueue_cancel` 很快:获取互斥锁、如果待处理则从列表中移除、释放互斥锁。微秒级。 -`taskqueue_drain` is fast if the task is idle. If the task is pending, the drain waits for it to run and complete; duration depends on queue depth and callback duration. If the task is running, the drain waits for the current invocation to return. +`taskqueue_drain` 在任务空闲时很快。如果任务待处理,排空会等待它运行并完成;持续时间取决于队列深度和回调时长。如果任务正在运行,排空会等待当前调用返回。 -`taskqueue_drain_all` is more expensive: it must wait for every task in the queue. Duration is proportional to the total work remaining. +`taskqueue_drain_all` 开销更大:它必须等待队列中的每个任务。持续时间与剩余总工作量成正比。 -`taskqueue_free` drains the queue, terminates the threads, and frees the state. The thread termination involves signalling each thread to exit and waiting for it to finish its current task. Microseconds to milliseconds depending on queue depth. +`taskqueue_free` 会排空队列、终止线程并释放状态。线程终止涉及通知每个线程退出并等待其完成当前任务。微秒到毫秒级,取决于队列深度。 -### Practical Implications +### 实际影响 -A few practical notes. +一些实践要点。 -**Single-thread taskqueues are cheap.** The per-instance cost is a few hundred bytes plus a 16-KB thread stack. On any realistic system, this is negligible. +**单线程 taskqueue 很便宜。** 每个实例的开销是几百字节加一个 16 KB 的线程栈。在任何实际系统中,这都可以忽略不计。 -**Shared taskqueues are cheaper per driver but contended.** `taskqueue_thread` is used by every driver that does not create its own. Under heavy load it becomes a serial bottleneck. For drivers with significant task traffic, a private queue avoids the contention. +**共享 taskqueue 每个驱动更便宜但存在竞争。** `taskqueue_thread` 被每个未创建自己队列的驱动使用。在高负载下它成为串行瓶颈。对于有显著任务流量的驱动,私有队列可以避免竞争。 -**Multi-thread taskqueues trade memory for parallelism.** Four threads is four 16-KB stacks plus four scheduler entries. Worthwhile when the workload is naturally parallel; wasted when the workload serialises on a single driver mutex. +**多线程 taskqueue 用内存换取并行性。** 四个线程就是四个 16 KB 的栈加四个调度器条目。在工作负载天然并行时值得;在工作负载在单个驱动互斥锁上串行化时则浪费。 -**Coalescing is free performance.** When enqueues come faster than the taskqueue can dispatch, coalescing folds the bursts into single firings. The driver pays one callback invocation for whatever work the `pending` count implies. +**合并是免费的性能提升。** 当入队速度超过 taskqueue 的分发速度时,合并将突发请求折叠为单次触发。驱动为 `pending` 计数所隐含的任何工作量支付一次回调调用。 -### Comparison To Other Approaches +### 与其他方法的比较 -A kernel thread created with `kproc_create` and managed by the driver costs: -- 16 KB stack plus scheduler entry (same as a taskqueue worker). -- No built-in enqueue/dispatch framework: the driver rolls its own queue and wakeup. -- No built-in coalescing or cancellation. +使用 `kproc_create` 创建并由驱动管理的内核线程的开销: +- 16 KB 栈加调度器条目(与 taskqueue 工作线程相同)。 +- 没有内置的入队/分发框架:驱动需要自行实现队列和唤醒。 +- 没有内置的合并或取消功能。 -For work that fits the task model (enqueue, dispatch, drain), a taskqueue is always the right choice. For work that does not (a long-running loop with its own rhythm), a `kproc_create` thread may fit better. +对于符合任务模型(入队、分发、排空)的工作,taskqueue 始终是正确的选择。对于不符合的工作(一个有自己节奏的长时间循环),`kproc_create` 线程可能更合适。 -A callout that enqueues a task combines the costs of both primitives. Worthwhile when the work needs both a specific deadline and thread context. +一个入队任务的 callout 结合了两种原语的开销。当工作既需要特定截止时间又需要线程上下文时值得使用。 -### When To Worry About Cost +### 何时需要担心开销 -Most drivers do not have to. Taskqueues are cheap; the kernel is well-tuned. Worry about cost only when: +大多数驱动不需要。Taskqueue 很便宜;内核经过了良好的调优。只在以下情况担心开销: -- Profiling shows taskqueue operations dominate CPU usage. (Use `dtrace` to confirm.) -- You are writing a high-rate driver (thousands of events per second or more) and the taskqueue is the serialisation point. -- The system has many drivers competing for `taskqueue_thread` and contention is measurable. +- 性能分析显示 taskqueue 操作主导了 CPU 使用。(用 `dtrace` 确认。) +- 你正在编写高速率驱动(每秒数千事件或更多),且 taskqueue 是串行化点。 +- 系统有许多驱动竞争 `taskqueue_thread`,且竞争可被测量。 -In all other cases, write the taskqueue naturally and trust the kernel to handle the load. +在所有其他情况下,自然地编写 taskqueue 代码,相信内核能处理负载。 ## Reference: The Task Coalescing Semantics, Precisely -Coalescing is the feature that most often surprises newcomers. A precise statement of the semantics, with worked examples, is worth its own reference subsection. +合并(coalescing)是最常让新手感到困惑的特性。精确地陈述其语义并配合实例,值得单独作为一个参考小节。 -### The Rule +### 规则 -When `taskqueue_enqueue(tq, &task)` is called on a task that is already pending (`task->ta_pending > 0`), the kernel increments `task->ta_pending` and returns success. The task is not linked onto the queue a second time. When the callback eventually runs, it runs exactly once, with the accumulated `ta_pending` value passed as its second argument (and the field is reset to zero before the callback is called). +当对一个已经处于待处理状态(`task->ta_pending > 0`)的任务调用 `taskqueue_enqueue(tq, &task)` 时,内核递增 `task->ta_pending` 并返回成功。任务不会被第二次链接到队列上。当回调最终运行时,它恰好运行一次,并将累积的 `ta_pending` 值作为第二个参数传入(该字段在回调被调用前重置为零)。 -The rule has edge cases worth naming. +这条规则有一些值得指出的边界情况。 -**The cap.** `ta_pending` is a `uint16_t`. It saturates at `USHRT_MAX` (65535). Enqueues past that point still return success but the counter does not grow further. In practice, reaching 65535 coalesced enqueues is a design problem, not a performance problem. +**上限。** `ta_pending` 是一个 `uint16_t`。它在 `USHRT_MAX`(65535)处饱和。超过该点的入队仍然返回成功,但计数器不再增长。在实践中,达到 65535 次合并入队是一个设计问题,而非性能问题。 -**The `TASKQUEUE_FAIL_IF_PENDING` flag.** If you pass this flag to `taskqueue_enqueue_flags`, the function returns `EEXIST` instead of coalescing. Useful when you want to know whether the enqueue produced a new pending state. +**`TASKQUEUE_FAIL_IF_PENDING` 标志。** 如果向 `taskqueue_enqueue_flags` 传入此标志,函数返回 `EEXIST` 而不是合并。当你想知道入队是否产生了新的待处理状态时很有用。 -**Timing.** The coalescing happens at enqueue time. If enqueue A and enqueue B both happen while the task is pending, both coalesce. If enqueue A causes the task to start running, and enqueue B happens while the callback is executing, enqueue B makes the task pending again (pending=1) and the callback will be invoked again after the current invocation returns. The second invocation sees `pending=1` because only B has accumulated. Both the first and second invocations happen; no enqueue is lost. +**时序。** 合并发生在入队时刻。如果入队 A 和入队 B 都在任务待处理期间发生,两者都会合并。如果入队 A 导致任务开始运行,而入队 B 在回调执行期间发生,入队 B 使任务再次变为待处理(pending=1),回调将在当前调用返回后再次被调用。第二次调用看到 `pending=1`,因为只有 B 被累积了。第一次和第二次调用都会发生;没有入队会丢失。 -**Priority.** If two different tasks are pending on the same queue and one has higher priority, the higher-priority one runs first regardless of enqueue order. Within a single task, priority is not a factor; all invocations of a given task run in sequence. +**优先级。** 如果同一队列上有两个不同的任务待处理,且其中一个优先级更高,则高优先级的先运行,不管入队顺序如何。对于单个任务,优先级不是影响因素;给定任务的所有调用按顺序运行。 -### Worked Examples +### 实例解析 -**Example 1: Simple single enqueue.** +**示例 1:简单单次入队。** ```c taskqueue_enqueue(tq, &task); @@ -3297,7 +3297,7 @@ taskqueue_enqueue(tq, &task); /* Callback sees pending == 1. */ ``` -**Example 2: Coalesced enqueue before dispatch.** +**示例 2:分发前的合并入队。** ```c taskqueue_enqueue(tq, &task); @@ -3308,7 +3308,7 @@ taskqueue_enqueue(tq, &task); /* Callback sees pending == 3. */ ``` -**Example 3: Enqueue during callback execution.** +**示例 3:回调执行期间的入队。** ```c taskqueue_enqueue(tq, &task); @@ -3320,7 +3320,7 @@ taskqueue_enqueue(tq, &task); /* Second callback invocation sees pending == 1. */ ``` -**Example 4: Cancel before dispatch.** +**示例 4:分发前的取消。** ```c taskqueue_enqueue(tq, &task); @@ -3330,7 +3330,7 @@ taskqueue_cancel(tq, &task, &pendp); /* pendp == 2; callback does not run. */ ``` -**Example 5: Cancel during execution.** +**示例 5:执行期间的取消。** ```c taskqueue_enqueue(tq, &task); @@ -3341,23 +3341,23 @@ taskqueue_cancel(tq, &task, &pendp); /* The currently executing invocation completes; the cancellation affects only future runs. */ ``` -### Design Implications +### 设计影响 -A few design implications follow from the rule. +从上述规则可以得出几个设计影响。 -**Your callback must be idempotent over `pending`.** Writing a callback that assumes `pending==1` breaks under load. Always use `pending` deliberately, either by looping `pending` times or by doing a single pass that handles whatever state has accumulated. +**回调必须对 `pending` 具有幂等性。** 编写假设 `pending==1` 的回调在高负载下会出问题。始终有意识地使用 `pending`,要么循环 `pending` 次,要么做一次处理累积状态的遍历。 -**Do not use "number of callback invocations" as a count of events.** Use `pending` from each invocation, summed. Or, better, use a per-event state structure (a queue inside the softc) that the callback drains. +**不要用"回调调用次数"作为事件计数。** 使用每次调用中的 `pending` 值求和。或者更好的方式,使用一个按事件的状态结构(softc 内部的队列)让回调去排空。 -**Coalescing changes per-event work into per-burst work.** A callback that does O(1) work per invocation, with `pending` discarded, handles the same amount of work regardless of enqueue rate. That is usually fine for "notify waiters" kinds of work; it is wrong for "process each event" kinds of work. +**合并将按事件的工作变为按突发的工作。** 一个每次调用做 O(1) 工作并丢弃 `pending` 的回调,无论入队速率如何都处理相同数量的工作。这对"通知等待者"类工作通常没问题;但对"处理每个事件"类工作则不对。 -**Coalescing lets you enqueue freely from edge contexts.** A callout that fires every millisecond can enqueue a task every millisecond; if the callback takes 10 ms to run, nine enqueues coalesce into one invocation per callback. The system converges naturally on the throughput the callback can sustain. +**合并让你可以自由地从边缘上下文入队。** 一个每毫秒触发的 callout 可以每毫秒入队一个任务;如果回调需要 10 毫秒运行,九次入队会合并为每次回调的一次调用。系统自然地收敛到回调所能维持的吞吐量。 ## Reference: The Taskqueue State Diagram -A short state diagram for a single task, as an aid to reasoning about the lifecycle. +一个简短的单任务状态图,作为推理生命周期的辅助工具。 ```text +-----------+ @@ -3388,39 +3388,39 @@ A short state diagram for a single task, as an aid to reasoning about the lifecy +-----------+ ``` -A task is always in exactly one of three states: IDLE, PENDING, or RUNNING. +一个任务始终处于以下三种状态之一:IDLE(空闲)、PENDING(待处理)或 RUNNING(运行中)。 -**IDLE.** Not on any queue. `ta_pending == 0`. Enqueue moves it to PENDING. +**IDLE。** 不在任何队列上。`ta_pending == 0`。入队操作将其转移到 PENDING。 -**PENDING.** On the taskqueue's pending list. `ta_pending >= 1`. Coalescing increments `ta_pending` without leaving PENDING. Cancellation moves it back to IDLE. +**PENDING。** 在 taskqueue 的待处理列表上。`ta_pending >= 1`。合并操作递增 `ta_pending` 但不离开 PENDING 状态。取消操作将其移回 IDLE。 -**RUNNING.** In `tq_active`, with the callback executing. `ta_pending` has been reset to zero, and the callback has received the previous value. New enqueues transition back to PENDING (so after the callback returns, the worker fires it again). Cancellation returns `EBUSY` in this state. +**RUNNING。** 在 `tq_active` 中,回调正在执行。`ta_pending` 已被重置为零,回调已收到先前的值。新的入队会转换回 PENDING(因此回调返回后,工作线程会再次触发它)。在此状态下取消返回 `EBUSY`。 -The state transitions are all serialised by `tq_mutex`. At any instant, the kernel can tell you which state a task is in, and the transitions are atomic. +所有状态转换都由 `tq_mutex` 串行化。在任何时刻,内核都能告诉你任务处于哪个状态,且转换是原子的。 -`taskqueue_drain(tq, &task)` waits until the task is IDLE and no new enqueues arrive before returning. That is the precise guarantee the drain provides. +`taskqueue_drain(tq, &task)` 等待直到任务处于 IDLE 状态且没有新的入队到达后才返回。这是排空操作提供的精确保证。 ## Reference: Observability Cheat Sheet -For quick reference during debugging. +调试时的快速参考。 -### List Every Taskqueue Thread +### 列出所有 Taskqueue 线程 ```text # procstat -t | grep taskq ``` -### List Every Task Submission Rate With DTrace +### 用 DTrace 列出所有任务提交速率 ```text # dtrace -n 'fbt::taskqueue_enqueue:entry { @[(caddr_t)arg1] = count(); }' -c 'sleep 10' ``` -The script counts enqueues per task pointer over ten seconds. The task pointers map back to drivers via `addr2line` or `kgdb`. +该脚本在十秒内统计每个任务指针的入队次数。任务指针可以通过 `addr2line` 或 `kgdb` 映射回驱动。 -### Measure Dispatch Latency +### 测量分发延迟 ```text # dtrace -n ' @@ -3432,7 +3432,7 @@ The script counts enqueues per task pointer over ten seconds. The task pointers ' -c 'sleep 10' ``` -### Measure Callback Duration +### 测量回调持续时间 ```text # dtrace -n ' @@ -3444,40 +3444,40 @@ The script counts enqueues per task pointer over ten seconds. The task pointers ' -c 'sleep 10' ``` -### Stack Trace of the Taskqueue Thread When Stuck +### Taskqueue 线程卡住时的栈跟踪 ```text # procstat -kk ``` -### Active Tasks Inside ddb +### ddb 中的活跃任务 -From the `ddb` prompt: +在 `ddb` 提示符下: ```text db> show taskqueues ``` -Lists every taskqueue, its active task (if any), and the pending queue. +列出每个 taskqueue、其活跃任务(如果有)和待处理队列。 -### Sysctl Knobs Your Driver Should Provide +### 驱动应提供的 Sysctl 旋钮 -For every task the driver owns, consider exposing: +对于驱动拥有的每个任务,考虑暴露: -- `_enqueues`: total enqueues attempted. -- `_coalesced`: count of times coalescing fired. -- `_runs`: total callback invocations. -- `_largest_pending`: peak pending count. +- `_enqueues`:尝试的入队总数。 +- `_coalesced`:合并发生的次数。 +- `_runs`:回调调用总数。 +- `_largest_pending`:峰值待处理计数。 -Under normal conditions: `enqueues == runs + coalesced`. Under coalescing: `runs < enqueues`. Under no load: `largest_pending == 1`. Under heavy load: `largest_pending` grows. +正常条件下:`enqueues == runs + coalesced`。合并条件下:`runs < enqueues`。无负载时:`largest_pending == 1`。高负载时:`largest_pending` 增长。 -These counters turn opaque driver behaviour into a readable sysctl display. The cost is a few atomic adds; the value is high. +这些计数器将不透明的驱动行为转化为可读的 sysctl 显示。开销只是几次原子加法;价值很高。 ## Reference: A Minimal Working Task Template -For copy-and-adapt convenience. Every piece has been introduced in the chapter; the template assembles them into a ready-to-use skeleton. +供复制和修改之用。每个部分都已在正文中介绍过;模板将它们组装成一个可直接使用的骨架。 ```c #include @@ -3564,101 +3564,101 @@ example_trigger_work(struct example_softc *sc) } ``` -Every element is essential. Dropping any of them reintroduces a bug this chapter warned against. +每个要素都是必不可少的。删掉任何一个都会重新引入本章警告过的 bug。 ## Reference: Comparison With Linux Workqueues -A short comparison for readers coming from Linux kernel work. Both systems solve the same problem; the differences are in naming, granularity, and defaults. +供来自 Linux 内核开发的读者参考的简短比较。两个系统解决相同的问题;差异在于命名、粒度和默认值。 -### Naming +### 命名 -| Concept | FreeBSD | Linux | +| 概念 | FreeBSD | Linux | |---|---|---| -| Unit of deferred work | `struct task` | `struct work_struct` | -| Queue | `struct taskqueue` | `struct workqueue_struct` | -| Shared queue | `taskqueue_thread` | `system_wq` | -| Unbound queue | `taskqueue_thread` with many threads | `system_unbound_wq` | -| Create a queue | `taskqueue_create` | `alloc_workqueue` | -| Enqueue | `taskqueue_enqueue` | `queue_work` | -| Enqueue with delay | `taskqueue_enqueue_timeout` | `queue_delayed_work` | -| Wait for work to finish | `taskqueue_drain` | `flush_work` | -| Destroy a queue | `taskqueue_free` | `destroy_workqueue` | -| Priority | `ta_priority` | `WQ_HIGHPRI` flag | -| Coalescing behaviour | Automatic, `pending` count exposed | `work_pending` check, no count | +| 延迟工作单元 | `struct task` | `struct work_struct` | +| 队列 | `struct taskqueue` | `struct workqueue_struct` | +| 共享队列 | `taskqueue_thread` | `system_wq` | +| 无绑定队列 | `taskqueue_thread`(多线程) | `system_unbound_wq` | +| 创建队列 | `taskqueue_create` | `alloc_workqueue` | +| 入队 | `taskqueue_enqueue` | `queue_work` | +| 延迟入队 | `taskqueue_enqueue_timeout` | `queue_delayed_work` | +| 等待工作完成 | `taskqueue_drain` | `flush_work` | +| 销毁队列 | `taskqueue_free` | `destroy_workqueue` | +| 优先级 | `ta_priority` | `WQ_HIGHPRI` 标志 | +| 合并行为 | 自动,暴露 `pending` 计数 | `work_pending` 检查,无计数 | -### Semantic Differences +### 语义差异 -**Coalescing visibility.** FreeBSD exposes the pending count to the callback; Linux does not. A Linux callback knows the work fired but not how many times it was requested. +**合并可见性。** FreeBSD 将待处理计数暴露给回调;Linux 不暴露。Linux 回调知道工作被触发了,但不知道被请求了多少次。 -**Timeout task vs. delayed work.** FreeBSD's `timeout_task` embeds a callout; Linux's `delayed_work` embeds a `timer_list`. Both behave the same from the user's point of view. +**超时任务 vs 延迟工作。** FreeBSD 的 `timeout_task` 嵌入了一个 callout;Linux 的 `delayed_work` 嵌入了一个 `timer_list`。从用户角度看两者行为相同。 -**Grouptaskqueues vs. percpu workqueues.** FreeBSD's `taskqgroup` is explicit and separate; Linux's `alloc_workqueue(..., WQ_UNBOUND | WQ_CPU_INTENSIVE)` has similar semantics with different knobs. +**Grouptaskqueue vs percpu 工作队列。** FreeBSD 的 `taskqgroup` 是显式且独立的;Linux 的 `alloc_workqueue(..., WQ_UNBOUND | WQ_CPU_INTENSIVE)` 有类似的语义但旋钮不同。 -**Epoch integration.** FreeBSD has `NET_TASK_INIT` for tasks that run inside the network epoch; Linux does not have a direct analogue (the RCU framework is similar but not identical). +**Epoch 集成。** FreeBSD 有 `NET_TASK_INIT` 用于在网络 epoch 内运行的任务;Linux 没有直接对应物(RCU 框架类似但不完全相同)。 -A driver ported from Linux to FreeBSD (or vice versa) can usually translate the deferred-work pattern nearly one-to-one. The structural differences are in the surrounding APIs (device registration, memory allocation, locking) more than in the taskqueue itself. +从 Linux 移植到 FreeBSD(或反之)的驱动通常可以几乎一一对应地翻译延迟工作模式。结构差异更多在周围的 API(设备注册、内存分配、锁定)而非 taskqueue 本身。 ## Reference: When Not To Use a Taskqueue -A short list of scenarios where another primitive is preferable. +简短列出其他原语更合适的场景。 -**The work has tight timing requirements.** Taskqueues add scheduling latency. For microsecond-scale deadlines, a `C_DIRECT_EXEC` callout or a `taskqueue_swi` is faster. For nanosecond-scale deadlines, none of the deferred-work mechanisms is fast enough; the work needs to happen inline. +**工作有严格的时序要求。** Taskqueue 会增加调度延迟。对于微秒级截止时间,`C_DIRECT_EXEC` callout 或 `taskqueue_swi` 更快。对于纳秒级截止时间,所有延迟工作机制都不够快;工作需要内联执行。 -**The work is a one-shot cleanup that has no producer to associate with.** A simple `free` inside a teardown path does not need a taskqueue; just call it directly. Deferral for deferral's sake adds no value. +**工作是一次性清理,没有关联的生产者。** 在拆卸路径中的简单 `free` 不需要 taskqueue;直接调用即可。为延迟而延迟没有任何价值。 -**The work must run at a specific scheduler priority higher than `PWAIT`.** If the work is genuinely high-priority (a real-time driver, an interrupt-threshold task), use `kthread_add` with an explicit priority rather than a generic taskqueue. +**工作必须在高于 `PWAIT` 的特定调度器优先级运行。** 如果工作是真正的高优先级(实时驱动、中断阈值任务),使用 `kthread_add` 配合显式优先级,而不是通用 taskqueue。 -**The work requires a specific thread context that a generic worker cannot provide.** Tasks run in a kernel thread with no specific user-process context. Work that needs a specific user's credentials, file-descriptor table, or address space must happen inside that process, not in a task. +**工作需要通用工作线程无法提供的特定线程上下文。** 任务在没有特定用户进程上下文的内核线程中运行。需要特定用户凭据、文件描述符表或地址空间的工作必须在该进程内完成,而不是在任务中。 -**The driver has only one task and it runs rarely.** A single `kthread_add` with a `cv_timedwait` loop may be clearer than the full taskqueue setup. Use judgment; for three or more tasks, taskqueues are almost always clearer. +**驱动只有一个任务且很少运行。** 一个使用 `cv_timedwait` 循环的 `kthread_add` 可能比完整的 taskqueue 设置更清晰。自行判断;对于三个或更多任务,taskqueue 几乎总是更清晰。 -For everything else, use a taskqueue. The default is "use `taskqueue(9)`"; the exceptions are narrow. +对于其他所有情况,使用 taskqueue。默认选择是"使用 `taskqueue(9)`";例外情况是狭窄的。 ## Reference: A Worked Reading of `subr_taskqueue.c` -One more reading exercise, because understanding the implementation makes the API's behaviour predictable. +再来一次阅读练习,因为理解实现能让 API 的行为变得可预测。 -The file is `/usr/src/sys/kern/subr_taskqueue.c`. The structure, briefly: +该文件是 `/usr/src/sys/kern/subr_taskqueue.c`。其结构简要如下: -**`struct taskqueue`.** Defined near the top of the file. Holds the pending queue (`tq_queue`), the active task list (`tq_active`), the internal mutex (`tq_mutex`), the enqueue callback (`tq_enqueue`), the worker threads (`tq_threads`), and flags. +**`struct taskqueue`。** 在文件顶部附近定义。包含待处理队列(`tq_queue`)、活跃任务列表(`tq_active`)、内部互斥锁(`tq_mutex`)、入队回调(`tq_enqueue`)、工作线程(`tq_threads`)和标志位。 -**`TQ_LOCK` / `TQ_UNLOCK` macros.** Just after the structure. Acquire the mutex (spin or sleep, depending on `tq_spin`). +**`TQ_LOCK` / `TQ_UNLOCK` 宏。** 紧跟在结构体定义之后。获取互斥锁(自旋或睡眠,取决于 `tq_spin`)。 -**`taskqueue_create` and `_taskqueue_create`.** Allocate the structure, initialise the mutex (MTX_DEF or MTX_SPIN), return. +**`taskqueue_create` 和 `_taskqueue_create`。** 分配结构体,初始化互斥锁(MTX_DEF 或 MTX_SPIN),返回。 -**`taskqueue_enqueue` and `taskqueue_enqueue_flags`.** Acquire the mutex, check `task->ta_pending`, coalesce or link, wake the worker (via the `enqueue` callback), release the mutex. +**`taskqueue_enqueue` 和 `taskqueue_enqueue_flags`。** 获取互斥锁,检查 `task->ta_pending`,合并或链接,唤醒工作线程(通过 `enqueue` 回调),释放互斥锁。 -**`taskqueue_enqueue_timeout`.** Schedule the internal callout; the callout's callback will later call `taskqueue_enqueue` on the underlying task. +**`taskqueue_enqueue_timeout`。** 调度内部 callout;callout 的回调稍后会调用底层任务的 `taskqueue_enqueue`。 -**`taskqueue_cancel` and `taskqueue_cancel_timeout`.** Remove from queue if pending; return `EBUSY` if running. +**`taskqueue_cancel` 和 `taskqueue_cancel_timeout`。** 如果待处理则从队列中移除;如果正在运行则返回 `EBUSY`。 -**`taskqueue_drain` and variants.** `msleep` on a condition that is set when the task is idle and not pending. +**`taskqueue_drain` 及其变体。** 在任务空闲且未待处理的条件上 `msleep`。 -**`taskqueue_run_locked`.** The heart of the subsystem. In a loop: take a task from the pending queue, record `ta_pending`, clear it, move to active, drop the mutex, optionally enter the net epoch, call the callback, re-acquire the mutex, signal any drainers. Loop until the queue is empty. +**`taskqueue_run_locked`。** 子系统的核心。在循环中:从待处理队列取出一个任务,记录 `ta_pending`,清零,移至活跃列表,释放互斥锁,可选进入网络 epoch,调用回调,重新获取互斥锁,通知排空等待者。循环直到队列为空。 -**`taskqueue_thread_loop`.** The worker thread's main loop. Acquire the taskqueue mutex, wait for work (`msleep`) if the queue is empty, call `taskqueue_run_locked` when work arrives, loop. +**`taskqueue_thread_loop`。** 工作线程的主循环。获取 taskqueue 互斥锁,如果队列为空则等待工作(`msleep`),工作到来时调用 `taskqueue_run_locked`,循环。 -**`taskqueue_free`.** Set the "draining" flag, wake every worker, wait for every worker to exit, drain any remaining tasks, free the structure. +**`taskqueue_free`。** 设置"排空中"标志,唤醒每个工作线程,等待每个工作线程退出,排空剩余任务,释放结构体。 -This reading cites each function by name rather than by line number, because line numbers drift between FreeBSD releases while symbol names survive. If you want approximate coordinates for `subr_taskqueue.c` in FreeBSD 14.3, the main entry points live near these lines: `_taskqueue_create` 141, `taskqueue_create` 178, `taskqueue_free` 217, `taskqueue_enqueue_flags` 305, `taskqueue_enqueue` 317, `taskqueue_enqueue_timeout` 382, `taskqueue_run_locked` 485, `taskqueue_cancel` 579, `taskqueue_cancel_timeout` 591, `taskqueue_drain` 612, `taskqueue_thread_loop` 820. Treat those numbers as a scroll hint; open the file and jump to the symbol. +这段阅读以函数名而非行号引用每个函数,因为行号在不同 FreeBSD 版本间会变化,而符号名不会。如果你想在 FreeBSD 14.3 中找到 `subr_taskqueue.c` 的大致位置,主要入口点大约在以下行:`_taskqueue_create` 141、`taskqueue_create` 178、`taskqueue_free` 217、`taskqueue_enqueue_flags` 305、`taskqueue_enqueue` 317、`taskqueue_enqueue_timeout` 382、`taskqueue_run_locked` 485、`taskqueue_cancel` 579、`taskqueue_cancel_timeout` 591、`taskqueue_drain` 612、`taskqueue_thread_loop` 820。将这些数字视为滚动提示;打开文件后跳转到符号名即可。 -Reading these functions once is a good investment. Everything Chapter 14 taught about the API's behaviour is visible in the implementation. +阅读这些函数一次是值得的投资。第 14 章所教授的关于 API 行为的一切都可以在实现中看到。 ## 最终导览:五种常见形状 -Five shapes that account for most taskqueue usage in the FreeBSD tree. Recognising them turns reading driver source from parsing to pattern-matching. +五种常见形状涵盖了 FreeBSD 源码树中大多数 taskqueue 的使用方式。识别它们能将阅读驱动源码从逐行解析变为模式匹配。 -### Shape A: The Solo Task +### 形状 A:独立任务 -One task, enqueued from one place, drained at detach. Simplest. Used by drivers that need to defer exactly one kind of work. +一个任务,从一个地方入队,在 detach 时排空。最简单。用于需要延迟恰好一种工作的驱动。 ```c TASK_INIT(&sc->task, 0, sc_task, sc); @@ -3668,9 +3668,9 @@ taskqueue_enqueue(sc->tq, &sc->task); taskqueue_drain(sc->tq, &sc->task); ``` -### Shape B: The Filter-Plus-Task Split +### 形状 B:过滤器加任务分离 -Interrupt filter does the minimum, enqueues a task for the rest. +中断过滤器做最少的工作,入队一个任务处理剩余部分。 ```c static int @@ -3682,9 +3682,9 @@ sc_filter(void *arg) } ``` -### Shape C: The Callout-Driven Periodic Task +### 形状 C:Callout 驱动的周期性任务 -Callout fires periodically, enqueues a task that does the work. +Callout 周期性触发,入队一个任务执行实际工作。 ```c static void @@ -3696,9 +3696,9 @@ sc_periodic_callout(void *arg) } ``` -### Shape D: The Timeout Task +### 形状 D:超时任务 -`timeout_task` for delayed work in thread context. +`timeout_task` 用于线程上下文中的延迟工作。 ```c TIMEOUT_TASK_INIT(sc->tq, &sc->delayed, 0, sc_delayed, sc); @@ -3708,9 +3708,9 @@ taskqueue_enqueue_timeout(sc->tq, &sc->delayed, delay_ticks); taskqueue_drain_timeout(sc->tq, &sc->delayed); ``` -### Shape E: The Self-Re-Enqueuing Task +### 形状 E:自重新入队的任务 -A task that schedules itself again from its own callback. +一个任务从自己的回调中再次调度自身。 ```c static void @@ -3723,81 +3723,81 @@ sc_self(void *arg, int pending) } ``` -Every driver you read will use some combination of these five shapes. Once they are familiar, the rest is implementation detail. +你阅读的每个驱动都会使用这五种形状的某种组合。一旦熟悉了它们,剩下的就只是实现细节了。 ## 总结:本章交付了什么 -A short inventory, for a reader who wants the compressed version after working through the full chapter. +简短的清单,供完成全章阅读后想要压缩版本的读者参考。 -**Concepts introduced.** +**引入的概念。** -- Deferred work as the bridge from edge contexts to thread context. -- The `struct task` / `struct timeout_task` data structures and their lifecycle. -- Taskqueues as the queue + worker-thread pair. -- Private versus predefined taskqueues and when each is right. -- Coalescing via `ta_pending` and the `pending` argument. -- Priority ordering within a queue. -- The `block`/`unblock`/`quiesce`/`drain_all` primitives. -- Detach ordering with callouts, tasks, selinfo, and taskqueue teardown. -- Debugging via `procstat`, `dtrace`, sysctl counters, and `WITNESS`. -- Introductory exposure to `epoch(9)`, grouptaskqueues, and per-CPU taskqueues. +- 延迟工作作为从边缘上下文到线程上下文的桥梁。 +- `struct task` / `struct timeout_task` 数据结构及其生命周期。 +- Taskqueue 作为队列加工作线程的组合。 +- 私有 taskqueue 与预定义 taskqueue 以及各自的适用场景。 +- 通过 `ta_pending` 和 `pending` 参数实现的合并。 +- 队列内的优先级排序。 +- `block`/`unblock`/`quiesce`/`drain_all` 原语。 +- 包含 callout、任务、selinfo 和 taskqueue 拆卸的 detach 顺序。 +- 通过 `procstat`、`dtrace`、sysctl 计数器和 `WITNESS` 进行调试。 +- 对 `epoch(9)`、grouptaskqueue 和每 CPU taskqueue 的初步接触。 -**Driver changes.** +**驱动变更。** -- Stage 1: one task enqueued from `tick_source`, drained at detach. -- Stage 2: a private taskqueue owned by the driver. -- Stage 3: a bulk-writer task demonstrating deliberate coalescing, a `timeout_task` for delayed reset. -- Stage 4: consolidation, version bump to `0.8-taskqueues`, full regression. +- 阶段 1:一个从 `tick_source` 入队、在 detach 时排空的任务。 +- 阶段 2:驱动拥有的私有 taskqueue。 +- 阶段 3:展示有意合并的批量写入任务,用于延迟重置的 `timeout_task`。 +- 阶段 4:整合,版本升级至 `0.8-taskqueues`,完整回归测试。 -**Documentation changes.** +**文档变更。** -- A Tasks section in `LOCKING.md`. -- A detach-ordering section that enumerates every drain step. -- Per-task documentation listing callback, lifetime, enqueue paths, and cancellation paths. +- `LOCKING.md` 中的 Tasks 节。 +- 枚举每个排空步骤的 detach 顺序节。 +- 每任务的文档,列出回调、生命周期、入队路径和取消路径。 -**Patterns catalogued.** +**编目的模式。** -- Deferred logging. -- Delayed reset. -- Filter-plus-task interrupt split. -- Async `copyin`/`copyout`. -- Retry-with-backoff. -- Deferred teardown. -- Statistics rollover. -- Block-during-reconfiguration. -- Drain-all at subsystem boundary. -- Synthetic event generation. +- 延迟日志。 +- 延迟重置。 +- 过滤器加任务的中断分离。 +- 异步 `copyin`/`copyout`。 +- 带退避的重试。 +- 延迟拆卸。 +- 统计滚动。 +- 重配置期间阻塞。 +- 子系统边界的排空全部。 +- 合成事件生成。 -**Debugging tools used.** +**使用的调试工具。** -- `procstat -t` for taskqueue thread state. -- `ps ax` for kernel thread inventory. -- `sysctl dev.` for driver-exposed counters. -- `dtrace` for enqueue latency and callback duration. -- `procstat -kk` for stuck-thread diagnosis. -- `WITNESS` and `INVARIANTS` as the debug-kernel safety net. +- `procstat -t` 用于 taskqueue 线程状态。 +- `ps ax` 用于内核线程清单。 +- `sysctl dev.` 用于驱动暴露的计数器。 +- `dtrace` 用于入队延迟和回调持续时间。 +- `procstat -kk` 用于卡住线程的诊断。 +- `WITNESS` 和 `INVARIANTS` 作为调试内核的安全网。 -**Deliverables.** +**交付物。** -- `content/chapters/part3/chapter-14.md` (this file). -- `examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/`. -- `examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/`. -- `examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/`. -- `examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/`. -- `examples/part-03/ch14-taskqueues-and-deferred-work/labs/` with `poll_waiter.c` and small helper scripts. -- `examples/part-03/ch14-taskqueues-and-deferred-work/LOCKING.md` with the Tasks section. -- `examples/part-03/ch14-taskqueues-and-deferred-work/README.md` with per-stage build and test instructions. +- `content/chapters/part3/chapter-14.md`(本文件)。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/`。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/`。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/`。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/`。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/labs/`,包含 `poll_waiter.c` 和小型辅助脚本。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/LOCKING.md`,包含 Tasks 节。 +- `examples/part-03/ch14-taskqueues-and-deferred-work/README.md`,包含每个阶段的构建和测试说明。 -That is the end of Chapter 14. Chapter 15 continues the synchronisation story. +第 14 章到此结束。第 15 章继续同步的故事。 ## Reference: Reading `taskqueue_run_locked` Line By Line -The heart of the taskqueue subsystem is a short loop inside `taskqueue_run_locked` in `/usr/src/sys/kern/subr_taskqueue.c`. Reading it once, slowly, pays off whenever you need to reason about the subsystem's behaviour. A narrated pass follows. +taskqueue 子系统的核心是 `/usr/src/sys/kern/subr_taskqueue.c` 中 `taskqueue_run_locked` 内的一个短循环。慢慢地读一遍,每当你需要推理子系统的行为时都会有所回报。以下是一段带注解的通读。 -The function is called from the worker thread's main loop, `taskqueue_thread_loop`, with the taskqueue mutex held. Its job is to process every pending task, release the mutex around the callback, and return with the mutex still held when the queue is empty. +该函数从工作线程的主循环 `taskqueue_thread_loop` 中调用,调用时持有 taskqueue 互斥锁。它的任务是处理每个待处理任务,在回调周围释放互斥锁,并在队列为空时带着互斥锁仍被持有而返回。 ```c static void @@ -3816,7 +3816,7 @@ taskqueue_run_locked(struct taskqueue *queue) in_net_epoch = false; ``` -The function starts by asserting the mutex is held and inserting a local `taskqueue_busy` structure into the active list. The `tb` structure represents this invocation of `taskqueue_run_locked`; later code uses it to track what this invocation is currently running. The `in_net_epoch` flag tracks whether we are currently inside the network epoch, so we do not enter it redundantly when consecutive tasks are all network-flagged. +函数首先断言互斥锁已被持有,并将一个局部的 `taskqueue_busy` 结构插入活跃列表。`tb` 结构代表 `taskqueue_run_locked` 的本次调用;后续代码用它来跟踪本次调用当前正在运行什么。`in_net_epoch` 标志跟踪我们当前是否处于网络 epoch 内,这样当连续的任务都是网络标记的时,就不会冗余地进入 epoch。 ```c while ((task = STAILQ_FIRST(&queue->tq_queue)) != NULL) { @@ -3831,9 +3831,9 @@ The function starts by asserting the mutex is held and inserting a local `taskqu TQ_UNLOCK(queue); ``` -The main loop. Pull the head off the pending queue. Snapshot the pending count into a local variable, reset the field to zero (so new enqueues that arrive during the callback increment from zero again). Record the task in the `tb` structure so drain callers can see what is running. Increment a sequence counter for stale-drain detection. Drop the mutex. +主循环。从待处理队列头部取出任务。将待处理计数快照到局部变量中,将字段重置为零(这样回调期间到达的新入队从零开始递增)。将任务记录在 `tb` 结构中,以便排空调用者能看到正在运行什么。递增序列计数器用于过时排空检测。释放互斥锁。 -Notice that between here and the next `TQ_LOCK`, the mutex is not held. This is the window where the callback runs; the rest of the kernel can enqueue more tasks (which will coalesce or queue up), drain other tasks (which will see `tb.tb_running == task` and wait), or run its own business. +注意从这里到下一个 `TQ_LOCK` 之间,互斥锁未被持有。这是回调运行的窗口;内核的其余部分可以入队更多任务(会合并或排队)、排空其他任务(会看到 `tb.tb_running == task` 并等待),或做自己的事情。 ```c KASSERT(task->ta_func != NULL, ("task->ta_func is NULL")); @@ -3855,35 +3855,35 @@ Notice that between here and the next `TQ_LOCK`, the mutex is not held. This is } ``` -The epoch bookkeeping: enter the net epoch if this task is net-flagged and we are not already in it; exit the epoch if we entered it for an earlier task but this one is not net-flagged. This lets consecutive net tasks share a single epoch entry, which is an optimisation the framework does for free. +Epoch 簿记:如果此任务是网络标记的且我们尚未进入 epoch,则进入网络 epoch;如果我们为较早的任务进入了 epoch 但此任务不是网络标记的,则退出 epoch。这让连续的网络任务共享单个 epoch 进入,这是框架免费提供的优化。 -Call the callback with the context and pending count. Re-acquire the mutex. Wake up any drain caller who is waiting for this specific task. Loop. +用上下文和待处理计数调用回调。重新获取互斥锁。唤醒任何等待此特定任务的排空调用者。循环。 -After the loop, if we are still in the net epoch, exit it. Remove the `tb` structure from the active list. +循环结束后,如果我们仍在网络 epoch 中,退出它。从活跃列表中移除 `tb` 结构。 -Seven observations from reading this function. +从阅读这个函数得出的七个观察。 -**Observation 1.** The mutex is dropped for exactly as long as the callback runs. No taskqueue-internal code runs with the callback; if the callback takes milliseconds, the taskqueue mutex is free for milliseconds. +**观察 1。** 互斥锁在回调运行期间恰好不被持有。没有 taskqueue 内部代码与回调同时运行;如果回调需要毫秒,taskqueue 互斥锁就空闲毫秒。 -**Observation 2.** `ta_pending` is reset before the callback runs, not after. A new enqueue during the callback makes the task pending again (pending=1). After the callback returns, the loop sees the new pending, pulls it off, and runs the callback a second time with pending=1. No enqueue is lost. +**观察 2。** `ta_pending` 在回调运行之前而非之后被重置。回调期间的新入队使任务再次变为待处理(pending=1)。回调返回后,循环看到新的待处理,将其取出,并以 pending=1 再次运行回调。没有入队会丢失。 -**Observation 3.** The `pending` value passed to the callback is the count at the moment the task was pulled off the queue, not at the moment the enqueue calls happened. If enqueues arrive during the callback, they do not contribute to this invocation's `pending`; they contribute to the next invocation's `pending`. +**观察 3。** 传给回调的 `pending` 值是任务从队列中取出时刻的计数,而非入队调用发生时刻的计数。如果回调期间有入队到达,它们不计入本次调用的 `pending`;它们计入下一次调用的 `pending`。 -**Observation 4.** The wakeup at the bottom of the loop wakes drain callers sleeping on the task's address. Drain uses `msleep(&task, &tq->mutex, ...)` and waits for the task to be off the queue and not currently running. The wakeup here is what makes the drain terminate. +**观察 4。** 循环底部的唤醒会唤醒在任务地址上睡眠的排空调用者。排空使用 `msleep(&task, &tq->mutex, ...)`,等待任务不在队列上且当前未运行。这里的唤醒就是使排空终止的原因。 -**Observation 5.** The sequence counter `tq_seq` and the `tb.tb_seq` allow drain-all to detect whether new tasks have been added since the drain started. Without the sequence, drain-all would race with new enqueues. +**观察 5。** 序列计数器 `tq_seq` 和 `tb.tb_seq` 允许 drain-all 检测在排空开始后是否有新任务被添加。没有序列号,drain-all 会与新入队竞争。 -**Observation 6.** `tb.tb_canceling` is a flag that `taskqueue_cancel` sets to tell a waiter "this task is currently being cancelled"; its purpose is to let concurrent cancel/drain calls coordinate. We have not discussed it in the main text because most drivers never see it. +**观察 6。** `tb.tb_canceling` 是 `taskqueue_cancel` 设置的标志,用于告诉等待者"此任务当前正在被取消";其目的是让并发的 cancel/drain 调用协调。我们在正文中没有讨论它,因为大多数驱动永远不会遇到它。 -**Observation 7.** Multiple worker threads can each be inside `taskqueue_run_locked` simultaneously, each dispatching a different task. The `tq_active` list holds all their `tb` structures. Different tasks on the same queue run in parallel; the same task cannot run in parallel with itself, because only one worker pulls it off at a time. +**观察 7。** 多个工作线程可以同时处于 `taskqueue_run_locked` 内部,每个分发不同的任务。`tq_active` 列表保存所有它们的 `tb` 结构。同一队列上的不同任务并行运行;同一任务不能与自身并行运行,因为同一时刻只有一个工作线程将其取出。 -Those observations together describe exactly what the taskqueue guarantees and what it does not. Every behaviour the chapter described earlier is a consequence of this short loop. +这些观察合在一起精确描述了 taskqueue 保证什么和不保证什么。本章前面描述的每个行为都是这个短循环的结果。 ## Reference: A Walkthrough of `taskqueue_drain` -Equally illuminating, equally short. From `/usr/src/sys/kern/subr_taskqueue.c`, roughly: +同样有启发,同样简短。来自 `/usr/src/sys/kern/subr_taskqueue.c`,大致如下: ```c void @@ -3899,107 +3899,107 @@ taskqueue_drain(struct taskqueue *queue, struct task *task) } ``` -The function acquires the taskqueue mutex, then loops until the task is neither pending nor running. Each iteration sleeps on the task's address; each wakeup at the bottom of `taskqueue_run_locked` wakes the drainer to re-check. +函数获取 taskqueue 互斥锁,然后循环直到任务既非待处理也非运行中。每次迭代在任务地址上睡眠;`taskqueue_run_locked` 底部的每次唤醒都会唤醒排空者重新检查。 -`task_is_running(queue, task)` walks the active list (`tq_active`) and returns true if any `tb.tb_running == task`. It is O(N) in the number of workers, but for most drivers N is 1 and this is O(1). +`task_is_running(queue, task)` 遍历活跃列表(`tq_active`),如果任何 `tb.tb_running == task` 则返回 true。它是工作线程数的 O(N),但对于大多数驱动 N 为 1,所以是 O(1)。 -The function does not hold the lock across the sleep; `TQ_SLEEP` (which expands to `msleep` or `msleep_spin`) drops the mutex during the sleep and re-acquires it on wakeup, which is the standard condition-variable pattern. +函数在睡眠期间不持有锁;`TQ_SLEEP`(展开为 `msleep` 或 `msleep_spin`)在睡眠期间释放互斥锁并在唤醒时重新获取,这是标准的条件变量模式。 -Observations from reading `taskqueue_drain`. +从阅读 `taskqueue_drain` 得出的观察。 -**Observation 1.** Drain is a condition-variable wait, using the task pointer as the wakeup channel. The wake comes from the `wakeup(task)` at the bottom of `taskqueue_run_locked`. +**观察 1。** 排空是一个条件变量等待,使用任务指针作为唤醒通道。唤醒来自 `taskqueue_run_locked` 底部的 `wakeup(task)`。 -**Observation 2.** Drain does not stop new enqueues from happening. If the task is enqueued again while the drain is waiting, the drain will continue waiting until that new enqueue fires and completes. This is why detach discipline requires draining every producer (callouts, other tasks, interrupt handlers) before draining the victim task. +**观察 2。** 排空不会阻止新入队发生。如果在排空等待期间任务被再次入队,排空将继续等待直到那次新入队触发并完成。这就是为什么 detach 纪律要求在排空目标任务之前先排空每个生产者(callout、其他任务、中断处理程序)。 -**Observation 3.** Drain on an idle task (never enqueued, or enqueued and completed) returns immediately. It is safe to call drain unconditionally in detach. +**观察 3。** 对空闲任务(从未入队,或已入队并已完成)的排空立即返回。在 detach 中无条件调用排空是安全的。 -**Observation 4.** Drain holds the taskqueue mutex across the initial check and before the sleep, which means drain cannot race with enqueue in a way that misses a newly pending task. If an enqueue arrives between the check and the sleep, `ta_pending` becomes non-zero and the drain loop re-iterates. +**观察 4。** 排空在初始检查之前和睡眠之前持有 taskqueue 互斥锁,这意味着排空不会以错过新待处理任务的方式与入队竞争。如果入队在检查和睡眠之间到达,`ta_pending` 变为非零,排空循环重新迭代。 -**Observation 5.** The `WITNESS_WARN` at the top asserts that the caller is in a context where sleeping is legal. If you try to call `taskqueue_drain` from a context that cannot sleep (a callout callback, for example), `WITNESS` complains. +**观察 5。** 顶部的 `WITNESS_WARN` 断言调用者处于可以合法睡眠的上下文中。如果你尝试从不能睡眠的上下文(例如 callout 回调)调用 `taskqueue_drain`,`WITNESS` 会发出警告。 -Two complementary functions are `taskqueue_cancel` (which removes the task from the queue if it is pending and returns `EBUSY` if it is running) and `taskqueue_drain_timeout` (which also cancels the embedded callout). Reading their implementations once is worthwhile; they are short. +两个互补函数是 `taskqueue_cancel`(如果待处理则从队列中移除任务,如果正在运行则返回 `EBUSY`)和 `taskqueue_drain_timeout`(还会取消嵌入的 callout)。阅读它们的实现一次是值得的;它们都很短。 ## Reference: The Lifecycle As Seen From the Softc -One more view, for completeness. The same information, organised around the softc instead of around the API. +为了完整性,再来一个视角。同样的信息,但以 softc 而非 API 为中心来组织。 -At **attach time**, the softc gains: +在 **attach 时**,softc 获得: -- A taskqueue pointer (`sc->tq`), created by `taskqueue_create` and populated by `taskqueue_start_threads`. -- One or more task structures (`sc->foo_task`), initialised by `TASK_INIT` or `TIMEOUT_TASK_INIT`. -- Counters and flags for observability (optional but recommended). +- 一个 taskqueue 指针(`sc->tq`),由 `taskqueue_create` 创建并由 `taskqueue_start_threads` 填充。 +- 一个或多个任务结构(`sc->foo_task`),由 `TASK_INIT` 或 `TIMEOUT_TASK_INIT` 初始化。 +- 用于可观察性的计数器和标志(可选但推荐)。 -At **runtime**, the softc's taskqueue state is: +在 **运行时**,softc 的 taskqueue 状态为: -- `sc->tq` is an opaque pointer; drivers never read its fields. -- `sc->foo_task` may be IDLE, PENDING, or RUNNING at any instant. -- The taskqueue's worker threads sleep most of the time, wake on enqueue, run callbacks, sleep again. +- `sc->tq` 是一个不透明指针;驱动从不读取其字段。 +- `sc->foo_task` 在任何时刻可能处于 IDLE、PENDING 或 RUNNING 状态。 +- taskqueue 的工作线程大部分时间在睡眠,入队时被唤醒,运行回调,再次睡眠。 -At **detach time**, the softc is torn down in this order: +在 **detach 时**,softc 按以下顺序拆卸: -1. Clear `sc->is_attached` under the mutex, broadcast cvs, release mutex. -2. Drain every callout. -3. Drain every task. -4. Drain selinfo. -5. Free the taskqueue. -6. Destroy the cdev and its alias. -7. Free the sysctl context. -8. Destroy the cbuf and counters. -9. Destroy the cvs, sx, mutex. +1. 在互斥锁保护下清除 `sc->is_attached`,广播条件变量,释放互斥锁。 +2. 排空每个 callout。 +3. 排空每个任务。 +4. 排空 selinfo。 +5. 释放 taskqueue。 +6. 销毁 cdev 及其别名。 +7. 释放 sysctl 上下文。 +8. 销毁 cbuf 和计数器。 +9. 销毁条件变量、sx 锁、互斥锁。 -After `taskqueue_free`, `sc->tq` becomes invalid. After the task drains, the `sc->foo_task` structures are idle and their storage can be reclaimed along with the softc. +`taskqueue_free` 之后,`sc->tq` 变为无效。任务排空之后,`sc->foo_task` 结构处于空闲状态,其存储可以随 softc 一起回收。 -The softc's lifetime is determined by the device's attach/detach. Tasks cannot outlive their softc. The drain at detach is what guarantees that property. +softc 的生命周期由设备的 attach/detach 决定。任务不能比其 softc 活得更久。detach 时的排空保证了这一属性。 ## Reference: A Glossary of Terms -For quick lookup. +供快速查阅。 -**Task.** An instance of `struct task`; a callback-plus-context bundled for enqueue onto a taskqueue. +**任务(Task)。** `struct task` 的实例;一个打包了回调和上下文、用于入队到 taskqueue 的单元。 -**Taskqueue.** An instance of `struct taskqueue`; a queue of pending tasks paired with one or more worker threads. +**Taskqueue。** `struct taskqueue` 的实例;一个待处理任务队列与一个或多个工作线程的配对。 -**Timeout task.** An instance of `struct timeout_task`; a task plus an internal callout, used for scheduled-in-the-future work. +**超时任务(Timeout task)。** `struct timeout_task` 的实例;一个任务加上一个内部 callout,用于未来某个时间点的计划工作。 -**Enqueue.** To add a task to a taskqueue. If the task is already pending, increment its pending count instead. +**入队(Enqueue)。** 将任务添加到 taskqueue。如果任务已处于待处理状态,则递增其待处理计数。 -**Drain.** To wait until a task is neither pending nor running. +**排空(Drain)。** 等待直到任务既非待处理也非运行中。 -**Dispatch.** The act of the taskqueue worker taking a task off the pending list and running its callback. +**分发(Dispatch)。** taskqueue 工作线程从待处理列表取出任务并运行其回调的动作。 -**Coalesce.** To fold redundant enqueues into a single pending-state increment rather than two list entries. +**合并(Coalesce)。** 将冗余的入队折叠为单次待处理状态递增,而非两个列表条目。 -**Pending count.** The value of `ta_pending`, representing how many coalesced enqueues are accumulated on this task. +**待处理计数(Pending count)。** `ta_pending` 的值,表示此任务上累积了多少次合并入队。 -**Idle task.** A task that is not pending and not running. `ta_pending == 0` and no worker has it. +**空闲任务(Idle task)。** 既非待处理也非运行中的任务。`ta_pending == 0` 且没有工作线程持有它。 -**Worker thread.** A kernel thread (usually one per taskqueue) whose job is to wait for work and run task callbacks. +**工作线程(Worker thread)。** 一个内核线程(通常每个 taskqueue 一个),其职责是等待工作并运行任务回调。 -**Edge context.** A constrained context (callout, interrupt filter, epoch section) where some operations are not permitted. +**边缘上下文(Edge context)。** 受限的上下文(callout、中断过滤器、epoch 区段),其中某些操作不被允许。 -**Thread context.** An ordinary kernel thread context where sleeping, sleepable-lock acquisition, and all standard operations are permitted. +**线程上下文(Thread context)。** 普通的内核线程上下文,允许睡眠、可睡眠锁获取和所有标准操作。 -**Detach ordering.** The sequence in which primitives are drained and freed at device detach, such that no primitive is freed while something can still reference it. +**Detach 顺序(Detach ordering)。** 在设备 detach 时排空和释放原语的顺序,使得没有原语在仍有东西引用它时被释放。 -**Drain race.** A bug where a primitive is freed while a callback or handler is still potentially running, caused by incorrect detach ordering. +**排空竞争(Drain race)。** 一个 bug,即原语在回调或处理程序仍可能运行时被释放,由不正确的 detach 顺序导致。 -**Pending-drop counter.** A diagnostic counter incremented when the callback's `pending` argument is greater than one, indicating coalescing occurred. +**待处理丢弃计数器(Pending-drop counter)。** 当回调的 `pending` 参数大于一时递增的诊断计数器,表明发生了合并。 -**Private taskqueue.** A taskqueue owned by the driver, created and freed with attach/detach, not shared with other drivers. +**私有 taskqueue(Private taskqueue)。** 由驱动拥有的 taskqueue,随 attach/detach 创建和释放,不与其他驱动共享。 -**Shared taskqueue.** A kernel-provided taskqueue (`taskqueue_thread`, `taskqueue_swi`, etc.) used by multiple drivers simultaneously. +**共享 taskqueue(Shared taskqueue)。** 内核提供的 taskqueue(`taskqueue_thread`、`taskqueue_swi` 等),由多个驱动同时使用。 -**Fast taskqueue.** A taskqueue created with `taskqueue_create_fast` that uses a spin mutex internally, safe for enqueue from filter-interrupt context. +**快速 taskqueue(Fast taskqueue)。** 使用 `taskqueue_create_fast` 创建的 taskqueue,内部使用自旋互斥锁,从过滤器中断上下文入队是安全的。 -**Grouptaskqueue.** A scalable variation where tasks are distributed across per-CPU queues. Used by high-rate network drivers. +**Grouptaskqueue。** 一种可扩展变体,任务分布在每 CPU 的队列上。由高速网络驱动使用。 -**Epoch.** A lockless read-synchronisation mechanism. The `net_epoch_preempt` epoch protects network state. +**Epoch。** 一种无锁读同步机制。`net_epoch_preempt` epoch 保护网络状态。 -Chapter 14 ends here. The next chapter takes the synchronisation story further. +第 14 章到此结束。下一章将继续讲述同步的故事。 diff --git a/translations/zh_CN/chapters/part4/chapter-16.md b/translations/zh_CN/chapters/part4/chapter-16.md index bd858de..203e5b5 100644 --- a/translations/zh_CN/chapters/part4/chapter-16.md +++ b/translations/zh_CN/chapters/part4/chapter-16.md @@ -1,6 +1,6 @@ --- title: "访问硬件" -description: "Part 4 opens with the first chapter that teaches the driver how to speak to hardware directly: what hardware I/O means, how memory-mapped I/O differs from port-mapped I/O, how bus_space(9) gives FreeBSD drivers a portable vocabulary for register access, how to simulate a register block in kernel memory so the reader can learn without real hardware, how to integrate register-style access into the evolving myfirst driver, and how to keep MMIO safe under concurrency." +description: "第四部分以第一章开始,教授驱动程序如何直接与硬件对话:硬件 I/O 的含义、内存映射 I/O 与端口映射 I/O 的区别、bus_space(9) 如何为 FreeBSD 驱动程序提供可移植的寄存器访问词汇、如何在内核内存中模拟寄存器块以便读者无需真实硬件即可学习、如何将寄存器式访问集成到不断演进的 myfirst 驱动程序中,以及如何在并发下保持 MMIO 的安全性。" partNumber: 4 partName: "硬件与平台级集成" chapter: 16 @@ -13,319 +13,319 @@ estimatedReadTime: 195 language: "zh-CN" --- -# Accessing Hardware +# 访问硬件 -## Reader Guidance & Outcomes +## 读者指南与学习目标 -Part 3 ended with a driver that knew how to coordinate itself. The `myfirst` module at version `0.9-coordination` has a mutex protecting its data path, a pair of condition variables that let readers and writers wait patiently for the buffer state they need, a shared and exclusive lock protecting its configuration, three callouts that give it internal time, a private taskqueue with three tasks that defer work out of constrained contexts, a counting semaphore that caps concurrent writers, an atomic flag that carries the shutdown story across every context, and a small header that names every synchronisation primitive the driver uses. The chapters that built it introduced seven primitives, tied them together with one detach ordering, and documented the whole story in a living `LOCKING.md`. +第三部分以一个懂得如何协调自身的驱动程序结束。版本为 `0.9-coordination` 的 `myfirst` 模块拥有一个保护其数据路径的互斥锁、一对让读写者耐心等待所需缓冲区状态的条件变量、一个保护其配置的共享/排他锁、三个提供内部计时的 callout、一个包含三个任务用于将工作从受限上下文中推迟执行的私有任务队列、一个限制并发写入者数量的计数信号量、一个在所有上下文中传递关闭状态的原子标志,以及一个小型头文件来命名驱动程序使用的每个同步原语。构建它的章节引入了七个原语,用一个分离顺序将它们联系在一起,并在一份活的 `LOCKING.md` 中记录了整个故事。 -What the driver does not yet have is a hardware story. Every invariant it coordinates is internal. Every byte that flows through it originates in user space through `write(2)` or is produced by a callout from its own imagination. Nothing in the driver reaches outside the kernel's own memory. A real FreeBSD driver usually exists because there is a device to talk to: a network card, a storage controller, a serial port, a sensor, a custom FPGA, a GPU. That conversation is what Part 4 is about, and Chapter 16 is where it begins. +驱动程序目前还没有硬件方面的故事。它协调的每个不变量都是内部的。流经它的每个字节要么源自用户空间通过 `write(2)` 产生,要么是由它自己的 callout 想象出来的。驱动程序中没有任何东西会触及内核自身内存之外。一个真正的 FreeBSD 驱动程序通常存在是因为有一个设备需要与之对话:网卡、存储控制器、串口、传感器、定制 FPGA、GPU。这个对话就是第四部分的内容,第 16 章就是它的起点。 -Chapter 16's scope is deliberately narrow. It teaches the mental model of hardware I/O and the vocabulary of `bus_space(9)`, the FreeBSD abstraction that lets a single driver talk to a device the same way on every supported architecture. It walks through a simulated register block so the reader can practise register-style access without owning real hardware, and it integrates that simulation into the `myfirst` driver in a way that evolves naturally from Chapter 15 rather than throwing the driver away. It covers the safety rules that MMIO demands (memory barriers, access ordering, locking around shared registers) and shows how to debug and trace register-level access. It ends with a small refactor that separates hardware-access code from the driver's business logic, preparing the file layout every later Part 4 chapter will rely on. +第 16 章的范围是刻意收窄的。它教授硬件 I/O 的心智模型和 `bus_space(9)` 的词汇,这是 FreeBSD 的抽象层,让单个驱动程序在所有支持的架构上以相同的方式与设备通信。它引导读者走完一个模拟寄存器块,使读者可以在没有真实硬件的情况下练习寄存器式访问,并将该模拟集成到 `myfirst` 驱动程序中,以自然地延续第 15 章的方式演进,而不是推翻重来。它涵盖了 MMIO 所要求的安全规则(内存屏障、访问排序、共享寄存器周围的加锁),并展示了如何调试和跟踪寄存器级访问。它以一次小型重构结束,将硬件访问代码与驱动程序的业务逻辑分离,为后续每个第四部分章节将依赖的文件布局做好准备。 -Several questions are deliberately postponed so that Chapter 16 can dwell on the vocabulary itself. Dynamic register behaviour, callout-driven status changes, and fault injection belong to Chapter 17. Real PCI devices, BAR mapping, vendor and device ID matching, `pciconf` and `pci(4)`, and the newbus glue that ties PCI drivers to the bus subsystem belong to Chapter 18. Interrupts and their split between filter handlers and interrupt threads are Chapter 19. DMA and bus master programming are Chapter 20 and Chapter 21. Chapter 16 stays inside the ground it can cover well, and it hands off explicitly when a topic deserves its own chapter. +几个问题被刻意推迟,以便第 16 章能专注于词汇本身。动态寄存器行为、callout 驱动的状态变化和故障注入属于第 17 章。真实 PCI 设备、BAR 映射、供应商和设备 ID 匹配、`pciconf` 和 `pci(4)`,以及将 PCI 驱动程序连接到总线子系统的 newbus 粘合代码属于第 18 章。中断及其在过滤处理程序和中断线程之间的划分是第 19 章。DMA 和总线主控编程是第 20 章和第 21 章。第 16 章停留在它能很好覆盖的范围内,并在一个主题值得独立成章时明确交接。 -Part 4 opens here, and an opening deserves a small pause. Part 3 taught you how to behave inside the driver when many actors touch shared state. Part 4 teaches how the driver reaches outside itself. An interrupt handler runs in a context Part 3 taught you how to reason about and accesses memory Part 4 will teach you how to map. A register write in Part 4 must respect a lock Part 3 taught you how to manage. The disciplines stack. Chapter 16 is your first practice with `bus_space(9)`; Part 3's discipline is what keeps the practice honest. +第四部分从此开始,一个开始值得稍作停顿。第三部分教你当多个参与者接触共享状态时如何在驱动程序内部正确行事。第四部分教驱动程序如何触及自身之外。中断处理程序运行在第三部分教过你如何推理的上下文中,访问第四部分将教你如何映射的内存。第四部分中的寄存器写入必须遵守第三部分教过你如何管理的锁。这些规范是叠加的。第 16 章是你对 `bus_space(9)` 的第一次实践;第三部分的规范是让这次实践保持诚实的基础。 -### Why bus_space(9) Earns a Chapter of Its Own +### 为什么 bus_space(9) 值得单独成章 -You may already be wondering whether MMIO really needs a whole chapter. Why not jump into Chapter 17's simulation or Chapter 18's real PCI work and pick up the accessor vocabulary in passing? If you have used `bus_space(9)` before, the primitive calls in this chapter will not be new to you. +你可能在想,MMIO 是否真的需要一整章。为什么不直接跳到第 17 章的模拟或第 18 章的真实 PCI 工作,顺便捡起访问器词汇?如果你以前用过 `bus_space(9)`,本章中的基本调用对你来说不会是新的。 -What Chapter 16 adds is the mental model. Hardware I/O is a topic where a small set of ideas done well pays off across every subsequent chapter, and a small set of ideas done sloppily produces quiet, persistent bugs that are hard to find later. The distinction between memory-mapped I/O and port-mapped I/O is simple once you have it and confusing until you do. The meaning of a `bus_space_tag_t` and a `bus_space_handle_t` is simple once you see what they stand for and opaque until then. The reason memory barriers matter around register access is obvious once you have thought about cache coherence and compiler reordering and irrelevant until the day a driver misbehaves for reasons you cannot explain. +第 16 章增加的是心智模型。硬件 I/O 是一个话题,一小组建构良好的想法会在后续每个章节中产生回报,而一小组建构粗糙的想法会产生难以发现的、安静且持久的 bug。内存映射 I/O 和端口映射 I/O 之间的区别,一旦你理解了就很简单,在此之前则令人困惑。`bus_space_tag_t` 和 `bus_space_handle_t` 的含义,一旦你看到它们代表什么就很简单,在此之前则是不透明的。内存屏障在寄存器访问周围重要的原因,一旦你思考过缓存一致性和编译器重排序就显而易见,而在驱动程序因你无法解释的原因而行为异常的那一天之前则无关紧要。 -The chapter also earns its place by being the chapter where the `myfirst` driver gains its first hardware-facing layer. Until now, the softc held only internal state: a circular buffer, some locks, some counters, some flags. After Chapter 16, the softc will hold a simulated register block and the accessors that read and write it. That change in the driver's shape is small but formative. It sets up the file organisation and the locking discipline that every later Part 4 chapter will extend. Skipping Chapter 16 would leave the reader trying to learn register-access idioms in the middle of learning PCI, interrupts, or DMA. Doing them one at a time is kinder. +本章也因是 `myfirst` 驱动程序获得其第一个面向硬件层的章节而赢得其位置。到目前为止,softc 只保存内部状态:一个环形缓冲区、一些锁、一些计数器、一些标志。第 16 章之后,softc 将保存一个模拟寄存器块和读写它的访问器。驱动程序形状的这个变化虽小但具有塑造性。它建立了后续每个第四部分章节将扩展的文件组织和加锁规范。跳过第 16 章会让读者在学 PCI、中断或 DMA 的同时试图学习寄存器访问惯用法。一次学一个更友善。 -### Where Chapter 15 Left the Driver +### 第 15 章留给我们的驱动程序 -A short checkpoint before we go further. Chapter 16 extends the driver produced at the end of Chapter 15 Stage 4, tagged as version `0.9-coordination`. If any of the items below feels uncertain, return to Chapter 15 before starting this chapter. +在继续之前做一个小检查点。第 16 章扩展的是第 15 章第 4 阶段结束时产生的驱动程序,标记为版本 `0.9-coordination`。如果以下任何项目让你感到不确定,在开始本章之前请回到第 15 章。 -- Your `myfirst` driver compiles cleanly and identifies itself as version `0.9-coordination`. -- The softc holds a data-path mutex (`sc->mtx`), a configuration sx (`sc->cfg_sx`), a stats-cache sx (`sc->stats_cache_sx`), two condition variables (`sc->data_cv`, `sc->room_cv`), three callouts (`heartbeat_co`, `watchdog_co`, `tick_source_co`), a private taskqueue (`sc->tq`) with four tasks (`selwake_task`, `bulk_writer_task`, `reset_delayed_task`, `recovery_task`), and a counting semaphore (`writers_sema`) that caps concurrent writers. -- A header `myfirst_sync.h` encapsulates every synchronisation operation under named inline functions. -- The lock order `sc->mtx -> sc->cfg_sx -> sc->stats_cache_sx` is documented in `LOCKING.md` and enforced by `WITNESS`. -- `INVARIANTS`, `WITNESS`, `WITNESS_SKIPSPIN`, `DDB`, `KDB`, and `KDB_UNATTENDED` are enabled in your test kernel, and you have built and booted it. -- The Chapter 15 stress kit runs cleanly under the debug kernel. +- 你的 `myfirst` 驱动程序能干净地编译,并标识自身为版本 `0.9-coordination`。 +- softc 包含一个数据路径互斥锁(`sc->mtx`)、一个配置 sx(`sc->cfg_sx`)、一个统计缓存 sx(`sc->stats_cache_sx`)、两个条件变量(`sc->data_cv`、`sc->room_cv`)、三个 callout(`heartbeat_co`、`watchdog_co`、`tick_source_co`)、一个包含四个任务(`selwake_task`、`bulk_writer_task`、`reset_delayed_task`、`recovery_task`)的私有任务队列(`sc->tq`),以及一个限制并发写入者的计数信号量(`writers_sema`)。 +- 一个头文件 `myfirst_sync.h` 将每个同步操作封装在命名的内联函数下。 +- 锁序 `sc->mtx -> sc->cfg_sx -> sc->stats_cache_sx` 记录在 `LOCKING.md` 中并由 `WITNESS` 强制执行。 +- `INVARIANTS`、`WITNESS`、`WITNESS_SKIPSPIN`、`DDB`、`KDB` 和 `KDB_UNATTENDED` 已在你的测试内核中启用,并且你已经构建并启动了它。 +- 第 15 章的压力测试套件在调试内核下运行干净。 -That driver is what Chapter 16 extends. The additions are again modest in volume: one new header (`myfirst_hw.h`), one new structure inside the softc (a simulated register block), a handful of accessor helpers, a small hardware-driven task, and a set of barriers and locks around register access. The mental model change is larger than the line count suggests. +那个驱动程序就是第 16 章所扩展的。新增的内容在代码量上同样不多:一个新的头文件(`myfirst_hw.h`)、softc 内部的一个新结构(模拟寄存器块)、少量访问器辅助函数、一个小型硬件驱动任务,以及一组围绕寄存器访问的屏障和锁。心智模型的变化比代码行数所暗示的要大。 -### What You Will Learn +### 你将学到什么 -Walking away from this chapter, you should be able to: +学完本章后,你应该能够: -- Describe what hardware I/O means in a driver context and why a driver cannot usually touch device memory by simply dereferencing a pointer. -- Distinguish memory-mapped I/O (MMIO) from port-mapped I/O (PIO), and explain why MMIO dominates modern FreeBSD drivers on modern platforms. -- Explain what a register is, what an offset is, and what a control or status field means, using the vocabulary real device datasheets use. -- Read a simple register map table and translate it into a C header of offsets and bitmasks. -- Describe the roles of `bus_space_tag_t` and `bus_space_handle_t` and why they are an abstraction rather than just a pointer. -- Recognise the shape of `bus_space_read_*`, `bus_space_write_*`, `bus_space_barrier`, `bus_space_read_multi_*`, `bus_space_read_region_*`, and their `bus_*` shorthand counterparts defined over a `struct resource *`. -- Simulate a register block in kernel memory, wrap access to it behind accessor helpers, and use those helpers to build a small driver-visible device that behaves like a real MMIO device without touching real hardware. -- Integrate simulated register access into the evolving `myfirst` driver, with the data path reading and writing through register accessors instead of touching a raw buffer. -- Identify when a register read has side effects and when a register write does, and why that matters for caching, compiler reordering, and debugging. -- Use `bus_space_barrier` correctly to enforce access ordering where it is needed, and recognise when it is not needed. -- Protect shared register state with the right kind of lock, and avoid busy-wait loops that starve other threads. -- Log register access in a way that helps you debug a driver without drowning the reader in noise. -- Refactor a driver so that its hardware-access layer is a named, documented, testable unit of code. -- Tag the driver as version `0.9-mmio`, update `LOCKING.md` and `HARDWARE.md`, and run the full regression suite with hardware-access enabled. +- 描述硬件 I/O 在驱动程序上下文中意味着什么,以及为什么驱动程序通常不能通过简单解引用指针来访问设备内存。 +- 区分内存映射 I/O(MMIO)和端口映射 I/O(PIO),并解释为什么 MMIO 在现代平台上的现代 FreeBSD 驱动程序中占主导地位。 +- 使用真实设备数据手册使用的词汇,解释什么是寄存器、什么是偏移量,以及控制字段或状态字段意味着什么。 +- 阅读简单的寄存器映射表并将其转换为包含偏移量和位掩码的 C 头文件。 +- 描述 `bus_space_tag_t` 和 `bus_space_handle_t` 的角色,以及为什么它们是一种抽象而不仅仅是指针。 +- 认识 `bus_space_read_*`、`bus_space_write_*`、`bus_space_barrier`、`bus_space_read_multi_*`、`bus_space_read_region_*` 及其定义在 `struct resource *` 上的 `bus_*` 简写形式的形式。 +- 在内核内存中模拟寄存器块,将对它的访问封装在访问器辅助函数后面,并使用这些辅助函数构建一个小的驱动程序可见设备,该设备表现得像真实的 MMIO 设备而无需触及真实硬件。 +- 将模拟寄存器访问集成到不断演进的 `myfirst` 驱动程序中,数据路径通过寄存器访问器进行读写,而不是直接操作原始缓冲区。 +- 识别寄存器读取何时有副作用、寄存器写入何时有副作用,以及为什么这对缓存、编译器重排序和调试很重要。 +- 正确使用 `bus_space_barrier` 在需要的地方强制执行访问排序,并认识什么时候不需要它。 +- 用正确类型的锁保护共享寄存器状态,避免忙等循环使其他线程饥饿。 +- 以有助于调试驱动程序而不会让读者淹没在噪音中的方式记录寄存器访问日志。 +- 重构驱动程序,使其硬件访问层成为一个命名的、有文档的、可测试的代码单元。 +- 将驱动程序标记为版本 `0.9-mmio`,更新 `LOCKING.md` 和 `HARDWARE.md`,并运行启用硬件访问的完整回归测试套件。 -The list is long; each item is narrow. The point of the chapter is the composition. +这个列表很长;每一项都很窄。本章的重点在于组合。 -### What This Chapter Does Not Cover +### 本章不涵盖的内容 -Several adjacent topics are explicitly deferred so Chapter 16 stays focused. +几个相邻主题被明确推迟,以保持第 16 章的专注。 -- **Full hardware simulation with dynamic behaviour.** The simulation in this chapter is static enough to teach the register-access vocabulary. Chapter 17 makes the simulation dynamic, with timers that change status registers, events that flip ready bits, and fault injection paths. -- **The PCI subsystem.** `pci(4)`, vendor and device ID matching, `pciconf`, `pci_enable_busmaster`, BAR mapping, MSI and MSI-X, and power management quirks belong to Chapter 18. Chapter 16 mentions PCI only when it is useful to say "this is where your BAR would come from if this were real". -- **Interrupt handlers.** `bus_setup_intr(9)`, filter handlers, interrupt threads, `INTR_MPSAFE`, and the filter-plus-task split are Chapter 19. Chapter 16 hints at them only to explain why a read with side effects matters. -- **DMA.** `bus_dma(9)`, `bus_dma_tag_create`, `bus_dmamap_load`, bounce buffers, cache flushing around DMA, and scatter-gather lists are Chapter 20 and Chapter 21. -- **Architecture-specific register access oddities.** Weakly-ordered memory models, arm64 device memory attributes, big-endian byte swapping on MIPS and PowerPC, and non-coherent caches on some embedded platforms are mentioned in passing; a deep treatment belongs to the portability chapters. -- **Real-world driver case studies.** Chapter 16 points at `if_ale.c`, `if_em.c`, and `uart_bus_pci.c` as examples of the patterns taught here, but it does not dissect them at length. Later chapters do that work where it fits their own themes. +- **具有动态行为的完整硬件模拟。** 本章的模拟足够静态,可以教授寄存器访问词汇。第 17 章使模拟变得动态,带有改变状态寄存器的计时器、翻转就绪位的事件和故障注入路径。 +- **PCI 子系统。** `pci(4)`、供应商和设备 ID 匹配、`pciconf`、`pci_enable_busmaster`、BAR 映射、MSI 和 MSI-X,以及电源管理特性属于第 18 章。第 16 章只在适合说"如果这是真的,你的 BAR 就会从这里来"的时候提及 PCI。 +- **中断处理程序。** `bus_setup_intr(9)`、过滤处理程序、中断线程、`INTR_MPSAFE` 以及过滤器加任务的拆分是第 19 章。第 16 章只是暗示它们,以解释为什么带副作用的读取很重要。 +- **DMA。** `bus_dma(9)`、`bus_dma_tag_create`、`bus_dmamap_load`、弹跳缓冲区、DMA 周围的缓存刷新以及散聚列表是第 20 章和第 21 章。 +- **架构特定的寄存器访问特性。** 弱序内存模型、arm64 设备内存属性、MIPS 和 PowerPC 上的大端字节交换,以及某些嵌入式平台上的非一致性缓存只是简单提及;深入处理属于可移植性章节。 +- **真实世界驱动程序案例研究。** 第 16 章将 `if_ale.c`、`if_em.c` 和 `uart_bus_pci.c` 指向为所授模式的示例,但不会长篇分析。后续章节在适合各自主题的地方做这项工作。 -Staying inside those lines keeps Chapter 16 a chapter about the vocabulary of hardware access. The vocabulary is what transfers; the specific subsystems are what Chapters 17 through 22 apply the vocabulary to. +保持在这些边界内让第 16 章成为一章关于硬件访问词汇的章节。词汇是可以迁移的;特定子系统是第 17 章到第 22 章将词汇应用到的对象。 -### Estimated Time Investment +### 预估时间投入 -- **Reading only**: three to four hours. The vocabulary is small but it requires thinking carefully about each term. -- **Reading plus typing the worked examples**: seven to nine hours over two sessions. The driver evolves in four stages and each stage is a small but real refactor. -- **Reading plus all labs and challenges**: twelve to fifteen hours over three or four sessions, including stress testing and reading some real FreeBSD drivers. +- **仅阅读**:三到四小时。词汇虽小,但需要仔细思考每个术语。 +- **阅读加输入示例代码**:分两次完成,共七到九小时。驱动程序分四个阶段演进,每个阶段都是一次小而真实的重构。 +- **阅读加所有实验和挑战**:分三到四次完成,共十二到十五小时,包括压力测试和阅读一些真实的 FreeBSD 驱动程序。 -Section 2 and Section 3 are the densest. If the abstraction of a tag and a handle feels opaque on first pass, that is normal. Stop, re-read the worked mapping in Section 3, and continue when the shape has settled. +第 2 节和第 3 节是最密集的。如果标签和句柄的抽象在第一次阅读时感觉不透明,那是正常的。停下来,重新阅读第 3 节中的映射示例,当形状稳定下来后继续。 -### Prerequisites +### 先决条件 -Before starting this chapter, confirm: +在开始本章之前,确认: -- Your driver source matches Chapter 15 Stage 4 (`stage4-final`). The starting point assumes every Chapter 15 primitive, every Chapter 14 taskqueue, every Chapter 13 callout, every Chapter 12 cv and sx, and the Chapter 11 concurrent IO model. -- Your lab machine runs FreeBSD 14.3 with `/usr/src` on disk and matching the running kernel. -- A debug kernel with `INVARIANTS`, `WITNESS`, `WITNESS_SKIPSPIN`, `DDB`, `KDB`, and `KDB_UNATTENDED` is built, installed, and booting cleanly. -- You understand the Chapter 15 detach ordering well enough to extend it without getting lost. -- You are comfortable reading hexadecimal offsets and bitmasks. +- 你的驱动程序源代码与第 15 章第 4 阶段(`stage4-final`)匹配。起点假设拥有第 15 章的每个原语、第 14 章的每个任务队列、第 13 章的每个 callout、第 12 章的每个 cv 和 sx,以及第 11 章的并发 IO 模型。 +- 你的实验机器运行 FreeBSD 14.3,`/usr/src` 在磁盘上并与运行中的内核匹配。 +- 一个启用了 `INVARIANTS`、`WITNESS`、`WITNESS_SKIPSPIN`、`DDB`、`KDB` 和 `KDB_UNATTENDED` 的调试内核已构建、安装并正常启动。 +- 你足够理解第 15 章的分离顺序,能够在扩展时不会迷失。 +- 你能熟练阅读十六进制偏移量和位掩码。 -If any item above is shaky, fix it now rather than pushing through Chapter 16 and trying to reason from a moving foundation. Hardware-access code is sensitive to small mistakes, and a debug kernel catches most of them on first contact. +如果以上任何项目不够稳固,现在就修复它,而不是硬推到第 16 章试图在不稳固的基础上推理。硬件访问代码对细微错误很敏感,调试内核在首次接触时就能捕获大部分错误。 -### How to Get the Most Out of This Chapter +### 如何从本章获得最大收益 -Three habits will pay off quickly. +三个习惯会很快产生回报。 -First, keep `/usr/src/sys/sys/bus.h` and `/usr/src/sys/x86/include/bus.h` bookmarked. The `bus.h` file in `/usr/src/sys/sys/` defines the shorthand `bus_read_*` and `bus_write_*` macros over a `struct resource *`. The per-architecture `bus.h` in `/usr/src/sys/x86/include/` (or its equivalent for your platform) defines the lower-level `bus_space_read_*` and `bus_space_write_*` functions and shows you exactly what they compile to. Reading those two files once takes about thirty minutes and removes almost all the mystery from the chapter. +第一,把 `/usr/src/sys/sys/bus.h` 和 `/usr/src/sys/x86/include/bus.h` 加上书签。`/usr/src/sys/sys/` 中的 `bus.h` 文件定义了 `struct resource *` 上的简写 `bus_read_*` 和 `bus_write_*` 宏。`/usr/src/sys/x86/include/`(或你平台的等效文件)中的每架构 `bus.h` 定义了较低层的 `bus_space_read_*` 和 `bus_space_write_*` 函数,并确切展示它们编译成什么。阅读这两个文件一次大约需要三十分钟,并且能消除本章中几乎所有的神秘感。 -Second, compare every new accessor to what you would have written with plain C. The exercise "if I did not have `bus_space_read_4`, how would I express this register read?" is instructive. The answer on x86 is usually "a `volatile` pointer dereference plus a compiler barrier". Seeing the contrast is how the value of the abstraction becomes concrete: the abstraction is the same code, wrapped in a name that carries portability, tracing, and documentation. +第二,将每个新的访问器与你用普通 C 会写出的代码进行比较。"如果我没有 `bus_space_read_4`,我会如何表达这个寄存器读取?"这个练习很有启发性。在 x86 上的答案通常是"一个 `volatile` 指针解引用加一个编译器屏障"。看到这种对比是让抽象的价值变得具体的方式:抽象是相同的代码,包装在一个携带可移植性、跟踪和文档的名称中。 -Third, type the changes by hand and run each stage. Hardware-access code is code where muscle memory matters. Typing `sc->regs[MYFIRST_REG_CONTROL]` and `bus_write_4(sc->res, MYFIRST_REG_CONTROL, value)` a dozen times is how the difference between raw access and abstracted access becomes visible at a glance. The companion source under `examples/part-04/ch16-accessing-hardware/` is the reference version, but the muscle memory comes from typing. +第三,亲手输入更改并运行每个阶段。硬件访问代码是需要肌肉记忆的代码。输入 `sc->regs[MYFIRST_REG_CONTROL]` 和 `bus_write_4(sc->res, MYFIRST_REG_CONTROL, value)` 十几次是让原始访问和抽象访问之间的区别一目了然的方式。`examples/part-04/ch16-accessing-hardware/` 下的配套源代码是参考版本,但肌肉记忆来自于亲手输入。 -### Roadmap Through the Chapter +### 本章路线图 -The sections in order are: +各节按顺序排列: -1. **What Is Hardware I/O?** The mental model of register access, how the driver talks to the device without touching its internals, and what kinds of resources drivers care about. -2. **Understanding Memory-Mapped I/O (MMIO).** How devices appear as memory regions, why a raw pointer cast is not how a driver reaches them, and what alignment and endianness mean here. -3. **Introduction to `bus_space(9)`.** The tag and handle abstraction, the shape of the read and write functions, and the difference between the `bus_space_*` family and the `bus_*` shorthand over a `struct resource *`. -4. **Simulating Hardware for Testing.** A register block allocated with `malloc(9)`, shaped to resemble a real device, with accessors that mirror `bus_space` semantics. Stage 1 of the Chapter 16 driver. -5. **Using `bus_space` in a Real Driver Context.** Integrating the simulated block into `myfirst`, exposing a tiny read-write register interface through the driver, and demonstrating how a task can change register state over time. Stage 2 begins here. -6. **Safety and Synchronisation with MMIO.** Memory barriers, access ordering, locking around registers, and why busy-wait loops are a mistake. Stage 3 of the driver adds the safety discipline. -7. **Debugging and Tracing Hardware Access.** Logging, DTrace, sysctl probes, and the small observability layer that makes register access visible without cluttering the driver. -8. **Refactoring and Versioning Your MMIO-Ready Driver.** The final split into `myfirst_hw.h` and `myfirst.c`, the documentation update, and the version bump to `0.9-mmio`. Stage 4 of the driver. +1. **什么是硬件 I/O?** 寄存器访问的心智模型,驱动程序如何在不触及设备内部的情况下与设备通信,以及驱动程序关心哪些类型的资源。 +2. **理解内存映射 I/O(MMIO)。** 设备如何作为内存区域出现,为什么原始指针类型转换不是驱动程序访问设备的方式,以及在此上下文中对齐和字节序意味着什么。 +3. **`bus_space(9)` 简介。** 标签和句柄抽象,读写函数的形式,以及 `bus_space_*` 系列与 `struct resource *` 上的 `bus_*` 简写之间的区别。 +4. **为测试模拟硬件。** 一个用 `malloc(9)` 分配的寄存器块,形状类似于真实设备,带有镜像 `bus_space` 语义的访问器。第 16 章驱动程序的第 1 阶段。 +5. **在真实驱动程序上下文中使用 `bus_space`。** 将模拟块集成到 `myfirst` 中,通过驱动程序暴露一个微小的读写寄存器接口,并演示任务如何随时间改变寄存器状态。第 2 阶段从这里开始。 +6. **MMIO 的安全与同步。** 内存屏障、访问排序、寄存器周围的加锁,以及为什么忙等循环是错误的。驱动程序的第 3 阶段添加了安全规范。 +7. **调试和跟踪硬件访问。** 日志记录、DTrace、sysctl 探针,以及使寄存器访问可见而不会使驱动程序变得杂乱的小型可观测性层。 +8. **重构和版本化你的 MMIO 就绪驱动程序。** 最终拆分为 `myfirst_hw.h` 和 `myfirst.c`,文档更新,以及版本号提升到 `0.9-mmio`。驱动程序的第 4 阶段。 -After the eight sections come hands-on labs, challenge exercises, a troubleshooting reference, a Wrapping Up that closes Part 3's habits and opens Part 4's, and a bridge to Chapter 17. The reference-and-cheat-sheet material at the end of the chapter is meant to be re-read as you work through later Part 4 chapters; the vocabulary of Chapter 16 is reused in every one of them. +八个节之后是动手实验、挑战练习、故障排除参考、一个关闭第三部分习惯并开启第四部分习惯的总结,以及通往第 17 章的桥梁。本章末尾的参考和速查材料旨在在你学习后续第四部分章节时重新阅读;第 16 章的词汇在它们每一个中都会被重用。 -If this is your first pass, read linearly and do the labs in order. If you are revisiting, Sections 3 and 6 stand alone and make good single-sitting reads. +如果这是你第一次阅读,请线性阅读并按顺序完成实验。如果你是复习,第 3 节和第 6 节可以独立阅读,适合单次坐下来阅读。 -## Section 1: What Is Hardware I/O? +## 第 1 节:什么是硬件 I/O? -The Chapter 15 driver's world is small. Everything it cares about, it allocates for itself. The circular buffer is a `cbuf_t` inside the softc. The heartbeat is a `struct callout` inside the softc. The writers semaphore is a `struct sema` inside the softc. Every piece of state the driver touches is memory the kernel allocator has given it. Reading from or writing to that state is a plain C memory access: a field assignment, a pointer dereference, or a call to a helper that does one of those things under a lock. +第 15 章驱动程序的世界很小。它关心的一切都是自己分配的。环形缓冲区是 softc 内部的一个 `cbuf_t`。心跳计时器是 softc 内部的一个 `struct callout`。写入者信号量是 softc 内部的一个 `struct sema`。驱动程序接触的每一块状态都是内核分配器给它的内存。从该状态读取或向其写入是一个普通的 C 内存访问:字段赋值、指针解引用,或者调用一个在锁保护下执行其中之一的辅助函数。 -Hardware changes that world. A hardware device is not kernel memory. It is a separate piece of silicon, usually on a different chip from the CPU, with its own registers, its own buffers, its own internal state, and its own rules for how the CPU may communicate with it. A driver's job is to translate the kernel's view of the world, which is software, into the device's view of the world, which is hardware. The first step in that translation is learning how the CPU and the device talk to each other at all. +硬件改变了这个世界。硬件设备不是内核内存。它是一块独立的硅片,通常在与 CPU 不同的芯片上,拥有自己的寄存器、自己的缓冲区、自己的内部状态,以及自己关于 CPU 如何与之通信的规则。驱动程序的工作是将内核的世界观(软件)转换为设备的世界观(硬件)。这种转换的第一步是学习 CPU 和设备究竟如何相互通信。 -This section introduces the mental model. Later sections build on it. The goal of Section 1 is not to make you write any code yet. The goal is to establish the vocabulary and the model clearly enough that everything that follows lands softly. +本节介绍心智模型。后续章节在此基础上构建。第 1 节的目标不是让你编写任何代码。目标是足够清晰地建立词汇和模型,使后续所有内容都能平稳落地。 -### The Device as a Cooperating Partner +### 设备作为协作伙伴 -A useful first picture is to think of a hardware device not as an object the driver controls, but as a cooperating partner the driver talks to. The device does some fixed amount of work autonomously. A disk rotates whether the driver is attentive or not. A network card receives packets off the wire without asking permission. A temperature sensor measures temperature continuously. A keyboard controller scans the keyboard matrix on a timer of its own. In every case, the device has internal behaviour the driver cannot directly influence. +一个有用的第一幅画面是:不要把硬件设备想象成驱动程序控制的对象,而要把它想象成驱动程序与之对话的协作伙伴。设备自主完成一定量的工作。磁盘不管驱动程序是否在关注都在旋转。网卡不经许可就从线路接收数据包。温度传感器持续测量温度。键盘控制器按自己的计时器扫描键盘矩阵。在每种情况下,设备都有驱动程序无法直接影响的内部行为。 -What the driver can do is send the device commands and receive the device's status and data. The device exposes a small interface: a set of registers, each with a specific meaning, each with a specific protocol for how the driver may read or write it. The driver writes a value to a control register to tell the device what to do. The driver reads a value from a status register to find out what the device is doing. The driver reads a value from a data register to get data the device has received. The driver writes a value to a data register to send data the device should transmit. +驱动程序能做的是向设备发送命令并接收设备的状态和数据。设备暴露一个小型接口:一组寄存器,每个都有特定含义,每个都有关于驱动程序如何读写的特定协议。驱动程序向控制寄存器写入值来告诉设备该做什么。驱动程序从状态寄存器读取值来了解设备正在做什么。驱动程序从数据寄存器读取值来获取设备已接收的数据。驱动程序向数据寄存器写入值来发送设备应该传输的数据。 -Registers, in this picture, are the conversation. The driver does not call a method on the device and does not pass arguments in the C sense. The driver writes a specific value at a specific offset, and the device reads that write and responds. The device writes a specific value at a specific offset, and the driver reads that write to see what the device is telling it. The protocol is entirely defined by the device's documentation, which is usually a datasheet. The driver's job is to follow the protocol. +在这个画面中,寄存器就是对话。驱动程序不是在设备上调用方法,也不是以 C 的意义传递参数。驱动程序在特定偏移量处写入特定值,设备读取该写入并做出响应。设备在特定偏移量处写入特定值,驱动程序读取该写入以了解设备在告诉它什么。协议完全由设备的文档定义,通常是数据手册。驱动程序的工作是遵循协议。 -That word "partner" is doing a lot of work. Hardware is famously unforgiving. A device does not document every wrong thing the driver could do; it simply does something wrong, or undefined, if the driver breaks the protocol. A driver that writes the wrong value to a control register may brick a device until the next power cycle. A driver that reads a status register before the device has finished a previous command may see stale data and make a bad decision. A driver that does not clear an interrupt flag before returning from an interrupt handler may leave the device thinking the interrupt is still pending. The partner metaphor is cooperative in intent; the actual relationship is one where the driver must be very polite and very attentive, because the device has no way to object except by misbehaving. +"伙伴"这个词承载了很多含义。硬件以不宽容著称。设备不会记录驱动程序可能做的每一件错事;如果驱动程序违反了协议,它只是做一些错误的或未定义的事情。向控制寄存器写入错误值的驱动程序可能会使设备变砖直到下一次加电循环。在设备完成上一个命令之前读取状态寄存器的驱动程序可能会看到陈旧数据并做出错误决定。从中断处理程序返回前不清除中断标志的驱动程序可能会让设备认为中断仍在挂起。伙伴的比喻在意图上是协作的;实际的关系是驱动程序必须非常有礼貌、非常专注,因为设备除了行为异常之外没有其他方式来表达反对。 -### What "Accessing Hardware" Really Means +### "访问硬件"真正意味着什么 -The phrase "accessing hardware" shows up in every kernel programming text, and it rewards a closer look. What does the CPU actually do when a driver reads a register from a device? +"访问硬件"这个短语出现在每一本内核编程教科书中,值得仔细审视。当驱动程序从设备读取寄存器时,CPU 实际上做了什么? -On modern platforms the most common answer is: the CPU issues a memory access to a specific physical address, and the memory controller routes that access to the device rather than to RAM. From the CPU's point of view, it looks like an ordinary load or store. From the device's point of view, it is a message from the CPU addressed to a specific internal register. The wiring in between, the memory controller and the bus fabric, is what makes the routing work. +在现代平台上,最常见的答案是:CPU 向特定物理地址发出内存访问,内存控制器将该访问路由到设备而不是 RAM。从 CPU 的角度来看,它看起来像一个普通的加载或存储。从设备的角度来看,它是来自 CPU 的、寻址到特定内部寄存器的消息。中间的布线,即内存控制器和总线结构,是使路由生效的关键。 -That is memory-mapped I/O. The CPU uses normal load and store instructions. The address happens to be routed to a device instead of to RAM. The device exposes its registers as a range of physical addresses, and the driver reads and writes within that range the way it would read and write any other memory. +这就是内存映射 I/O。CPU 使用普通的加载和存储指令。地址恰好被路由到设备而不是 RAM。设备将其寄存器暴露为一段物理地址范围,驱动程序在该范围内读写,就像读写任何其他内存一样。 -An older, less common answer on x86 CPUs is: the CPU issues a special I/O instruction (`in` or `out`) to a specific I/O port number, and the chipset routes that instruction to the device. The CPU is not using a load or store; it is using a dedicated instruction that operates on a separate address space, called I/O port space or port-mapped I/O. This was the original mechanism on x86 and is still in use for some legacy devices, but modern drivers rarely see it except in compatibility paths. +在 x86 CPU 上,一个更老、不太常见的答案是:CPU 向特定 I/O 端口号发出特殊 I/O 指令(`in` 或 `out`),芯片组将该指令路由到设备。CPU 不是在使用加载或存储;它在使用一条在独立地址空间(称为 I/O 端口空间或端口映射 I/O)上操作的专用指令。这是 x86 上最初的机制,一些传统设备仍在使用,但现代驱动程序除了兼容路径外很少见到它。 -FreeBSD abstracts both mechanisms behind a single API. The driver does not care, most of the time, whether a register is reached through a memory access or through an I/O instruction. The abstraction is `bus_space(9)`, which Section 3 introduces. For now, notice that "accessing hardware" is a physical operation on the CPU that the OS hides behind a software interface. The driver writes `bus_space_write_4(tag, handle, offset, value)`, and the kernel does the right thing depending on the platform and the resource type. +FreeBSD 将两种机制抽象到单个 API 后面。驱动程序大多数时候不关心寄存器是通过内存访问还是通过 I/O 指令到达的。这个抽象是 `bus_space(9)`,第 3 节将介绍它。目前只需注意,"访问硬件"是 CPU 上的物理操作,操作系统将其隐藏在软件接口后面。驱动程序写入 `bus_space_write_4(tag, handle, offset, value)`,内核根据平台和资源类型做正确的事情。 -### Why a Raw Pointer Cast Is Not How Drivers Reach Hardware +### 为什么原始指针类型转换不是驱动程序访问硬件的方式 -A new reader might reasonably ask: if a device appears as a range of physical addresses, why not just take the address of the device's registers, cast it to a `volatile uint32_t *`, and dereference it? Technically, on some platforms, that works. Practically, no FreeBSD driver does this, and several real reasons make the raw cast a poor choice. +新读者可能会合理地问:如果设备表现为一段物理地址范围,为什么不直接取设备寄存器的地址,将其转换为 `volatile uint32_t *`,然后解引用它?从技术上讲,在某些平台上这是可行的。实际上,没有 FreeBSD 驱动程序这样做,有几个真实的原因使原始类型转换成为糟糕的选择。 -First, the driver does not know the physical address of the device at compile time. The address is assigned by the bus enumeration code at boot or hotplug, based on the Base Address Registers (BARs) that the device advertises. The driver's attach routine asks the bus subsystem for the resource; the bus subsystem returns a handle that carries the mapping. The driver then uses the handle through the `bus_space` API. There is no place in the driver's source where the physical address is a constant. +第一,驱动程序在编译时不知道设备的物理地址。地址是由总线枚举代码在启动或热插拔时分配的,基于设备通告的基址寄存器(BAR)。驱动程序的 attach 例程向总线子系统请求资源;总线子系统返回一个携带映射的句柄。驱动程序然后通过 `bus_space` API 使用该句柄。驱动程序源代码中没有任何地方将物理地址作为常量。 -Second, physical addresses are not virtual addresses. The CPU runs in virtual address mode; dereferencing a pointer reads from virtual memory, not physical memory. The kernel's `pmap(9)` layer maintains the translation. A driver that wants to dereference a device's registers needs a virtual mapping into the device's physical range, with the right cache and access attributes. `bus_space_map` does this. A raw pointer cast does not. +第二,物理地址不是虚拟地址。CPU 运行在虚拟地址模式;解引用指针从虚拟内存读取,而不是从物理内存读取。内核的 `pmap(9)` 层维护这种转换。想要解引用设备寄存器的驱动程序需要到设备物理范围的虚拟映射,并具有正确的缓存和访问属性。`bus_space_map` 做这件事。原始指针类型转换不做。 -Third, different architectures require different access attributes for device memory than for RAM. Device memory must usually be marked uncached, or weakly-cached, or marked as "device memory" in the MMU's page tables, so that the CPU does not reorder or cache the accesses in ways that confuse the device. On arm64, device memory pages use the `nGnRnE` or `nGnRE` attributes that disable speculative prefetching. On x86, the `PAT` and `MTRR` mechanisms mark device regions as uncached or write-combining. A raw pointer cast uses whatever attributes the surrounding virtual mapping happens to have, which is usually cached, which is usually wrong for device registers. +第三,不同架构对设备内存和 RAM 要求不同的访问属性。设备内存通常必须标记为不可缓存、弱缓存或在 MMU 的页表中标记为"设备内存",以便 CPU 不会以使设备困惑的方式重排序或缓存访问。在 arm64 上,设备内存页使用 `nGnRnE` 或 `nGnRE` 属性来禁用推测性预取。在 x86 上,`PAT` 和 `MTRR` 机制将设备区域标记为不可缓存或写合并。原始指针类型转换使用周围虚拟映射碰巧具有的任何属性,这通常是有缓存的,对设备寄存器来说通常是错误的。 -Fourth, `bus_space` carries extra information beyond just where to read and write. The tag encodes which address space (memory or I/O port) is in use. On architectures where the two are different, the tag chooses the correct CPU instruction. On architectures where a driver might map a region with byte-swapping for endianness, the tag encodes that too. The tag-plus-handle interface is a portable way to express "access this device with the right semantics", where a raw pointer is just "poke this virtual address and hope". +第四,`bus_space` 携带关于在哪里读写之外的额外信息。标签编码了正在使用的地址空间(内存或 I/O 端口)。在两者不同的架构上,标签选择正确的 CPU 指令。在驱动程序可能为字节序而映射带有字节交换的区域时,标签也编码了这一点。标签加句柄的接口是一种可移植的方式来表达"以正确的语义访问此设备",而原始指针只是"戳一下这个虚拟地址然后祈祷"。 -Fifth, `bus_space` supports tracing, hardware access auditing, and optional sanity checks through the `bus_san(9)` layer when the kernel is built with sanitisers enabled. A raw pointer cast is invisible to those tools. If you ever want to know when your driver read a particular register, `bus_space` can tell you; a raw dereference cannot. +第五,`bus_space` 支持跟踪、硬件访问审计,以及在内核启用清理器时通过 `bus_san(9)` 层进行可选的健全性检查。原始指针类型转换对这些工具是不可见的。如果你想知道驱动程序何时读取了特定寄存器,`bus_space` 可以告诉你;原始解引用不能。 -The short version is: FreeBSD drivers use `bus_space` because it abstracts a real problem the driver needs to solve, and the raw pointer cast works on some platforms by accident rather than by design. Accepting the abstraction is inexpensive; refusing it creates bugs that surface weeks after deployment. +简短版本是:FreeBSD 驱动程序使用 `bus_space` 是因为它抽象了驱动程序需要解决的真实问题,而原始指针类型转换在某些平台上有效只是巧合而非设计。接受这种抽象代价很低;拒绝它会在部署数周后产生 bug。 -### Categories of Resources a Driver Cares About +### 驱动程序关心的资源类别 -Most drivers deal with a small handful of resource categories. Each has a different access pattern. Chapter 16 focuses on one of them (memory-mapped registers), and the others are covered in later chapters. Knowing the whole catalogue helps you place the current topic. +大多数驱动程序处理少量的资源类别。每个类别有不同的访问模式。第 16 章专注于其中之一(内存映射寄存器),其他在后续章节中介绍。了解整个目录有助于你定位当前主题。 -**Memory-mapped I/O (MMIO) registers.** A range of device physical addresses, mapped into the kernel's virtual address space, used to send commands and receive status. Every modern device has at least one MMIO region; most have several. Chapter 16's focus. +**内存映射 I/O(MMIO)寄存器。** 一段设备物理地址范围,映射到内核的虚拟地址空间,用于发送命令和接收状态。每个现代设备至少有一个 MMIO 区域;大多数有多个。第 16 章的焦点。 -**Port-mapped I/O (PIO) registers.** A range of I/O port numbers on x86, accessed through the `in` and `out` CPU instructions. Older devices used this as their primary mechanism. Newer devices sometimes expose a small compatibility window through ports (a legacy serial controller, for example) while putting the main interface in MMIO. The `bus_space` API abstracts both behind the same read and write calls, which is why this chapter treats them together. +**端口映射 I/O(PIO)寄存器。** x86 上的一段 I/O 端口号范围,通过 `in` 和 `out` CPU 指令访问。较旧的设备使用它作为主要机制。较新的设备有时通过端口暴露一个小的兼容窗口(例如传统串行控制器),同时将主接口放在 MMIO 中。`bus_space` API 将两者抽象在相同的读写调用后面,这就是为什么本章将它们放在一起处理。 -**Interrupts.** A signal from the device to the CPU that something has happened. The driver registers an interrupt handler through `bus_setup_intr(9)`, and the kernel arranges for the handler to run when the interrupt line asserts. Chapter 19 covers interrupts. +**中断。** 从设备到 CPU 的信号,表示发生了某事。驱动程序通过 `bus_setup_intr(9)` 注册中断处理程序,内核安排在中断线触发时运行该处理程序。第 19 章涵盖中断。 -**DMA channels.** The device reads or writes directly into system RAM, bypassing the CPU. The driver prepares a DMA descriptor that tells the device which RAM addresses it may use. FreeBSD's `bus_dma(9)` API manages the mappings, the cache coherence, and the synchronisation. Chapters 20 and 21 cover DMA. +**DMA 通道。** 设备绕过 CPU 直接读取或写入系统 RAM。驱动程序准备一个 DMA 描述符,告诉设备可以使用哪些 RAM 地址。FreeBSD 的 `bus_dma(9)` API 管理映射、缓存一致性和同步。第 20 章和第 21 章涵盖 DMA。 -**Configuration space.** On PCI, a separate address space per device, used to describe the device to the OS. BARs live here, the vendor and device IDs live here, power management state lives here. Most drivers read configuration space only once, during attach, to discover the device's capabilities. Chapter 18 covers PCI configuration space. +**配置空间。** 在 PCI 上,每个设备的独立地址空间,用于向操作系统描述设备。BAR 在这里,供应商和设备 ID 在这里,电源管理状态在这里。大多数驱动程序只在 attach 期间读取一次配置空间,以发现设备的能力。第 18 章涵盖 PCI 配置空间。 -**Bus-specific capabilities.** MSI, MSI-X, PCIe extended capabilities, hot-plug events, errata workarounds. Bus-specific chapters cover these. +**总线特定的能力。** MSI、MSI-X、PCIe 扩展能力、热插拔事件、勘误解决方案。总线特定的章节涵盖这些。 -This chapter lives in the MMIO box. The `bus_space` abstraction also covers PIO, so we will see port-mapped paths in passing, but the working example is MMIO throughout. +本章位于 MMIO 框内。`bus_space` 抽象也涵盖 PIO,所以我们会顺带看到端口映射路径,但工作示例始终是 MMIO。 -### The Register, Closer Up +### 寄存器,近看 -A register, in the device's language, is a unit of communication. It has a name, an offset, a width, a set of fields, and a protocol. +在设备的语言中,寄存器是一个通信单元。它有名称、偏移量、宽度、一组字段和一个协议。 -The **name** is how the datasheet refers to it. `CONTROL`, `STATUS`, `DATA_IN`, `DATA_OUT`, `INTR_MASK`. Names are for humans; the device does not know them. +**名称**是数据手册引用它的方式。`CONTROL`、`STATUS`、`DATA_IN`、`DATA_OUT`、`INTR_MASK`。名称是给人类用的;设备不知道它们。 -The **offset** is the distance from the start of the device's register block to the start of this specific register. Offsets are usually given in hexadecimal. `CONTROL` at `0x00`. `STATUS` at `0x04`. `DATA_IN` at `0x08`. `DATA_OUT` at `0x0c`. `INTR_MASK` at `0x10`. The driver uses offsets in every read and write. +**偏移量**是从设备寄存器块起始处到这个特定寄存器起始处的距离。偏移量通常以十六进制给出。`CONTROL` 在 `0x00`。`STATUS` 在 `0x04`。`DATA_IN` 在 `0x08`。`DATA_OUT` 在 `0x0c`。`INTR_MASK` 在 `0x10`。驱动程序在每次读写中使用偏移量。 -The **width** is how many bits the register carries. Common widths are 8, 16, 32, and 64 bits. A 32-bit register is accessed with `bus_space_read_4` and `bus_space_write_4`, where the `4` is the width in bytes. Mismatching the width is a surprisingly common bug; reading a 32-bit register with an 8-bit access reads only one byte, and on some platforms with byte-lane restrictions it may return the wrong byte or no byte at all. +**宽度**是寄存器携带的位数。常见宽度是 8、16、32 和 64 位。一个 32 位寄存器用 `bus_space_read_4` 和 `bus_space_write_4` 访问,其中 `4` 是以字节为单位的宽度。宽度不匹配是一个令人惊讶的常见 bug;用 8 位访问读取 32 位寄存器只读一个字节,而在某些有字节通道限制的平台上,它可能返回错误的字节或不返回任何字节。 -The **fields** inside a register are sub-bit-ranges that each mean something specific. A 32-bit `CONTROL` register might have an `ENABLE` bit at bit 0, a `RESET` bit at bit 1, a 4-bit `MODE` field at bits 4 through 7, and a 16-bit `THRESHOLD` field at bits 16 through 31, with the remaining bits reserved. The driver uses bit masks and shifts to extract or set specific fields, and the datasheet defines every mask and shift. +寄存器内部的**字段**是子位范围,每个都有特定含义。一个 32 位的 `CONTROL` 寄存器可能在第 0 位有一个 `ENABLE` 位,在第 1 位有一个 `RESET` 位,在第 4 到 7 位有一个 4 位的 `MODE` 字段,在第 16 到 31 位有一个 16 位的 `THRESHOLD` 字段,其余位保留。驱动程序使用位掩码和移位来提取或设置特定字段,数据手册定义了每个掩码和移位。 -The **protocol** is the rules the driver must follow when reading or writing the register. Some protocols are trivial ("write this register with the value you want"). Some are subtle ("set the ENABLE bit, then poll the READY bit in STATUS for up to 100 microseconds, then write the DATA_IN register"). Some have side effects that the driver must know about ("reading STATUS clears the error bits"). Getting the protocol right is the bulk of driver development time in many hardware projects. +**协议**是驱动程序在读写寄存器时必须遵循的规则。有些协议很简单("用你想要的值写这个寄存器")。有些很微妙("设置 ENABLE 位,然后轮询 STATUS 中的 READY 位最多 100 微秒,然后写 DATA_IN 寄存器")。有些有驱动程序必须了解的副作用("读取 STATUS 会清除错误位")。在许多硬件项目中,正确实现协议占了驱动程序开发时间的大部分。 -For Chapter 16 the registers are simple, because the device is simulated. But the vocabulary is the vocabulary of real datasheets, and every term introduced here transfers directly to any real device you will meet later. +对于第 16 章,寄存器很简单,因为设备是模拟的。但词汇是真实数据手册的词汇,这里引入的每个术语都可以直接迁移到你以后将遇到的任何真实设备。 -### A First Mental Model: The Control Panel +### 第一个心智模型:控制面板 -A useful analogy, only if you keep it disciplined, is that of a control panel on an industrial machine. The machine does its work on its own schedule. The panel exposes knobs the operator can turn to tell the machine what to do, gauges the operator can read to see what the machine is doing, and a few lights that go on and off to signal events. The operator does not reach inside the machine; the operator reaches the machine through the panel. +一个有用的类比(前提是你保持克制)是工业机器上的控制面板。机器按照自己的时间表工作。面板暴露了操作员可以转动的旋钮来告诉机器该做什么,操作员可以读取的仪表来了解机器在做什么,以及一些亮灭的灯来发出事件信号。操作员不会把手伸进机器内部;操作员通过面板与机器交互。 -The driver is the operator. The register block is the control panel. A knob on the panel is a control field in a register. A gauge is a status field. A light is a status bit. The wiring behind the panel is the device's internal logic, which the driver does not see and cannot directly influence. The cable between the operator and the panel is `bus_space`: it carries the operator's turns of the knob and the gauge's readings back and forth, in a language the operator and the panel both understand. +驱动程序就是操作员。寄存器块就是控制面板。面板上的旋钮是寄存器中的控制字段。仪表是状态字段。灯是状态位。面板后面的布线是设备的内部逻辑,驱动程序看不到也不能直接影响。操作员和面板之间的电缆是 `bus_space`:它以一种操作员和面板都懂的语言,来回传递操作员对旋钮的转动和仪表的读数。 -The analogy breaks down quickly if pushed. Real hardware has timing constraints the panel does not. Real hardware has side effects that the panel does not. Real hardware speaks a protocol that changes when the machine's internal state changes. But for the first pass, the panel is good enough: the driver writes to a control field, the device reacts, the driver reads a status field, the device tells it what happened. +如果过度推演,这个类比很快就会崩溃。真实硬件有面板没有的时序约束。真实硬件有面板没有的副作用。真实硬件说的协议会随着机器内部状态的改变而改变。但对于第一遍来说,面板已经够用了:驱动程序写入控制字段,设备做出反应,驱动程序读取状态字段,设备告诉它发生了什么。 -Later sections replace the analogy with more precise mental models: the register block as a window into device state, the MMIO region as a memory range with side-effects, the `bus_space` interface as a platform-aware messenger. For now, the panel is the on-ramp. +后续章节用更精确的心智模型替换了这个类比:寄存器块作为设备状态的窗口、MMIO 区域作为带副作用的内存范围、`bus_space` 接口作为平台感知的信使。目前,面板是入口匝道。 -### Why Simulating Hardware Is a Good First Practice +### 为什么模拟硬件是好的首次实践 -Chapter 16's teaching strategy is to simulate a device rather than require the reader to have a specific piece of real hardware. The reasons are practical and deliberate. +第 16 章的教学策略是模拟一个设备,而不是要求读者拥有特定的真实硬件。这些原因是实际的和经过深思熟虑的。 -A reader who is practising register-style access for the first time benefits enormously from an environment where they can see the register values directly. A real PCI device's registers are hidden behind a BAR; the reader can read them with `pciconf -r`, but only for specific known offsets, and the values change based on device state in ways a datasheet may not fully document. A simulated device, by contrast, is a struct in kernel memory. The reader can print its contents with a sysctl. The reader can modify it from user space through an ioctl. The reader can inspect it in ddb. The simulation closes the loop between action and observation, which is what makes the practice effective. +首次练习寄存器式访问的读者从能直接看到寄存器值的环境中获益匪浅。真实 PCI 设备的寄存器隐藏在 BAR 后面;读者可以用 `pciconf -r` 读取它们,但只能读取特定的已知偏移量,而且这些值以数据手册可能不完全记录的方式根据设备状态变化。相比之下,模拟设备是内核内存中的一个结构体。读者可以用 sysctl 打印其内容。可以通过 ioctl 从用户空间修改它。可以在 ddb 中检查它。模拟关闭了操作和观察之间的循环,这正是使练习有效的原因。 -A simulated device is also safe. A real device that receives a wrong register value may lock up, corrupt data, or require a physical power cycle. A simulated device that receives a wrong register value does nothing worse than set a wrong bit in kernel memory; if the driver leaks that, `INVARIANTS` will complain. Beginners benefit from the safety net. +模拟设备也是安全的。收到错误寄存器值的真实设备可能会锁定、损坏数据或需要物理加电循环。收到错误寄存器值的模拟设备最坏也只是在内核内存中设置了错误的位;如果驱动程序泄漏了它,`INVARIANTS` 会报告。初学者从安全网中受益。 -A simulated device is reproducible. Every reader running the Chapter 16 code sees the same register values in the same order. A real device's behaviour depends on firmware version, hardware revision, and environmental conditions. Teaching over a reproducible target is much easier than teaching over the union of every possible target. +模拟设备是可复现的。运行第 16 章代码的每个读者都以相同的顺序看到相同的寄存器值。真实设备的行为取决于固件版本、硬件修订和环境条件。在可复现的目标上教学比在所有可能目标的联合上教学容易得多。 -Chapter 17 expands the simulation with timers, events, and fault injection. Chapter 18 introduces a real PCI device (typically a virtio device in a VM) so the reader can practise the real-hardware path. Chapter 16 lays the ground by teaching the vocabulary against a static simulation, which is the gentlest version of the material. +第 17 章通过计时器、事件和故障注入扩展模拟。第 18 章引入真实 PCI 设备(通常是虚拟机中的 virtio 设备),以便读者可以练习真实硬件路径。第 16 章通过在静态模拟上教授词汇来奠定基础,这是最温和的材料版本。 -### A Glance at Real Drivers That Use Hardware I/O +### 使用硬件 I/O 的真实驱动程序一览 -Before moving on, a short tour of real FreeBSD drivers that exercise the patterns Chapter 16 teaches. You do not need to read these files yet; they are waypoints you can return to as the chapter unfolds. +在继续之前,快速浏览使用第 16 章所授模式的真实 FreeBSD 驱动程序。你现在不需要阅读这些文件;它们是你可以在本章展开过程中返回的路标。 -`/usr/src/sys/dev/uart/uart_bus_pci.c` is a PCI glue layer for UART (serial) controllers. It shows how a driver finds its PCI device, claims an MMIO resource, and hands the resource to a lower layer that actually drives the hardware. It is small and readable, and it uses `bus_space` only indirectly. +`/usr/src/sys/dev/uart/uart_bus_pci.c` 是 UART(串行)控制器的 PCI 粘合层。它展示了驱动程序如何找到其 PCI 设备、声明 MMIO 资源,并将资源交给实际驱动硬件的较低层。它小而可读,只间接使用 `bus_space`。 -`/usr/src/sys/dev/uart/uart_dev_ns8250.c` is the real UART driver for the classic 8250-family serial controller. It is the file where register reads and writes happen. The register layout is defined in `uart_bus.h` and `uart_dev_ns8250.h`. The reads use the abstraction the chapter teaches. +`/usr/src/sys/dev/uart/uart_dev_ns8250.c` 是经典 8250 系列串行控制器的真实 UART 驱动程序。它是寄存器读写发生的地方。寄存器布局定义在 `uart_bus.h` 和 `uart_dev_ns8250.h` 中。读取使用了本章教授的抽象。 -`/usr/src/sys/dev/ale/if_ale.c` is an Ethernet driver for the Attansic L1E chipset. Its `if_alevar.h` defines `CSR_READ_4` and `CSR_WRITE_4` macros over `bus_read_4` and `bus_write_4`, which is a pattern you will adopt in your own driver by Stage 4 of this chapter. +`/usr/src/sys/dev/ale/if_ale.c` 是 Attansic L1E 芯片组的以太网驱动程序。它的 `if_alevar.h` 在 `bus_read_4` 和 `bus_write_4` 上定义了 `CSR_READ_4` 和 `CSR_WRITE_4` 宏,这是你将在本章第 4 阶段在自己的驱动程序中采用的模式。 -`/usr/src/sys/dev/e1000/if_em.c` is the driver for Intel's gigabit Ethernet controllers (e1000 family). It is larger and more complex than `if_ale.c`, but it uses the same `bus_space` vocabulary. Its attach path is a good reference for how a non-trivial driver allocates MMIO resources. +`/usr/src/sys/dev/e1000/if_em.c` 是 Intel 千兆以太网控制器(e1000 系列)的驱动程序。它比 `if_ale.c` 更大更复杂,但使用相同的 `bus_space` 词汇。它的 attach 路径是非平凡驱动程序如何分配 MMIO 资源的良好参考。 -`/usr/src/sys/dev/led/led.c` is the LED driver. It is a pseudo-device driver that does not talk to real hardware at all; it exposes a small interface through `/dev/led.NAME` and delegates the actual LED control to whichever driver registered it. Chapter 16's simulated device borrows the shape of this driver: a small, self-contained module with a clear interface and no dependency on external hardware. +`/usr/src/sys/dev/led/led.c` 是 LED 驱动程序。它是一个根本不与真实硬件通信的伪设备驱动程序;它通过 `/dev/led.NAME` 暴露一个小接口,并将实际的 LED 控制委托给注册它的任何驱动程序。第 16 章的模拟设备借鉴了这个驱动程序的形式:一个小型的、自包含的模块,有清晰的接口,不依赖外部硬件。 -These files will reappear throughout Part 4. Chapter 16 uses them as tour points; later chapters dissect them where their patterns are the chapter's focus. +这些文件将在第四部分中反复出现。第 16 章将它们用作巡览点;后续章节在它们的模式是章节焦点的地方分析它们。 -### What Comes Next in This Chapter +### 本章接下来的内容 -Section 2 moves from the abstract picture to the specific mechanism of memory-mapped I/O. It explains what a mapping is, why device memory is accessed with different rules than ordinary memory, and how the driver can think about alignment, endianness, and caching. Section 3 introduces `bus_space(9)` itself. Section 4 builds the simulated device. Section 5 integrates it into `myfirst`. Section 6 adds the safety discipline. Sections 7 and 8 finish the chapter with debugging, refactoring, and versioning. +第 2 节从抽象图景转向内存映射 I/O 的具体机制。它解释什么是映射、为什么设备内存必须以不同于普通内存的规则访问,以及驱动程序应该如何考虑对齐、字节序和缓存。第 3 节介绍 `bus_space(9)` 本身。第 4 节构建模拟设备。第 5 节将其集成到 `myfirst` 中。第 6 节添加安全规范。第 7 和 8 节以调试、重构和版本化完成本章。 -The pace from here is slower than Section 1. Section 1 was meant to be read linearly and absorbed as a whole; the later sections are meant to be read section by section, with breaks to type the code and run it. +从这里开始的节奏比第 1 节慢。第 1 节旨在线性阅读并作为一个整体吸收;后续章节旨在逐节阅读,中间有休息来输入代码并运行。 -### Wrapping Up Section 1 +### 第 1 节总结 -Hardware I/O is the activity through which a driver talks to a device. The driver cannot reach inside the device; it can only send commands and read status through a defined register interface. On modern platforms the interface is usually memory-mapped; on x86 there is a legacy port-mapped path as well. The FreeBSD abstraction `bus_space(9)` hides the difference from the driver most of the time. A register is a named, offset-located, width-specific unit of communication, with fields and a protocol that the device's datasheet defines. +硬件 I/O 是驱动程序与设备对话的活动。驱动程序无法触及设备内部;它只能通过定义好的寄存器接口发送命令和读取状态。在现代平台上,接口通常是内存映射的;在 x86 上还有一个传统的端口映射路径。FreeBSD 的抽象 `bus_space(9)` 大部分时间对驱动程序隐藏了差异。寄存器是一个命名的、按偏移量定位的、宽度特定的通信单元,带有由设备数据手册定义的字段和协议。 -Chapter 16's simulation lets you practise the vocabulary without real hardware. Later Part 4 chapters apply the vocabulary to real subsystems. The vocabulary is what transfers, and the rest of this chapter exists to give you that vocabulary with enough depth to use it comfortably. +第 16 章的模拟让你在没有真实硬件的情况下练习词汇。后续第四部分章节将词汇应用到真实子系统。词汇是可以迁移的,本章的其余部分旨在给你足够的深度来舒适地使用这些词汇。 -Section 2 begins by looking closely at memory-mapped I/O. +第 2 节从仔细审视内存映射 I/O 开始。 -## Section 2: Understanding Memory-Mapped I/O (MMIO) +## 第 2 节:理解内存映射 I/O(MMIO) -Section 1 introduced the idea that a device's registers can be reached through ordinary-looking memory accesses. That idea is worth slowing down for. Memory-mapped I/O is the dominant mechanism on modern FreeBSD platforms, and understanding it well is what makes every later chapter in Part 4 feel tractable rather than mysterious. +第 1 节介绍了设备的寄存器可以通过看起来普通的内存访问来达到的概念。这个概念值得放慢脚步来理解。内存映射 I/O 是现代 FreeBSD 平台上的主导机制,深入理解它将使第四部分的每个后续章节显得可驾驭而非神秘。 -This section answers three closely related questions. How does a device appear in memory? Why must the CPU access that memory with different rules than ordinary memory? What does a driver need to think about when reading and writing a register? +本节回答三个密切相关的问题。设备如何出现在内存中?为什么 CPU 必须以不同于普通内存的规则访问该内存?驱动程序在读写寄存器时需要考虑什么? -The section works from the ground up: physical addresses, virtual mappings, cache attributes, alignment, and endianness. Each piece is small. The composition is where the subtlety lives. +本节从基础开始:物理地址、虚拟映射、缓存属性、对齐和字节序。每个部分都很小。微妙之处在于它们的组合。 -### Physical Addresses and Device Memory +### 物理地址与设备内存 -The CPU executes instructions. Each load and store instruction names a virtual address, which the memory management unit (MMU) translates into a physical address. Physical addresses are what the memory controller sees. The memory controller's job is to route the access to the right destination. +CPU 执行指令。每条加载和存储指令命名一个虚拟地址,内存管理单元(MMU)将其转换为物理地址。物理地址是内存控制器看到的。内存控制器的工作是将访问路由到正确的目的地。 -For most physical addresses, the destination is DRAM. The controller reads or writes a location in system RAM and returns the result to the CPU. This is the common case. Every `malloc(9)` allocation the driver makes returns kernel memory whose physical address is backed by DRAM. +对于大多数物理地址,目的地是 DRAM。控制器读取或写入系统 RAM 中的一个位置并将结果返回给 CPU。这是常见情况。驱动程序进行的每个 `malloc(9)` 分配返回的内核内存,其物理地址都由 DRAM 支持。 -Some physical address ranges, however, are routed to devices instead. The memory controller is configured at boot (by firmware, usually by the BIOS or UEFI on x86, or by the device tree on arm and the `acpi` tables on everything) to send accesses in certain ranges to specific devices. A PCI device might live at physical address `0xfebf0000` through `0xfebfffff`, a 64 KiB region. An embedded UART might live at `0x10000000` through `0x10000fff`, a 4 KiB region. Whatever the range, an access inside it routes to the device rather than to RAM. +然而,一些物理地址范围被路由到设备。内存控制器在启动时由固件配置(在 x86 上通常是 BIOS 或 UEFI,在 arm 上是设备树,在所有平台上是 `acpi` 表),将某些范围内的访问发送到特定设备。一个 PCI 设备可能位于物理地址 `0xfebf0000` 到 `0xfebfffff`,一个 64 KiB 的区域。一个嵌入式 UART 可能位于 `0x10000000` 到 `0x10000fff`,一个 4 KiB 的区域。无论范围如何,其中的访问路由到设备而不是 RAM。 -From the CPU's point of view, the access looks identical to an access to RAM. The instruction is the same; the address happens to be elsewhere. From the device's point of view, the access looks like an incoming message: a read at offset X of the device's internal register file, or a write of some value at offset Y. +从 CPU 的角度来看,该访问看起来与对 RAM 的访问完全相同。指令是相同的;地址恰好指向别处。从设备的角度来看,该访问看起来像一条传入消息:对设备内部寄存器文件偏移量 X 的读取,或在偏移量 Y 处写入某个值。 -The key property is that the same CPU instruction (a load or a store) is being reused for a different purpose. That is where "memory-mapped" in MMIO comes from: the device's interface is mapped into the CPU's memory address space, so memory-access instructions reach it. +关键属性是相同的 CPU 指令(加载或存储)被重新用于不同目的。这就是 MMIO 中"内存映射"的由来:设备的接口被映射到 CPU 的内存地址空间中,因此内存访问指令可以到达它。 -Port-mapped I/O, the x86 alternative, uses separate instructions (`in`, `out`, and their wider variants) that target a different address space. The port space has its own 16-bit address range on x86. Modern FreeBSD drivers rarely reach port space directly, because modern devices prefer MMIO, but the abstraction is the same: the driver writes a value at an address, and the address happens to route to a device. +端口映射 I/O,即 x86 的替代方案,使用独立的指令(`in`、`out` 及其更宽的变体)来寻址不同的地址空间。端口空间在 x86 上有自己的 16 位地址范围。现代 FreeBSD 驱动程序很少直接访问端口空间,因为现代设备更偏好 MMIO,但抽象是相同的:驱动程序在某个地址写入一个值,该地址恰好路由到设备。 -### The Virtual Mapping +### 虚拟映射 -The CPU does not access physical memory directly. Every memory access goes through the MMU, which translates a virtual address into a physical address using page tables. The kernel maintains those page tables in its `pmap(9)` layer. For a driver to read device registers, it needs a virtual mapping into the device's physical range. +CPU 不直接访问物理内存。每次内存访问都经过 MMU,MMU 使用页表将虚拟地址转换为物理地址。内核在其 `pmap(9)` 层中维护这些页表。驱动程序要读取设备寄存器,它需要到设备物理范围的虚拟映射。 -When the kernel's bus subsystem discovers a device and the driver's attach routine requests an MMIO resource, the bus layer does two things. First, it finds the physical address range the device occupies, which the device's Base Address Register (BAR) or the platform's device tree describes. Second, it establishes a virtual mapping from a fresh kernel virtual address range to that physical range, with appropriate cache and access attributes. The result is a virtual address that, when dereferenced, produces an access at the corresponding physical address, which the memory controller then routes to the device. +当内核的总线子系统发现设备并且驱动程序的 attach 例程请求 MMIO 资源时,总线层做两件事。第一,它找到设备占用的物理地址范围,这由设备的基址寄存器(BAR)或平台的设备树描述。第二,它建立一个从新的内核虚拟地址范围到该物理范围的虚拟映射,并带有适当的缓存和访问属性。结果是一个虚拟地址,当被解引用时,在相应的物理地址产生访问,内存控制器随后将其路由到设备。 -The handle that `bus_alloc_resource` returns is (on most platforms) a wrapper around that kernel virtual address. The driver does not typically see the address; it passes the resource handle to `bus_space_read_*` and `bus_space_write_*`, which extract the virtual address internally. But the underlying mechanism is a plain virtual-to-physical mapping, set up once at attach and torn down at detach. +`bus_alloc_resource` 返回的句柄(在大多数平台上)是该内核虚拟地址的包装。驱动程序通常不直接看到该地址;它将资源句柄传递给 `bus_space_read_*` 和 `bus_space_write_*`,后者在内部提取虚拟地址。但底层机制是一个简单的虚拟到物理映射,在 attach 时设置一次,在 detach 时拆除。 -This matters for two reasons. First, it explains why `bus_alloc_resource` is not something a driver can skip. Without the resource allocation, there is no virtual mapping; without a virtual mapping, any attempt to access the device will fault or access random memory. Second, it explains why the virtual address is not a constant: the kernel picks it at attach time, and two boots of the same system may produce different addresses. +这很重要,原因有二。第一,它解释了为什么 `bus_alloc_resource` 不是驱动程序可以跳过的。没有资源分配,就没有虚拟映射;没有虚拟映射,任何访问设备的尝试都会产生异常或访问随机内存。第二,它解释了为什么虚拟地址不是一个常量:内核在 attach 时选择它,同一系统的两次启动可能产生不同的地址。 -### Cache Attributes Matter +### 缓存属性很重要 -Memory pages have cache attributes. Ordinary RAM uses "write-back" caching: the CPU caches reads and writes in its L1, L2, and L3 caches, writing back to RAM only when the cache line is evicted or explicitly flushed. Write-back caching is great for performance on RAM, where the memory controller's job is to preserve whatever value the CPU most recently wrote. +内存页有缓存属性。普通 RAM 使用"写回"缓存:CPU 在其 L1、L2 和 L3 缓存中缓存读写,仅在缓存行被驱逐或显式刷新时才写回 RAM。写回缓存对 RAM 的性能很好,因为内存控制器的工作是保留 CPU 最近写入的任何值。 -Device memory is different. A device's registers usually have side effects on read and on write. Reading a `STATUS` register may consume an event the device has signalled. Writing a `DATA_IN` register may queue data for transmission. Caching a read of a status register means the CPU returns a stale value on the second read; caching a write of a data register means the write goes to the cache and never reaches the device until the cache happens to evict the line. +设备内存不同。设备的寄存器通常在读取和写入时有副作用。读取 `STATUS` 寄存器可能会消费设备已发出的事件信号。写入 `DATA_IN` 寄存器可能会将数据排队等待传输。缓存对状态寄存器的读取意味着 CPU 在第二次读取时返回过期的值;缓存对数据寄存器的写入意味着写入进入缓存而永远不会到达设备,直到缓存碰巧驱逐该行。 -For these reasons, device memory pages are marked with different cache attributes than ordinary memory. On x86, the attributes are controlled through the PAT (Page Attribute Table) and MTRR (Memory Type Range Registers). Device memory is typically marked `UC` (uncached) or `WC` (write-combining). On arm64, device memory pages use the `Device-nGnRnE` or `Device-nGnRE` attributes, which disable caching and speculation. The specific names are architecture-dependent; the principle is the same: the CPU must treat device memory differently from RAM. +由于这些原因,设备内存页被标记为与普通内存不同的缓存属性。在 x86 上,属性通过 PAT(页属性表)和 MTRR(内存类型范围寄存器)控制。设备内存通常标记为 `UC`(不可缓存)或 `WC`(写合并)。在 arm64 上,设备内存页使用 `Device-nGnRnE` 或 `Device-nGnRE` 属性,禁用缓存和推测。具体名称取决于架构;原则是相同的:CPU 必须以不同于 RAM 的方式对待设备内存。 -`bus_space_map` (or the equivalent path inside `bus_alloc_resource`) knows to request the right cache attributes when it establishes the virtual mapping. A driver that dereferences a raw pointer into a device region without going through `bus_space` skips this step and gets whatever attributes the surrounding mapping happens to have, which is usually wrong. +`bus_space_map`(或 `bus_alloc_resource` 内部的等效路径)知道在建立虚拟映射时请求正确的缓存属性。通过原始指针解引用到设备区域而不经过 `bus_space` 的驱动程序跳过了这一步,得到周围映射碰巧具有的任何属性,这通常是错误的。 -This is one of the most concrete reasons to use the FreeBSD abstraction: the abstraction encodes a correctness requirement (uncached access to devices) that a raw pointer cast cannot. +这是使用 FreeBSD 抽象的最具体原因之一:抽象编码了一个正确性要求(对设备的不可缓存访问),而原始指针类型转换无法做到。 -### Alignment +### 对齐 -Hardware registers have alignment requirements. A 32-bit register must be accessed with a 32-bit load or store at an offset that is a multiple of 4. A 64-bit register must be accessed with a 64-bit load or store at an offset that is a multiple of 8. On most architectures, an unaligned access to device memory is either slower (decomposed into multiple smaller accesses by the hardware) or outright illegal (trapping with an alignment fault). +硬件寄存器有对齐要求。32 位寄存器必须以 4 的倍数的偏移量用 32 位加载或存储访问。64 位寄存器必须以 8 的倍数的偏移量用 64 位加载或存储访问。在大多数架构上,对设备内存的未对齐访问要么更慢(被硬件分解为多个较小的访问),要么完全不合法(触发对齐异常)。 -The rule for drivers is simple: when reading or writing a register, use the function whose width matches the register's width, and use the correct offset. If the register is 32 bits wide at offset `0x10`, the access is `bus_space_read_4(tag, handle, 0x10)` or `bus_space_write_4(tag, handle, 0x10, value)`. If the register is 16 bits wide at offset `0x08`, it is `bus_space_read_2(tag, handle, 0x08)` or `bus_space_write_2(tag, handle, 0x08, value)`. The byte-wide variants `bus_space_read_1` and `bus_space_write_1` exist for 8-bit registers. +驱动程序的规则很简单:读写寄存器时,使用宽度与寄存器宽度匹配的函数,并使用正确的偏移量。如果寄存器宽 32 位,偏移量为 `0x10`,访问为 `bus_space_read_4(tag, handle, 0x10)` 或 `bus_space_write_4(tag, handle, 0x10, value)`。如果寄存器宽 16 位,偏移量为 `0x08`,则是 `bus_space_read_2(tag, handle, 0x08)` 或 `bus_space_write_2(tag, handle, 0x08, value)`。字节宽度变体 `bus_space_read_1` 和 `bus_space_write_1` 用于 8 位寄存器。 -Mismatching the width is a common early-stage bug and often silent on x86, which has very permissive alignment rules. On arm64 the same code may fault on first contact. Drivers that are developed on x86 and then ported to arm64 often trip on exactly this issue, which is why the FreeBSD style guidance favours matching widths strictly from the beginning. +宽度不匹配是早期常见的 bug,在 x86 上通常是无声的,因为 x86 的对齐规则非常宽松。在 arm64 上,相同的代码可能在首次接触时就会触发异常。在 x86 上开发然后移植到 arm64 的驱动程序经常恰好在这个问题上绊倒,这就是为什么 FreeBSD 风格指南主张从一开始就严格匹配宽度。 -There is also an offset alignment rule. The offset must be a multiple of the access width. A 32-bit read at offset `0x10` is fine (`0x10` is a multiple of 4). A 32-bit read at offset `0x11` is wrong, even if the device nominally has a register starting there; the hardware will usually refuse or return garbage. This rule is easy to follow when the offsets come from a well-named header; it becomes a trap when offsets are computed arithmetically and the arithmetic is wrong. +还有一个偏移量对齐规则。偏移量必须是访问宽度的倍数。偏移量 `0x10` 处的 32 位读取没问题(`0x10` 是 4 的倍数)。偏移量 `0x11` 处的 32 位读取是错误的,即使设备名义上在那里有一个寄存器;硬件通常会拒绝或返回垃圾。当偏移量来自命名良好的头文件时,这个规则很容易遵循;当偏移量是通过算术计算得出的而算术又出错时,它就成了陷阱。 -### Endianness +### 字节序 -Device memory and the CPU's native byte order may disagree. A device that originated in a PowerPC or network context may present 32-bit registers in big-endian order, meaning the most significant byte of the register is at the lowest byte address within the register. An x86 CPU is little-endian, so the lowest byte address holds the least significant byte. When the CPU reads the device's big-endian register and interprets it with little-endian semantics, the bytes are in the wrong order. +设备内存和 CPU 的本机字节顺序可能不一致。源自 PowerPC 或网络环境的设备可能以大端序呈现 32 位寄存器,意味着寄存器的最高有效字节在寄存器内的最低字节地址。x86 CPU 是小端序,所以最低字节地址存放最低有效字节。当 CPU 读取设备的大端序寄存器并以小端序语义解释它时,字节的顺序是错误的。 -FreeBSD's `bus_space` family has stream variants (`bus_space_read_stream_*`) and ordinary variants (`bus_space_read_*`). On architectures where the bus tag encodes an endian swap, the ordinary variants swap bytes to produce a host-order value. The stream variants do not swap; they return the bytes in device order. A driver that is reading a device whose registers are in a different endianness than the CPU will use the ordinary variants most of the time, relying on the tag to handle the swap. A driver that is reading a data payload (a stream of bytes whose interpretation depends on the protocol, not on the register layout) may use the stream variants. +FreeBSD 的 `bus_space` 系列有流式变体(`bus_space_read_stream_*`)和普通变体(`bus_space_read_*`)。在总线标签编码了字节序交换的架构上,普通变体交换字节以产生主机序值。流式变体不交换;它们按设备顺序返回字节。读取寄存器字节序与 CPU 不同的设备的驱动程序大部分时候使用普通变体,依赖标签来处理交换。读取数据负载(一个字节流,其解释取决于协议而非寄存器布局)的驱动程序可能使用流式变体。 -On x86 the distinction often does not matter because the bus tag does not encode an endian swap by default. The stream variants are aliases for the ordinary ones in `/usr/src/sys/x86/include/bus.h`: +在 x86 上,这种区别通常无关紧要,因为总线标签默认不编码字节序交换。流式变体在 `/usr/src/sys/x86/include/bus.h` 中是普通变体的别名: ```c #define bus_space_read_stream_1(t, h, o) bus_space_read_1((t), (h), (o)) @@ -333,113 +333,113 @@ On x86 the distinction often does not matter because the bus tag does not encode #define bus_space_read_stream_4(t, h, o) bus_space_read_4((t), (h), (o)) ``` -The comment in that file explains: "Stream accesses are the same as normal accesses on x86; there are no supported bus systems with an endianess different from the host one." On other architectures, the two families can differ, and a driver that cares about endianness picks the appropriate variant based on what the device expects. +该文件中的注释解释道:"Stream accesses are the same as normal accesses on x86; there are no supported bus systems with an endianess different from the host one." 在其他架构上,这两个系列可能不同,关心字节序的驱动程序根据设备的期望选择适当的变体。 -For Chapter 16, the simulation is designed to be host-endian. The chapter's drivers use the ordinary `bus_space_read_*` and `bus_space_write_*` without worrying about byte swaps. Later chapters that deal with real network controllers will revisit the endianness story. +对于第 16 章,模拟被设计为主机字节序。本章的驱动程序使用普通的 `bus_space_read_*` 和 `bus_space_write_*`,不用担心字节交换。处理真实网络控制器的后续章节将重新讨论字节序问题。 -### Read and Write Side Effects +### 读写的副作用 -One of the most important properties of device memory, and one that trips up drivers that treat it as ordinary memory, is that reads and writes can have side effects. +设备内存最重要的属性之一,也是把把它当作普通内存的驱动程序绊倒的属性,是读写可能有副作用。 -A write to a control register is, by design, a side effect: writing `1` to the `ENABLE` bit tells the device to start operating. The driver expects that side effect, because that is what the register is for. The subtlety is that the write has a side effect on the device even though the value written is also remembered; a driver that writes `0x00000001` to `CONTROL` and then reads `CONTROL` may see `0x00000001` (if the register echoes the written value) or some other value (if the register echoes the device's current state, which may differ from the last written value). +向控制寄存器写入值,按设计,就是一种副作用:向 `ENABLE` 位写入 `1` 告诉设备开始运行。驱动程序预期那个副作用,因为那就是寄存器的用途。微妙之处在于,即使写入的值也被记住了,写入对设备仍有副作用;向 `CONTROL` 写入 `0x00000001` 然后读取 `CONTROL` 的驱动程序可能看到 `0x00000001`(如果寄存器回显写入的值)或其他某个值(如果寄存器回显设备当前的状态,这可能与最后写入的值不同)。 -A read from a status register may also be a side effect. Some devices implement "read-to-clear" semantics, where reading the register returns the current status and, as part of the read, clears pending error bits or interrupt flags. A driver that reads the status twice in close succession may see different values on the two reads, because the first read changed the device's internal state. This is by design; the datasheet says so. +从状态寄存器读取也可能有副作用。一些设备实现了"读即清除"语义,读取寄存器返回当前状态,并且作为读取的一部分,清除挂起的错误位或中断标志。连续两次读取状态的驱动程序可能在两次读取中看到不同的值,因为第一次读取改变了设备的内部状态。这是设计使然;数据手册如是说。 -Some registers are **write-only**. Reading them returns a fixed value (often all zeros) and reveals nothing about the device. Writing them has the intended effect. A driver that tries to read a write-only register to check its current value will be misled. +一些寄存器是**只写**的。读取它们返回一个固定值(通常全为零),不揭示任何关于设备的信息。写入它们有预期效果。试图读取只写寄存器来检查其当前值的驱动程序会被误导。 -Some registers are **read-only**. Writing them is either ignored or hazardous. A driver that writes a read-only register may do nothing (if the hardware is defensive) or may cause undefined behaviour (if it is not). +一些寄存器是**只读**的。写入它们要么被忽略,要么有危险。写入只读寄存器的驱动程序可能什么都不做(如果硬件有防护)或导致未定义行为(如果没有)。 -Some registers are **read-modify-write** unsafe. A naive update pattern (read the current value, modify one field, write the value back) is safe on a register where the read returns the current contents and the write replaces them. It is unsafe on a register where the read has side effects, where the write has side effects on unintended fields, or where another agent (another CPU, a DMA engine, an interrupt handler) can modify the register between the read and the write. +一些寄存器对**读-改-写**不安全。一个朴素更新模式(读取当前值、修改一个字段、写回该值)在读返回当前内容且写替换它们的寄存器上是安全的。但在读有副作用、写对非目标字段有副作用,或者另一个代理(另一个 CPU、DMA 引擎、中断处理程序)可以在读和写之间修改寄存器的寄存器上是不安全的。 -For Chapter 16 the simulated device has a simple protocol: reads and writes each affect only the specific field the caller changes, and no read has side effects. This is not realistic; Chapter 17 introduces read-to-clear and write-only behaviours. For now, the simplicity is a feature: the reader can focus on the mechanics of access without also juggling the device's protocol quirks. +对于第 16 章,模拟设备有一个简单的协议:读写各自只影响调用者更改的特定字段,没有读取有副作用。这并不现实;第 17 章引入读即清除和只写行为。目前,简单性是一个特性:读者可以专注于访问的机制,而不必同时应付设备的协议怪癖。 -### A Concrete Picture: A Device's Register Block +### 一个具体的画面:设备的寄存器块 -A concrete example, though invented, makes the picture stick. Imagine a simple temperature-and-fan controller exposed as a 64-byte MMIO region. The register map might look like this: +一个具体的例子(虽然是虚构的)能让画面深入人心。想象一个作为 64 字节 MMIO 区域暴露的简单温度和风扇控制器。寄存器映射可能如下: -| Offset | Width | Name | Direction | Description | -|--------|--------|-----------------|-----------|-------------------------------------------| -| 0x00 | 32 bit | `CONTROL` | Read/Write| Global enable, reset, and mode bits. | -| 0x04 | 32 bit | `STATUS` | Read-only | Device ready, fault, data-available. | -| 0x08 | 32 bit | `TEMP_SAMPLE` | Read-only | Most recent temperature reading. | -| 0x0c | 32 bit | `FAN_PWM` | Read/Write| Fan PWM duty cycle (0-255). | -| 0x10 | 32 bit | `INTR_MASK` | Read/Write| Per-interrupt enable bits. | -| 0x14 | 32 bit | `INTR_STATUS` | Read/Clear| Pending interrupt flags (read-to-clear). | -| 0x18 | 32 bit | `DEVICE_ID` | Read-only | Fixed identifier; vendor code. | -| 0x1c | 32 bit | `FIRMWARE_REV` | Read-only | Device firmware revision. | -| 0x20-0x3f | 32 bytes | reserved | - | Must be written as zero; reads undefined. | +| 偏移量 | 宽度 | 名称 | 方向 | 描述 | +|--------|--------|-----------------|----------|------------------------------------------| +| 0x00 | 32 位 | `CONTROL` | 读/写 | 全局使能、复位和模式位。 | +| 0x04 | 32 位 | `STATUS` | 只读 | 设备就绪、故障、数据可用。 | +| 0x08 | 32 位 | `TEMP_SAMPLE` | 只读 | 最近的温度读数。 | +| 0x0c | 32 位 | `FAN_PWM` | 读/写 | 风扇 PWM 占空比(0-255)。 | +| 0x10 | 32 位 | `INTR_MASK` | 读/写 | 每个中断的使能位。 | +| 0x14 | 32 位 | `INTR_STATUS` | 读/清除 | 挂起的中断标志(读即清除)。 | +| 0x18 | 32 位 | `DEVICE_ID` | 只读 | 固定标识符;供应商代码。 | +| 0x1c | 32 位 | `FIRMWARE_REV` | 只读 | 设备固件版本。 | +| 0x20-0x3f | 32 字节 | 保留 | - | 必须写入零;读取未定义。 | -A driver for this device would read `DEVICE_ID` at attach to confirm the hardware is what the driver expects, write `CONTROL` to enable the device, poll `STATUS` to confirm the device is ready, periodically read `TEMP_SAMPLE` to report the temperature, and periodically write `FAN_PWM` to adjust the fan. The interrupt path would read `INTR_STATUS` to see which events are pending (which also clears them) and write `INTR_MASK` during setup to choose which interrupts to enable. +这个设备的驱动程序会在 attach 时读取 `DEVICE_ID` 来确认硬件是驱动程序所期望的,写入 `CONTROL` 来启用设备,轮询 `STATUS` 确认设备就绪,定期读取 `TEMP_SAMPLE` 报告温度,定期写入 `FAN_PWM` 调整风扇。中断路径会读取 `INTR_STATUS` 查看哪些事件挂起(这也清除它们),在设置期间写入 `INTR_MASK` 选择启用哪些中断。 -Chapter 16's simulated device borrows heavily from this shape. The simulation has a `CONTROL`, a `STATUS`, a `DATA_IN`, a `DATA_OUT`, an `INTR_MASK`, and an `INTR_STATUS`. It is deliberately a toy; the fields and protocol are chosen so the reader can manipulate them easily from user space through the driver's existing `read(2)` and `write(2)` paths. The register map is kept simple because Chapter 17 will introduce the complexity that real devices add on top. +第 16 章的模拟设备大量借鉴了这个形状。模拟有一个 `CONTROL`、一个 `STATUS`、一个 `DATA_IN`、一个 `DATA_OUT`、一个 `INTR_MASK` 和一个 `INTR_STATUS`。它故意是一个玩具;字段和协议被选择为读者可以通过驱动程序现有的 `read(2)` 和 `write(2)` 路径从用户空间轻松操作它们。寄存器映射保持简单,因为第 17 章将引入真实设备在此之上添加的复杂性。 -### The Shape of a Register Access +### 寄存器访问的形式 -Putting the pieces together, a single register access consists of: +把各部分组合起来,一次寄存器访问由以下步骤组成: -1. The driver has a `bus_space_tag_t` and a `bus_space_handle_t` that together describe a specific device region with specific cache attributes. -2. The driver picks an offset within the region, corresponding to a register defined in the device's datasheet. -3. The driver picks an access width that matches the register's width. -4. The driver calls `bus_space_read_*` or `bus_space_write_*` with tag, handle, offset, and (for writes) value. -5. The kernel's `bus_space` implementation for the current architecture compiles the call down to the appropriate CPU instruction (a `mov` on x86 MMIO, an `inb`/`outb` on x86 PIO, a `ldr`/`str` on arm64, and so on). -6. The memory controller or I/O fabric routes the access to the device. -7. The device responds: for a read, it returns the requested value; for a write, it performs the action the register's protocol defines. +1. 驱动程序拥有一个 `bus_space_tag_t` 和一个 `bus_space_handle_t`,它们共同描述了一个具有特定缓存属性的特定设备区域。 +2. 驱动程序在该区域内选择一个偏移量,对应于设备数据手册中定义的寄存器。 +3. 驱动程序选择与寄存器宽度匹配的访问宽度。 +4. 驱动程序使用标签、句柄、偏移量以及(对于写入)值调用 `bus_space_read_*` 或 `bus_space_write_*`。 +5. 当前架构的内核 `bus_space` 实现将调用编译为适当的 CPU 指令(x86 MMIO 上的 `mov`、x86 PIO 上的 `inb`/`outb`、arm64 上的 `ldr`/`str` 等)。 +6. 内存控制器或 I/O 结构将访问路由到设备。 +7. 设备响应:对于读取,它返回请求的值;对于写入,它执行寄存器协议定义的操作。 -The abstraction hides all of this from the driver, most of the time. The driver writes `bus_space_read_4(tag, handle, 0x04)` and gets a 32-bit value back. The machinery between the C call and the device is the kernel's and the hardware's job. +抽象大部分时间对驱动程序隐藏了所有这些。驱动程序写入 `bus_space_read_4(tag, handle, 0x04)` 并获得一个 32 位值。C 调用和设备之间的机制是内核和硬件的工作。 -What the driver must remain aware of is the handful of correctness rules: alignment, width, side effects, and access ordering. The chapter revisits ordering in Section 6. +驱动程序必须保持意识的是少数几条正确性规则:对齐、宽度、副作用和访问排序。第 6 节将重新讨论排序。 -### What MMIO Is Not +### MMIO 不是什么 -A short list of things MMIO is not, to clear up common confusions. +简短列出 MMIO 不是什么,以澄清常见混淆。 -**MMIO is not DMA.** DMA is when the device reads or writes system RAM on its own. MMIO is when the CPU reads or writes the device's registers. Both may be used in the same driver, for different purposes. DMA is faster for bulk data; MMIO is necessary for commands and status. Chapter 20 and Chapter 21 cover DMA. +**MMIO 不是 DMA。** DMA 是设备自行读写系统 RAM。MMIO 是 CPU 读写设备的寄存器。两者可能在同一驱动程序中用于不同目的。DMA 对批量数据更快;MMIO 对命令和状态是必需的。第 20 章和第 21 章涵盖 DMA。 -**MMIO is not shared memory.** Shared memory (in the POSIX sense) is RAM accessible to multiple processes. MMIO is device memory accessible to the kernel only. User space cannot (and should not) access MMIO directly; the driver mediates. +**MMIO 不是共享内存。** 共享内存(POSIX 意义上的)是多个进程可访问的 RAM。MMIO 是只有内核可访问的设备内存。用户空间不能(也不应该)直接访问 MMIO;驱动程序充当中介。 -**MMIO is not a block of RAM with the device living behind it.** MMIO is a direct interface to the device's internal registers. Reading MMIO does not return kernel memory; it returns whatever the device decides to return at that offset. Writing MMIO does not store a value in kernel memory; it sends a message to the device at that offset. +**MMIO 不是设备在其后面的一块 RAM。** MMIO 是设备内部寄存器的直接接口。读取 MMIO 不返回内核内存;它返回设备在该偏移量处决定返回的任何内容。写入 MMIO 不在内核内存中存储值;它在该偏移量处向设备发送消息。 -**MMIO is not free.** Each access is a transaction on the CPU's bus. On a deep cache hierarchy with high memory latency, a single uncached MMIO read can take hundreds of cycles, because the CPU cannot use the cache and must wait for the device to respond. Drivers that issue thousands of MMIO accesses per operation are usually doing something wrong; most operations can be batched or eliminated. +**MMIO 不是免费的。** 每次访问是 CPU 总线上的一次事务。在具有高内存延迟的深缓存层次结构中,单次不可缓存的 MMIO 读取可能需要数百个周期,因为 CPU 不能使用缓存,必须等待设备响应。每次操作发出数千次 MMIO 访问的驱动程序通常做错了什么;大多数操作可以批处理或消除。 -### Wrapping Up Section 2 +### 第 2 节总结 -Memory-mapped I/O is the mechanism by which a modern CPU reaches a device through ordinary load and store instructions, with the address routed to the device instead of to RAM. The kernel's virtual mapping layer and the `bus_space` abstraction together hide the plumbing, but the driver must still be aware of alignment, endianness, cache attributes, and side effects. A register is accessed with a read or write of the right width at the right offset; the kernel compiles the call into the appropriate CPU instruction for the current architecture. +内存映射 I/O 是现代 CPU 通过普通加载和存储指令到达设备的机制,地址被路由到设备而不是 RAM。内核的虚拟映射层和 `bus_space` 抽象共同隐藏了管道,但驱动程序仍必须意识到对齐、字节序、缓存属性和副作用。寄存器通过以正确宽度在正确偏移量处的读写来访问;内核将调用编译为当前架构的适当 CPU 指令。 -Section 3 introduces `bus_space(9)` itself: the tag, the handle, the read and write functions, and the shape of the API as it appears in every FreeBSD driver that talks to hardware. After Section 3, you will be ready to simulate a register block in Section 4 and start writing code. +第 3 节介绍 `bus_space(9)` 本身:标签、句柄、读写函数,以及 API 在每个与硬件通信的 FreeBSD 驱动程序中出现的形式。第 3 节之后,你将准备好在第 4 节中模拟寄存器块并开始编写代码。 -## Section 3: Introduction to `bus_space(9)` +## 第 3 节:`bus_space(9)` 简介 -`bus_space(9)` is the FreeBSD abstraction for portable hardware access. Every driver that talks to memory-mapped or port-mapped hardware uses it, directly or through a thin wrapper. The abstraction is small: two opaque types, a dozen read and write functions in several widths, a barrier function, and a few helpers for multi-register and region accesses. Section 3 walks through the whole thing in the order a reader would naturally meet it. +`bus_space(9)` 是 FreeBSD 用于可移植硬件访问的抽象层。每个与内存映射或端口映射硬件通信的驱动程序都使用它,直接使用或通过薄包装使用。这个抽象很小:两个不透明类型、十几种不同宽度的读写函数、一个屏障函数,以及一些用于多寄存器和区域访问的辅助函数。第 3 节按读者自然遇到的顺序走完整个内容。 -The section starts with the two types, moves to the read and write functions, covers the multi and region helpers, introduces the barrier function, and closes with the `bus_*` shorthand defined over a `struct resource *` that most real drivers use in practice. By the end you will recognise every `bus_space` call you meet in `/usr/src/sys/dev/`, and you will have a mental model for writing your own. +本节从两个类型开始,转到读写函数,涵盖多访问和区域访问辅助函数,引入屏障函数,最后以大多数真实驱动程序实际使用的定义在 `struct resource *` 上的 `bus_*` 简写结束。学完后,你将认出在 `/usr/src/sys/dev/` 中遇到的每个 `bus_space` 调用,并拥有编写自己调用的心智模型。 -### The Two Types: `bus_space_tag_t` and `bus_space_handle_t` +### 两个类型:`bus_space_tag_t` 和 `bus_space_handle_t` -Every `bus_space` call takes a tag and a handle as its first two arguments, in that order. Understanding what each one represents is the first step. +每个 `bus_space` 调用都按顺序接受一个标签和一个句柄作为前两个参数。理解每个代表什么是第一步。 -A **`bus_space_tag_t`** identifies an address space. "Address space" here is narrower than its general usage; it specifically refers to the combination of a bus and an access method. On x86, there are two address spaces: memory and I/O port. Each has its own tag value. On other architectures, there may be more: a memory space with host-endian access, a memory space with swapped-endian access, and so on. The tag tells the `bus_space` functions which rules to apply. +**`bus_space_tag_t`** 标识一个地址空间。"地址空间"在这里比其一般用法更窄;它特指总线和访问方法的组合。在 x86 上,有两个地址空间:内存和 I/O 端口。每个都有自己的标签值。在其他架构上,可能有更多:具有主机字节序访问的内存空间、具有交换字节序访问的内存空间等。标签告诉 `bus_space` 函数应用哪些规则。 -The tag is architecture-specific. On x86, the tag is an integer: `0` for I/O port space (`X86_BUS_SPACE_IO`) and `1` for memory space (`X86_BUS_SPACE_MEM`). On arm64, the tag is a pointer to a structure that describes the bus's endian and access behaviour. On MIPS, it is yet another shape. Drivers do not usually see these architecture details; they obtain the tag from the bus subsystem (through `rman_get_bustag(resource)` or equivalent) and pass it through without inspection. +标签是架构特定的。在 x86 上,标签是一个整数:I/O 端口空间为 `0`(`X86_BUS_SPACE_IO`),内存空间为 `1`(`X86_BUS_SPACE_MEM`)。在 arm64 上,标签是指向描述总线字节序和访问行为的结构的指针。在 MIPS 上,它又是另一种形式。驱动程序通常不直接看到这些架构细节;它们从总线子系统获取标签(通过 `rman_get_bustag(resource)` 或等效方式)并直接传递而不检查。 -A **`bus_space_handle_t`** identifies a specific region within the address space. It is effectively a pointer, but the pointer's meaning depends on the tag. For a memory tag on x86, the handle is the kernel virtual address at which the device's physical range has been mapped. For an I/O port tag on x86, the handle is the I/O port base address. For more elaborate tags, the handle may be a structure or an encoded value. Drivers treat the handle as opaque and pass it through. +**`bus_space_handle_t`** 标识地址空间内的特定区域。它实际上是一个指针,但指针的含义取决于标签。对于 x86 上的内存标签,句柄是设备物理范围被映射到的内核虚拟地址。对于 x86 上的 I/O 端口标签,句柄是 I/O 端口基地址。对于更复杂的标签,句柄可能是一个结构或一个编码值。驱动程序将句柄视为不透明的并直接传递。 -The pairing is important. A tag alone does not identify a specific device; it identifies only the address space. A handle alone does not carry the access rules. The pair (tag, handle) together identifies a specific mappable region with specific access rules, and that pair is what the `bus_space_read_*` and `bus_space_write_*` functions operate on. +这种配对很重要。仅标签不能标识特定设备;它只标识地址空间。仅句柄不携带访问规则。一对(标签,句柄)共同标识具有特定访问规则的特定可映射区域,`bus_space_read_*` 和 `bus_space_write_*` 函数就操作在这个对上。 -In practice a driver obtains a `struct resource *` from the bus subsystem at attach time and extracts the tag and handle from it with `rman_get_bustag` and `rman_get_bushandle`. It stores the pair in the softc, or it stores the resource pointer and uses the shorthand `bus_read_*` and `bus_write_*` macros that extract the tag and handle internally. Section 5 walks through the real pattern. +实际上,驱动程序在 attach 时从总线子系统获取 `struct resource *`,并用 `rman_get_bustag` 和 `rman_get_bushandle` 从中提取标签和句柄。它将该对存储在 softc 中,或者存储资源指针并使用在内部提取标签和句柄的简写 `bus_read_*` 和 `bus_write_*` 宏。第 5 节走完实际的模式。 -### Offsets +### 偏移量 -Every read and write function takes an **offset** inside the region. The offset is a `bus_size_t`, which is typically a 64-bit unsigned integer, measured in bytes from the start of the region. A 32-bit register at the start of a device's MMIO region has offset 0. A 32-bit register at the next slot has offset 4. A 32-bit register at offset `0x10` is 16 bytes into the region. +每个读写函数都接受区域内的一个**偏移量**。偏移量是 `bus_size_t`,通常是一个 64 位无符号整数,以字节为单位从区域起始处计算。设备 MMIO 区域起始处的 32 位寄存器偏移量为 0。下一个槽位的 32 位寄存器偏移量为 4。偏移量 `0x10` 处的 32 位寄存器在区域内 16 字节处。 -Offsets are expressed in bytes regardless of the access width. `bus_space_read_4(tag, handle, 0x10)` reads a 32-bit value starting at byte offset `0x10`. `bus_space_read_2(tag, handle, 0x12)` reads a 16-bit value starting at byte offset `0x12`. The function's suffix names the width in bytes, not the offset granularity. +偏移量以字节表示,与访问宽度无关。`bus_space_read_4(tag, handle, 0x10)` 读取从字节偏移 `0x10` 开始的 32 位值。`bus_space_read_2(tag, handle, 0x12)` 读取从字节偏移 `0x12` 开始的 16 位值。函数的后缀以字节命名宽度,而不是偏移粒度。 -The driver is responsible for ensuring the offset falls within the mapped region. `bus_space` does not check bounds; an out-of-range access is a driver bug that reads or writes whatever happens to be beyond the device's mapping, which on most platforms is either unmapped memory (faulting the kernel) or another device's memory (corrupting that device's state). Keep your offsets in headers, derive them from the datasheet, and never compute them arithmetically without bounds-checking the result. +驱动程序负责确保偏移量在映射区域内。`bus_space` 不检查边界;超出范围的访问是驱动程序的 bug,会读写设备映射之外的任何内容,在大多数平台上要么是未映射内存(导致内核异常),要么是另一个设备的内存(损坏该设备的状态)。将偏移量保留在头文件中,从数据手册推导它们,永远不要在没有边界检查结果的情况下用算术计算偏移量。 -### The Read Functions +### 读取函数 -The basic read functions come in four widths: +基本读取函数有四种宽度: ```c u_int8_t bus_space_read_1(bus_space_tag_t tag, bus_space_handle_t handle, @@ -452,9 +452,9 @@ uint64_t bus_space_read_8(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset); ``` -The `_1`, `_2`, `_4`, `_8` suffixes are access widths in bytes. `_1` is an 8-bit read, `_2` is a 16-bit read, `_4` is a 32-bit read, `_8` is a 64-bit read. The return type is the corresponding unsigned integer. +`_1`、`_2`、`_4`、`_8` 后缀是以字节为单位的访问宽度。`_1` 是 8 位读取,`_2` 是 16 位读取,`_4` 是 32 位读取,`_8` 是 64 位读取。返回类型是对应的无符号整数。 -Not all widths are supported on all platforms. On x86, `bus_space_read_8` is defined only for `__amd64__` (the 64-bit x86) and only for memory space, not I/O port space. The definition in `/usr/src/sys/x86/include/bus.h` is explicit: +并非所有宽度都在所有平台上受支持。在 x86 上,`bus_space_read_8` 仅为 `__amd64__`(64 位 x86)定义,且仅用于内存空间,不用于 I/O 端口空间。`/usr/src/sys/x86/include/bus.h` 中的定义很明确: ```c #ifdef __amd64__ @@ -469,9 +469,9 @@ bus_space_read_8(bus_space_tag_t tag, bus_space_handle_t handle, #endif ``` -A 64-bit I/O port access returns `BUS_SPACE_INVALID_DATA` (all bits set). A 64-bit memory access dereferences the handle plus offset as a `volatile uint64_t *`. The `volatile` qualifier is what stops the compiler from caching or reordering the access. +64 位 I/O 端口访问返回 `BUS_SPACE_INVALID_DATA`(所有位置位)。64 位内存访问将句柄加偏移量作为 `volatile uint64_t *` 解引用。`volatile` 限定符正是阻止编译器缓存或重排序访问的关键。 -The 32-bit case is similar: +32 位情况类似: ```c static __inline u_int32_t @@ -484,13 +484,13 @@ bus_space_read_4(bus_space_tag_t tag, bus_space_handle_t handle, } ``` -Memory space compiles to a `volatile` dereference. I/O port space compiles to an `inl` instruction that reads a long from an I/O port. +内存空间编译为 `volatile` 解引用。I/O 端口空间编译为从 I/O 端口读取长字的 `inl` 指令。 -The 16-bit (`inw`, `*(volatile u_int16_t *)`) and 8-bit (`inb`, `*(volatile u_int8_t *)`) cases follow the same pattern. On a 64-bit x86, `bus_space_read_4` on a memory region compiles to a single `mov` instruction from the mapped address. The cost of the abstraction at runtime, on this common platform, is literally one instruction's worth of call-frame setup if the inline expands, which it does in release builds. +16 位(`inw`、`*(volatile u_int16_t *)`)和 8 位(`inb`、`*(volatile u_int8_t *)`)情况遵循相同模式。在 64 位 x86 上,内存区域上的 `bus_space_read_4` 编译为从映射地址的单条 `mov` 指令。在这个常见平台上,抽象在运行时的开销,如果内联展开的话,实际上只是一条指令的调用帧设置,而它在发布版本中确实会展开。 -### The Write Functions +### 写入函数 -The write functions mirror the read functions: +写入函数与读取函数镜像: ```c void bus_space_write_1(bus_space_tag_t tag, bus_space_handle_t handle, @@ -503,7 +503,7 @@ void bus_space_write_8(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset, uint64_t value); ``` -On x86 memory space, a write compiles to a `volatile` store: +在 x86 内存空间上,写入编译为 `volatile` 存储: ```c static __inline void @@ -517,15 +517,15 @@ bus_space_write_4(bus_space_tag_t tag, bus_space_handle_t bsh, } ``` -Port-mapped I/O compiles to an `outl`. The driver writes the same source line regardless of platform; the kernel's per-architecture `bus.h` does the rest. +端口映射 I/O 编译为 `outl`。驱动程序无论平台都写相同的源代码行;内核的每架构 `bus.h` 完成其余工作。 -As with reads, `bus_space_write_8` to I/O port space on x86 is not supported; the function silently returns without emitting a write. This reflects the hardware: x86 I/O ports are 32-bit at most. +与读取一样,x86 上对 I/O 端口空间的 `bus_space_write_8` 不受支持;函数静默返回而不发出写入。这反映了硬件:x86 I/O 端口最多 32 位。 -### The Multi and Region Helpers +### 多访问和区域访问辅助函数 -Sometimes a driver wants to read or write many values from or to a single register, or many values across a range of registers. The `bus_space` API provides two families of helpers. +有时驱动程序想要从单个寄存器读写多个值,或跨一系列寄存器读写多个值。`bus_space` API 提供了两个系列的辅助函数。 -**Multi accesses** repeatedly access a single register, transferring a buffer of values through it. The register stays at a fixed offset; the buffer is consumed or produced. The use case is a FIFO-style register, where the device's internal queue is exposed through a single address, and reading or writing that address pops or pushes one entry. +**多访问**重复访问单个寄存器,通过它传输值的缓冲区。寄存器保持在固定偏移量;缓冲区被消费或产生。用例是 FIFO 式寄存器,设备内部队列通过单个地址暴露,读取或写入该地址弹出一个或压入一个条目。 ```c void bus_space_read_multi_1(bus_space_tag_t tag, bus_space_handle_t handle, @@ -536,9 +536,9 @@ void bus_space_read_multi_4(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset, u_int32_t *buf, size_t count); ``` -`bus_space_read_multi_4(tag, handle, 0x20, buf, 16)` reads a 32-bit value from offset `0x20` sixteen times, storing each value in successive entries of `buf`. The offset does not change between reads; only the buffer pointer advances. +`bus_space_read_multi_4(tag, handle, 0x20, buf, 16)` 从偏移量 `0x20` 读取 32 位值十六次,将每个值存储在 `buf` 的连续条目中。读取之间偏移量不变;只有缓冲区指针前进。 -The write variants mirror the reads: +写入变体与读取镜像: ```c void bus_space_write_multi_1(bus_space_tag_t tag, bus_space_handle_t handle, @@ -549,7 +549,7 @@ void bus_space_write_multi_4(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset, const u_int32_t *buf, size_t count); ``` -**Region accesses** transfer across a range of offsets. The offset advances each step; the buffer advances each step. The use case is a memory-like region inside the device, such as a block of configuration data or a frame buffer slice. +**区域访问**跨一系列偏移量传输。偏移量每步前进;缓冲区每步前进。用例是设备内部的类内存区域,如配置数据块或帧缓冲区切片。 ```c void bus_space_read_region_1(bus_space_tag_t tag, bus_space_handle_t handle, @@ -562,30 +562,30 @@ void bus_space_write_region_4(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset, const u_int32_t *buf, size_t count); ``` -`bus_space_read_region_4(tag, handle, 0x100, buf, 16)` reads 16 consecutive 32-bit values starting at offset `0x100` and ending at offset `0x13c`, storing them in `buf[0]` through `buf[15]`. +`bus_space_read_region_4(tag, handle, 0x100, buf, 16)` 从偏移量 `0x100` 开始到偏移量 `0x13c` 结束,读取 16 个连续的 32 位值,存储在 `buf[0]` 到 `buf[15]` 中。 -The distinction between multi and region corresponds to two different hardware patterns. A FIFO register at a single offset is a multi; a configuration block that spans many offsets is a region. Using the wrong family leaves the driver doing the wrong thing, even if the loop count matches, so take care to pick the right one. +多访问和区域访问之间的区别对应于两种不同的硬件模式。单个偏移量处的 FIFO 寄存器是多访问;跨越多个偏移量的配置块是区域访问。使用错误的系列会让驱动程序做错误的事情,即使循环次数匹配,所以注意选择正确的系列。 -Chapter 16's simulated device does not use multi or region accesses; the driver addresses registers one at a time. Chapter 17's richer simulation and later PCI-based chapters introduce the multi and region patterns where they apply. +第 16 章的模拟设备不使用多访问或区域访问;驱动程序逐个访问寄存器。第 17 章更丰富的模拟和后续基于 PCI 的章节在适用的地方引入多访问和区域访问模式。 -### The Barrier Function +### 屏障函数 -`bus_space_barrier` is the function that most drivers forget exists until they need it, and its correct use is one of the quiet disciplines of solid hardware programming. +`bus_space_barrier` 是大多数驱动程序在需要之前忘记其存在的函数,其正确使用是扎实硬件编程的静默规范之一。 ```c void bus_space_barrier(bus_space_tag_t tag, bus_space_handle_t handle, bus_size_t offset, bus_size_t length, int flags); ``` -The function enforces ordering on `bus_space` reads and writes issued before the call, relative to those issued after. The `flags` argument is a bitmask: +该函数对调用之前发出的 `bus_space` 读写和之后发出的读写强制排序。`flags` 参数是位掩码: -- `BUS_SPACE_BARRIER_READ` makes prior reads complete before subsequent reads. -- `BUS_SPACE_BARRIER_WRITE` makes prior writes complete before subsequent writes. -- The two may be OR-ed together to enforce both directions. +- `BUS_SPACE_BARRIER_READ` 使之前的读取在后续读取之前完成。 +- `BUS_SPACE_BARRIER_WRITE` 使之前的写入在后续写入之前完成。 +- 两者可以 OR 在一起以强制两个方向。 -The `offset` and `length` parameters describe the region the barrier applies to. On x86 these are ignored; the barrier applies to the whole CPU. On other architectures, a bus bridge may be able to enforce barriers more narrowly, and the parameters are informative. +`offset` 和 `length` 参数描述屏障应用的区域。在 x86 上这些被忽略;屏障应用于整个 CPU。在其他架构上,总线桥可能能够更窄地强制屏障,这些参数是提供信息的。 -On x86 specifically, `bus_space_barrier` compiles to a small and well-defined sequence. From `/usr/src/sys/x86/include/bus.h`: +在 x86 上具体来说,`bus_space_barrier` 编译为一个简小且定义明确的序列。来自 `/usr/src/sys/x86/include/bus.h`: ```c static __inline void @@ -603,25 +603,25 @@ bus_space_barrier(bus_space_tag_t tag __unused, bus_space_handle_t bsh __unused, } ``` -A read barrier on amd64 emits a `lock addl` on the stack, which is a cheap way to issue a full memory fence on x86. A write barrier emits only a compiler barrier (`__compiler_membar()`), because x86 hardware retires writes in program order and the only reordering a driver can experience on writes is from the compiler. The distinction between "the CPU might reorder this" and "the compiler might reorder this" matters, and the x86 `bus_space_barrier` encodes it with minimum cost. +amd64 上的读取屏障在栈上发出 `lock addl`,这是在 x86 上发出完整内存屏障的廉价方式。写入屏障仅发出编译器屏障(`__compiler_membar()`),因为 x86 硬件按程序顺序完成写入,驱动程序在写入上唯一可能经历的重排序来自编译器。"CPU 可能重排序这个"和"编译器可能重排序这个"之间的区别很重要,x86 的 `bus_space_barrier` 以最低成本编码了它。 -On arm64 the barrier compiles to a `dsb` or `dmb` instruction depending on the flags, because arm64's memory model is weaker and actual CPU reordering is possible. The driver's source does not change; the same `bus_space_barrier` call picks the right instruction for each platform. +在 arm64 上,屏障根据标志编译为 `dsb` 或 `dmb` 指令,因为 arm64 的内存模型更弱,实际的 CPU 重排序是可能的。驱动程序的源代码不变;相同的 `bus_space_barrier` 调用为每个平台选择正确的指令。 -When is a barrier required? The rule of thumb is: when the correctness of one register access depends on another access having completed first. Examples: +什么时候需要屏障?经验法则是:当一个寄存器访问的正确性取决于另一个访问先完成时。示例: -- A driver writes a command to `CONTROL` and reads the result from `STATUS`. The read must not be speculated before the write. A `bus_space_barrier(tag, handle, 0, 0, BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ)` between them enforces the ordering. -- A driver clears an interrupt flag in `INTR_STATUS` and expects the clear to reach the device before re-enabling interrupts. A write barrier after the clear, before the re-enable, is the correct discipline. -- A driver posts a DMA descriptor to memory and then writes a "doorbell" register to tell the device to process it. A write barrier between the memory write and the doorbell write is required on weakly-ordered platforms. +- 驱动程序向 `CONTROL` 写入命令并从 `STATUS` 读取结果。读取不能被推测到写入之前。在它们之间加 `bus_space_barrier(tag, handle, 0, 0, BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ)` 强制排序。 +- 驱动程序在 `INTR_STATUS` 中清除中断标志,期望清除在重新启用中断之前到达设备。清除之后的写入屏障,在重新启用之前,是正确的做法。 +- 驱动程序将 DMA 描述符写入内存,然后写入"门铃"寄存器告诉设备处理它。在内存写入和门铃写入之间的写入屏障在弱序平台上是必需的。 -On x86, many of these cases are handled by the platform's strong ordering model, and a driver written without explicit barriers often works. The same driver ported to arm64 may fail subtly. The rule "use barriers when ordering matters" produces portable code; the rule "barriers do nothing on x86 so skip them" produces code that breaks on half of FreeBSD's supported platforms. +在 x86 上,这些情况中的许多由平台的强排序模型处理,没有显式屏障的驱动程序通常也能工作。同一个驱动程序移植到 arm64 可能会微妙地失败。"在排序重要时使用屏障"的规则产生可移植的代码;"屏障在 x86 上什么也不做所以跳过它们"的规则产生的代码在 FreeBSD 支持的平台的一半上会出错。 -Section 6 of this chapter revisits barriers with worked examples in the simulated driver. +本章第 6 节将在模拟驱动程序中用实例重新讨论屏障。 -### The `bus_*` Shorthand over a `struct resource *` +### `struct resource *` 上的 `bus_*` 简写 -The `bus_space_*` family takes a tag and a handle. In practice, drivers do not usually carry those around; they carry a `struct resource *`, which is what `bus_alloc_resource_any` returns. The resource structure contains the tag and the handle, among other things. Passing them separately would be noise. +`bus_space_*` 系列接受标签和句柄。实际上,驱动程序通常不随身携带它们;它们携带 `struct resource *`,这就是 `bus_alloc_resource_any` 返回的。资源结构包含标签和句柄以及其他内容。分别传递它们会是噪音。 -To eliminate the noise, `/usr/src/sys/sys/bus.h` defines a family of shorthand macros that take a `struct resource *` and extract the tag and handle internally: +为了消除噪音,`/usr/src/sys/sys/bus.h` 定义了一族简写宏,接受 `struct resource *` 并在内部提取标签和句柄: ```c #define bus_read_1(r, o) \ @@ -638,24 +638,24 @@ To eliminate the noise, `/usr/src/sys/sys/bus.h` defines a family of shorthand m bus_space_barrier((r)->r_bustag, (r)->r_bushandle, (o), (l), (f)) ``` -There are equivalents for `_multi` and `_region` variants, stream variants, and the barrier. The macros cover the same functionality as the underlying `bus_space_*` family, just with a more compact call shape. +`_multi` 和 `_region` 变体、流式变体和屏障有对应的等价宏。这些宏覆盖与底层 `bus_space_*` 系列相同的功能,只是调用形式更紧凑。 -Most drivers in `/usr/src/sys/dev/` use the shorthand. A typical usage looks like this, adapted from `if_alevar.h`: +`/usr/src/sys/dev/` 中的大多数驱动程序使用简写。一个典型的用法如下,改编自 `if_alevar.h`: ```c #define CSR_READ_4(sc, reg) bus_read_4((sc)->res[0], (reg)) #define CSR_WRITE_4(sc, reg, val) bus_write_4((sc)->res[0], (reg), (val)) ``` -The driver defines its own `CSR_READ_4` and `CSR_WRITE_4` macros in terms of `bus_read_4` and `bus_write_4`, abstracting one more layer on top. The softc holds an array of `struct resource *` pointers, and the macros reach through to the first one (the main MMIO region) without the driver having to write out the resource dereference every time. +驱动程序在 `bus_read_4` 和 `bus_write_4` 之上定义自己的 `CSR_READ_4` 和 `CSR_WRITE_4` 宏,在顶层再抽象一层。softc 保存 `struct resource *` 指针数组,宏直接到达第一个(主 MMIO 区域),驱动程序不必每次都写出资源解引用。 -This is a deliberate pattern. It makes register access statements short and scanable. It centralises the resource reference in one place, so if the driver later maps a second region, only the macros change. And it gives the driver's code a consistent look that anyone familiar with `/usr/src/sys/dev/` will recognise immediately. +这是刻意的模式。它使寄存器访问语句短小可扫描。它将资源引用集中在一个地方,所以如果驱动程序后来映射了第二个区域,只有宏需要改变。它给驱动程序的代码以一致的样式,任何熟悉 `/usr/src/sys/dev/` 的人都能立即认出。 -Chapter 16's simulated driver adopts this pattern by Stage 4. The early stages use the `bus_space_*` family directly, to keep the mechanism visible; the final refactor wraps the accesses in `CSR_READ_*` and `CSR_WRITE_*` macros the way a production driver would. +第 16 章的模拟驱动程序在第 4 阶段采用这个模式。早期阶段直接使用 `bus_space_*` 系列以保持机制可见;最终重构将访问包装在 `CSR_READ_*` 和 `CSR_WRITE_*` 宏中,就像生产驱动程序那样。 -### Setup and Teardown +### 设置和拆除 -A driver that uses `bus_space` does not call `bus_space_map` directly in most cases. Instead, it asks the bus subsystem for a resource through `bus_alloc_resource_any`: +使用 `bus_space` 的驱动程序在大多数情况下不直接调用 `bus_space_map`。相反,它通过 `bus_alloc_resource_any` 向总线子系统请求资源: ```c int rid = 0; @@ -668,42 +668,42 @@ if (res == NULL) { } ``` -The arguments are: +参数是: -- `dev` is the `device_t` for the driver's device. -- `SYS_RES_MEMORY` selects a memory-mapped resource. `SYS_RES_IOPORT` selects a port-mapped resource. `SYS_RES_IRQ` selects an IRQ (used in Chapter 19). -- `rid` is the "resource ID", the index of the resource within the device's resources. A PCI device's first BAR is usually rid 0 (which for a legacy PCI device corresponds to the BAR at PCI config offset `0x10`). `rid` is a pointer because the bus subsystem may update it to reflect the actual rid it used, though for `_any` allocations on a known rid, the value passed in is usually returned unchanged. -- `RF_ACTIVE` tells the bus to activate the resource immediately, which includes establishing the virtual mapping. Without `RF_ACTIVE`, the resource is reserved but not mapped. +- `dev` 是驱动程序设备的 `device_t`。 +- `SYS_RES_MEMORY` 选择内存映射资源。`SYS_RES_IOPORT` 选择端口映射资源。`SYS_RES_IRQ` 选择 IRQ(第 19 章使用)。 +- `rid` 是"资源 ID",设备资源中资源的索引。PCI 设备的第一个 BAR 通常是 rid 0(对于传统 PCI 设备对应 PCI 配置偏移 `0x10` 处的 BAR)。`rid` 是指针,因为总线子系统可能更新它以反映它使用的实际 rid,尽管对于已知 rid 上的 `_any` 分配,传入的值通常原样返回。 +- `RF_ACTIVE` 告诉总线立即激活资源,包括建立虚拟映射。没有 `RF_ACTIVE`,资源被保留但未映射。 -On success, `res` is a valid `struct resource *` whose tag and handle can be extracted with `rman_get_bustag(res)` and `rman_get_bushandle(res)`, or whose tag and handle are used implicitly by the `bus_read_*` and `bus_write_*` shorthand macros. +成功时,`res` 是一个有效的 `struct resource *`,其标签和句柄可以用 `rman_get_bustag(res)` 和 `rman_get_bushandle(res)` 提取,或者由 `bus_read_*` 和 `bus_write_*` 简写宏隐式使用。 -At detach, the driver releases the resource: +在 detach 时,驱动程序释放资源: ```c bus_release_resource(dev, SYS_RES_MEMORY, rid, res); ``` -The release undoes the allocation, including tearing down the virtual mapping and marking the range available for reuse. +释放撤销分配,包括拆除虚拟映射并将范围标记为可重用。 -This is the boilerplate every driver follows for MMIO resources. Chapter 16's simulated device skips it entirely, because there is no bus to allocate from; the "resource" is a chunk of kernel memory the driver allocated with `malloc(9)`. Chapter 17 introduces a slightly more sophisticated simulation that mimics the allocation path. Chapter 18, when real PCI enters the picture, uses the full `bus_alloc_resource_any` flow. +这是每个驱动程序为 MMIO 资源遵循的样板。第 16 章的模拟设备完全跳过了它,因为没有总线可以分配;"资源"是驱动程序用 `malloc(9)` 分配的一块内核内存。第 17 章引入一个稍微更复杂的模拟来模仿分配路径。第 18 章,当真实 PCI 出现时,使用完整的 `bus_alloc_resource_any` 流程。 -### A First Stand-Alone Example +### 第一个独立示例 -Even without real hardware, a simple stand-alone program illustrates the shape of a `bus_space` call. Imagine a driver that wants to read the 32-bit `DEVICE_ID` register at offset `0x18` from a device whose MMIO region has been allocated as `res`: +即使没有真实硬件,一个简单的独立程序也能说明 `bus_space` 调用的形式。想象一个驱动程序想要从 MMIO 区域已分配为 `res` 的设备中读取偏移量 `0x18` 处的 32 位 `DEVICE_ID` 寄存器: ```c uint32_t devid = bus_read_4(sc->res, 0x18); ``` -One line. The `sc->res` holds the `struct resource *`. The offset `0x18` comes from the datasheet. The return value is the 32-bit contents of the register. +一行。`sc->res` 保存 `struct resource *`。偏移量 `0x18` 来自数据手册。返回值是寄存器的 32 位内容。 -To write a control value: +写入控制值: ```c bus_write_4(sc->res, 0x00, 0x00000001); /* set ENABLE bit */ ``` -To enforce ordering between the write and a subsequent read: +在写入和后续读取之间强制排序: ```c bus_write_4(sc->res, 0x00, 0x00000001); @@ -711,13 +711,13 @@ bus_barrier(sc->res, 0, 0, BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ); uint32_t status = bus_read_4(sc->res, 0x04); ``` -The barrier ensures the write reaches the device before the read is issued. On x86 the barrier is cheap; on arm64 it emits a fence instruction. The driver does not know or care which; the abstraction handles it. +屏障确保写入在读取发出之前到达设备。在 x86 上屏障开销很低;在 arm64 上它发出一条围栏指令。驱动程序不知道也不关心哪个;抽象处理它。 -These are three-line shapes that will appear, with small variations, in every driver you write in Part 4 and beyond. The patterns look identical whether the target is a real network card, a USB controller, a storage adapter, or a simulated device. +这些三行模式将在你在第四部分及以后编写的每个驱动程序中出现,只有小变化。无论目标是真实网卡、USB 控制器、存储适配器还是模拟设备,模式看起来都一样。 -### A Look at a Real Driver's `bus_space` Usage +### 真实驱动程序中 `bus_space` 使用的一瞥 -To connect the vocabulary to real code, open `/usr/src/sys/dev/ale/if_alevar.h` and scroll to the `CSR_WRITE_*` / `CSR_READ_*` macro block. You will find: +要将词汇与真实代码联系起来,打开 `/usr/src/sys/dev/ale/if_alevar.h` 滚动到 `CSR_WRITE_*` / `CSR_READ_*` 宏块。你会发现: ```c #define CSR_WRITE_4(_sc, reg, val) \ @@ -732,72 +732,72 @@ To connect the vocabulary to real code, open `/usr/src/sys/dev/ale/if_alevar.h` bus_read_4((_sc)->ale_res[0], (reg)) ``` -The softc stores an array `ale_res[]` of resources; the macros reach into the first slot. Everywhere else in the driver, a register access reads as `CSR_READ_4(sc, ALE_SOME_REG)` and reads naturally. +softc 存储资源数组 `ale_res[]`;宏直接到达第一个槽位。在驱动程序的其他地方,寄存器访问读作 `CSR_READ_4(sc, ALE_SOME_REG)`,读起来很自然。 -Or open `/usr/src/sys/dev/e1000/if_em.c` and search for `bus_alloc_resource_any`. You will find: +或者打开 `/usr/src/sys/dev/e1000/if_em.c` 搜索 `bus_alloc_resource_any`。你会发现: ```c sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); ``` -The resource goes into the softc's `memory` field; the rest of the driver uses macros over `sc->memory`. The pattern repeats in every driver you will meet in Part 4. +资源进入 softc 的 `memory` 字段;驱动程序的其余部分使用 `sc->memory` 上的宏。这个模式在你将在第四部分遇到的每个驱动程序中重复。 -Chapter 16 builds up to this pattern gradually. Stage 1 uses plain struct access to emphasise the mechanics. Stage 2 introduces `bus_space_*` directly against a simulated handle. Stage 3 adds barriers and locking. Stage 4 wraps everything in `CSR_*` macros over a `struct resource *`-compatible pointer, matching the real-driver idiom. +第 16 章逐步构建到这个模式。第 1 阶段使用普通结构体访问来强调机制。第 2 阶段直接对模拟句柄引入 `bus_space_*`。第 3 阶段添加屏障和加锁。第 4 阶段将一切包装在兼容 `struct resource *` 指针的 `CSR_*` 宏中,匹配真实驱动程序的惯用法。 -> **A note on line numbers.** The chapter cites FreeBSD source by function, macro, or structure name rather than by line number, because line numbers drift between releases while symbol names survive. For approximate coordinates in FreeBSD 14.3, for orientation only: the `CSR_WRITE_*` macros in `if_alevar.h` sit near line 228, `em_allocate_pci_resources` in `if_em.c` near line 2415, `ale_attach` in `if_ale.c` near line 451, and the `ale_attach` resource-alloc and register-read block spans roughly lines 463 to 580. Open the file and jump to the symbol; the line is whatever your editor reports. +> **关于行号的说明。** 本章通过函数、宏或结构名称而非行号引用 FreeBSD 源代码,因为行号在版本之间会变化而符号名称会保留。对于 FreeBSD 14.3 中的大致位置(仅供定位):`if_alevar.h` 中的 `CSR_WRITE_*` 宏大约在第 228 行,`if_em.c` 中的 `em_allocate_pci_resources` 大约在第 2415 行,`if_ale.c` 中的 `ale_attach` 大约在第 451 行,`ale_attach` 的资源分配和寄存器读取块大致跨越第 463 到 580 行。打开文件跳转到符号;行号就是你的编辑器报告的数字。 -### Wrapping Up Section 3 +### 第 3 节总结 -`bus_space(9)` is a small, focused abstraction over hardware access. A tag identifies an address space; a handle identifies a specific region within it. Read and write functions come in 8, 16, 32, and 64-bit widths. Multi accesses repeat on a single offset; region accesses walk across offsets. Barriers enforce ordering where it matters. The `bus_*` shorthand over a `struct resource *` is what most drivers use day to day. +`bus_space(9)` 是硬件访问的一个小而专注的抽象。标签标识地址空间;句柄标识其中的特定区域。读写函数有 8、16、32 和 64 位宽度。多访问在单个偏移量上重复;区域访问跨偏移量步进。屏障在排序重要的地方强制排序。`struct resource *` 上的 `bus_*` 简写是大多数驱动程序日常使用的。 -The mechanism underneath compiles to CPU instructions that match the platform: a `mov` on x86 MMIO, an `in` or `out` on x86 PIO, a `ldr` or `str` on arm64. The driver writes portable code; the compiler does the translation. +底层机制编译为与平台匹配的 CPU 指令:x86 MMIO 上的 `mov`、x86 PIO 上的 `in` 或 `out`、arm64 上的 `ldr` 或 `str`。驱动程序编写可移植的代码;编译器完成翻译。 -Section 4 now takes you from vocabulary to practice. We build a simulated register block in kernel memory, wrap it with accessor helpers, and start Stage 1 of the Chapter 16 driver refactor. +第 4 节现在带你从词汇到实践。我们在内核内存中构建一个模拟寄存器块,用访问器辅助函数包装它,并开始第 16 章驱动程序重构的第 1 阶段。 -## Section 4: Simulating Hardware for Testing +## 第 4 节:为测试模拟硬件 -Real hardware is a tough teacher. It is expensive to buy, fragile to mishandle, inconsistent across revisions, and unkind to beginners. For Chapter 16's purposes we want something different: an environment where the reader can practise register-style access, see the results, break things safely, and observe what happens. The answer is to simulate a device in kernel memory. +真实硬件是一位严厉的老师。它购买成本高、误操作容易损坏、不同修订版之间不一致,对初学者也不友好。对于第 16 章的目的,我们需要不同的东西:一个让读者可以练习寄存器式访问、查看结果、安全地破坏东西并观察发生什么的环境。答案是在内核内存中模拟一个设备。 -This section builds that simulation from scratch. First a mental model (what does "simulate a device" mean?), then a register map for the device we are going to fake, then the allocation, the accessors, and the first integration with the `myfirst` driver. By the end of Section 4 the driver has Stage 1: a softc that carries a register block, accessors that read and write it, and a couple of sysctls that let you poke at the simulation from user space. +本节从零开始构建该模拟。首先是心智模型("模拟设备"意味着什么?),然后是我们要伪造的设备的寄存器映射,接着是分配、访问器,以及与 `myfirst` 驱动程序的首次集成。到第 4 节结束时,驱动程序完成了第 1 阶段:一个携带寄存器块的 softc、读写它的访问器,以及几个让你从用户空间戳弄模拟的 sysctl。 -### What "Simulating Hardware" Means Here +### "模拟硬件"在这里的含义 -The simulation is deliberately minimal in Section 4. A chunk of kernel memory, allocated once, sized to match a register block, and accessed through functions that look like `bus_space` calls. Reads fetch values from the chunk; writes store values into the chunk. There is no dynamic behaviour yet: no timers changing a status register, no events setting a ready bit, no fault injection. Chapter 17 adds all of that. Section 4 gives you the skeleton. +第 4 节的模拟刻意保持最小化。一块内核内存,分配一次,大小匹配寄存器块,通过看起来像 `bus_space` 调用的函数访问。读取从块中获取值;写入将值存储到块中。目前没有动态行为:没有计时器改变状态寄存器,没有事件设置就绪位,没有故障注入。第 17 章添加所有这些。第 4 节给你骨架。 -This narrowness is deliberate. Chapter 16's job is to teach the access mechanism. A richer simulation, where the reader has to reason about both the mechanism and the device's behaviour, would compete for attention with the vocabulary the reader is still learning. Section 4's simulation exists so every register read and write returns a predictable result, which lets the reader focus on correctness of access rather than on whether the device liked the access or not. +这种窄范围是刻意的。第 16 章的工作是教授访问机制。更丰富的模拟,读者必须同时推理机制和设备行为,会与读者仍在学习的词汇争夺注意力。第 4 节的模拟存在是为了让每次寄存器读写返回可预测的结果,让读者专注于访问的正确性,而不是设备是否接受了该访问。 -A small but important point about the simulation: because the "device" is kernel memory, the reader can inspect it, poke it, and dump it through mechanisms the kernel already provides (`sysctl`, `ddb`, `gdb` on a core dump). This transparency is a pedagogical feature. A real device's registers are only visible through the register interface; the simulated registers are visible through the interface *and* through the allocator. When something goes wrong in the driver, the reader can compare "what the driver thinks the register is" with "what the register actually contains". That debugging pathway is very educational and will be lost when we eventually point the driver at real hardware. +关于模拟的一个小但重要的点:因为"设备"是内核内存,读者可以通过内核已有的机制(`sysctl`、`ddb`、核心转储上的 `gdb`)检查它、戳弄它和转储它。这种透明性是一个教学特性。真实设备的寄存器只能通过寄存器接口看到;模拟寄存器可以通过接口*和*通过分配器看到。当驱动程序出了问题时,读者可以比较"驱动程序认为寄存器是什么"和"寄存器实际包含什么"。这条调试路径非常有教育意义,当我们最终让驱动程序面对真实硬件时会失去它。 -### The Register Map for the Simulated Device +### 模拟设备的寄存器映射 -Before allocating anything, decide what the device looks like. Picking a register map up front is exactly what a datasheet does for real hardware, and doing it before writing code is a habit worth building. +在分配任何东西之前,先决定设备是什么样的。预先选择寄存器映射正是数据手册对真实硬件所做的事情,在编写代码之前做这件事是一个值得培养的习惯。 -The Chapter 16 simulated device is a minimal "widget": it can accept a command, report a status, receive a single byte of data, and send a single byte back. The register map is: +第 16 章的模拟设备是一个最小的“小部件”:它可以接受命令、报告状态、接收一个数据字节并发送一个字节回来。寄存器映射如下: -| Offset | Width | Name | Direction | Description | +| 偏移量 | 宽度 | 名称 | 方向 | 描述 | |--------|--------|-----------------|-----------|---------------------------------------------------------| -| 0x00 | 32 bit | `CTRL` | Read/Write| Control: enable, reset, mode bits. | -| 0x04 | 32 bit | `STATUS` | Read-only | Status: ready, busy, error, data available. | -| 0x08 | 32 bit | `DATA_IN` | Write-only| Data written to the device for processing. | -| 0x0c | 32 bit | `DATA_OUT` | Read-only | Data the device has produced. | -| 0x10 | 32 bit | `INTR_MASK` | Read/Write| Interrupt enable mask. | -| 0x14 | 32 bit | `INTR_STATUS` | Read/Clear| Pending interrupt flags (read-to-clear, Chapter 17). | -| 0x18 | 32 bit | `DEVICE_ID` | Read-only | Fixed identifier: 0x4D594649 ('MYFI'). | -| 0x1c | 32 bit | `FIRMWARE_REV` | Read-only | Firmware revision: encoded as major<<16 | minor. | -| 0x20 | 32 bit | `SCRATCH_A` | Read/Write| Free scratch register. Always echoes writes. | -| 0x24 | 32 bit | `SCRATCH_B` | Read/Write| Free scratch register. Always echoes writes. | +| 0x00 | 32 位 | `CTRL` | 读/写 | 控制:使能、复位、模式位。 | +| 0x04 | 32 位 | `STATUS` | 只读 | 状态:就绪、忙、错误、数据可用。 | +| 0x08 | 32 位 | `DATA_IN` | 只写 | 写入设备以供处理的数据。 | +| 0x0c | 32 位 | `DATA_OUT` | 只读 | 设备已产生的数据。 | +| 0x10 | 32 位 | `INTR_MASK` | 读/写 | 中断使能掩码。 | +| 0x14 | 32 位 | `INTR_STATUS` | 读/清除 | 挂起的中断标志(读即清除,第 17 章)。 | +| 0x18 | 32 位 | `DEVICE_ID` | 只读 | 固定标识符:0x4D594649('MYFI')。 | +| 0x1c | 32 位 | `FIRMWARE_REV` | 只读 | 固件修订版:编码为 major<<16 | minor。 | +| 0x20 | 32 位 | `SCRATCH_A` | 读/写 | 自由暂存寄存器。始终回显写入。 | +| 0x24 | 32 位 | `SCRATCH_B` | 读/写 | 自由暂存寄存器。始终回显写入。 | -The total size is 40 bytes of register space, which we round up to 64 bytes to give ourselves room to grow in Chapter 17. +总大小是 40 字节的寄存器空间,我们向上取整到 64 字节,为第 17 章的扩展留出空间。 -For Chapter 16, all register access is simplified to direct read-and-write on kernel memory. Read-to-clear semantics on `INTR_STATUS`, write-only semantics on `DATA_IN`, and the behaviour of `CTRL` on reset are deferred to Chapter 17. For now, `DATA_IN` echoes whatever the driver wrote; `INTR_STATUS` holds whatever value the driver last set; and the whole block behaves like a plain block of 32-bit slots. +对于第 16 章,所有寄存器访问都简化为对内核内存的直接读写。`INTR_STATUS` 上的读即清除语义、`DATA_IN` 上的只写语义以及 `CTRL` 在复位时的行为推迟到第 17 章。目前,`DATA_IN` 回显驱动程序写入的任何内容;`INTR_STATUS` 保存驱动程序最后设置的任何值;整个块表现得像一个普通的 32 位槽块。 -This is deliberate. Chapter 16 is teaching register access. Chapter 17 introduces the protocol layer. Splitting the two keeps each chapter focused. +这是刻意的。第 16 章教授寄存器访问。第 17 章引入协议层。将两者分开保持每章的焦点。 -### The Register Offsets Header +### 寄存器偏移量头文件 -A real driver separates register offsets into a header so the datasheet mapping lives in one place. The Chapter 16 driver follows the same discipline. Create a file `myfirst_hw.h` alongside `myfirst.c`: +真实驱动程序将寄存器偏移量分离到头文件中,这样数据手册映射就存在于一个地方。第 16 章的驱动程序遵循同样的规范。在 `myfirst.c` 旁边创建一个文件 `myfirst_hw.h`: ```c /* myfirst_hw.h -- Chapter 16 simulated register definitions. */ @@ -847,13 +847,13 @@ A real driver separates register offsets into a header so the datasheet mapping #endif /* _MYFIRST_HW_H_ */ ``` -Every offset is a named constant. Every bit mask has a name. Every fixed value has a constant. Later chapters add more registers and more bits; the header grows incrementally. The discipline of "no magic numbers inside the driver's code" starts here and pays off throughout Part 4. +每个偏移量是一个命名常量。每个位掩码都有一个名称。每个固定值都有一个常量。后续章节会向这个头文件添加更多寄存器;目前以上十个寄存器就是整个设备。 -A note on the `u` suffix on the numeric constants. The `u` makes each constant an `unsigned int`, which is important when the value has the high bit set (32-bit registers use the full `0x80000000` bit, which a plain `int` constant cannot represent portably). Using `u` everywhere keeps the driver consistent; getting into the habit prevents the class of bug where a signed-vs-unsigned mismatch leads to a sign-extended comparison that silently passes or fails. +关于数字常量上的 `u` 后缀的说明。`u` 使每个常量成为 `unsigned int`,当常量用于与无符号类型(`uint32_t`、`bus_size_t` 等)的比较或赋值时很重要。没有 `u`,编译器可能在 `WARNS=6` 时发出有符号/无符号比较警告。 -### Allocating the Register Block +### 分配寄存器块 -With the offsets defined, the driver needs a register block. For the simulation, the block is kernel memory. Add the following to the softc (in `myfirst.c` where the softc is declared): +定义了偏移量后,驱动程序需要一个寄存器块。对于模拟,该块是内核内存。向 softc 添加以下字段: ```c struct myfirst_softc { @@ -865,17 +865,17 @@ struct myfirst_softc { }; ``` -`regs_buf` is a byte pointer to an allocation. Using `uint8_t *` rather than `uint32_t *` makes the per-byte offset arithmetic in the accessors straightforward; we cast to the appropriate width at each access. +`regs_buf` 是指向分配的字节指针。使用 `uint8_t *` 而不是 `uint32_t *` 使按字节偏移的算术更直接:头文件中的每个偏移量都是字节偏移量,访问器辅助函数在内部转换为 `uint32_t`。`regs_len` 记录分配大小供拆除路径使用。 -Before the allocation itself, a small but useful improvement. The Chapter 15 driver uses `M_DEVBUF`, the kernel's generic driver-memory bucket, for its allocations. That works, but it blurs our driver's footprint with every other driver on the system: `vmstat -m` reports the aggregated usage under `devbuf`, with no way to tell what came from `myfirst`. Chapter 16 is a good moment to introduce a per-driver malloc type. Near the top of `myfirst.c`, alongside the other file-scoped declarations: +在分配之前,一个小但有用的改进。第 15 章驱动程序使用 `M_DEVBUF`,内核的通用 malloc 类型。第 16 章引入驱动程序特定的类型: ```c static MALLOC_DEFINE(M_MYFIRST, "myfirst", "myfirst driver allocations"); ``` -`MALLOC_DEFINE` registers a new malloc bucket named `myfirst`, with the long description used by `vmstat -m`. Every allocation the driver makes from this chapter onward is tagged with `M_MYFIRST`, so `vmstat -m` can report the driver's total memory use directly. Chapter 15's allocations that previously used `M_DEVBUF` can be migrated to `M_MYFIRST` in the same pass, or left alone; the practical difference is small and the migration is purely cosmetic. +`MALLOC_DEFINE` 注册一个名为 `myfirst` 的新 malloc 桶,带有 `vmstat -m` 使用的长描述。每个标记为 `M_MYFIRST` 的分配都会出现在该桶下。加载驱动程序后,`vmstat -m | grep myfirst` 显示计数和总字节数。 -With the type defined, the allocation happens in `myfirst_attach`, before any code that might access the registers: +定义了类型后,分配在 `myfirst_attach` 中进行,在任何可能访问寄存器的代码之前: ```c /* In myfirst_attach, after softc initialisation, before registering /dev nodes. */ @@ -888,11 +888,11 @@ sc->regs_buf = malloc(sc->regs_size, M_MYFIRST, M_WAITOK | M_ZERO); *(uint32_t *)(sc->regs_buf + MYFIRST_REG_STATUS) = MYFIRST_STATUS_READY; ``` -`M_WAITOK | M_ZERO` produces a zero-filled allocation that can sleep to complete if memory is tight, which is fine at attach time. `M_WAITOK` is the right choice because the caller is the kernel's attach path, which is a process context and can block; `M_NOWAIT` would be required only from a callout or filter-interrupt context. +`M_WAITOK | M_ZERO` 产生一个零填充的分配,如果内存紧张可以睡眠等待完成,这在 attach 时没问题。64 字节的分配覆盖所有十个寄存器并有余量。 -The initialisation writes three fixed values: the device ID, the firmware revision, and an initial `STATUS` with the `READY` bit set. A real device would set these through hardware logic at power-on; the simulation does them explicitly in code. +初始化写入三个固定值:设备 ID、固件修订版,以及设置了 `READY` 位的初始 `STATUS`。所有其他寄存器从零开始。 -The teardown is symmetric, in `myfirst_detach`: +拆除是对称的,在 `myfirst_detach` 中: ```c /* In myfirst_detach, after all consumers of regs_buf have quiesced. */ @@ -903,15 +903,15 @@ if (sc->regs_buf != NULL) { } ``` -As always in the Chapter 11-15 tradition, the free happens after every code path that could touch the memory has finished. By the time we reach this point in detach, the callouts are drained, the taskqueue is drained, the cdev is destroyed, and no syscall can reach the driver. +按照第 11-15 章的传统,释放在每个可能接触该内存的代码路径都完成后进行: -A subtle but important point: the allocation uses `malloc(9)` rather than `contigmalloc(9)` or `bus_dmamem_alloc(9)`. For simulation, any kernel memory works. For real hardware with DMA requirements, the allocation would need to be physically contiguous, page-aligned, and bounce-buffered as appropriate; that is Chapter 20's topic, not ours. +一个微妙但重要的点:分配使用 `malloc(9)` 而不是 `contigmalloc(9)` 或 `bus_dmamem_alloc(9)`。对于模拟,物理连续性不重要,因为 CPU 通过内核的虚拟映射访问寄存器,而不是通过设备的 DMA 引擎。真实设备的 MMIO 区域来自 `bus_alloc_resource`;模拟使用 `malloc` 是因为背后没有总线。 -### The First Accessor Helpers +### 第一个访问器辅助函数 -Direct struct access through raw casts (`*(uint32_t *)(sc->regs_buf + MYFIRST_REG_CTRL)`) works but is ugly, unsafe (no bounds checking), and inconsistent with the `bus_space` idiom the chapter is teaching. Replace it with named accessors. +通过原始类型转换直接访问结构体(`*(uint32_t *)(sc->regs_buf + MYFIRST_REG_CTRL)`)可以工作但难看、不安全(没有边界检查)且难以 grep。真实驱动程序将寄存器访问包装在辅助函数或宏中,集中类型转换、边界检查和(稍后的)加锁。 -In `myfirst_hw.h`, add function prototypes and inline definitions: +在 `myfirst_hw.h` 中,添加函数原型和内联定义: ```c /* Simulated accessor helpers. Stage 1: direct memory, no barriers. */ @@ -936,15 +936,15 @@ myfirst_reg_write(uint8_t *regs_buf, size_t regs_size, bus_size_t offset, } ``` -Two helpers: one read, one write. Each bounds-checks the offset with `KASSERT` so an out-of-range access is caught immediately on a debug kernel. Each uses `volatile` to prevent the compiler from caching or reordering the access. `bus_size_t` is the same type `bus_space` uses for offsets; using it keeps the accessors compatible with the later transition. +两个辅助函数:一个读取,一个写入。每个都用 `KASSERT` 进行偏移量边界检查,使超出范围的访问在调试内核中立即被捕获。每个将字节指针基址加偏移量转换为 `volatile uint32_t *` 并解引用。`volatile` 防止编译器缓存或重排序该访问。 -A driver that wants to read `STATUS` from its softc now writes: +想要从 softc 读取 `STATUS` 的驱动程序现在写: ```c uint32_t status = myfirst_reg_read(sc->regs_buf, sc->regs_size, MYFIRST_REG_STATUS); ``` -Two arguments of boilerplate per call feels like a lot. Real drivers wrap their accessors in shorter macros that take the softc directly. Let us do the same: +每次调用两个参数的样板感觉很多。真实驱动程序将访问器包装在更短的宏中,接受 softc 和寄存器名称。在 `myfirst_hw.h` 中添加: ```c #define MYFIRST_REG_READ(sc, offset) \ @@ -953,15 +953,15 @@ Two arguments of boilerplate per call feels like a lot. Real drivers wrap their myfirst_reg_write((sc)->regs_buf, (sc)->regs_size, (offset), (value)) ``` -Now the register access reads: +现在寄存器访问读作: ```c uint32_t status = MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS); ``` -Short, named, scannable. The macros do not add cost beyond the inline expansion the compiler would have done anyway. +简短、命名、可扫描。这些宏不增加超过编译器本来就会做的内联展开的开销。 -One more helper worth introducing for Stage 1. A common operation is "read a register, modify one field, write it back": +第 1 阶段值得引入的另一个辅助函数。一个常见的操作是“读取寄存器,修改一个字段,写回”。这被称为读-改-写模式,并为它设置一个辅助函数可以省去以后重复的代码。在 `myfirst_hw.h` 中添加: ```c static __inline void @@ -977,7 +977,7 @@ myfirst_reg_update(struct myfirst_softc *sc, bus_size_t offset, } ``` -The helper reads the register, clears the bits named in `clear_mask`, sets the bits named in `set_mask`, and writes the result back. A typical use: +辅助函数读取寄存器,清除 `clear_mask` 中命名的位,设置 `set_mask` 中命名的位,并写回结果。这在形式上与真实驱动程序用于切换寄存器中各个字段的模式相同。 ```c /* Clear the ENABLE bit in CTRL. */ @@ -991,11 +991,11 @@ myfirst_reg_update(sc, MYFIRST_REG_CTRL, MYFIRST_CTRL_MODE_MASK, 3 << MYFIRST_CTRL_MODE_SHIFT); ``` -A caveat: `myfirst_reg_update` as written is not atomic. Between the read and the write, another context could read the same register, modify it, and write it back; our write would then overwrite the other context's update. For Stage 1 this is acceptable, because the simulated registers are accessed only from the syscall context and are not shared with interrupts or tasks yet. Section 6 revisits the atomicity story and introduces locking around the update. +一个警告:`myfirst_reg_update` 按照目前写法不是原子的。在读取和写入之间,另一个上下文可能会修改寄存器。对于第 16 章的模拟这不是问题,因为只有一个上下文接触寄存器。第 6 节添加了适当的锁。 -### Exposing the Registers Through Sysctls +### 通过 Sysctl 暴露寄存器 -To make the Stage 1 register block observable without writing a user-space tool, expose each register as a read-only sysctl. In `myfirst_attach`, alongside the other sysctl definitions: +为了使第 1 阶段寄存器块可观察而不必编写用户空间工具,通过 sysctl 暴露每个寄存器。在 `myfirst_attach` 中,在寄存器初始化之后,添加: ```c /* Chapter 16, Stage 1: sysctls that read the simulated registers. */ @@ -1015,9 +1015,9 @@ SYSCTL_ADD_PROC(&sc->sysctl_ctx, myfirst_sysctl_reg, "IU", "Device ID register (read-only view)"); ``` -(Equivalent entries for each interesting register follow the same pattern. The examples/part-04 source has the full list.) +(每个有趣寄存器的等价条目遵循相同模式。examples/part-04 源代码有完整列表。) -The sysctl handler translates the arg1/arg2 pair into a register read: +sysctl 处理程序将 arg1/arg2 对转换为寄存器读取: ```c static int @@ -1034,7 +1034,7 @@ myfirst_sysctl_reg(SYSCTL_HANDLER_ARGS) } ``` -With these sysctls in place, the reader can type: +有了这些 sysctl,读者可以输入: ```text # sysctl dev.myfirst.0.reg_ctrl @@ -1045,11 +1045,11 @@ dev.myfirst.0.reg_status: 1 dev.myfirst.0.reg_device_id: 1298498121 ``` -`1298498121` in decimal is `0x4D594649`, the fixed device ID. `1` in `reg_status` is the `READY` bit. These are the values the attach path set; the reader can see them from user space. The loop from "the driver writes a register" to "the reader observes the register value" is closed. +`1298498121` 十进制即 `0x4D594649`,固定设备 ID。`reg_status` 中的 `1` 是 `READY` 位。这些是 attach 路径设置的值;读者可以从用户空间看到它们。从“驱动程序写入寄存器”到“读者观察寄存器值”的循环被关闭了。 -### A Writeable Sysctl for `CTRL` and `DATA_IN` +### `CTRL` 和 `DATA_IN` 的可写 Sysctl -Reading is half the story. The Stage 1 simulation also benefits from a writeable sysctl that lets the reader poke register values: +读取只是故事的一半。第 1 阶段模拟也受益于一个可写 sysctl,让读者从用户空间修改 `CTRL` 和 `DATA_IN` 寄存器。 ```c SYSCTL_ADD_PROC(&sc->sysctl_ctx, @@ -1059,7 +1059,7 @@ SYSCTL_ADD_PROC(&sc->sysctl_ctx, "Control register (writeable, Stage 1 test aid)"); ``` -With the write handler: +有了写入处理程序: ```c static int @@ -1081,9 +1081,9 @@ myfirst_sysctl_reg_write(SYSCTL_HANDLER_ARGS) } ``` -The handler reads the current value, accepts a new value from the caller, writes it back. Writes are unrestricted for now; later sections add validation and side effects. +处理程序读取当前值,接受来自调用者的新值,写回。写入受 `sc->mtx` 保护。 -The reader can now experiment: +读者现在可以实验: ```text # sysctl dev.myfirst.0.reg_ctrl_set @@ -1094,29 +1094,29 @@ dev.myfirst.0.reg_ctrl_set: 0 -> 1 dev.myfirst.0.reg_ctrl: 1 ``` -Setting the `ctrl_set` sysctl to `1` enables the (notional) device by setting the `ENABLE` bit in `CTRL`. Reading `reg_ctrl` confirms it. The loop is now complete: user space writes, the register updates, user space reads, the value matches. +将 `ctrl_set` sysctl 设置为 `1` 通过在 `CTRL` 中设置 `ENABLE` 位来启用(名义上的)设备。再次设置为 `0` 将其清除。 -### The Observer Pattern: Coupling Registers to Driver State +### 观察者模式:将寄存器与驱动程序状态耦合 -At this point the driver has a register block that is inert. Writing to `CTRL` does not make the driver do anything. Reading from `STATUS` returns whatever was last written. The registers exist; the driver ignores them. +此时驱动程序有一个惰性的寄存器块。写入 `CTRL` 不会使驱动程序做任何事情不同。读取 `STATUS` 总是返回相同的值。寄存器还没有连接到驱动程序的行为。 -Stage 1's closing step couples two small pieces of driver state to the register block, so that user-space observation of registers reflects something real. +第 1 阶段的最后一步将驱动程序状态的两个小片段与寄存器块耦合,以便用户可见的状态变化。 -The first coupling: clear the `READY` bit in `STATUS` while the driver is in a reset state, and set it when the driver is attached and operational. In `myfirst_attach`, immediately after allocating `regs_buf`: +第一个耦合:在驱动程序处于复位状态时清除 `STATUS` 中的 `READY` 位,并在 attach 完成时设置它: ```c MYFIRST_REG_WRITE(sc, MYFIRST_REG_STATUS, MYFIRST_STATUS_READY); ``` -In `myfirst_detach`, before freeing `regs_buf`: +在 `myfirst_detach` 中,在释放 `regs_buf` 之前: ```c MYFIRST_REG_WRITE(sc, MYFIRST_REG_STATUS, 0); ``` -(In practice, detach's `free(regs_buf)` makes the clearing pointless, but the explicit clear documents the intent and mirrors how a real driver would signal the device that the driver is going away.) +(实际上,detach 的 `free(regs_buf)` 使这个清除变得毫无意义,但显式清除记录了意图,并反映了真实驱动程序如何向设备发出驱动程序即将离开的信号。) -The second coupling: if the user-space caller sets `CTRL.ENABLE`, set a soft flag in the softc that the driver uses to decide whether to emit heartbeat output. If the user clears it, the flag clears. This needs a small change in the writeable sysctl handler and a short routine that applies the change: +第二个耦合:如果用户空间调用者设置了 `CTRL.ENABLE`,在 softc 中设置一个软标志,使驱动程序可以注意到转变。 ```c static void @@ -1130,7 +1130,7 @@ myfirst_ctrl_update(struct myfirst_softc *sc, uint32_t old, uint32_t new) } ``` -The writeable sysctl handler calls it after updating the register: +可写 sysctl 处理程序在更新寄存器后调用它: ```c static int @@ -1158,23 +1158,23 @@ myfirst_sysctl_reg_write(SYSCTL_HANDLER_ARGS) } ``` -Now writing `1` to `reg_ctrl_set` produces a `device_printf` in `dmesg` noting the transition. Writing `0` to `reg_ctrl_set` produces another. The register is no longer inert; it drives an observable behaviour. +现在向 `reg_ctrl_set` 写入 `1` 会在 `dmesg` 中产生一条 `device_printf`,记录状态转变。向 `reg_ctrl_set` 写入 `0` 会产生另一条。寄存器不再是惰性的;它驱动了一个可观察的行为。 -This is a tiny example of a pattern that will recur: the register is a control surface, the driver reacts to register changes, user-space (or in real drivers, the device) triggers those changes. In Chapter 17 we automate the device side with a callout that changes registers on a timer; in Chapter 18 we point the driver at a real PCI device. +这是一个将会反复出现的模式的微小示例:寄存器是控制面,驱动程序响应它。 -### What Stage 1 Accomplished +### 第 1 阶段完成了什么 -At the end of Section 4, the driver has: +在第 4 节结束时,驱动程序有: -- A `myfirst_hw.h` header with register offsets, bit masks, and fixed values. -- A `regs_buf` in the softc, allocated at attach and freed at detach. -- Accessor helpers (`myfirst_reg_read`, `myfirst_reg_write`, `myfirst_reg_update`) and macros (`MYFIRST_REG_READ`, `MYFIRST_REG_WRITE`) that wrap access. -- Sysctls that expose several registers for read and a writeable sysctl for one of them. -- A small coupling between `CTRL.ENABLE` and a driver-level printf. +- 一个 `myfirst_hw.h` 头文件,包含寄存器偏移量、位掩码和固定值。 +- softc 中的 `regs_buf`,在 attach 时分配,在 detach 时释放。 +- 访问器辅助函数和宏。 +- 暴露多个寄存器用于读取的 sysctl,以及一个可写 sysctl。 +- `CTRL.ENABLE` 与驱动程序级 printf 之间的一个小耦合。 -The version tag becomes `0.9-mmio-stage1`. The driver still does everything Chapter 15 gave it; it has simply grown a register-shaped appendage. +版本标签变为 `0.9-mmio-stage1`。驱动程序仍然拥有第 15 章给它的所有功能;它只是长出了一个寄存器形状的附肢。 -Build, load, and test: +构建、加载并测试: ```text # cd examples/part-04/ch16-accessing-hardware/stage1-register-map @@ -1188,39 +1188,39 @@ Build, load, and test: # kldunload myfirst ``` -You should see the ENABLE transitions in `dmesg` and the register values changing through `sysctl`. If any step fails, Section 4's troubleshooting entries at the end of the chapter catch the most common problems. +你应该在 `dmesg` 中看到 ENABLE 转变,在 `sysctl` 中看到寄存器值的变化。如果任何步骤失败,本章末尾第 4 节的故障排除条目会捕获最常见的问题。 -### A Note on What Stage 1 Is Not +### 第 1 阶段不是什么 -Stage 1 is a register-shaped state container. It is not yet using `bus_space(9)` at the API level. The accessors are plain C memory access behind a named helper. Section 5 takes the next step: replace those helpers with real `bus_space_*` calls that operate on the same kernel memory, so the driver's access pattern matches what a real driver with a real resource would look like. +第 1 阶段是一个寄存器形状的状态容器。它尚未在 API 层面使用 `bus_space(9)`。访问器是命名辅助函数背后的普通 C 内存访问。第 5 节迈出下一步:用操作相同内核内存的真实 `bus_space_*` 调用替换这些辅助函数,使驱动程序的访问模式匹配带有真实资源的真实驱动程序的样子。 -The reason to introduce the abstraction in two passes is pedagogical. Stage 1 makes the mechanism visible: you can see exactly what `MYFIRST_REG_READ` does under the covers. Stage 2 replaces the visible mechanism with the portable API, and you can compare the two and see that the API is doing nothing the helper was not already doing, only more portably and with platform-appropriate barriers where needed. The two-step teaches both. +分两遍引入抽象的原因是教学性的。第 1 阶段让机制可见:你可以准确看到 `MYFIRST_REG_READ` 在底层做了什么。第 2 阶段用可移植 API 替换可见机制,你可以比较两者,看到 API 没有做辅助函数没有做的任何事,只是更可移植并在需要时带有平台适当的屏障。这两步教学教授了两方面。 -### Wrapping Up Section 4 +### 总结第 4 节 -Simulating hardware starts with a register map and a chunk of kernel memory. A small header declares the offsets, bit masks, and fixed values. A softc field holds the allocation. Accessor helpers wrap read and write. Sysctls expose the registers so the reader can observe and poke them from user space. Small couplings between registers and driver-level behaviour make the abstraction concrete. +模拟硬件从一个寄存器映射和一块内核内存开始。一个小型头文件声明偏移量、位掩码和固定值。softc 的一个字段持有分配。访问器辅助函数包装读写。sysctl 暴露寄存器,使读者可以从用户空间观察和戳弄它们。寄存器与驱动程序级行为之间的小耦合使抽象变得具体。 -The driver is now at Stage 1 of Chapter 16. Section 5 integrates `bus_space(9)` into this setup, replacing the direct accessors with the portable API the rest of FreeBSD uses. +驱动程序现在处于第 16 章的第 1 阶段。第 5 节将 `bus_space(9)` 集成到这个设置中,用 FreeBSD 其余部分使用的可移植 API 替换直接访问器。 -## Section 5: Using `bus_space` in a Real Driver Context +## 第 5 节:在真实驱动程序上下文中使用 `bus_space` -Section 4 gave the driver a simulated register block and direct accessors. Section 5 replaces the direct accessors with the `bus_space(9)` API and integrates register access into the `myfirst` data path. The shape of the driver changes in a few small but deliberate ways, all of which look more like a real hardware driver than the Stage 1 version did. +第 4 节给驱动程序提供了模拟寄存器块和直接访问器。第 5 节用 `bus_space(9)` API 替换直接访问器,并将寄存器访问集成到 `myfirst` 数据路径中。驱动程序的形状以几个小而刻意的方式变化,所有这些都比第 1 阶段版本更像真实的硬件驱动程序。 -This section starts with the smallest possible change (replace the accessor bodies with `bus_space_*` calls) and builds up. By the end, the driver's `write(2)` path produces a register access as a side effect, the driver's `read(2)` path reflects register state, and a task can change register values on a timer so the reader can watch the device "breathe" without user-space poking. +本节从最小的可能变化开始(用 `bus_space_*` 调用替换访问器主体)并逐步构建。到最后,驱动程序的 `write(2)` 路径产生寄存器访问作为副作用,`read(2)` 路径反映寄存器状态,一个任务可以按计时器改变寄存器值,让读者无需用户空间戳弄就能看到设备"呼吸"。 -### The Pedagogical Trick: Using `bus_space` on Kernel Memory +### 教学技巧:在内核内存上使用 `bus_space` -A minor sleight-of-hand that makes Section 5 possible: on x86, the `bus_space_read_*` and `bus_space_write_*` functions for memory space compile to a plain `volatile` dereference of `handle + offset`. The handle is just a `uintptr_t`-shaped value that the functions cast to a pointer. If we set the handle to `(bus_space_handle_t)sc->regs_buf`, and the tag to `X86_BUS_SPACE_MEM`, the `bus_space_read_4(tag, handle, offset)` call will do `*(volatile u_int32_t *)(regs_buf + offset)`, which is exactly what our Stage 1 accessor did. +使第 5 节成为可能的一个小技巧:在 x86 上,内存空间的 `bus_space_read_*` 和 `bus_space_write_*` 函数编译为 `handle + offset` 的普通 `volatile` 解引用。句柄只是一个 `uintptr_t` 形状的值,函数将其转换为指针。如果我们将句柄设置为 `(bus_space_handle_t)sc->regs_buf`,标签设置为 `X86_BUS_SPACE_MEM`,`bus_space_read_4(tag, handle, offset)` 调用会执行 `*(volatile u_int32_t *)(regs_buf + offset)`,这正是第 1 阶段访问器所做的。 -That means, on x86 at least, we can drive our simulated register block through the real `bus_space` API by filling in a tag and handle that point at our `malloc`'d memory. The driver's code then becomes indistinguishable, at the source level, from a driver that is accessing real MMIO. That is the whole point: the vocabulary transfers. +这意味着,至少在 x86 上,我们可以通过填写指向我们 `malloc` 分配内存的标签和句柄,通过真实的 `bus_space` API 来驱动我们的模拟寄存器块。驱动程序代码在源代码级别就变得与访问真实 MMIO 的驱动程序无法区分。这就是全部意义:词汇是可以迁移的。 -On non-x86 platforms, the trick is slightly less clean. On arm64 and some other architectures, `bus_space_tag_t` is a pointer to a structure describing the bus, and using a manufactured tag requires more setup. For Chapter 16 the simulation path is x86-centric; the chapter acknowledges the architectural limitation and defers portability-across-architectures to the later portability chapter. The lessons Chapter 16 teaches are universally applicable; only this one shortcut for simulation is x86-specific. +在非 x86 平台上,这个技巧稍微不那么干净。 -### Stage 2: Setting Up the Simulated Tag and Handle +### 第 2 阶段:设置模拟标签和句柄 -Add two fields to the softc: +向 softc 添加两个字段: ```c struct myfirst_softc { @@ -1232,7 +1232,7 @@ struct myfirst_softc { }; ``` -In `myfirst_attach`, after allocating `regs_buf`: +在 `myfirst_attach` 中,分配 `regs_buf` 之后: ```c #if defined(__amd64__) || defined(__i386__) @@ -1243,13 +1243,13 @@ sc->regs_tag = X86_BUS_SPACE_MEM; sc->regs_handle = (bus_space_handle_t)(uintptr_t)sc->regs_buf; ``` -That is all the setup. The handle is the virtual address of the allocation cast through `uintptr_t`; the tag is the architecture's constant for memory space. +这就是全部设置。 -The `#error` for non-x86 is a deliberate teaching signal: the chapter explicitly flags what is portable (the vocabulary) and what is not (this specific simulation shortcut). Chapter 17 and the portability chapter will teach a cleaner alternative. Until then, x86 is the supported platform for the chapter's exercises. +非 x86 上的 `#error` 是一个刻意的教学信号:本章明确标记了什么是可移植的(词汇)和什么是不可移植的(这个特定的模拟快捷方式)。第 17 章和可移植性章节将教授更干净的替代方案。在那之前,x86 是本章练习支持的平台。 -### Replacing the Accessors +### 替换访问器 -With the tag and handle set up, the accessors become one-liners over `bus_space_*`: +设置好标签和句柄后,访问器变成 ```c static __inline uint32_t @@ -1271,18 +1271,18 @@ myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, uint32_t value) } ``` -The signature changes: the helpers now take a `struct myfirst_softc *` rather than `regs_buf` and `regs_size` separately. Internal bounds checking is retained; the KASSERT fires if a bug in the driver produces an out-of-range offset. The body uses `bus_space_read_4` and `bus_space_write_4` instead of direct memory access. +签名变了:辅助函数现在接受 -The `MYFIRST_REG_READ` and `MYFIRST_REG_WRITE` macros simplify accordingly: +`MYFIRST_REG_READ` 和 `MYFIRST_REG_WRITE` 宏相应简化: ```c #define MYFIRST_REG_READ(sc, offset) myfirst_reg_read((sc), (offset)) #define MYFIRST_REG_WRITE(sc, offset, value) myfirst_reg_write((sc), (offset), (value)) ``` -Every register access in the driver, including the sysctl handlers and `myfirst_reg_update`, continues to use these macros. None of the call sites change. The driver's behaviour is identical to Stage 1, but the access path now travels through `bus_space`, and the path would work just as well if `regs_tag` and `regs_handle` came from `rman_get_bustag` and `rman_get_bushandle` on a real resource. +驱动程序中的每个寄存器访问,包括 sysctl -Build the driver and confirm it still passes the Stage 1 sysctl exercises: +构建驱动程序并确认它仍通过 ```text # cd examples/part-04/ch16-accessing-hardware/stage2-bus-space @@ -1295,13 +1295,13 @@ dev.myfirst.0.reg_device_id: 1298498121 # kldunload myfirst ``` -The output matches Stage 1. The driver now uses `bus_space` the way a real driver does. +输出与第 1 阶段匹配。驱动程序现在使用 -### Exposing `DATA_IN` Through the Write Path +### 通过写入路径暴露 `DATA_IN` -With the accessor layer in place, Stage 2 couples the driver's `write(2)` syscall to the `DATA_IN` register. Every byte written to the device file `/dev/myfirst0` now ends up at the `DATA_IN` register, where the reader can observe it. +有了访问器层,第 2 阶段将数据路径连接到寄存器,使写入产生可观察的副作用。 -Modify `myfirst_write` (the `d_write` callback). The existing handler reads bytes from the uio, copies them into the ring buffer, signals waiters, and returns. The new handler does the same, plus: just before returning, it writes the most recently copied byte to `DATA_IN` and sets the `DATA_AV` bit in `STATUS`: +修改 `myfirst_write`(`d_write` 回调),在环缓冲区复制之后记录写入的最后一个字节到 `DATA_IN`,并在 `STATUS` 中设置 `DATA_AV` 位: ```c static int @@ -1345,7 +1345,7 @@ myfirst_write(struct cdev *cdev, struct uio *uio, int flag) } ``` -Now, after any `echo foo > /dev/myfirst0`, the `DATA_IN` register contains the byte value of `'o'` (the last character of `"foo\n"` is `\n`, actually, which is `0x0a`), and the `DATA_AV` bit in `STATUS` is set. The reader can observe this through sysctl: +现在,在执行 `echo foo > /dev/myfirst0` 之后,`DATA_IN` 寄存器包含 `'o'` 的字节值(`"foo\n"` 的最后一个字符实际上是 `\n`,即 `0x0a`),`STATUS` 中的 `DATA_AV` 位被设置。读者可以通过 sysctl 观察到这一点: ```text # echo -n "Hello" > /dev/myfirst0 @@ -1355,11 +1355,11 @@ dev.myfirst.0.reg_data_in: 111 dev.myfirst.0.reg_status: 9 ``` -`111` is the ASCII code for `'o'`, the last byte of "Hello". `9` is `MYFIRST_STATUS_READY | MYFIRST_STATUS_DATA_AV` (`1 | 8 = 9`). The driver has, for the first time, produced an externally-observable register-level side effect in response to user-space action. +`111` 是 `'o'` 的 ASCII 码,"Hello" 的最后一个字节。`9` 是 `MYFIRST_STATUS_READY | MYFIRST_STATUS_DATA_AV`(`1 | 8 = 9`)。驱动程序首次产生了对用户空间操作的寄存器级可观察副作用。 -### Exposing `DATA_OUT` Through the Read Path +### 通过读取路径暴露 `DATA_OUT` -Symmetrically, every byte read from `/dev/myfirst0` can update `DATA_OUT` to reflect what was last read. Modify `myfirst_read`: +对称地,每次从驱动程序读取时,`DATA_OUT` 反映读取的最后一个字节,当环缓冲区排空时清除 `DATA_AV`: ```c static int @@ -1389,11 +1389,11 @@ myfirst_read(struct cdev *cdev, struct uio *uio, int flag) /* ... existing unlock and cv_signal ... */ - /* Chapter 16 Stage 2: reflect the last byte in DATA_OUT. */ + /* 第 16 章第 2 阶段:将最后一个字节反映到 DATA_OUT。 */ if (read_any) { MYFIRST_REG_WRITE(sc, MYFIRST_REG_DATA_OUT, (uint32_t)last_byte); - /* If the ring buffer is now empty, clear DATA_AV. */ + /* 如果环缓冲区现在为空,清除 DATA_AV。 */ if (cbuf_is_empty(&sc->cb)) myfirst_reg_update(sc, MYFIRST_REG_STATUS, MYFIRST_STATUS_DATA_AV, 0); @@ -1403,9 +1403,9 @@ myfirst_read(struct cdev *cdev, struct uio *uio, int flag) } ``` -Now `DATA_OUT` reflects the last byte the reader read, and `DATA_AV` clears when the ring buffer drains. The loop from "user writes a byte" to "driver updates register" to "user reads a byte" to "driver updates registers" is closed. +现在 `DATA_OUT` 反映读取者读取的最后一个字节,`DATA_AV` 在环缓冲区排空时清除。从"用户写入一个字节"到"驱动程序更新寄存器"到"用户读取一个字节"到"驱动程序更新寄存器"的循环被闭合了。 -Testing: +测试: ```text # echo -n "ABC" > /dev/myfirst0 @@ -1418,20 +1418,20 @@ dev.myfirst.0.reg_data_out: 67 dev.myfirst.0.reg_status: 1 ``` -`67` is `'C'`, the last byte written. After the `dd` consumes all three bytes, `DATA_OUT` holds `'C'` (the last byte read) and `STATUS` is back to just `READY` because `DATA_AV` cleared. +`67` 是 `'C'`,最后写入的字节。`dd` 消费了全部三个字节后,`DATA_OUT` 持有 `'C'`(最后读取的字节),`STATUS` 回到只有 `READY`,因为 `DATA_AV` 已被清除。 -### Driving Register State From a Task +### 通过任务驱动寄存器状态 -The register block so far reflects driver actions triggered by user-space syscalls. To illustrate a task-driven pattern, add a small task that periodically increments `SCRATCH_A`. This is an artificial example; it exists so the reader can see register values changing autonomously in response to task-triggered events, preparing for Chapter 17 where callouts and timers drive more realistic changes. +到目前为止寄存器块反映驱动程序操作的结果。第 2 阶段添加了一个小任务,自主改变一个寄存器,使驱动程序在用户不戳弄时也能"呼吸"。 -In the softc: +在 softc 中: ```c struct task reg_ticker_task; int reg_ticker_enabled; ``` -The task callback: +任务回调: ```c static void @@ -1447,14 +1447,14 @@ myfirst_reg_ticker_cb(void *arg, int pending) } ``` -The task is enqueued from the existing tick_source callout (Chapter 14's callout that already fires on a timer). In the callout callback, alongside the selwake task enqueue: +任务从现有的 tick_source callout(第 14 章已经按计时器触发的 callout)入队。在 callout 回调中,与 selwake 任务入队一起: ```c if (sc->reg_ticker_enabled) taskqueue_enqueue(sc->tq, &sc->reg_ticker_task); ``` -And a sysctl to enable it: +以及一个启用它的 sysctl: ```c SYSCTL_ADD_INT(&sc->sysctl_ctx, @@ -1463,20 +1463,20 @@ SYSCTL_ADD_INT(&sc->sysctl_ctx, "Enable the periodic register ticker (increments SCRATCH_A each tick)"); ``` -Initialisation in attach: +attach 中的初始化: ```c TASK_INIT(&sc->reg_ticker_task, 0, myfirst_reg_ticker_cb, sc); sc->reg_ticker_enabled = 0; ``` -Drain in detach, in the existing task drain block: +在 detach 中排空,在现有的任务排空块中: ```c taskqueue_drain(sc->tq, &sc->reg_ticker_task); ``` -With this in place, enabling the ticker produces a visible register effect: +有了这个,启用 ticker 后: ```text # sysctl dev.myfirst.0.reg_ticker_enabled=1 @@ -1489,11 +1489,11 @@ dev.myfirst.0.reg_scratch_a: 10 # sysctl dev.myfirst.0.reg_ticker_enabled=0 ``` -The register value climbs at one per second, as the tick_source callout fires. The driver is now exhibiting autonomous register-level behaviour, triggered by a task, mediated by `bus_space`. +寄存器值以每秒一个的速度增长,完全自主,不需要用户空间交互。 -### The Full Stage 2 Sysctl Tree +### 第 2 阶段完整的 Sysctl 树 -After Stage 2 the full sysctl tree under `dev.myfirst.0` looks roughly like: +第 2 阶段之后完整的 sysctl 树如下: ```text dev.myfirst.0.debug_level @@ -1522,38 +1522,40 @@ dev.myfirst.0.reg_ctrl_set dev.myfirst.0.reg_ticker_enabled ``` -Ten register views, one writeable register, one ticker toggle, plus every previous sysctl from Chapters 11 through 15. The driver has grown, but every addition is small and named. +十个寄存器视图、一个可写寄存器、一个 ticker 开关,加上第 11 到 15 章的每个 sysctl。驱动程序增长了,但每个新增部分都小而有命名。 -### A Note on Reads From `STATUS` While the Driver Is Running +### 关于驱动程序运行时从 `STATUS` 读取的说明 -In the Stage 1 and Stage 2 setups, reading `STATUS` via sysctl returns whatever bits the driver most recently set. No read has side effects. This is intentional for Chapter 16. But notice a subtle consequence: the driver can set the `STATUS.DATA_AV` bit in the write path and clear it in the read path, and the user-space reader can observe the bit change over time. Running `sysctl -w dev.myfirst.0.reg_status=0` is possible through the writeable sysctl, but the driver's automatic updates will re-set the bit on the next write to the device file. +在第 1 阶段和第 2 阶段的设置中,`STATUS` 寄存器是静态的:在 attach 时设置 `READY`,其他什么都不做。当驱动程序的数据路径开始修改 `DATA_AV` 位并且 ticker 修改 `SCRATCH_A` 时,`STATUS` 的读取可能会在不同时刻返回不同的值,具体取决于读取相对于写入发生的时间。 -This is how a "polled" device driver works at a conceptual level: the driver polls the status register periodically, reacts to state changes, and updates driver-visible state accordingly. A real device's `STATUS` bits change for hardware reasons; the simulated device's bits change for simulated-driver reasons. The mechanism is the same. +这就是”轮询式”设备驱动程序的工作方式:读取状态寄存器,检查感兴趣的位,做出决定。读者已经通过 sysctl 完成了这种操作。当第 17 章引入动态行为时,轮询与中断的区别将变得更加重要。 -Chapter 19 introduces interrupts, which replace the polling model with an event-driven one. Until then, polling is a reasonable pattern for the simulated device. +第 19 章引入中断,替换轮询循环以实现效率。 -### The Detach Path, Updated +### 更新后的 Detach 路径 -Every chapter in Part 3 added a few lines to the detach ordering. Chapter 16 Stage 2 adds two: drain the `reg_ticker_task` and free the register buffer. The full detach order at Stage 2: +第 3 部分的每章都给 detach 路径增加了新步骤。第 16 章增加寄存器缓冲区释放。更新后的顺序: -1. Refuse detach if `active_fhs > 0`. -2. Clear `is_attached` (atomically), broadcast cvs. -3. Drain all callouts (heartbeat, watchdog, tick_source). -4. Drain all tasks (selwake, bulk_writer, reset_delayed, recovery, reg_ticker). -5. `seldrain(&sc->rsel)`, `seldrain(&sc->wsel)`. -6. `taskqueue_free(sc->tq)`. -7. Destroy cdev. -8. Release sysctl context. -9. **Free `regs_buf`.** (New in Stage 2.) -10. Destroy cbuf, counters, cvs, sx locks, semaphore, mutex. +1. 如果 `active_fhs > 0`,拒绝 detach。 +2. 清除 `is_attached`(原子操作),广播 cv。 +3. 排空所有 callout(heartbeat、watchdog、tick_source)。 +4. 排空所有任务(selwake、bulk_writer、reset_delayed、recovery、reg_ticker)。 +5. `seldrain(&sc->rsel)`、`seldrain(&sc->wsel)`。 +6. `taskqueue_free(sc->tq)`。 +7. 销毁 cdev。 +8. 释放 sysctl 上下文。 +9. **释放 `regs_buf`。**(第 2 阶段新增。) +10. 销毁 cbuf、计数器、cv、sx 锁、信号量、互斥锁。 -The `regs_buf` free happens after the sysctl context is torn down, because a sysctl handler could in principle be running on another CPU during detach. After `sysctl_ctx_free`, no sysctl handler can reach the softc, and the free is safe. Real drivers follow the same discipline for their resource releases. +`regs_buf` 的释放在 sysctl 上下文拆除之后进行,因为在 detach 期间,sysctl 处理程序原则上可能在另一个 CPU 上运行。在 `sysctl_ctx_free` 之后,没有 sysctl 处理程序能到达 softc,释放是安全的。真实驱动程序对其资源释放遵循相同的规范。 -### Updating `LOCKING.md` (Now `HARDWARE.md` Too) +### 更新 `LOCKING.md`(现在也是 `HARDWARE.md`) -Part 3 established `LOCKING.md` as the driver's synchronisation map. Chapter 16 opens a sibling document: `HARDWARE.md`. It lives alongside `LOCKING.md` and documents the register interface, access patterns, and ownership rules for hardware-facing state. +第 3 部分建立了 `LOCKING.md` 作为驱动程序锁定规范的文档。第 16 章添加一个平行的 `HARDWARE.md` 来记录寄存器接口。 -A first cut: +第一版: + +第一版: ```text # myfirst Hardware Interface @@ -1594,20 +1596,20 @@ a lock. See Section 6 for the locking story. - Ticker task: MYFIRST_REG_WRITE(SCRATCH_A) ``` -The document is short now and will grow as later chapters add more registers and more access paths. The discipline of documenting the register interface alongside the code is the same as Part 3's discipline of documenting locks. +该文档现在很短,会在后续章节添加更多寄存器和更多访问路径时增长。将寄存器接口与代码一起记录的规范,与第 3 部分记录锁的规范相同。 -### Stage 2 Complete +### 第 2 阶段完成 -At the end of Section 5, the driver is at `0.9-mmio-stage2`. It has: +在第 5 节结束时,驱动程序处于 `0.9-mmio-stage2`。它拥有: -- A real `bus_space_*` access path over a simulated tag and handle. -- `DATA_IN` reflecting the last written byte, with `DATA_AV` tracking the ring buffer's state. -- `DATA_OUT` reflecting the last read byte. -- A task that autonomously increments a scratch register on a timer. -- Full sysctl visibility into every register. -- A `HARDWARE.md` document describing the interface. +- 一个通过模拟标签和句柄的真实 `bus_space_*` 访问路径。 +- `DATA_IN` 反映最后写入的字节,`DATA_AV` 跟踪环缓冲区的状态。 +- `DATA_OUT` 反映最后读取的字节。 +- 一个按计时器自主递增暂存寄存器的任务。 +- 每个寄存器的完整 sysctl 可见性。 +- 一个描述接口的 `HARDWARE.md` 文档。 -Build, load, test, observe, unload: +构建、加载、测试、观察、卸载: ```text # cd examples/part-04/ch16-accessing-hardware/stage2-bus-space @@ -1623,11 +1625,11 @@ Build, load, test, observe, unload: # kldunload myfirst ``` -The outputs should tell a consistent story about what the driver and the registers are doing. +输出应该讲述一个关于驱动程序和寄存器正在做什么的一致故事。 -### A Look at a Real Pattern: The `em` Attach Path +### 真实模式的一瞥:`em` 的 Attach 路径 -Now that Stage 2 mirrors a real driver's structure, a brief look at what Stage 2 would look like if the register block were a real PCI MMIO region, just to anchor the expectation. In `/usr/src/sys/dev/e1000/if_em.c`, inside `em_allocate_pci_resources`, you will find: +既然第 2 阶段已经镜像了真实驱动程序的结构,简短看一下如果寄存器块是真实的 PCI MMIO 区域,第 2 阶段会是什么样子,只是为了锚定预期。在 `/usr/src/sys/dev/e1000/if_em.c` 中,在 `em_allocate_pci_resources` 内部,你会发现: ```c sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); @@ -1640,39 +1642,39 @@ sc->osdep.mem_bus_space_handle = rman_get_bushandle(sc->memory); sc->hw.hw_addr = (uint8_t *)&sc->osdep.mem_bus_space_handle; ``` -The resource is allocated, the tag and handle are extracted into the softc's `osdep` structure, and an additional `hw_addr` pointer is set up for the hardware-abstraction-layer code that Intel shares between drivers. The rest of the driver uses macros (`E1000_READ_REG`, `E1000_WRITE_REG`) defined over `bus_space_*` to talk to the hardware. +资源被分配后,标签和句柄被提取到 softc 的 `osdep` 结构中,并设置了一个额外的 `hw_addr` 指针,供 Intel 在驱动程序之间共享的硬件抽象层代码使用。驱动程序的其余部分使用定义在 `bus_space_*` 之上的宏(`E1000_READ_REG`、`E1000_WRITE_REG`)与硬件对话。 -The shape is the same as our Stage 2. The difference is exactly one function call: `bus_alloc_resource_any` for a real driver, `malloc(9)` plus a handcrafted tag for ours. Everything above the allocation layer is identical. +形状与我们的第 2 阶段相同。区别正好是一个函数调用:真实驱动程序用 `bus_alloc_resource_any`,我们用 `malloc(9)` 加手工标签。分配层之上的所有东西都是相同的。 -Chapter 18 will swap our `malloc` for `bus_alloc_resource_any` and point the driver at a real PCI device. The driver's upper layers will not change. +第 18 章将把我们的 `malloc` 替换为 `bus_alloc_resource_any`,并将驱动程序指向真实的 PCI 设备。驱动程序的上层不会改变。 -### Wrapping Up Section 5 +### 总结第 5 节 -Stage 2 replaces the direct accessors of Stage 1 with real `bus_space(9)` calls operating on the simulated tag and handle. The driver's `write(2)` and `read(2)` paths now produce register-level side effects. A task updates a scratch register on a timer. The `HARDWARE.md` document describes the register interface. The driver's shape closely matches that of a real driver like `if_em`. +第 2 阶段用操作模拟标签和句柄的真实 `bus_space(9)` 调用替换了第 1 阶段的直接访问器。驱动程序的 `write(2)` 和 `read(2)` 路径现在产生寄存器级副作用。一个任务按计时器更新暂存寄存器。`HARDWARE.md` 文档描述了寄存器接口。驱动程序的形状与 `if_em` 等真实驱动程序紧密匹配。 -Section 6 introduces the safety discipline that real MMIO demands: memory barriers, locking around shared registers, and the reasons busy-wait loops are a mistake. Stage 3 of the driver adds that discipline. +第 6 节引入真实 MMIO 所要求的安全规范:内存屏障、共享寄存器周围的加锁,以及忙等循环是错误的原因。驱动程序的第 3 阶段添加了该规范。 -## Section 6: Safety and Synchronization with MMIO +## 第 6 节:MMIO 的安全与同步 -Stage 2 works, but it is unsafe in three specific ways that Section 6 names and fixes. The first is that register access is not atomic. The second is that register ordering is not enforced. The third is that there is no discipline around what context may access which registers. Each of these is a category of bug that can hurt a real driver; each is fixable with discipline the chapter has already taught in Part 3, applied to the new hardware-facing state. +第 2 阶段可以工作,但在三个方面不安全,第 6 节会命名并修复它们。第一,寄存器访问不是原子的。第二,寄存器排序没有被强制执行。第三,没有关于哪个上下文可以访问哪些寄存器的规范。这些中的每一个都是可能伤害真实驱动程序的 bug 类别;每一个都可以用第 3 部分已经教过的规范来修复,应用到新的硬件面向状态。 -This section walks through each problem, explains why it matters, and produces Stage 3 of the driver: a version that is correct under concurrent access, ordering-safe for platforms that need it, and clearly partitioned by context. +本节走查每个问题,解释为什么它很重要,并产生驱动程序的第 3 阶段:一个在并发访问下正确的版本。 -### Why a Register Access Can Be Unsafe Without a Lock +### 为什么寄存器访问在没有锁的情况下可能不安全 -Consider two user-space threads writing different bytes to `/dev/myfirst0` concurrently. In Stage 2, both call `myfirst_write`, which in turn calls `MYFIRST_REG_WRITE(sc, MYFIRST_REG_DATA_IN, last_byte)`. Without a lock, the two writes race: one finishes first, one finishes second, and `DATA_IN` ends up with whichever value was written last. That is not wrong, exactly; both bytes were really the last byte of their respective writes. But the driver has no way of telling which value in `DATA_IN` came from which writer. +考虑两个用户空间线程并发写入不同的字节到 `/dev/myfirst0`。 -More subtly, consider `myfirst_reg_update`, which does a read-modify-write sequence on a register. Two threads calling it on the same register in parallel can produce a classic lost-update. Thread A reads `CTRL = 0`. Thread B reads `CTRL = 0`. Thread A sets the `ENABLE` bit and writes `CTRL = 1`. Thread B sets the `RESET` bit and writes `CTRL = 2`. The result is `CTRL = 2`, with `ENABLE` lost. On any register where multiple contexts perform read-modify-write operations, this is a data-race bug that can cause real protocol failures. +更微妙的是,考虑 `myfirst_reg_update`,它对寄存器执行读-改-写序列。 -The solution is familiar: a lock. The only question is which lock. Chapter 11's `sc->mtx` protects the data path; it is the natural choice for register access that happens inside the data path. A separate mutex, `sc->reg_mtx`, can be introduced for register access that happens outside the data path (sysctl handlers, the ticker task). The two can be the same lock, or different locks, depending on the driver's access patterns. +解决方案很熟悉:一个锁。唯一的问题是用哪个锁。 -For Stage 3, we take the simpler path: use `sc->mtx` for every register access. This enforces the rule "no register access without the driver mutex" with a single primitive. The cost is that sysctl handlers and the ticker task must acquire the driver mutex briefly, which serialises them with the data path. For a driver this small, the cost is negligible. +对于第 3 阶段,我们采取更简单的路径:对所有寄存器访问使用 `sc->mtx`。 -### Adding the Lock +### 添加锁 -Modify `myfirst_reg_read` and `myfirst_reg_write` to assert that the driver lock is held, and modify their callers to acquire it. An assertion is cheaper than acquiring the lock inside the accessor, and it makes the locking rule visible at every call site. +修改访问器以断言驱动程序锁被持有。 ```c static __inline uint32_t @@ -1692,9 +1694,9 @@ myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, uint32_t value) } ``` -The `MYFIRST_ASSERT` macro from Chapter 11 asserts that `sc->mtx` is held in `MA_OWNED` mode. A debug kernel catches any caller that forgot to acquire the lock; a production kernel elides the check. +`MYFIRST_ASSERT` 宏是 `mtx_assert(&sc->mtx, MA_OWNED)` 的薄包装,在第 11 章引入。它在调试内核中确认锁被持有。 -Now every call site must acquire the lock. The sysctl handler becomes: +现在每个调用点都必须获取锁。sysctl 处理程序变为: ```c static int @@ -1719,9 +1721,9 @@ myfirst_sysctl_reg(SYSCTL_HANDLER_ARGS) } ``` -The lock is acquired before the register read, held briefly, released before the sysctl framework's `sysctl_handle_int`. The framework may sleep (it copies the value to user space), so the lock cannot be held across that call. +锁在寄存器读取之前获取,短暂持有,在 sysctl 框架的 `sysctl_handle_int` 之前释放。框架可能会睡眠(它将值复制到用户空间),所以锁不能跨该调用持有。 -Similarly, the writeable sysctl handler: +类似地,可写 sysctl 处理程序: ```c static int @@ -1762,11 +1764,11 @@ myfirst_sysctl_reg_write(SYSCTL_HANDLER_ARGS) } ``` -The handler acquires the lock twice: once to read the current value, once to apply the new value. Between them the lock is released and `sysctl_handle_int` runs. The pattern is slightly awkward but is standard in FreeBSD: you acquire a lock for a brief operation, release it for a sleepable call, reacquire for the next brief operation, and tolerate the fact that state may have changed in between. +处理程序两次获取锁:一次读取当前值,一次应用新值。在两次之间锁被释放,`sysctl_handle_int` 运行。这个模式略显笨拙但在 FreeBSD 中是标准的:你为一个简短操作获取锁,为可睡眠调用释放它,为下一个简短操作重新获取,并容忍状态在此期间可能已改变的事实。 -The `myfirst_ctrl_update` call now happens under the lock, so its printf still works but any future state changes it makes can rely on lock ownership. +`myfirst_ctrl_update` 调用现在在锁下发生,所以它的 printf 仍然可以工作,但它可能做的任何未来状态改变都可以依赖锁的所有权。 -The ticker task callback likewise acquires the lock: +ticker 任务回调同样获取锁: ```c static void @@ -1786,7 +1788,7 @@ myfirst_reg_ticker_cb(void *arg, int pending) } ``` -And the `myfirst_write` and `myfirst_read` paths, which already held `sc->mtx` around ring-buffer access, need to extend the hold across the register updates, or to release and reacquire briefly. The simplest change is to keep the register updates inside the existing locked region: +而 `myfirst_write` 和 `myfirst_read` 路径已经在环缓冲区访问周围持有 `sc->mtx`,需要将持有扩展到寄存器更新,或者简短释放再重新获取。最简单的改变是将寄存器更新保持在现有锁定区域内: ```c /* In myfirst_write, while still holding sc->mtx after the ring-buffer update: */ @@ -1796,20 +1798,20 @@ if (wrote_any) { } ``` -Because `myfirst_reg_update` now asserts the mutex is held, and it is, the call succeeds. The lock-hold time grows slightly, but only by a handful of `bus_space_write_4` calls, which compile to single `mov` instructions; the cost is negligible. +因为 `myfirst_reg_update` 现在断言互斥锁被持有,而且确实被持有,调用成功。锁持有时间略有增长,但只增加了少量 `bus_space_write_4` 调用,它们编译为单条 `mov` 指令;代价可以忽略不计。 -### Why Barriers Matter Even On x86 +### 为什么屏障即使在 x86 上也很重要 -With locking in place, the driver is correct under concurrency on x86. On weakly-ordered platforms (arm64, RISC-V, some older MIPS), the story is not quite finished. A sequence like: +有了加锁,驱动程序在 x86 上的并发下是正确的。在弱序平台(arm64、RISC-V、一些较旧的 MIPS)上,情况还不完全一样。像这样的序列: ```c MYFIRST_REG_WRITE(sc, MYFIRST_REG_DATA_IN, value); MYFIRST_REG_WRITE(sc, MYFIRST_REG_CTRL, CTRL_GO); ``` -implies that the `DATA_IN` write reaches the device before the `CTRL.GO` trigger. On x86, hardware preserves program order for stores, and the compiler's reordering is limited by the `volatile` qualifier in `bus_space_write_4`. On arm64, the CPU can reorder the two stores, and the device might see `CTRL.GO` before `DATA_IN` is ready, which breaks the protocol. +意味着 `DATA_IN` 写入在 `CTRL.GO` 触发之前到达设备。在 x86 上,硬件为存储保留程序顺序,编译器的重排序受 `bus_space_write_4` 中的 `volatile` 限定符限制。在 arm64 上,CPU 可以重排序两个存储,设备可能在 `DATA_IN` 准备好之前看到 `CTRL.GO`,这会破坏协议。 -The fix is a write barrier: +修复方法是写屏障: ```c MYFIRST_REG_WRITE(sc, MYFIRST_REG_DATA_IN, value); @@ -1818,11 +1820,11 @@ bus_space_barrier(sc->regs_tag, sc->regs_handle, 0, sc->regs_size, MYFIRST_REG_WRITE(sc, MYFIRST_REG_CTRL, CTRL_GO); ``` -On x86 this barrier is a compiler fence. On arm64 it is a DSB or DMB that forces the first store to complete before the second is issued. +在 x86 上这个屏障是一个编译器围栏。在 arm64 上它是一条 DSB 或 DMB,强制第一个存储在第二个发出之前完成。 -For Chapter 16 the protocol we are simulating does not actually require this ordering, because our "device" is kernel memory whose observers all take the same lock and do not reorder within a critical section. But the habit is worth developing. When the code eventually talks to a real device, the barriers will be there, and the driver will be portable across architectures. +对于第 16 章,我们模拟的协议实际上不需要这种排序,因为我们的"设备"是内核内存,其观察者都获取同一把锁,不会在临界区内重排序。但这个习惯值得培养。当代码最终与真实设备对话时,屏障会在那里,驱动程序将能跨架构可移植。 -As a teaching vehicle, introduce a helper that makes barrier-annotated writes easy: +作为教学工具,引入一个使带屏障注释的写入变得容易的辅助函数: ```c static __inline void @@ -1836,24 +1838,24 @@ myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, } ``` -Flags are `BUS_SPACE_BARRIER_READ`, `BUS_SPACE_BARRIER_WRITE`, or the OR of the two. A driver that reads status right after writing a command uses the combined flag. One that only wants subsequent writes to see this write's effect uses just `WRITE`. +标志为 `BUS_SPACE_BARRIER_READ`、`BUS_SPACE_BARRIER_WRITE` 或两者的 OR。在写入命令后立即读取状态的驱动程序使用组合标志。只希望后续写入看到当前写入效果的驱动程序仅使用 `WRITE`。 -The Stage 3 driver does not use `myfirst_reg_write_barrier` in many places; it is defined and used in a single demonstration path (inside the ticker, after the scratch increment, to illustrate the usage). Later chapters that deal with real protocols will use it more heavily. +第 3 阶段的驱动程序在很多地方不使用 `myfirst_reg_write_barrier`;它被定义并在单个演示路径中使用(在 ticker 中,在暂存递增之后,以说明用法)。后续处理真实协议的章节会更频繁地使用它。 -### Partitioning Register Access by Context +### 按上下文划分寄存器访问 -With locking uniform, the next question is: which contexts access which registers, and is that mix intentional? +有了统一的加锁,下一个问题是:哪些上下文访问哪些寄存器,这种混合是否有意为之? -A Stage 3 audit on the driver shows: +对驱动程序进行第 3 阶段审计显示: - Syscall context (write): accesses `DATA_IN`, `STATUS`. - Syscall context (read): accesses `DATA_OUT`, `STATUS`. - Sysctl context: accesses every register (read) and `CTRL`, `SCRATCH_A`, `SCRATCH_B`, etc. (write) through the writeable sysctl. - Task context (ticker): accesses `SCRATCH_A`. -Every access is lock-protected. Every access touches a register the driver has explicitly allocated for that purpose. The access discipline is simple: syscalls read and write the data registers and the data-available bit; sysctls are for inspection and one-off configuration; the ticker writes one specific register. A rule of "contexts do not overlap their register responsibilities" is easy to state and easy to hold. +每次访问都受锁保护。每次访问都接触驱动程序为该目的明确分配的寄存器。访问规范很简单:系统调用读写数据寄存器和数据可用位;sysctl 用于检查和一次性配置;ticker 写入一个特定寄存器。"上下文不重叠其寄存器职责"的规则易于陈述也易于坚持。 -This is the kind of thing `HARDWARE.md` exists to document. Update the document to include per-register ownership: +这就是 `HARDWARE.md` 存在要文档化的内容。更新文档以包含每寄存器所有权: ```text ## Per-Register Owners @@ -1870,11 +1872,11 @@ SCRATCH_A: ticker task; sysctl writer SCRATCH_B: sysctl writer only ``` -A future contributor can glance at this table and immediately see where a register write is expected. A future change that adds a new owner must update the table, which keeps the documentation honest. +未来的贡献者可以扫一眼这个表格,立即看到哪里预期有寄存器写入。添加新所有者的未来更改必须更新该表格,这使文档保持诚实。 -### Avoiding Busy-Wait Loops +### 避免忙等循环 -One style of bug that new driver authors fall into is the busy-wait loop for register state. The canonical example: +新驱动程序作者容易陷入的一种 bug 风格是忙等循环等待寄存器状态。典型的例子: ```c /* BAD: busy-waits forever if the device never becomes ready. */ @@ -1882,11 +1884,11 @@ while ((MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_READY) == 0) ; ``` -The loop spins reading the register until the `READY` bit becomes set. On real hardware, the time between "not ready" and "ready" may be microseconds. On an overloaded system, it may be longer. During the spin, the CPU is consumed by the loop; no other thread on that CPU can run; the driver's own other threads cannot even unlock the mutex the loop may be holding. +循环不断读取寄存器直到 `READY` 位被设置。在真实硬件上,从"未就绪"到"就绪"之间的时间可能是微秒级。在过载系统上,可能更长。在旋转期间,CPU 被循环消耗;该 CPU 上的其他线程无法运行;驱动程序自身的其他线程甚至无法解锁循环可能持有的互斥锁。 -Several better patterns exist. +有几种更好的模式。 -**Bounded spin with `DELAY(9)` for short waits.** If the expected wait is short (less than a few hundred microseconds, typically), use a loop with a bounded iteration count and a `DELAY` between iterations. `DELAY(usec)` busy-waits for at least `usec` microseconds, allowing the CPU to serve interrupts in the meantime. +**使用 `DELAY(9)` 的有界旋转用于短等待。** 如果预期等待很短(通常少于几百微秒),使用有界迭代计数的循环并在迭代之间加 `DELAY`。`DELAY(usec)` 忙等至少 `usec` 微秒,允许 CPU 在此期间处理中断。 ```c for (i = 0; i < 100; i++) { @@ -1900,9 +1902,9 @@ if ((MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_READY) == 0) { } ``` -The loop runs at most 100 times, waiting 10 microseconds between reads, for a total bound of 1 millisecond. On a successful completion the loop exits early. On timeout the driver gives up and returns an error. +循环最多运行 100 次,在读取之间等待 10 微秒,总上限为 1 毫秒。成功完成时循环提前退出。超时时驱动程序放弃并返回错误。 -**Sleep-based wait with `msleep`.** For longer expected waits (milliseconds to seconds), do not busy-wait at all. Sleep the thread until a wakeup arrives, or until a timeout fires. The example below is hypothetical (our simulated device never clears `READY` in Chapter 16), but it shows the shape you will reach for when real hardware starts changing status bits: +**使用 `msleep` 的基于睡眠的等待。** 对于更长的预期等待(毫秒到秒),不要忙等。让线程睡眠直到唤醒到来,或直到超时触发。下面的示例是假设性的(我们第 16 章的模拟设备从不清除 `READY`),但它展示了当真实硬件开始改变状态位时你会使用的模式形状: ```c /* Hypothetical; assumes sc->status_wait is a dummy address the driver @@ -1919,9 +1921,9 @@ while ((MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_READY) == 0) { } ``` -The thread sleeps on `&sc->status_wait`, with the driver mutex as the interlock, for up to 100ms. A wakeup from another context (typically an interrupt handler or a task that observed the register change) breaks the sleep. On arm64, where register polling would be expensive and imprecise, this pattern is strongly preferred. Chapter 17 makes this pattern concrete: a callout flips `READY` on a timer, and a syscall path sleeps on the matching channel until the callout wakes it up. +线程在 `&sc->status_wait` 上睡眠,以驱动程序互斥锁为互锁,最长 100ms。来自另一个上下文的唤醒(通常是观察到寄存器变化的中断处理程序或任务)打破睡眠。在 arm64 上,寄存器轮询是昂贵且不精确的,这种模式强烈推荐。第 17 章使这个模式具体化:一个 callout 按计时器翻转 `READY`,一个系统调用路径在匹配的通道上睡眠,直到 callout 唤醒它。 -**Event-driven with `cv_wait`.** Same as above, but using a condition variable, which is more natural in Part 3's idiom: +**使用 `cv_wait` 的事件驱动。** 与上面相同,但使用条件变量,在第 3 部分的惯用法中更自然: ```c MYFIRST_LOCK(sc); @@ -1931,21 +1933,21 @@ while ((MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_READY) == 0) { MYFIRST_UNLOCK(sc); ``` -With a matching `cv_signal` in whichever context sets the bit. +在设置位的任何上下文中有匹配的 `cv_signal`。 -Chapter 16's simulated device does not need any of these patterns yet, because the `READY` bit is set at attach and never cleared. But the patterns are named here because Section 6 is the right place to introduce them, and Chapter 17 will use them when status bits start changing dynamically. +第 16 章的模拟设备还不需要这些模式中的任何一个,因为 `READY` 位在 attach 时设置并且从不清除。但模式在这里命名是因为第 6 节是引入它们的正确位置,第 17 章将在状态位开始动态变化时使用它们。 -### Interrupts and MMIO: A Forward Pointer +### 中断与 MMIO:一个前瞻提示 -A brief note on a topic Chapter 19 owns. When a real driver has an interrupt handler that runs in filter or ithread context, register access from the handler has additional constraints. Filter handlers run in an interrupt context with very limited primitives available; they typically acknowledge the interrupt by writing a register, record the event somehow, and defer the real work to a task. The acknowledgement write is the kind of thing `bus_space_write_*` exists for, and it runs under specific locking rules that differ from the ordinary driver mutex. +关于第 19 章主题的简短说明。当真实驱动程序有在过滤器或 ithread 上下文中运行的中断处理程序时,来自处理程序的寄存器访问有额外的约束。过滤器处理程序在只有非常有限原语可用的中断上下文中运行;它们通常确认中断并可能读取状态寄存器。中断线程运行在更完整的上下文中,可以做更多工作。第 16 章的模拟不需要担心这些,因为没有中断。第 19 章详细涵盖中断处理程序约束。 -Chapter 16's driver has no interrupt handler, so this concern does not yet apply. Chapter 19 introduces the handler and the lock-type changes it forces. For now, treat "interrupt context accessing registers" as a topic you know exists and will learn about later; the register-access mechanism (`bus_space_*`) is the same, but the locking around it changes. +第 16 章的驱动程序没有中断处理程序,所以这个顾虑暂时不适用。第 19 章引入处理程序及它所迫使其改变的锁类型。目前,把"中断上下文访问寄存器"当作一个你知道存在并将稍后学习的主题;寄存器访问机制(`bus_space_*`)是相同的,但周围的加锁会改变。 -### Stage 3 Complete +### 第 3 阶段完成 -With locking added, barriers introduced, context ownership documented, and busy-wait patterns discouraged, the driver is at `0.9-mmio-stage3`. The shape of the driver is still that of Stage 2, but every register access is now lock-protected, every context's access pattern is documented, and the driver is prepared to handle more sophisticated hardware protocols in later chapters. +添加了加锁、引入了屏障、记录了上下文所有权并劝阻了忙等模式后,驱动程序处于 `0.9-mmio-stage3`。驱动程序的形状与第 2 阶段仍然相同,但每次寄存器访问现在都受锁保护,每个上下文的访问模式都有文档,驱动程序已准备好在后续章节中处理更复杂的硬件协议。 -Build, test, and stress: +构建、测试和压力测试: ```text # cd examples/part-04/ch16-accessing-hardware/stage3-synchronized @@ -1954,39 +1956,39 @@ Build, test, and stress: # examples/part-04/ch16-accessing-hardware/labs/reg_stress.sh ``` -The stress script spawns several concurrent writers, readers, sysctl readers, and ticker-toggle operations, and checks that the final register state is consistent. Under WITNESS, any locking violation produces an immediate warning; under INVARIANTS, any out-of-bounds access produces a panic. If the script completes cleanly, the driver's register discipline is sound. +压力测试脚本生成多个并发写入者、读取者、sysctl 读取者和 ticker 切换操作,并检查最终寄存器状态是否一致。在 WITNESS 下,任何加锁违规都会产生即时警告;在 INVARIANTS 下,任何越界访问都会产生 panic。如果脚本干净完成,驱动程序的寄存器规范是健全的。 -### Wrapping Up Section 6 +### 总结第 6 节 -MMIO safety rests on three disciplines: locking (every register access happens under the appropriate lock), ordering (barriers where the protocol requires them, even if the platform is x86), and context partitioning (each register has a named owner and an intended access path). The driver's `HARDWARE.md` captures the last two; the mutex assertions in the accessors enforce the first. +MMIO 安全建立在三个规范之上:加锁(每次寄存器访问在适当的锁下发生)、排序(协议要求屏障的地方使用屏障,即使平台是 x86)和上下文分区(每个寄存器有命名所有者和预期访问路径)。驱动程序的 `HARDWARE.md` 捕获后两者;访问器中的互斥锁断言强制执行前者。 -Section 7 takes the next step: making the register access observable for debugging. Logs, sysctls, DTrace probes, and the small observability layer that catches bugs before they become crashes. +第 7 节迈出下一步:使寄存器访问可观察以便调试。日志、sysctl、DTrace 探针,以及捕获 bug 使其不致变成崩溃的小型可观测性层。 -## Section 7: Debugging and Tracing Hardware Access +## 第 7 节:调试和跟踪硬件访问 -A register access is, by design, invisible. It compiles to a CPU instruction that reads or writes a handful of bytes. There is no stack frame, no call log, no return value you can `printf` without adding code. When a driver works, invisibility is a virtue. When it does not, invisibility is the problem. +寄存器访问在设计上就是不可见的。它编译为读取或写入少量字节的 CPU 指令。没有栈帧、没有调用日志、没有你可以不经添加代码就 `printf` 的返回值。当驱动程序正常工作时,不可见是一种优点。当它不正常工作时,不可见就是问题所在。 -Section 7 covers the tools and idioms that make register access visible enough to debug without being so noisy that the driver becomes unreadable. The goal is a small observability layer: enough instrumentation to catch bugs early, placed where a beginner can switch it on and off, and integrated with the logging the rest of the driver already does. +第 7 节覆盖了使寄存器访问可见到足以调试但又不会太嘈杂以至于驱动程序变得不可读的工具和惯用法。目标是一个小型可观测性层:足够的仪器来尽早捕获 bug,放置在初学者可以开关的地方,并与驱动程序其余部分已经使用的日志集成。 -### What You Want to Observe +### 你想观察什么 -Three things are worth seeing when a driver is misbehaving. +当驱动程序行为异常时,有三件事值得看。 -**The value at a specific register, right now.** The sysctl handlers from Stage 2 already give you this. A `sysctl dev.myfirst.0.reg_ctrl` returns the current value at any moment, and nothing else in the driver's behaviour changes because of the read. +**特定寄存器的当前值。** 第 2 阶段的 sysctl 处理程序已经提供了这个。`sysctl dev.myfirst.0.reg_ctrl` 在任何时刻返回当前值,并且驱动程序的行为不会因为读取而改变。 -**The sequence of register accesses the driver made recently.** When a bug involves register ordering or incorrect bit manipulation, knowing "the driver wrote 0x1 then 0x2 then 0x4 in that order" is exactly what you need. The raw sequence cannot be reconstructed from register contents alone. +**驱动程序最近进行的寄存器访问序列。** 当 bug 涉及寄存器排序或错误的位操作时,知道"驱动程序依次写了 0x1、0x2、0x4"正是你需要的。原始序列无法仅从寄存器内容重构。 -**The stack and context for a specific register access.** When a write happens from an unexpected code path, you want to know which function did it, which thread was running, and what was on the stack. DTrace is good at this. +**特定寄存器访问的栈和上下文。** 当写入来自意外的代码路径时,你想知道是哪个函数做的、哪个线程在运行、栈上有什么。DTrace 擅长这个。 -The rest of this section walks through each kind of observation and shows what to add to the driver to support it. +本节其余部分走遍每种观察并展示向驱动程序添加什么来支持它。 -### A Simple Access Log +### 一个简单的访问日志 -The simplest observability tool is a log of the last N register accesses, kept in a ring buffer inside the softc. Every register read and write records an entry; the sysctl exposes the ring. +最简单的可观测性工具是最近 N 次寄存器访问的日志,保存在 softc 内的环缓冲区中。每次寄存器读写记录一个条目;sysctl 暴露该环。 -Define the log entry: +定义日志条目: ```c #define MYFIRST_ACCESS_LOG_SIZE 64 @@ -2002,9 +2004,9 @@ struct myfirst_access_log_entry { }; ``` -Each entry is 24 bytes, holding the time (nanoseconds since boot), the value, the offset, whether it was a read or a write, the access width, and a tag identifying the caller's context (syscall, task, sysctl). Padding rounds to 24; a log of 64 entries is 1.5 KiB, which is trivially small. +每个条目 24 字节,保存时间(自启动以来的纳秒)、值、偏移量、是读还是写、访问宽度和标识调用者上下文的标签(系统调用、任务、sysctl)。填充到 24 字节;64 个条目的日志是 1.5 KiB,微不足道。 -Add the ring to the softc: +向 softc 添加环: ```c struct myfirst_access_log_entry access_log[MYFIRST_ACCESS_LOG_SIZE]; @@ -2012,7 +2014,7 @@ unsigned int access_log_head; /* index of next write */ bool access_log_enabled; ``` -Record an entry in the accessors. Stage 3's `myfirst_reg_write` becomes: +在访问器中记录条目。第 3 阶段的 `myfirst_reg_write` 变为: ```c static __inline void @@ -2034,11 +2036,11 @@ myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, uint32_t value) } ``` -(`nanouptime_ns()` is a small helper that wraps `nanouptime()` and returns a `uint64_t`. `myfirst_current_context_tag()` returns a small code like `'S'` for syscall, `'T'` for task, `'C'` for sysctl; its implementation is a few-line switch on the current thread's identity.) +(`nanouptime_ns()` 是一个包装 `nanouptime()` 并返回 `uint64_t` 的小辅助函数。`myfirst_current_context_tag()` 返回一个小代码,如 `'S'` 表示系统调用、`'T'` 表示任务、`'C'` 表示 sysctl;其实现是基于当前线程身份的几行 switch。) -The read accessor records the read (value is the value read). Access recording happens under the driver mutex (Stage 3 requires the mutex for every register access), so the ring itself needs no additional locking. +读取访问器记录读取(值是读取到的值)。访问记录在驱动程序互斥锁下发生(第 3 阶段要求每次寄存器访问都有互斥锁),所以环本身不需要额外的加锁。 -Enable with a sysctl: +通过 sysctl 启用: ```c SYSCTL_ADD_BOOL(&sc->sysctl_ctx, @@ -2047,7 +2049,7 @@ SYSCTL_ADD_BOOL(&sc->sysctl_ctx, "Record every register access in a ring buffer"); ``` -Expose the log through a special sysctl handler that dumps the ring: +通过一个特殊的 sysctl 处理程序暴露日志,该处理程序转储环: ```c static int @@ -2082,7 +2084,7 @@ myfirst_sysctl_access_log(SYSCTL_HANDLER_ARGS) } ``` -The handler walks the ring from the oldest to the newest entry, skipping empty slots, and formats each as a line. The output looks like: +处理程序从最旧到最新遍历环,跳过空槽,将每条格式化为一行。输出看起来像: ```text 123456789 ns W4 off=0x00 val=0x00000001 ctx=C @@ -2091,15 +2093,15 @@ The handler walks the ring from the oldest to the newest entry, skipping empty s 124001567 ns W4 off=0x04 val=0x00000009 ctx=S ``` -Four entries: a writeable-sysctl write to `CTRL`, then its immediate readback (both `ctx=C`), then a syscall write that set `DATA_IN` to `0x41` ('A') and updated `STATUS` to `0x9` (READY | DATA_AV). The context tag makes the source obvious. +四条记录:一次可写 sysctl 对 `CTRL` 的写入,然后是它的立即回读(都是 `ctx=C`),然后是一次系统调用写入将 `DATA_IN` 设为 `0x41`('A')并将 `STATUS` 更新为 `0x9`(READY | DATA_AV)。上下文标签使来源一目了然。 -For debugging, this log is priceless. You see exactly what the driver did, in order, with timestamps. +对于调试来说,这个日志是无价的。你可以准确看到驱动程序做了什么,按顺序,带时间戳。 -### Kernel Printf: A Controlled Flood +### 内核 Printf:受控的洪水 -Sometimes the log is not enough and you want a printed message per register access, perhaps during a specific failing test. The driver should support a knob for that. +有时日志不够,你想为每次寄存器访问打印一条消息,可能是在特定的失败测试期间。驱动程序应该为此提供一个旋钮。 -Add a debug-level sysctl (if one does not already exist from Chapter 12's `debug_level`) and use it in the accessors: +添加一个 debug-level sysctl(如果第 12 章的 `debug_level` 还没有的话)并在访问器中使用它: ```c #define MYFIRST_DBG_REGS 0x10u @@ -2120,15 +2122,15 @@ myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, uint32_t value) } ``` -When `debug_level` has the `MYFIRST_DBG_REGS` bit set, every register write is printed to the console. Setting it during a test and clearing it immediately afterwards gives a focused log without flooding the system for the duration of the driver's life. +当 `debug_level` 设置了 `MYFIRST_DBG_REGS` 位时,每次寄存器写入都会打印到控制台。在测试期间设置它并在之后立即清除,可以获得聚焦的日志,不会在驱动程序生命期内淹没系统。 -The debug-level bitfield is a common FreeBSD pattern. Many real drivers use a sysctl of `debug` or `verbose` with bits for different subsystems: `DBG_PROBE`, `DBG_ATTACH`, `DBG_INTR`, `DBG_REGS`, and so on. The user enables only the subset they need. +debug-level 位字段是一个常见的 FreeBSD 模式。许多真实驱动程序使用 `debug` 或 `verbose` sysctl,其位对应不同子系统:`DBG_PROBE`、`DBG_ATTACH`、`DBG_INTR`、`DBG_REGS` 等等。用户只启用他们需要的子集。 -### DTrace Probes +### DTrace 探针 -DTrace is the right tool when you want to observe register access patterns without modifying the driver. FreeBSD's `fbt` (function boundary tracing) provider automatically instruments every non-inlined function in the kernel. If `myfirst_reg_read` and `myfirst_reg_write` are compiled as out-of-line functions (not inlined), DTrace can hook them. +当你想在不修改驱动程序的情况下观察寄存器访问模式时,DTrace 是正确的工具。FreeBSD 的 `fbt`(函数边界跟踪)提供程序自动为内核中每个非内联函数插入仪器。如果 `myfirst_reg_read` 和 `myfirst_reg_write` 被编译为非内联函数(而非内联的),DTrace 可以钩住它们。 -By default, `static __inline` functions are candidates for inlining, and inlined functions do not have fbt probes. To make the accessors DTrace-visible in debug builds, split the declarations: +默认情况下,`static __inline` 函数是内联的候选者,内联函数没有 fbt 探针。为了在调试构建中使访问器对 DTrace 可见,拆分声明: ```c #ifdef MYFIRST_DEBUG_REG_TRACE @@ -2143,21 +2145,21 @@ static __inline void myfirst_reg_write(struct myfirst_softc *sc, #endif ``` -With `MYFIRST_DEBUG_REG_TRACE` set at compile time, the accessors are regular functions with function-boundary probes. DTrace can then show every call: +设置了 `MYFIRST_DEBUG_REG_TRACE` 后在编译时,访问器变为带有函数边界探针的常规函数。DTrace 然后可以显示每次调用: ```text # dtrace -n 'fbt::myfirst_reg_write:entry { printf("off=%#x val=%#x", arg1, arg2); }' ``` -The output lists every register write with its offset and value, live, across the whole system. DTrace can aggregate, count, filter by stack, and join with process information in ways a hand-rolled log cannot match. +输出列出每次寄存器写入及其偏移量和值,实时的,覆盖整个系统。DTrace 可以以手工日志无法匹配的方式聚合、计数、按栈过滤,并与进程信息关联。 -For a release build, leave `MYFIRST_DEBUG_REG_TRACE` unset; the accessors inline and pay no runtime cost. For a debugging build, set the macro and get full visibility. +对于发布构建,保持 `MYFIRST_DEBUG_REG_TRACE` 未设置;访问器内联展开且不付出运行时代价。对于调试构建,设置该宏获得完全可见性。 -### Specialised DTrace Probes: `sdt(9)` +### 专用 DTrace 探针:`sdt(9)` -A more targeted alternative to fbt probes is to register Statically Defined Tracepoints (SDT) at specific points in the driver. FreeBSD's `sdt(9)` API lets you declare probes that DTrace can hook by name, without the overhead of a full function-boundary trace. +fbt 探针的一个更有针对性的替代方案是在驱动程序的特定点注册静态定义跟踪点(SDT)。FreeBSD 的 `sdt(9)` API 让你声明 DTrace 可以按名称钩住的探针,无需完整函数边界跟踪的开销。 -A probe for every register write: +为每次寄存器写入定义一个探针: ```c #include @@ -2169,27 +2171,27 @@ SDT_PROBE_DEFINE2(myfirst, , , reg_read, "struct myfirst_softc *", "bus_size_t"); ``` -And in the accessor: +在访问器中: ```c SDT_PROBE3(myfirst, , , reg_write, sc, offset, value); ``` -DTrace picks up the probe by name: +DTrace 按名称获取探针: ```text # dtrace -n 'sdt::myfirst:::reg_write { printf("off=%#x val=%#x", arg1, arg2); }' ``` -The probe is visible in DTrace regardless of inlining, because the kernel registers it statically. When DTrace is not running the probe, it is a no-op on modern x86 (a single NOP instruction in the inlined expansion). +无论是否内联,探针在 DTrace 中都可见,因为内核静态注册了它。当 DTrace 没有运行该探针时,在现代 x86 上它是空操作(内联展开中的单条 NOP 指令)。 -SDT probes are appropriate for production code. They are permanent, named, documented parts of the driver interface. A driver's users might rely on specific SDT probe names for their own monitoring tools; removing them breaks those tools. +SDT 探针适合生产代码。它们是驱动程序接口的永久、命名、有文档的部分。驱动程序的用户可能依赖特定的 SDT 探针名称来构建他们自己的监控工具;移除它们会破坏这些工具。 -Chapter 16 introduces SDT lightly. Later chapters (especially Chapter 23 on debugging and tracing) dig in. +第 16 章简要介绍 SDT。后续章节(特别是关于调试和跟踪的第 23 章)将深入探讨。 -### The Heartbeat Log From Stage 1 Onwards +### 从第 1 阶段开始的心跳日志 -One piece of instrumentation the driver already has is Chapter 13's heartbeat callout. With Chapter 16's register state added, the heartbeat becomes more informative if it prints a register snapshot: +驱动程序已经拥有的一块仪器是第 13 章的心跳 callout。加上第 16 章的寄存器状态后,如果心跳打印一个寄存器快照,它就变得更信息丰富: ```c static void @@ -2221,24 +2223,24 @@ myfirst_heartbeat_cb(void *arg) } ``` -With the heartbeat bit set and a 1-second interval, the driver logs its register state every second. During a failing test, the heartbeat output often shows exactly when the state went off the rails. +设置了心跳位并以 1 秒间隔运行时,驱动程序每秒记录其寄存器状态。在失败的测试期间,心跳输出通常能准确显示状态何时出了问题。 -### Using `kgdb` on a Core Dump +### 使用 `kgdb` 分析核心转储 -When a driver panics, the kernel produces a core dump. `kgdb` can read the dump and inspect the softc. With the register block inside the softc, a single command can print the current register values: +当驱动程序 panic 时,内核产生核心转储。`kgdb` 可以读取转储并检查 softc。寄存器块在 softc 内部,一条命令就可以打印当前寄存器值: ```text (kgdb) print *(struct myfirst_softc *)0xfffff8000a123400 (kgdb) x/16xw ((struct myfirst_softc *)0xfffff8000a123400)->regs_buf ``` -The `x/16xw` command dumps 16 words in hex at the register buffer's address. The output is literally the 64 bytes of register state at the moment of panic. A developer staring at those bytes can often spot the wrong value that led to the panic. +`x/16xw` 命令以十六进制转储寄存器缓冲区地址处的 16 个字。输出就是 panic 时刻 64 字节寄存器状态的字面值。盯着这些字节的开发者通常能发现导致 panic 的错误值。 -The reason this works is the simulation: `regs_buf` is kernel memory, visible to kgdb. A real device's registers would not be visible in a core dump, because the core dump captures RAM only, not device state. For simulated devices and DMA descriptors, a core dump is a gold mine. +这之所以有效是因为模拟:`regs_buf` 是内核内存,对 kgdb 可见。真实设备的寄存器在核心转储中不可见,因为核心转储只捕获 RAM,不捕获设备状态。对于模拟设备和 DMA 描述符,核心转储是一座金矿。 -### DDB Extensions +### DDB 扩展 -For live debugging without a panic, `ddb` can be extended with driver-specific commands. The `DB_COMMAND` macro registers a new command that ddb recognises at the prompt: +对于没有 panic 的实时调试,`ddb` 可以用驱动程序特定的命令扩展。`DB_COMMAND` 宏注册一个 ddb 在提示符下识别的新命令: ```c #include @@ -2260,7 +2262,7 @@ DB_COMMAND(myfirst_regs, myfirst_ddb_regs) } ``` -At the `db>` prompt during a break: +在断点处的 `db>` 提示符下: ```text db> myfirst_regs @@ -2270,47 +2272,47 @@ DATA_IN 0x0000006f ... ``` -ddb commands are a niche tool. Chapter 16 introduces them to show that they exist. Later chapters (especially Chapter 23) use them more. For now, the access log and DTrace cover most day-to-day debugging. +ddb 命令是一个小众工具。第 16 章引入它们以展示它们的存在。后续章节(特别是第 23 章)会更多使用它们。目前,访问日志和 DTrace 覆盖了大部分日常调试。 -### What to Do When a Register Read Returns Garbage +### 当寄存器读取返回垃圾数据时该怎么办 -A short field guide to the most common mistakes that produce a "garbage" register value, with the diagnostic to try for each. +一份关于产生"垃圾"寄存器值的最常见错误的简短指南,附带每种情况的诊断方法。 -**Wrong offset.** The offset in the code does not match the offset in the datasheet. Diagnostic: cross-check the offset against the datasheet, and audit the header for transcription errors. +**错误偏移量。** 代码中的偏移量与数据手册中的偏移量不匹配。诊断:将偏移量与数据手册交叉核对,审计头文件中的转录错误。 -**Wrong width.** The code reads 32 bits of a 16-bit register, or reads 8 bits of a 32-bit register. Diagnostic: verify the width in the datasheet, and adjust the call. +**错误宽度。** 代码读取了 16 位寄存器的 32 位,或读取了 32 位寄存器的 8 位。诊断:验证数据手册中的宽度,调整调用。 -**Missing virtual mapping.** The resource was allocated without `RF_ACTIVE`, or the driver is reading from a saved pointer that points to freed memory. Diagnostic: confirm `bus_alloc_resource_any` was called with `RF_ACTIVE`; assert `sc->regs_buf != NULL` before reading in the simulation path. +**缺少虚拟映射。** 资源在没有 `RF_ACTIVE` 的情况下分配,或驱动程序从指向已释放内存的保存指针读取。诊断:确认 `bus_alloc_resource_any` 是用 `RF_ACTIVE` 调用的;在模拟路径中读取前断言 `sc->regs_buf != NULL`。 -**Race with another writer.** Another context wrote a different value between the read and the expected observation. Diagnostic: enable the access log, reproduce the issue, inspect the log. +**与另一个写入者的竞争。** 另一个上下文在读取和预期观察之间写入了不同的值。诊断:启用访问日志,重现问题,检查日志。 -**Read-to-clear side effect the code did not expect.** The previous read cleared the bits you now expect to see. Diagnostic: check the datasheet for read side effects; consider whether the reading code should cache the value. +**代码未预期的读即清除副作用。** 前一次读取清除了你现在期望看到的位。诊断:检查数据手册的读副作用;考虑读取代码是否应该缓存该值。 -**Cache attribute mismatch.** On platforms where it matters, the virtual mapping was set up with wrong cache attributes. Diagnostic: not usually a problem on x86 with `bus_alloc_resource_any`; on other platforms, check `pmap_mapdev_attr` and the bus provider. Rare in practice if you are using the standard bus allocation path. +**缓存属性不匹配。** 在缓存属性重要的平台上,虚拟映射使用了错误的缓存属性设置。诊断:在使用 `bus_alloc_resource_any` 的 x86 上通常不是问题;在其他平台上,检查 `pmap_mapdev_attr` 和总线提供者。如果使用标准总线分配路径,这在实践中很少见。 -**Endianness mismatch.** On a big-endian device accessed from a little-endian CPU without the right tag or stream accessor, the bytes come back in the wrong order. Diagnostic: compare the value byte-swapped; if it now makes sense, you need the `_stream_` accessors or a swap-aware tag. +**字节序不匹配。** 在没有正确标签或流式访问器的情况下,从小端 CPU 访问大端设备,字节以错误顺序返回。诊断:比较字节交换后的值;如果现在有意义,你需要 `_stream_` 访问器或交换感知的标签。 -Each diagnosis points to a different fix. Keeping them in mind saves hours. +每种诊断指向不同的修复方法。把它们记在心可以节省数小时。 -### What to Do When a Register Write Has No Effect +### 当寄存器写入没有效果时该怎么办 -Sister field guide for writes. +写入的对应指南。 -**The register is read-only or write-once.** The datasheet defines the register as readable only, or writable only until the first successful write. Diagnostic: check the datasheet's direction column. +**寄存器是只读或一次可写的。** 数据手册将寄存器定义为仅可读,或仅在第一次成功写入前可写。诊断:检查数据手册的方向列。 -**The write was masked out.** The register has bits that are writable only under specific conditions (device disabled, chip in test mode, a specific field set). Diagnostic: enable debug_level printing; confirm the write happened; then check the device's state. +**写入被屏蔽。** 寄存器有些位仅在特定条件下可写(设备禁用、芯片处于测试模式、设置了特定字段)。诊断:启用 debug_level 打印;确认写入发生了;然后检查设备的状态。 -**The write was reordered.** A barrier-needed sequence was issued without barriers, and the device saw the writes in a different order than the code intended. Diagnostic: add explicit `bus_space_barrier` calls and retest. +**写入被重排序。** 需要屏障的序列在没有屏障的情况下发出,设备以与代码意图不同的顺序看到写入。诊断:添加显式 `bus_space_barrier` 调用并重新测试。 -**The write was lost to a concurrent read-modify-write.** Another context clobbered the new value. Diagnostic: access log; locking audit. +**写入因并发读-改-写而丢失。** 另一个上下文覆盖了新值。诊断:访问日志;加锁审计。 -**The write went to the wrong offset.** A transcription error or an arithmetic mistake aimed the write at a different register. Diagnostic: access log; comparison with the datasheet. +**写入到了错误的偏移量。** 转录错误或算术错误将写入对准了不同的寄存器。诊断:访问日志;与数据手册比较。 -The overlap with the read diagnostic is high: most issues boil down to "the code is not doing what you think it is", and the access log is the most direct way to see what the code is doing. +与读取诊断的重叠很高:大多数问题归结为"代码没有做你以为它在做的事",而访问日志是看到代码实际在做什么的最直接方式。 -### A Lab: The Access Log Does Its Job +### 实验:访问日志发挥作用 -A small exercise that shows the access log paying off. Enable it, exercise the driver, dump the log. +一个展示访问日志价值的小练习。启用它,运行驱动程序,转储日志。 ```text # sysctl dev.myfirst.0.access_log_enabled=1 @@ -2322,29 +2324,29 @@ A small exercise that shows the access log paying off. Enable it, exercise the d # sysctl dev.myfirst.0.access_log ``` -The last sysctl emits several dozen lines: the ticker's `SCRATCH_A` increments, the write's `DATA_IN` update and `STATUS` ORing, the read's `DATA_OUT` update and `STATUS` AND-ing, and every sysctl-driven read of a register along the way. The log reads like a transcript of the driver's conversation with itself. +最后一个 sysctl 发出几十行:ticker 的 `SCRATCH_A` 递增、写入的 `DATA_IN` 更新和 `STATUS` 或操作、读取的 `DATA_OUT` 更新和 `STATUS` 与操作,以及沿途中每个 sysctl 驱动的寄存器读取。日志读起来就像驱动程序与自己对话的记录。 -A beginner who sees this transcript for the first time usually has a moment of recognition: "oh, *that* is what the driver is doing under the covers". The moment is the whole point of the exercise. +初学者第一次看到这个记录时通常会有一个顿悟时刻:"哦,*原来*驱动程序在底层是这样做的"。这个时刻就是这个练习的全部意义。 -### Wrapping Up Section 7 +### 总结第 7 节 -The register access path is invisible by default. A small observability layer makes it visible: a ring buffer of recent accesses, a debug bitfield that controls per-access printf, DTrace probes through fbt or sdt, an enhanced heartbeat that logs register snapshots, and ddb or kgdb access to the softc for post-mortem inspection. Each tool fits a different use case, and together they cover almost every register-level bug a driver can have. +寄存器访问路径默认是不可见的。一个小型可观测性层使其可见:最近访问的环缓冲区、控制每次访问 printf 的调试位字段、通过 fbt 或 sdt 的 DTrace 探针、记录寄存器快照的增强心跳,以及用于事后检查 softc 的 ddb 或 kgdb 访问。每种工具适合不同的用例,它们一起覆盖了驱动程序可能拥有的几乎所有寄存器级 bug。 -Section 8 consolidates everything Chapter 16 has added into a refactored, documented, versioned driver. The final stage. +第 8 节将第 16 章添加的所有内容整合到一个重构的、有文档的、版本化的驱动程序中。最终阶段。 -## Section 8: Refactoring and Versioning Your MMIO-Ready Driver +## 第 8 节:重构和版本化你的 MMIO 就绪驱动程序 -Stage 3 produced a correct driver. Section 8 produces a maintainable one. The changes Stage 4 makes are organisational: split the hardware-access code out of `myfirst.c` into its own file, wrap the remaining register accesses in macros that mirror the `CSR_*` idiom real drivers use, update `HARDWARE.md` to its final form, bump the version to `0.9-mmio`, and run the full regression pass. +第 3 阶段产生了正确的驱动程序。第 8 节产生可维护的驱动程序。第 4 阶段所做的更改是组织性的:将硬件访问代码从 `myfirst.c` 拆分到自己的文件中,将剩余的寄存器访问包装在镜像真实驱动程序使用的 `CSR_*` 惯用法的宏中,将 `HARDWARE.md` 更新到最终形式,将版本提升到 `0.9-mmio`,并运行完整的回归测试。 -A driver that works is valuable. A driver that works *and* reads cleanly to the next person who opens it is far more valuable. Section 8 is about that second step. +一个能工作的驱动程序是有价值的。一个能工作*并且*下一个打开它的人能轻松阅读的驱动程序则更有价值得多。第 8 节就是关于这第二步的。 -### The File Split +### 文件拆分 -Through Chapter 15, the `myfirst` driver lived in one C file plus a header. Chapter 16 adds about 200 to 300 lines of hardware-access code, which is enough that a reader opening `myfirst.c` is now greeted by a mix of "driver business logic" and "hardware register mechanics" that compete for attention. +到第 15 章为止,`myfirst` 驱动程序存在于一个 C 文件加一个头文件中。第 16 章添加了大约 200 到 300 行硬件访问代码,这足以让打开 `myfirst.c` 的读者现在被"驱动程序业务逻辑"和"硬件寄存器机制"的混合体争夺注意力。 -Stage 4 separates them. Create a new file `myfirst_hw.c` alongside `myfirst.c`. Move into it: +第 4 阶段将它们分离。在 `myfirst.c` 旁边创建一个新文件 `myfirst_hw.c`。将以下内容移入其中: - The accessor implementations (`myfirst_reg_read`, `myfirst_reg_write`, `myfirst_reg_update`, `myfirst_reg_write_barrier`). - The register-driven side-effect helpers (`myfirst_ctrl_update`). @@ -2352,14 +2354,14 @@ Stage 4 separates them. Create a new file `myfirst_hw.c` alongside `myfirst.c`. - The access log rotation helpers. - The sysctl handlers for register views (`myfirst_sysctl_reg`, `myfirst_sysctl_reg_write`, `myfirst_sysctl_access_log`). -Move into `myfirst_hw.h`: +将以下内容移入 `myfirst_hw.h`: -- Register offsets and bit masks (already there). -- Fixed-value constants (already there). -- Function prototypes for the hardware-access API (`myfirst_hw_attach`, `myfirst_hw_detach`, `myfirst_hw_set_ctrl`, `myfirst_hw_add_sysctls`, etc.). -- A small struct defining the hardware state (fewer softc fields, more grouping). +- 寄存器偏移量和位掩码(已在那里)。 +- 固定值常量(已在那里)。 +- 硬件访问 API 的函数原型(`myfirst_hw_attach`、`myfirst_hw_detach`、`myfirst_hw_set_ctrl`、`myfirst_hw_add_sysctls` 等)。 +- 定义硬件状态的小结构(更少的 softc 字段,更多的分组)。 -The remaining `myfirst.c` keeps: +剩余的 `myfirst.c` 保留: - The softc declaration (including a `struct myfirst_hw *hw` pointer to a sub-struct for hardware state). - The driver lifecycle (attach, detach, module init). @@ -2368,11 +2370,11 @@ The remaining `myfirst.c` keeps: - The non-hardware tasks (selwake, bulk_writer, reset_delayed, recovery). - The non-hardware sysctls. -This split mirrors how real drivers with multiple subsystems organise themselves. A network driver might have `foo.c` for the main lifecycle, `foo_hw.c` for hardware access, `foo_rx.c` for the receive path, `foo_tx.c` for the transmit path. The principle is that each file holds code of one kind, and cross-file calls go through a named API. +这种拆分镜像了具有多个子系统的真实驱动程序如何组织自己。一个网络驱动程序可能有 `foo.c` 用于主生命周期、`foo_hw.c` 用于硬件访问、`foo_rx.c` 用于接收路径、`foo_tx.c` 用于发送路径。原则是每个文件持有一种类型的代码,跨文件调用通过命名 API 进行。 -### The Hardware State Structure +### 硬件状态结构 -Inside `myfirst_hw.h`, group the hardware-related fields into their own structure: +在 `myfirst_hw.h` 内部,将硬件相关字段分组到它们自己的结构中: ```c struct myfirst_hw { @@ -2390,7 +2392,7 @@ struct myfirst_hw { }; ``` -Add a pointer to it in the softc: +在 softc 中添加指向它的指针: ```c struct myfirst_softc { @@ -2399,7 +2401,7 @@ struct myfirst_softc { }; ``` -Allocate the hw struct in `myfirst_hw_attach`: +在 `myfirst_hw_attach` 中分配 hw 结构: ```c int @@ -2433,7 +2435,7 @@ myfirst_hw_attach(struct myfirst_softc *sc) } ``` -Free it in `myfirst_hw_detach`: +在 `myfirst_hw_detach` 中释放它: ```c void @@ -2455,11 +2457,11 @@ myfirst_hw_detach(struct myfirst_softc *sc) } ``` -The `myfirst_attach` and `myfirst_detach` functions now call `myfirst_hw_attach(sc)` and `myfirst_hw_detach(sc)` at the appropriate points in their ordering. The hardware sub-attach fits between "softc locks initialised" and "cdev registered"; the hardware sub-detach fits between "tasks drained" and "sysctl context released". +`myfirst_attach` 和 `myfirst_detach` 函数现在在其排序的适当点调用 `myfirst_hw_attach(sc)` 和 `myfirst_hw_detach(sc)`。硬件子 attach 适合放在"softc 锁初始化"和"cdev 注册"之间;硬件子 detach 适合放在"任务排空"和"sysctl 上下文释放"之间。 -### The CSR Macros +### CSR 宏 -Wrap the register accesses in macros that match the real-driver idiom: +将寄存器访问包装在匹配真实驱动程序惯用法的宏中: ```c #define CSR_READ_4(sc, off) \ @@ -2470,26 +2472,26 @@ Wrap the register accesses in macros that match the real-driver idiom: myfirst_reg_update((sc), (off), (clear), (set)) ``` -The driver body now reads: +驱动程序体现在读作: ```c -/* In myfirst_write: */ +/* 在 myfirst_write 中: */ CSR_WRITE_4(sc, MYFIRST_REG_DATA_IN, (uint32_t)last_byte); CSR_UPDATE_4(sc, MYFIRST_REG_STATUS, 0, MYFIRST_STATUS_DATA_AV); -/* In the ticker: */ +/* 在 ticker 中: */ uint32_t v = CSR_READ_4(sc, MYFIRST_REG_SCRATCH_A); CSR_WRITE_4(sc, MYFIRST_REG_SCRATCH_A, v + 1); -/* In the heartbeat: */ +/* 在心跳中: */ uint32_t status = CSR_READ_4(sc, MYFIRST_REG_STATUS); ``` -The call sites read like they are talking to hardware, because that is exactly what the abstraction represents. A newcomer opening the driver and reading any of these lines immediately understands what is happening: the driver is reading or writing a register named by a constant from the hardware header. +调用点读起来就像在与硬件对话,因为这正是抽象所代表的。一个打开驱动程序阅读这些行中任何一行的新来者会立即理解正在发生什么:驱动程序正在读取或写入由硬件头文件中常量命名的寄存器。 -### Moving Sysctls +### 移动 Sysctl -The register-view sysctls move to `myfirst_hw_add_sysctls`: +寄存器视图 sysctl 移到 `myfirst_hw_add_sysctls`: ```c void @@ -2501,11 +2503,11 @@ myfirst_hw_add_sysctls(struct myfirst_softc *sc) } ``` -The function is called from `myfirst_attach` at the usual point where sysctls are registered. The main file no longer needs to care about which sysctls exist for hardware; it delegates. +该函数从 `myfirst_attach` 在通常注册 sysctl 的位置调用。主文件不再需要关心硬件有哪些 sysctl;它委托出去。 -### Final `HARDWARE.md` +### 最终 `HARDWARE.md` -With the file split and API stable, `HARDWARE.md` finalises: +随着文件拆分和 API 稳定,`HARDWARE.md` 定稿: ```text # myfirst Hardware Interface @@ -2560,19 +2562,19 @@ Chapter 18 drivers use rman_get_bustag and rman_get_bushandle on a resource from bus_alloc_resource_any, which is portable by design. ``` -The document is now a single source of truth for how the driver accesses hardware. A future contributor reads it once to understand the interface and never again needs to reverse-engineer it from code. +该文档现在是驱动程序如何访问硬件的唯一事实来源。未来的贡献者读一次就能理解接口,再也不需要从代码逆向工程。 -### The Version Bump +### 版本提升 -In `myfirst.c`: +在 `myfirst.c` 中: ```c #define MYFIRST_VERSION "0.9-mmio" ``` -The string appears in `kldstat -v` output (through `MODULE_VERSION`) and in the `device_printf` at attach time. Bumping it is a small change with a big signalling value: anyone looking at the running driver knows exactly which chapter's features it has. +该字符串出现在 `kldstat -v` 输出中(通过 `MODULE_VERSION`)和 attach 时的 `device_printf` 中。提升它是一个小改动但具有大的信号价值:任何查看运行中驱动程序的人都能准确知道它拥有哪个章节的功能。 -Update the top-of-file comment to note the additions: +更新文件顶部注释以记录新增内容: ```c /* @@ -2587,13 +2589,13 @@ Update the top-of-file comment to note the additions: */ ``` -The top-of-file comment is the shortest path for a newcomer to understand the driver's history. Keeping it current is a small discipline with a big payoff. +文件顶部注释是新来者理解驱动程序历史的最短路径。保持它最新是一个小规范但回报很大。 -### The Final Regression Pass +### 最终回归测试 -Chapter 15 established the regression discipline: after every version bump, run the full stress suite from every previous chapter, confirm WITNESS is silent, confirm INVARIANTS is silent, confirm `kldunload` completes cleanly. +第 15 章建立了回归规范:每次版本提升后,运行以前每个章节的完整压力测试套件,确认 WITNESS 无声、确认 INVARIANTS 无声、确认 `kldunload` 干净完成。 -For Stage 4 that means: +对于第 4 阶段,这意味着: - The Chapter 11 concurrency tests (multiple writers, multiple readers) pass. - The Chapter 12 blocking tests (reader waits for data, writer waits for room) pass. @@ -2603,9 +2605,9 @@ For Stage 4 that means: - The Chapter 16 register tests (see the Hands-On Labs below) pass. - `kldunload myfirst` returns cleanly after the full suite. -No test is skipped. A regression in any previous chapter's test is a bug, not a deferred issue. The discipline is the same as it has been throughout Part 3. +不跳过任何测试。之前任何章节测试中的回归都是 bug,不是推迟的问题。这个规范与第 3 部分中的一样。 -### Running the Final Stage +### 运行最终阶段 ```text # cd examples/part-04/ch16-accessing-hardware/stage4-final @@ -2617,52 +2619,52 @@ No test is skipped. A regression in any previous chapter's test is a bug, not a # sysctl dev.myfirst.0 | head -40 ``` -The `kldstat -v` output should show `myfirst` at version `0.9-mmio`. The `dmesg` tail should show the device probe and attach with no errors. The `sysctl` output should list every Chapter 11 through Chapter 16 sysctl, including the register sysctls. +`kldstat -v` 输出应该显示 `myfirst` 版本为 `0.9-mmio`。`dmesg` 尾部应该显示设备探测和 attach 无错误。`sysctl` 输出应该列出第 11 到 16 章的每个 sysctl,包括寄存器 sysctl。 -Run the stress suite: +运行压力测试套件: ```text # ../labs/full_regression.sh ``` -If every test passes, Chapter 16 is complete. +如果每个测试都通过,第 16 章完成。 -### A Small Rule for Chapter 16's Refactor +### 第 16 章重构的一个小规则 -A rule of thumb that Stage 4 embodies: when a module acquires a new responsibility, give it its own file before the responsibility grows big enough to require one. Chapter 16 adds register access as a new responsibility. The responsibility is currently small: 200 to 300 lines across all the code. Splitting it into `myfirst_hw.c` now, while it is still small, is cheap. Splitting it later, when Chapter 18 adds PCI attach logic and Chapter 19 adds an interrupt handler and Chapter 20 adds DMA, would require disentangling three intertwined subsystems at once, which is expensive. +第 4 阶段体现的经验法则:当一个模块获得新职责时,在职责增长到需要自己的文件之前给它一个。 -The same rule applied to Chapter 10's cbuf: the ring buffer got its own `cbuf.c` as soon as it had any logic beyond "declare a struct", which paid off when concurrency and state machines entered the picture. It applies to every future subsystem this driver grows. +同样的规则也适用于第 10 章的 cbuf:环缓冲区在拥有超出"声明结构体"的任何逻辑时就获得了自己的 `cbuf.c`,这在并发和状态机进入画面时得到了回报。它适用于该驱动程序未来增长的每个子系统。 -### What Stage 4 Accomplished +### 第 4 阶段完成了什么 -The driver is now at `0.9-mmio`. Compared to `0.9-coordination`, it has: +驱动程序现在处于 `0.9-mmio`。与 `0.9-coordination` 相比,它拥有: -- A separate hardware-access layer in `myfirst_hw.c` and `myfirst_hw.h`. -- A full register map, documented in `myfirst_hw.h` and `HARDWARE.md`. -- `bus_space(9)`-based register accessors wrapped in `CSR_*` macros. -- Lock-protected, barrier-aware register access. -- An access log for post-hoc debugging. -- Per-register context ownership documented in `HARDWARE.md`. -- A ticker task that demonstrates autonomous register behaviour. -- An end-to-end path from user-space write to register update to user-space read. +- `myfirst_hw.c` 和 `myfirst_hw.h` 中独立的硬件访问层。 +- 完整的寄存器映射,记录在 `myfirst_hw.h` 和 `HARDWARE.md` 中。 +- 包装在 `CSR_*` 宏中的基于 `bus_space(9)` 的寄存器访问器。 +- 受锁保护、带屏障的寄存器访问。 +- 用于事后调试的访问日志。 +- 记录在 `HARDWARE.md` 中的每寄存器上下文所有权。 +- 演示自主寄存器行为的 ticker 任务。 +- 从用户空间写入到寄存器更新到用户空间读取的端到端路径。 -The driver's code is recognisably FreeBSD. The layout is the layout real drivers use. The vocabulary is the vocabulary real drivers share. A reader opening the driver for the first time finds a familiar structure, reads the headers to understand the registers, and can navigate the code by subsystem. +驱动程序的代码是可辨识的 FreeBSD 风格。布局是真实驱动程序使用的布局。词汇是真实驱动程序共享的词汇。首次打开驱动程序的读者会找到熟悉的结构,阅读头文件理解寄存器,并可以按子系统导航代码。 -### Wrapping Up Section 8 +### 总结第 8 节 -The refactor is small in code but large in organisation. A file split, a structure grouping, a macro layer, a documented interface, a version bump, and a regression pass. Each is a few minutes of work. Together they turn a correct driver into a maintainable one. +重构在代码上很小但在组织上很大。一次文件拆分、一次结构分组、一层宏、一个有文档的接口、一次版本提升和一次回归测试。每项都是几分钟的工作。它们一起将正确的驱动程序变成了可维护的驱动程序。 -The Chapter 16 driver is done. The chapter closes with labs, challenges, troubleshooting, and a bridge to Chapter 17, where the simulated device acquires dynamic behaviour. +第 16 章驱动程序完成。本章以实验、挑战、故障排除和通往第 17 章的桥梁结束,在那里模拟设备将获得动态行为。 -## Hands-On Labs +## 动手实验 -Labs in Chapter 16 focus on two things: observing register access while exercising the driver, and breaking the register contract to see how the driver reacts. Each lab takes 15 to 45 minutes. +第 16 章的实验集中在两件事上:在运行驱动程序时观察寄存器访问,以及破坏寄存器约定以查看驱动程序如何反应。每个实验需要 15 到 45 分钟。 -### Lab 1: Observe the Register Dance +### 实验 1:观察寄存器舞蹈 -Enable the access log. Exercise the driver across its full interface. Dump the log. Read the transcript. +启用访问日志。通过驱动程序的完整接口运行它。转储日志。阅读记录。 ```text # kldload ./myfirst.ko @@ -2678,36 +2680,36 @@ Enable the access log. Exercise the driver across its full interface. Dump the l # sysctl dev.myfirst.0.access_log ``` -You should see, in order: +你应该看到,按顺序: -- Five writes to `DATA_IN` (one per byte of "hello"). -- Updates to `STATUS` setting the `DATA_AV` bit. -- Five writes to `DATA_OUT` (one per byte read). -- Updates to `STATUS` clearing the `DATA_AV` bit as the buffer drains. -- The sysctl-driven `CTRL` write to enable, plus the read-back. -- Two increments of `SCRATCH_A` from the ticker. +- 五次对 `DATA_IN` 的写入("hello" 的每个字节一次)。 +- 对 `STATUS` 设置 `DATA_AV` 位的更新。 +- 五次对 `DATA_OUT` 的写入(每个读取字节一次)。 +- 对 `STATUS` 清除 `DATA_AV` 位的更新,随缓冲区排空。 +- sysctl 驱动的 `CTRL` 写入以启用,加上回读。 +- 来自 ticker 的两次 `SCRATCH_A` 递增。 -Read each line. Every value should make sense. If a value does not make sense, the driver has a bug, the test has a typo, or your understanding of the register protocol has a gap. +阅读每一行。每个值都应该合理。如果某个值不合理,驱动程序有 bug、测试有拼写错误,或者你对寄存器协议的理解有差距。 -### Lab 2: Trigger a Lock Violation (Debug Kernel) +### 实验 2:触发锁违规(调试内核) -This lab only works on a kernel built with `WITNESS` enabled. If you are not running one, skip this lab. +本实验仅在启用了 `WITNESS` 的内核上有效。如果你没有运行这样的内核,跳过本实验。 -Temporarily remove the `MYFIRST_LOCK(sc)` from the sysctl read handler. Rebuild and reload the driver. Run: +临时从 sysctl 读取处理程序中移除 `MYFIRST_LOCK(sc)`。重新构建并重新加载驱动程序。运行: ```text # sysctl dev.myfirst.0.reg_ctrl ``` -The console should emit a `WITNESS` warning about an unprotected register access (via the `MYFIRST_ASSERT` in `myfirst_reg_read`). The sysctl output may still return a plausible value, because the lack of locking does not always produce incorrect results, but the assertion makes the violation visible. +控制台应该发出一条关于未受保护寄存器访问的 `WITNESS` 警告(通过 `myfirst_reg_read` 中的 `MYFIRST_ASSERT`)。sysctl 输出可能仍然返回一个合理的值,因为缺少加锁并不总是产生不正确的结果,但断言使违规可见。 -Restore the lock. Rebuild. Verify the warning is gone. +恢复锁。重新构建。验证警告消失了。 -This lab demonstrates the value of `MYFIRST_ASSERT` as a safety net. A production driver without the assertion would carry the bug silently until something went wrong. +本实验展示了 `MYFIRST_ASSERT` 作为安全网的价值。没有断言的生产驱动程序会静默地携带 bug,直到出了问题。 -### Lab 3: Simulate a Concurrent Writer Race +### 实验 3:模拟并发写入者竞争 -Two processes writing simultaneously to `/dev/myfirst0` exercise the register update code path twice over. Run: +两个进程同时写入 `/dev/myfirst0` 会两次运行寄存器更新代码路径。运行: ```text # for i in 1 2 3 4; do @@ -2719,13 +2721,13 @@ done # sysctl dev.myfirst.0.reg_status ``` -The `DATA_IN` register should hold the ASCII code of whichever writer ran last (`'1'` = 49, `'2'` = 50, `'3'` = 51, `'4'` = 52). The result is non-deterministic, which is the point: register state from concurrent writers reflects the last winner. +`DATA_IN` 寄存器应该持有最后运行的写入者的 ASCII 码(`'1'` = 49、`'2'` = 50、`'3'` = 51、`'4'` = 52)。结果是不确定的,这就是重点:来自并发写入者的寄存器状态反映了最后的赢家。 -With Stage 3 locking, the driver is correct (no lost updates, no torn reads). Without Stage 3 locking (try reverting to Stage 2 and re-running), you may observe inconsistencies or WITNESS warnings. +有了第 3 阶段的加锁,驱动程序是正确的(没有丢失的更新、没有撕裂读取)。没有第 3 阶段的加锁(尝试回退到第 2 阶段并重新运行),你可能会观察到不一致或 WITNESS 警告。 -### Lab 4: Watch the Heartbeat Register Log +### 实验 4:观察心跳寄存器日志 -Enable the heartbeat debug bit, increase the interval, and let it run. +启用心跳调试位,增加间隔,让它运行。 ```text # sysctl dev.myfirst.0.debug_level=0x8 # MYFIRST_DBG_HEARTBEAT @@ -2739,31 +2741,31 @@ Enable the heartbeat debug bit, increase the interval, and let it run. # sysctl dev.myfirst.0.heartbeat_interval_ms=0 ``` -The dmesg tail should contain five lines, one per heartbeat, each showing the current register values. `SCRATCH_A` should climb by one per heartbeat because the ticker is firing in parallel. +dmesg 尾部应该包含五行,每次心跳一行,每行显示当前寄存器值。`SCRATCH_A` 应该每个心跳递增一,因为 ticker 在并行运行。 -This lab demonstrates how a production driver might use a debug log to observe live behaviour without interrupting the driver's normal operation. +本实验展示了生产驱动程序可能如何使用调试日志来观察实时行为,而不中断驱动程序的正常运行。 -### Lab 5: Add a New Register +### 实验 5:添加新寄存器 -A practical exercise. Add a new register `SCRATCH_C` at offset `0x28`. Extend the header, extend the sysctl list, extend `HARDWARE.md`. Rebuild, reload, and verify the new register is readable and writable via sysctl. +一个实践练习。在偏移量 `0x28` 处添加一个新寄存器 `SCRATCH_C`。扩展头文件、扩展 sysctl 列表、扩展 `HARDWARE.md`。重新构建、重新加载,并验证新寄存器可通过 sysctl 读写。 -This exercises the full workflow of adding a register: header change, sysctl addition, documentation update, test. A driver that makes all four steps easy is a well-organised driver. +这个练习锻炼了添加寄存器的完整工作流:头文件更改、sysctl 添加、文档更新、测试。一个使所有四个步骤都容易的驱动程序是一个组织良好的驱动程序。 -### Lab 6: Inject a Bogus Access (Debug Kernel) +### 实验 6:注入伪造访问(调试内核) -A deliberate break-and-observe exercise. +一个故意破坏并观察的练习。 -Modify the ticker callback to read from an out-of-bounds offset: `MYFIRST_REG_READ(sc, 0x80)`. Rebuild. Enable the ticker. On a debug kernel with INVARIANTS, the KASSERT in `myfirst_reg_read` should panic the kernel within a few seconds, with the panic string naming the offset. +修改 ticker 回调以从越界偏移量读取:`MYFIRST_REG_READ(sc, 0x80)`。重新构建。启用 ticker。在启用 INVARIANTS 的调试内核上,`myfirst_reg_read` 中的 KASSERT 应该在几秒钟内使内核 panic,panic 字符串会命名该偏移量。 -Restore the callback. Rebuild. Verify the driver runs cleanly again. +恢复回调。重新构建。验证驱动程序再次干净运行。 -This lab shows the value of bounds assertions: an out-of-bounds access fires immediately instead of silently corrupting nearby memory. Production code should never remove these assertions; they pay their cost many times over the life of the driver. +本实验展示了边界断言的价值:越界访问立即触发,而不是静默地损坏邻近内存。生产代码永远不应移除这些断言;它们在驱动程序生命周期中多次回本。 -### Lab 7: Trace With DTrace +### 实验 7:使用 DTrace 跟踪 -Compile the driver with `CFLAGS+=-DMYFIRST_DEBUG_REG_TRACE` to make the accessors out-of-line. Rebuild and reload. +编译驱动程序时使用 `CFLAGS+=-DMYFIRST_DEBUG_REG_TRACE` 使访问器变为非内联。重新构建并重新加载。 -Run DTrace: +运行 DTrace: ```text # dtrace -n 'fbt::myfirst_reg_write:entry { @@ -2771,27 +2773,27 @@ Run DTrace: }' ``` -In another terminal: +在另一个终端中: ```text # echo hi > /dev/myfirst0 ``` -DTrace should print two lines, one per register write (`DATA_IN` and the `STATUS` update). +DTrace 应该打印两行,每个寄存器写入一行(`DATA_IN` 和 `STATUS` 更新)。 -Try more advanced queries: +尝试更高级的查询: ```text # dtrace -n 'fbt::myfirst_reg_write:entry /arg1 == 0/ { @ = count(); }' ``` -Counts writes to `CTRL` (offset 0) for the duration of the run. Leave it running while triggering various operations, then Ctrl-C to see the total. +统计在运行期间对 `CTRL`(偏移量 0)的写入次数。在触发各种操作时让它运行,然后 Ctrl-C 查看总数。 -DTrace's power comes from the combination of low overhead, flexible filtering, and rich aggregation. A beginner who grows comfortable with it early will save hours on every later debugging session. +DTrace 的强大来自于低开销、灵活过滤和丰富聚合的组合。一个早早熟悉它的初学者将在每次后续调试会话中节省数小时。 -### Lab 8: The Watchdog-Meets-Register Scenario +### 实验 8:看门狗遇上寄存器场景 -The Chapter 13 watchdog callout was introduced to catch stalls in the ring buffer. Chapter 16's register integration adds a second failure mode: the watchdog could detect a register in an impossible state. Extend the watchdog callback to complain if `STATUS.ERROR` is set: +第 13 章的看门狗 callout 是为了捕获环缓冲区中的停滞而引入的。第 16 章的寄存器集成添加了第二种故障模式:看门狗可以检测到处于不可能状态的寄存器。扩展看门狗回调以在 `STATUS.ERROR` 被设置时发出警报: ```c if (MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_ERROR) { @@ -2799,298 +2801,298 @@ if (MYFIRST_REG_READ(sc, MYFIRST_REG_STATUS) & MYFIRST_STATUS_ERROR) { } ``` -Set the error bit from a sysctl handler: +从 sysctl 处理程序设置错误位: ```text -# sysctl dev.myfirst.0.reg_ctrl_set=?? # use your writeable-register sysctl +# sysctl dev.myfirst.0.reg_ctrl_set=?? # 使用你的可写寄存器 sysctl ``` -(You can similarly make a writeable sysctl for `STATUS` to trigger the watchdog check.) +(你可以类似地为 `STATUS` 创建一个可写 sysctl 来触发看门狗检查。) -On the next watchdog tick (default 5 seconds), the message should appear. Clear the bit; the message should stop. +在下一个看门狗 tick(默认 5 秒)时,消息应该出现。清除该位;消息应该停止。 -This lab integrates the register path with the callout-driven monitoring path, showing how the two subsystems compose. +本实验将寄存器路径与 callout 驱动的监控路径集成,展示两个子系统如何组合。 -## Challenge Exercises +## 挑战练习 -Challenges go further than labs. Each should take one to four hours and exercises judgment, not just keystrokes. +挑战比实验更进一步。每个应该花费一到四个小时,锻炼的是判断力而不仅仅是按键。 -### Challenge 1: Per-File-Handle Register Snapshot +### 挑战 1:每文件句柄寄存器快照 -Each open file descriptor gets its own snapshot of the register block, captured at open time and accessible via a custom ioctl. Modify `myfirst_open` to snapshot the registers into a per-fd structure; implement an ioctl that returns the snapshot; write a user-space program that opens `/dev/myfirst0`, fetches the snapshot, and prints it. +每个打开的文件描述符获得自己的寄存器块快照,在打开时捕获,并可通过自定义 ioctl 访问。修改 `myfirst_open` 将寄存器快照到一个每文件描述符结构中;实现一个返回快照的 ioctl;编写一个用户空间程序,打开 `/dev/myfirst0`,获取快照并打印它。 -Think about: how much memory does the snapshot cost per open? When should the snapshot be refreshed? Should a second ioctl be added to refresh? +思考:快照每次打开花费多少内存?快照应该何时刷新?是否应该添加第二个 ioctl 来刷新? -### Challenge 2: Register Diff Logging +### 挑战 2:寄存器差异日志 -Extend the access log to record only *changes* to registers (where the new value differs from the previous value at the same offset). Writes that do not change the value are not logged. This compresses the log significantly and focuses it on meaningful state transitions. +扩展访问日志,仅记录寄存器的*变化*(新值与同一偏移量的前一个值不同)。不改变值的写入不被记录。这显著压缩了日志,使其聚焦于有意义的状态转换。 -Think about: how do you track the "previous value"? Is it per-offset, or do you store it alongside each log entry? +思考:你如何跟踪"前一个值"?是每偏移量存储,还是与每个日志条目一起存储? -### Challenge 3: Loopback Mode +### 挑战 3:环回模式 -Add a `CTRL.LOOPBACK` bit (already defined in `myfirst_hw.h`). When the bit is set, writes to `DATA_IN` are also copied to `DATA_OUT`, making the driver "loop back" user-space writes without needing a read. Implement the logic, add a lab test, and confirm user-space reads return the bytes just written. +添加一个 `CTRL.LOOPBACK` 位(已在 `myfirst_hw.h` 中定义)。当该位被设置时,对 `DATA_IN` 的写入也复制到 `DATA_OUT`,使驱动程序"环回"用户空间写入而无需读取。实现逻辑,添加一个实验测试,并确认用户空间读取返回刚写入的字节。 -Think about: where in the write path does the copy belong? Is it still correct if multiple bytes are written in one call? Do you set `DATA_AV` differently in loopback mode? +思考:复制属于写入路径的哪个位置?如果一次调用中写入多个字节是否仍然正确?环回模式下 `DATA_AV` 的设置是否不同? -### Challenge 4: Read-to-Clear on `INTR_STATUS` +### 挑战 4:`INTR_STATUS` 的读即清除 -The Chapter 16 simulation has `INTR_STATUS` as a plain register. Real hardware often uses read-to-clear semantics. Implement them: make the sysctl read of `reg_intr_status` return the current value and then clear it, so the next read returns zero. Add a way to set pending bits (a writeable sysctl that ORs into the register). +第 16 章模拟中 `INTR_STATUS` 是一个普通寄存器。真实硬件通常使用读即清除语义。实现它们:使 `reg_intr_status` 的 sysctl 读取返回当前值然后清除它,使下一次读取返回零。添加一种设置挂起位的方式(一个或入寄存器的可写 sysctl)。 -Think about: is the read-to-clear behaviour safe for the debug sysctl? How do you handle the case where the sysctl is used to observe the value? +思考:读即清除行为对调试 sysctl 是否安全?你如何处理使用 sysctl 观察值的情况? -### Challenge 5: A Barrier Correctness Stress Test +### 挑战 5:屏障正确性压力测试 -Write a stress harness that exercises a specific pattern: write to `CTRL`, issue a barrier, read `STATUS`, verify the read reflects the write. Run it thousands of times, measure how often the verification fails. On x86 with correct barriers, failures should be zero. +编写一个压力测试工具,运行特定模式:写入 `CTRL`、发出屏障、读取 `STATUS`、验证读取反映了写入。运行数千次,测量验证失败的频率。在 x86 上使用正确的屏障时,失败应该为零。 -Then remove the barrier and run again. On x86, failures might still be zero (strong memory model). On arm64 (if you have access), removing the barrier may produce failures. +然后移除屏障再运行。在 x86 上,失败可能仍然为零(强内存模型)。在 arm64 上(如果你有访问权限),移除屏障可能产生失败。 -Think about: what does this exercise tell you about the cost and value of barriers on different architectures? Should a driver always include them? +思考:这个练习告诉你关于屏障在不同架构上的成本和价值什么?驱动程序是否应该总是包含它们? -### Challenge 6: A Register-Aware Lockstat Run +### 挑战 6:寄存器感知的 Lockstat 运行 -Use `lockstat` to profile your Stage 3 driver under load. Identify the hottest locks. Is the driver mutex (`sc->mtx`) saturated by register access, or by the ring buffer path, or by neither? Generate a report and interpret the numbers. +使用 `lockstat` 对你的第 3 阶段驱动程序进行负载下的性能分析。识别最热的锁。驱动程序互斥锁(`sc->mtx`)是被寄存器访问饱和、被环缓冲区路径饱和,还是两者都不是?生成一份报告并解释这些数字。 -Think about: does the result change if you split out a dedicated `sc->reg_mtx` for register access? Do WITNESS warnings appear? Is the driver faster or slower? +思考:如果你为寄存器访问拆出一个专用 `sc->reg_mtx`,结果是否会改变?是否出现 WITNESS 警告?驱动程序是更快还是更慢? -### Challenge 7: Read a Real Driver's Register Interface +### 挑战 7:阅读真实驱动程序的寄存器接口 -Pick a real driver in `/usr/src/sys/dev/` and read its register header. Candidates include `/usr/src/sys/dev/ale/if_alereg.h`, `/usr/src/sys/dev/e1000/e1000_regs.h`, and `/usr/src/sys/dev/uart/uart_dev_ns8250.h`. Answer: +在 `/usr/src/sys/dev/` 中选择一个真实驱动程序并阅读其寄存器头文件。候选包括 `/usr/src/sys/dev/ale/if_alereg.h`、`/usr/src/sys/dev/e1000/e1000_regs.h` 和 `/usr/src/sys/dev/uart/uart_dev_ns8250.h`。回答: -- How many registers does the driver define? -- What width are they (8, 16, 32, 64 bits)? -- Which registers have bit-field macros? Are there any bit-field macros that correspond to fields spanning multiple bytes? -- How does the driver wrap `bus_read_*` and `bus_write_*` (if at all)? -- How are the register offsets documented (comments, external spec references)? +- 驱动程序定义了多少个寄存器? +- 它们的宽度是多少(8、16、32、64 位)? +- 哪些寄存器有位字段宏?是否有跨越多个字节的位字段宏? +- 驱动程序如何包装 `bus_read_*` 和 `bus_write_*`(如果有)? +- 寄存器偏移量如何被记录(注释、外部规范引用)? -Writing up the answers as a one-page analysis is a great way to consolidate Chapter 16's material. You will likely also find patterns you want to apply to your own driver. +将答案写成一份一页分析是巩固第 16 章内容的好方法。你可能还会发现想应用到自己驱动程序的模式。 -## Troubleshooting Reference +## 故障排除参考 -A quick reference for the problems Chapter 16's code is most likely to surface. +快速参考。 -### Driver fails to load +### 驱动程序加载失败 -- **"resolve_symbol failed"**: Missing include or a typo in a function name. Check `/var/log/messages` for the exact symbol; add the include; retry. -- **"undefined reference to bus_space_read_4"**: Missing `#include `. This pulls in the per-architecture bus header. -- **"invalid KMOD Makefile"**: A typo in the Makefile. Compare against the stage's known-good Makefile. +- **"resolve_symbol failed"**:缺少 include 或函数名拼写错误。检查 `/var/log/messages` 中的确切符号;添加 include;重试。 +- **"undefined reference to bus_space_read_4"**:缺少 `#include `。这会引入每架构的总线头文件。 +- **"invalid KMOD Makefile"**:Makefile 中有拼写错误。与该阶段的已知良好 Makefile 比较。 -### Driver loads but `dmesg` shows `myfirst: cannot allocate register block` +### 驱动程序加载但 `dmesg` 显示 `myfirst: cannot allocate register block` -`malloc(9)` returned NULL at attach. Usually means `M_WAITOK` was passed but the system was under memory pressure; rare for a 64-byte allocation. Check the kernel's malloc statistics (`vmstat -m`) for `myfirst`. Try a reboot. +`malloc(9)` 在 attach 时返回 NULL。通常意味着传了 `M_WAITOK` 但系统内存紧张;64 字节分配很少出现这种情况。检查内核的 malloc 统计(`vmstat -m`)中的 `myfirst`。尝试重启。 -### `sysctl dev.myfirst.0.reg_ctrl` returns ENOENT +### `sysctl dev.myfirst.0.reg_ctrl` 返回 ENOENT -The sysctl was not registered. Confirm `myfirst_hw_add_sysctls` is called in attach. Confirm the sysctl context and tree are the same as the rest of the driver's sysctls. Look for a typo in `OID_AUTO` or the leaf name. +sysctl 未注册。确认 `myfirst_hw_add_sysctls` 在 attach 中被调用。确认 sysctl 上下文和树与驱动程序其余 sysctl 相同。检查 `OID_AUTO` 或叶名称中的拼写错误。 -### `sysctl dev.myfirst.0.reg_ctrl` returns a plausible value, but changes never happen +### `sysctl dev.myfirst.0.reg_ctrl` 返回合理值,但更改从不发生 -The writeable sysctl `reg_ctrl_set` might be missing `CTLFLAG_RW`. Without `_RW`, the sysctl is read-only. Also check the handler is not short-circuiting because of an early ENODEV return. +可写 sysctl `reg_ctrl_set` 可能缺少 `CTLFLAG_RW`。没有 `_RW`,sysctl 是只读的。还要检查处理程序是否因为早期 ENODEV 返回而短路。 -### Kernel panic on first register write: "page fault in kernel mode" +### 首次寄存器写入时内核 panic:"page fault in kernel mode" -`sc->regs_buf` is NULL or dangling. Confirm `myfirst_hw_attach` ran successfully and set `sc->hw->regs_buf`. Confirm nothing freed the buffer prematurely (detach running in parallel, or a `free` in an error path). +`sc->regs_buf` 是 NULL 或悬垂指针。确认 `myfirst_hw_attach` 成功运行并设置了 `sc->hw->regs_buf`。确认没有东西过早释放了缓冲区(detach 并行运行,或错误路径中的 `free`)。 -### Kernel panic: "myfirst: register read past end of register block" +### 内核 panic:"myfirst: register read past end of register block" -The `KASSERT` fired. A bug in the driver is passing an out-of-range offset. Use the crash stack to find the call site. Common cause: an arithmetic expression for the offset that exceeds `MYFIRST_REG_SIZE`. +`KASSERT` 触发了。驱动程序中的 bug 传递了越界偏移量。使用崩溃栈找到调用点。常见原因:偏移量的算术表达式超过了 `MYFIRST_REG_SIZE`。 -### `WITNESS` warning: "acquiring duplicate lock" +### `WITNESS` 警告:"acquiring duplicate lock" -Usually a sign that a call chain is acquiring `sc->mtx` recursively. The Chapter 11 mutex is a sleep mutex without the `MTX_RECURSE` flag, which is correct. Trace the stack; one of the callers is re-entering. +通常是调用链递归获取 `sc->mtx` 的信号。第 11 章的互斥锁是没有 `MTX_RECURSE` 标志的睡眠互斥锁,这是正确的。跟踪栈;其中一个调用者在重入。 -### `WITNESS` warning: "lock order reversal" +### `WITNESS` 警告:"lock order reversal" -The driver is holding `sc->mtx` while acquiring another lock (or vice versa) in an order that violates the documented order. Check `LOCKING.md` against the stack trace and fix the call site. +驱动程序在持有 `sc->mtx` 时获取另一个锁(或反之),顺序违反了记录的顺序。根据栈跟踪检查 `LOCKING.md` 并修复调用点。 -### Ticker does not fire +### Ticker 不触发 -The tick source callout's interval is zero (disabled). Confirm `dev.myfirst.0.tick_source_interval_ms` is positive. Confirm `reg_ticker_enabled` is 1. Look at the access log for SCRATCH_A writes; if there are none, the callout is the problem. If there are, the sysctl may be stale (re-read it). +tick source callout 的间隔为零(禁用)。确认 `dev.myfirst.0.tick_source_interval_ms` 为正。确认 `reg_ticker_enabled` 为 1。查看访问日志中是否有 SCRATCH_A 写入;如果没有,callout 是问题所在。如果有,sysctl 可能是过期的(重新读取它)。 -### Access log returns empty +### 访问日志返回空 -Confirm `access_log_enabled` is 1. Confirm the driver mutex is being acquired in access paths (the log update happens under the lock). If the log is genuinely empty but registers should have been accessed, check the access paths for missing accessor calls. +确认 `access_log_enabled` 为 1。确认驱动程序互斥锁在访问路径中被获取(日志更新在锁下发生)。如果日志确实为空但寄存器应该已被访问,检查访问路径是否缺少访问器调用。 -### `dmesg` shows no output from `myfirst_ctrl_update` +### `dmesg` 中没有来自 `myfirst_ctrl_update` 的输出 -The debug_level is 0, or the specific bit is not set. Set `debug_level` to include the right bits and retry. +debug_level 为 0,或特定位未设置。将 `debug_level` 设置为包含正确的位并重试。 -### `kldunload myfirst` returns EBUSY +### `kldunload myfirst` 返回 EBUSY -Open file descriptors still exist on the device. Close them (or use `fstat -f /dev/myfirst0` to find who holds them) and retry. +设备上仍有打开的文件描述符。关闭它们(或使用 `fstat -f /dev/myfirst0` 找到持有者)并重试。 -### `kldunload myfirst` hangs +### `kldunload myfirst` 挂起 -Detach is stuck draining a primitive. Use `procstat -kk ` to see where. Usually the stuck drain is a task or callout that is not cancelling. Check the detach ordering against `LOCKING.md`. +Detach 卡在排空某个原语上。使用 `procstat -kk ` 查看卡在哪里。通常卡住的排空是一个未取消的任务或 callout。根据 `LOCKING.md` 检查 detach 排序。 -### The stress test complains about WITNESS warnings +### 压力测试抱怨 WITNESS 警告 -Each warning is a real bug. Fix one, retest, continue. Do not mass-disable WITNESS and call the issue resolved; the warnings are pointing at the problem. +每个警告都是一个真实的 bug。修复一个,重新测试,继续。不要批量禁用 WITNESS 就认为问题解决了;警告正指向问题所在。 -## Wrapping Up +## 总结 -Chapter 16 opened Part 4 by giving the `myfirst` driver its first hardware story. The driver now has a register block, even if that block is simulated. It uses `bus_space(9)` the way a real driver does. It protects register access with the Chapter 11 mutex, inserts barriers where ordering matters, and documents every register and every access path. It has an access log for post-hoc debugging, DTrace probes for live observation, and a ddb command for live inspection. It is organised across two files: the main driver lifecycle and the hardware-access layer. +第 16 章通过给 `myfirst` 驱动程序第一个硬件故事来开启第四部分。驱动程序现在有一个寄存器块,即使该块是模拟的。它像真实驱动程序一样使用 `bus_space(9)`。它用第 11 章的互斥锁保护寄存器访问,在排序重要的地方插入屏障,并拥有一个可观测性层。 -What Chapter 16 deliberately did not do: real PCI (Chapter 18), real interrupts (Chapter 19), real DMA (Chapters 20 and 21), full hardware simulation with dynamic behaviour (Chapter 17). Each of those topics deserves its own chapter; each builds on Chapter 16's vocabulary. +第 16 章刻意没有做的:真实 PCI(第 18 章)、真实中断(第 19 章)、真实 DMA(第 20 和 21 章)、带动态行为的完整硬件模拟(第 17 章)。这些主题每一个都值得单独成章;每一个都建立在第 16 章的词汇之上。 -The version is `0.9-mmio`. The file layout is `myfirst.c` plus `myfirst_hw.c` plus `myfirst_hw.h` plus `myfirst_sync.h` plus `cbuf.c` plus `cbuf.h`. The documentation is `LOCKING.md` plus the new `HARDWARE.md`. The test suite has grown by the Chapter 16 labs. Every earlier Part 3 test still passes. +版本是 `0.9-mmio`。文件布局是 `myfirst.c` 加 `myfirst_hw.c` 加 `myfirst_hw.h` 加 `myfirst_sync.h` 加 `cbuf.c` 加 `cbuf.h`。文档是 `LOCKING.md` 加新的 `HARDWARE.md`。测试套件已通过第 16 章实验增长。每个更早的第 3 部分测试仍然通过。 -### A Reflection Before Chapter 17 +### 第 17 章前的反思 -A pause before the next chapter. Chapter 16 was a careful introduction to a set of ideas that will recur for the rest of Part 4 and beyond. The register read and write, the barrier, the bus tag and handle, the locking discipline around MMIO: these are the pieces every later hardware-facing chapter uses without re-teaching them. You have met them all once, in a setting where you could observe, experiment, and make mistakes safely. +在下一章之前稍作停顿。第 16 章是对一组将在第四部分余下章节及以后反复出现的想法的仔细介绍。寄存器读写、屏障、总线标签和句柄、MMIO 周围的加锁规范:这些是每个后续面向硬件的章节都会使用而不重新教授的片段。你已经在可以观察、实验和安全的犯错环境中与它们全部见过一次面。 -The same pattern that defined Part 3 defines Part 4: introduce a primitive, apply it to the driver in a small refactor, document it, test it, move on. The difference is that Part 4's primitives face outward. The driver is no longer a self-contained world; it is a participant in a conversation with hardware. That conversation has rules the driver must respect, and the rules have consequences when they are broken. +定义第 3 部分的相同模式定义了第 4 部分:引入一个原语,以小重构的形式将其应用到驱动程序中,记录它,测试它,继续。区别在于第 4 部分的原语面向外部。驱动程序不再是一个自包含的世界;它是与硬件对话的参与者。这场对话有驱动程序必须遵守的规则,规则被违反时有后果。 -Chapter 17 makes the hardware side of the conversation more interesting. The simulated device will grow a callout that changes `STATUS` bits over time. It will signal "data available" after a write by flipping a bit on a delay. It will fail occasionally to teach error-handling paths. The register vocabulary stays the same; the device behaviour becomes richer. +第 17 章使对话的硬件侧更有趣。模拟设备将获得一个随时间改变 `STATUS` 位的 callout。它将在写入后通过延迟翻转一个位来发出"数据可用"信号。它将偶尔失败以教授错误处理路径。寄存器词汇保持不变;设备行为变得更丰富。 -### What to Do If You Are Stuck +### 如果你卡住了该怎么办 -If the Chapter 16 material feels overwhelming on first pass, a few suggestions. +如果第 16 章的内容在第一次阅读时感觉压倒性的,有几条建议。 -First, re-read Section 3. The `bus_space` vocabulary is the foundation; if it is shaky, everything else is shaky. +第一,重新阅读第 3 节。`bus_space` 词汇是基础;如果它不稳固,其他一切都不稳固。 -Second, type Stage 1 by hand, end to end, and run it. Muscle memory produces understanding in a way that reading does not. +第二,亲手从头到尾输入第 1 阶段并运行它。肌肉记忆以一种阅读无法做到的方式产生理解。 -Third, open `/usr/src/sys/dev/ale/if_alevar.h` and find the `CSR_*` macros. The real driver's idiom is the same as your Stage 4's. Seeing the pattern in a production driver makes the abstraction feel less arbitrary. +第三,打开 `/usr/src/sys/dev/ale/if_alevar.h` 并找到 `CSR_*` 宏。真实驱动程序的惯用法与你第 4 阶段的一样。在生产驱动程序中看到这个模式使抽象感觉不那么随意。 -Fourth, skip the challenges on first pass. The labs are calibrated for Chapter 16; the challenges assume the chapter's material is already solid. Come back to them after Chapter 17 if they feel out of reach now. +第四,第一次阅读时跳过挑战。实验是为第 16 章校准的;挑战假设章节的内容已经扎实。如果它们现在感觉够不到,在第 17 章之后再回来。 -Chapter 16's goal was clarity of vocabulary. If you have that, the rest of Part 4 will feel navigable. +第 16 章的目标是词汇的清晰。如果你有了这个,第四部分的其余部分将感觉可导航。 -## Bridge to Chapter 17 +## 通往第 17 章的桥梁 -Chapter 17 is titled *Simulating Hardware*. Its scope is the deeper simulation that Chapter 16 deliberately stepped around: a register block whose contents change over time, whose protocol has side effects, and whose failures can be injected deliberately for testing. The driver at `0.9-mmio` has a register block that behaves statically; Chapter 17 makes it breathe. +第 17 章标题为*模拟硬件*。其范围是第 16 章刻意回避的更深层模拟:一个内容随时间变化的寄存器块,其协议有副作用,其故障可以被故意注入以进行测试。处于 `0.9-mmio` 的驱动程序拥有一个静态行为的寄存器块;第 17 章使它呼吸起来。 -Chapter 16 prepared the ground in four specific ways. +第 16 章在四个具体方面做好了准备。 -First, **you have a register map**. The offsets, bit masks, and register semantics are documented in `myfirst_hw.h` and `HARDWARE.md`. Chapter 17 extends the map with a few new registers and enriches the protocol of the existing ones; the structure is established. +第一,**你有一个寄存器映射**。偏移量、位掩码和寄存器语义记录在 `myfirst_hw.h` 和 `HARDWARE.md` 中。第 17 章用几个新寄存器扩展映射并丰富现有寄存器的协议;结构已经建立。 -Second, **you have lock-protected, barrier-aware accessors**. Chapter 17 introduces a callout that updates registers periodically from its own context. Without Chapter 16's locking discipline, the callout would race with the syscall path. With it, the callout slots into the existing mutex without additional work. +第二,**你有受锁保护的、带屏障的访问器**。第 17 章引入一个从自己的上下文定期更新寄存器的 callout。没有第 16 章的加锁规范,callout 会与系统调用路径竞争。有了它,callout 无需额外工作就能插入现有互斥锁。 -Third, **you have an access log**. Chapter 17 uses more elaborate register updates (read-to-clear `INTR_STATUS`, write-triggered delayed `DATA_AV`, simulated errors). The access log is how you will see those updates in action, and Chapter 17 leans on it heavily. +第三,**你有一个访问日志**。第 17 章使用更精细的寄存器更新(读即清除 `INTR_STATUS`、写入触发的延迟 `DATA_AV`、模拟错误)。访问日志是你将看到这些更新的方式,第 17 章严重依赖它。 -Fourth, **you have a split file layout**. Chapter 17's simulation logic lands in `myfirst_hw.c`, alongside the Chapter 16 accessors. The main driver file stays focused on the driver lifecycle. The split keeps the simulation code contained. +第四,**你有拆分的文件布局**。第 17 章的模拟逻辑落在 `myfirst_hw.c` 中,与第 16 章的访问器并列。主驱动程序文件保持聚焦在驱动程序生命周期上。拆分使模拟代码保持独立。 -Specific topics Chapter 17 will cover: +第 17 章将涵盖的具体主题: -- A callout that updates `STATUS` bits on a schedule, simulating autonomous device activity. -- A write-to-trigger-delayed-event pattern: writing `CTRL.GO` schedules a callout that, after a delay, flips `STATUS.DATA_AV`. -- Read-to-clear semantics on `INTR_STATUS`, with the driver's sysctl being careful not to inadvertently clear bits. -- Simulated error injection: a sysctl that causes the next operation to "fail" with a fault bit set in `STATUS`. -- Timeouts: the driver reacts correctly when the simulated device fails to become ready. -- A latency simulation path with `DELAY(9)` and `callout_reset_sbt` for different granularities. +- 一个按计划更新 `STATUS` 位的 callout,模拟自主设备活动。 +- 一个写入触发延迟事件模式:写入 `CTRL.GO` 安排一个 callout,在延迟后翻转 `STATUS.DATA_AV`。 +- `INTR_STATUS` 上的读即清除语义,驱动程序的 sysctl 小心不无意中清除位。 +- 模拟错误注入:一个导致下一个操作"失败"并在 `STATUS` 中设置故障位的 sysctl。 +- 超时:当模拟设备未能变为就绪时驱动程序正确反应。 +- 一个使用 `DELAY(9)` 和 `callout_reset_sbt` 进行不同粒度的延迟模拟路径。 -You do not need to read ahead. Chapter 16 is sufficient preparation. Bring your `myfirst` driver at `0.9-mmio`, your `LOCKING.md`, your `HARDWARE.md`, your `WITNESS`-enabled kernel, and your test kit. Chapter 17 starts where Chapter 16 ended. +你不需要提前阅读。第 16 章已足够准备。带上你的 `myfirst` 驱动程序(版本 `0.9-mmio`)、你的 `LOCKING.md`、你的 `HARDWARE.md`、你启用 WITNESS 的内核和你的测试工具包。第 17 章从第 16 章结束的地方开始。 -A small closing reflection. Part 3 taught you the synchronisation vocabulary and a driver that coordinated itself. Chapter 16 added a register vocabulary and a driver that now has a hardware surface. Chapter 17 will give that surface dynamic behaviour; Chapter 18 will replace the simulation with real PCI hardware; Chapter 19 will add interrupts; Chapter 20 and Chapter 21 will add DMA. Each of those chapters is narrower than its topic suggests because Chapter 16 did the vocabulary work first. +一个简短的结束反思。第 3 部分教你同步词汇和一个能协调自身的驱动程序。第 16 章添加了寄存器词汇和一个现在拥有硬件表面的驱动程序。第 17 章将给那个表面动态行为;第 18 章将用真实 PCI 硬件替换模拟;第 19 章将添加中断;第 20 章和第 21 章将添加 DMA。这些章节中的每一个都比其标题暗示的范围更窄,因为第 16 章先做了词汇工作。 -The hardware conversation is now beginning. The vocabulary is yours. Chapter 17 opens the next round. +硬件对话现在正在开始。词汇是你的。第 17 章开启下一轮。 -## Reference: `bus_space(9)` Cheat Sheet +## 参考:`bus_space(9)` 速查表 -A one-page summary of the `bus_space(9)` API, for quick reference while coding. +`bus_space(9)` API 的一页摘要,供编码时快速参考。 -### Types +### 类型 -| Type | Meaning | +| 类型 | 含义 | |----------------------|---------------------------------------------------| -| `bus_space_tag_t` | Identifies the address space (memory or I/O). | -| `bus_space_handle_t` | Identifies a specific region in the address space.| -| `bus_size_t` | Unsigned integer for offsets inside a region. | +| `bus_space_tag_t` | 标识地址空间(内存或 I/O)。 | +| `bus_space_handle_t` | 标识地址空间内的特定区域。| +| `bus_size_t` | 区域内偏移量的无符号整数。 | -### Reads +### 读取 -| Function | Width | Notes | +| 函数 | 宽度 | 说明 | |---------------------------------|-------|------------------------------| -| `bus_space_read_1(t, h, o)` | 8 | Returns `u_int8_t` | -| `bus_space_read_2(t, h, o)` | 16 | Returns `u_int16_t` | -| `bus_space_read_4(t, h, o)` | 32 | Returns `u_int32_t` | -| `bus_space_read_8(t, h, o)` | 64 | amd64 memory only | +| `bus_space_read_1(t, h, o)` | 8 | 返回 `u_int8_t` | +| `bus_space_read_2(t, h, o)` | 16 | 返回 `u_int16_t` | +| `bus_space_read_4(t, h, o)` | 32 | 返回 `u_int32_t` | +| `bus_space_read_8(t, h, o)` | 64 | 仅 amd64 内存空间 | -### Writes +### 写入 -| Function | Width | Notes | +| 函数 | 宽度 | 说明 | |------------------------------------|-------|------------------------------| -| `bus_space_write_1(t, h, o, v)` | 8 | `v` is `u_int8_t` | -| `bus_space_write_2(t, h, o, v)` | 16 | `v` is `u_int16_t` | -| `bus_space_write_4(t, h, o, v)` | 32 | `v` is `u_int32_t` | -| `bus_space_write_8(t, h, o, v)` | 64 | amd64 memory only | +| `bus_space_write_1(t, h, o, v)` | 8 | `v` 为 `u_int8_t` | +| `bus_space_write_2(t, h, o, v)` | 16 | `v` 为 `u_int16_t` | +| `bus_space_write_4(t, h, o, v)` | 32 | `v` 为 `u_int32_t` | +| `bus_space_write_8(t, h, o, v)` | 64 | 仅 amd64 内存空间 | -### Multi Accesses (same offset, different buffer positions) +### 多访问(相同偏移量,不同缓冲区位置) -| Function | Purpose | +| 函数 | 用途 | |--------------------------------------------------|------------------------------------------| -| `bus_space_read_multi_1(t, h, o, buf, count)` | Read `count` bytes from `o`. | -| `bus_space_read_multi_4(t, h, o, buf, count)` | Read `count` 32-bit values from `o`. | -| `bus_space_write_multi_4(t, h, o, buf, count)` | Write `count` 32-bit values to `o`. | +| `bus_space_read_multi_1(t, h, o, buf, count)` | 从 `o` 读取 `count` 个字节。 | +| `bus_space_read_multi_4(t, h, o, buf, count)` | 从 `o` 读取 `count` 个 32 位值。 | +| `bus_space_write_multi_4(t, h, o, buf, count)` | 向 `o` 写入 `count` 个 32 位值。 | -### Region Accesses (advancing offset and buffer) +### 区域访问(前进偏移量和缓冲区) -| Function | Purpose | +| 函数 | 用途 | |---------------------------------------------------|--------------------------------------------| -| `bus_space_read_region_4(t, h, o, buf, count)` | Read `count` 32-bit values from `o..` | -| `bus_space_write_region_4(t, h, o, buf, count)` | Write `count` 32-bit values to `o..` | +| `bus_space_read_region_4(t, h, o, buf, count)` | 从 `o..` 读取 `count` 个 32 位值 | +| `bus_space_write_region_4(t, h, o, buf, count)` | 向 `o..` 写入 `count` 个 32 位值 | -### Barrier +### 屏障 -| Function | Purpose | +| 函数 | 用途 | |----------------------------------------------|-------------------------------------------------| -| `bus_space_barrier(t, h, o, len, flags)` | Enforce read/write ordering over offset range. | +| `bus_space_barrier(t, h, o, len, flags)` | 在偏移量范围内强制读/写排序。 | -Flags: +标志: -| Flag | Meaning | +| 标志 | 含义 | |-------------------------------|-------------------------------------------| -| `BUS_SPACE_BARRIER_READ` | Prior reads complete before later reads. | -| `BUS_SPACE_BARRIER_WRITE` | Prior writes complete before later writes.| +| `BUS_SPACE_BARRIER_READ` | 先前的读取在后续读取之前完成。 | +| `BUS_SPACE_BARRIER_WRITE` | 先前的写入在后续写入之前完成。| -### Resource Shorthand (`/usr/src/sys/sys/bus.h`) +### 资源简写(`/usr/src/sys/sys/bus.h`) -| Function | Equivalent | +| 函数 | 等价形式 | |-----------------------------------|-------------------------------------------------| | `bus_read_4(r, o)` | `bus_space_read_4(r->r_bustag, r->r_bushandle, o)` | | `bus_write_4(r, o, v)` | `bus_space_write_4(r->r_bustag, r->r_bushandle, o, v)` | | `bus_barrier(r, o, l, f)` | `bus_space_barrier(r->r_bustag, r->r_bushandle, o, l, f)` | -### Allocation +### 分配 -| Function | Purpose | +| 函数 | 用途 | |---------------------------------------------------------------------|-----------------------------| -| `bus_alloc_resource_any(dev, type, &rid, flags)` | Allocate a resource. | -| `bus_release_resource(dev, type, rid, res)` | Release a resource. | -| `rman_get_bustag(res)` | Extract the tag. | -| `rman_get_bushandle(res)` | Extract the handle. | +| `bus_alloc_resource_any(dev, type, &rid, flags)` | 分配资源。 | +| `bus_release_resource(dev, type, rid, res)` | 释放资源。 | +| `rman_get_bustag(res)` | 提取标签。 | +| `rman_get_bushandle(res)` | 提取句柄。 | -### Types of Resource +### 资源类型 -| Constant | Meaning | +| 常量 | 含义 | |--------------------|--------------------------------| -| `SYS_RES_MEMORY` | Memory-mapped I/O region. | -| `SYS_RES_IOPORT` | I/O port range. | -| `SYS_RES_IRQ` | Interrupt line. | +| `SYS_RES_MEMORY` | 内存映射 I/O 区域。 | +| `SYS_RES_IOPORT` | I/O 端口范围。 | +| `SYS_RES_IRQ` | 中断线。 | -### Flags +### 标志 -| Constant | Meaning | +| 常量 | 含义 | |----------------|-----------------------------------------------| -| `RF_ACTIVE` | Activate the resource (establish mapping). | -| `RF_SHAREABLE` | The resource may be shared with other drivers.| +| `RF_ACTIVE` | 激活资源(建立映射)。 | +| `RF_SHAREABLE` | 资源可以与其他驱动程序共享。| -## Reference: Further Reading +## 参考:延伸阅读 -### Manual Pages +### 手册页 - `bus_space(9)`: the full API reference. - `bus_dma(9)`: DMA API (Chapter 20 reference). @@ -3100,7 +3102,7 @@ Flags: - `device(9)`: the device identity API. - `memguard(9)`: kernel memory debugging. -### Source Files +### 源文件 - `/usr/src/sys/sys/bus.h`: the bus shorthand macros and the resource API. - `/usr/src/sys/x86/include/bus.h`: the x86 bus_space implementation. @@ -3110,173 +3112,172 @@ Flags: - `/usr/src/sys/dev/uart/uart_dev_ns8250.c`: a register-heavy driver for a classic device. - `/usr/src/sys/dev/led/led.c`: a pseudo-device driver with no hardware. -### Reading Order +### 阅读顺序 -If you want to go deeper before Chapter 17, read in this order: +如果你想在第 17 章之前深入阅读,按以下顺序: -1. `/usr/src/sys/sys/bus.h`, the `bus_read_*` / `bus_write_*` shorthand-macro block (search for `#define bus_read_1`). -2. `/usr/src/sys/x86/include/bus.h` in full (the implementation). -3. `/usr/src/sys/dev/ale/if_alevar.h` in full (the softc, macros, constants). -4. `/usr/src/sys/dev/ale/if_ale.c` attach path (search for `bus_alloc_resource`). -5. `/usr/src/sys/dev/e1000/if_em.c` attach path (same search). +1. `/usr/src/sys/sys/bus.h`,`bus_read_*` / `bus_write_*` 简写宏块(搜索 `#define bus_read_1`)。 +2. `/usr/src/sys/x86/include/bus.h` 完整文件(实现)。 +3. `/usr/src/sys/dev/ale/if_alevar.h` 完整文件(softc、宏、常量)。 +4. `/usr/src/sys/dev/ale/if_ale.c` attach 路径(搜索 `bus_alloc_resource`)。 +5. `/usr/src/sys/dev/e1000/if_em.c` attach 路径(相同搜索)。 -Each reading is 15 to 45 minutes. The cumulative effect is a strong grasp of the idioms Chapter 16 introduced. +每次阅读需要 15 到 45 分钟。累积效果是对第 16 章引入的惯用法有扎实的掌握。 -## Reference: A Glossary of Chapter 16 Terms +## 参考:第 16 章术语词汇表 -### Terms Introduced in This Chapter +### 本章引入的术语 -**access log**: A ring buffer of recent register accesses, kept in the softc for debugging. +**access log(访问日志)**:softc 中保存的最近寄存器访问的环缓冲区,用于调试。 -**alignment**: The requirement that a register access's offset be a multiple of the access width. +**alignment(对齐)**:寄存器访问的偏移量必须是访问宽度倍数的要求。 -**barrier**: A function or instruction that enforces ordering between prior and subsequent memory accesses. +**barrier(屏障)**:强制先前和后续内存访问之间排序的函数或指令。 -**BAR (Base Address Register)**: On PCI, a device's register that advertises the physical address of its MMIO region. Chapter 18 treats BARs directly. +**BAR (Base Address Register,基址寄存器)**:PCI 上通告其 MMIO 区域物理地址的设备寄存器。第 18 章直接处理 BAR。 -**bus_space_handle_t**: An opaque identifier of a specific region within a bus address space. +**bus_space_handle_t**:总线地址空间内特定区域的不透明标识符。 -**bus_space_tag_t**: An opaque identifier of a bus address space (typically memory or I/O port). +**bus_space_tag_t**:总线地址空间(通常是内存或 I/O 端口)的不透明标识符。 -**CSR macro**: A driver-specific wrapper macro (e.g., `CSR_READ_4`) that abstracts register access behind a short name. +**CSR macro(CSR 宏)**:驱动程序特定的包装宏(如 `CSR_READ_4`),将寄存器访问抽象在短名称后面。 -**endianness**: The byte order in which a multi-byte register is laid out. Little-endian puts the low byte first; big-endian puts the high byte first. +**endianness(字节序)**:多字节寄存器的字节排列顺序。小端序将低字节放在前面;大端序将高字节放在前面。 -**field**: A sub-bit-range of a register, with its own name and meaning. +**field(字段)**:寄存器的子位范围,有自己的名称和含义。 -**firmware revision register**: A read-only register that reports the device's firmware version. +**firmware revision register(固件修订寄存器)**:报告设备固件版本的只读寄存器。 -**I/O port**: An x86-specific address space, accessed with `in` and `out` instructions. Contrasts with MMIO. +**I/O port(I/O 端口)**:x86 特定的地址空间,通过 `in` 和 `out` 指令访问。与 MMIO 相对。 -**MMIO (memory-mapped I/O)**: The mechanism where device registers are exposed as a range of physical addresses, reachable through ordinary load and store instructions. +**MMIO (memory-mapped I/O,内存映射 I/O)**:设备寄存器作为物理地址范围暴露、通过普通加载和存储指令到达的机制。 -**offset**: The distance, in bytes, from the start of a device region to a specific register. +**offset(偏移量)**:从设备区域起始处到特定寄存器的距离,以字节为单位。 -**PIO (port-mapped I/O)**: On x86, the alternative to MMIO, using separate I/O port instructions. +**PIO (port-mapped I/O,端口映射 I/O)**:x86 上 MMIO 的替代方案,使用独立的 I/O 端口指令。 -**region**: A contiguous range of device address space, or the API family that walks across offsets. +**region(区域)**:设备地址空间的连续范围,或跨偏移量步进的 API 系列。 -**register**: A named, offset-located, width-specific unit of communication between the driver and a device. +**register(寄存器)**:驱动程序与设备之间的命名的、按偏移量定位的、宽度特定的通信单元。 -**register map**: A table describing every register in a device's interface: offset, width, direction, meaning. +**register map(寄存器映射)**:描述设备接口中每个寄存器的表格:偏移量、宽度、方向、含义。 -**resource (FreeBSD)**: A named allocation from the bus subsystem, encapsulating a tag, handle, and ownership of a specific range. +**resource (FreeBSD)(资源)**:总线子系统的命名分配,封装标签、句柄和对特定范围的所有权。 -**sbuf**: The sbuf(9) kernel API for building variable-length strings, used by the access-log sysctl handler. +**sbuf**:用于构建可变长度字符串的 `sbuf(9)` 内核 API,被访问日志 sysctl 处理程序使用。 -**side effect (register)**: A change in device state that a read or write causes as part of its semantics, beyond returning or storing the value. +**side effect (register)(副作用)**:读写作为其语义的一部分导致的设备状态变化,超出返回或存储值的范围。 -**simulation**: In Chapter 16, the use of kernel memory allocated with `malloc(9)` to stand in for a device's MMIO region. +**simulation(模拟)**:在第 16 章中,用 `malloc(9)` 分配的内核内存替代设备的 MMIO 区域。 -**stream accessor**: A `bus_space_*_stream_*` variant that does not apply endian swaps. +**stream accessor(流式访问器)**:不应用字节序交换的 `bus_space_*_stream_*` 变体。 -**virtual mapping**: The MMU's translation from a virtual address to a physical address, with specific cache and access attributes. +**virtual mapping(虚拟映射)**:MMU 从虚拟地址到物理地址的转换,带有特定的缓存和访问属性。 -**width**: The bit count of a register or an access function's operand (8, 16, 32, 64). +**width(宽度)**:寄存器或访问函数操作数的位数(8、16、32、64)。 -### Terms Previously Introduced (Reminders) +### 之前引入的术语(提醒) -- **softc**: The per-instance driver state structure (Chapter 6). -- **device_t**: The kernel's identity for a device instance (Chapter 6). -- **malloc(9)**: The kernel allocator (Chapter 5). -- **WITNESS**: The kernel's lock-order checker (Chapter 11). -- **INVARIANTS**: The kernel's defensive assertion framework (Chapter 11). -- **callout**: A timer primitive that invokes a callback after a delay (Chapter 13). -- **taskqueue**: A deferred-work primitive (Chapter 14). -- **cv_wait / cv_timedwait_sig**: Condition-variable waits (Chapter 12, Chapter 15). +- **softc**:每实例驱动程序状态结构(第 6 章)。 +- **device_t**:内核对设备实例的标识(第 6 章)。 +- **malloc(9)**:内核分配器(第 5 章)。 +- **WITNESS**:内核的锁序检查器(第 11 章)。 +- **INVARIANTS**:内核的防御性断言框架(第 11 章)。 +- **callout**:延迟后调用回调的计时器原语(第 13 章)。 +- **taskqueue**:延迟工作原语(第 14 章)。 +- **cv_wait / cv_timedwait_sig**:条件变量等待(第 12 章、第 15 章)。 -## Reference: The Chapter 16 Driver Diff Summary +## 参考:第 16 章驱动程序差异摘要 -A compact view of what Chapter 16 added to the `myfirst` driver, stage by stage, for readers who want to see the whole arc on one page. +第 16 章逐阶段给 `myfirst` 驱动程序添加内容的紧凑视图,适合想在一页上看到全貌的读者。 -### Stage 1 (Section 4) +### 第 1 阶段(第 4 节) -- New file: `myfirst_hw.h` with register offsets, masks, fixed values. -- `regs_buf` and `regs_size` in softc; allocated and freed in attach/detach. -- Accessor helpers: `myfirst_reg_read`, `myfirst_reg_write`, `myfirst_reg_update`. -- Macros: `MYFIRST_REG_READ`, `MYFIRST_REG_WRITE`. -- Sysctls: `reg_ctrl`, `reg_status`, `reg_device_id`, `reg_firmware_rev` (read), `reg_ctrl_set` (write). -- Coupling: `myfirst_ctrl_update` on CTRL writes. -- Version tag: `0.9-mmio-stage1`. +- 新文件:`myfirst_hw.h`,包含寄存器偏移量、掩码和固定值。 +- softc 中的 `regs_buf` 和 `regs_size`;在 attach/detach 中分配和释放。 +- 访问器辅助函数和宏:`MYFIRST_REG_READ`、`MYFIRST_REG_WRITE`。 +- Sysctl:`reg_ctrl`、`reg_status`、`reg_device_id`、`reg_firmware_rev`(读取)、`reg_ctrl_set`(写入)。 +- 耦合:`myfirst_ctrl_update` 在 CTRL 写入时触发。 +- 版本标签:`0.9-mmio-stage1`。 -### Stage 2 (Section 5) +### 第 2 阶段(第 5 节) -- Added `regs_tag`, `regs_handle` in softc. -- Accessor bodies rewritten to use `bus_space_read_4` and `bus_space_write_4`. -- Write path updates `DATA_IN` and `STATUS.DATA_AV`. -- Read path updates `DATA_OUT` and clears `STATUS.DATA_AV` when the buffer drains. -- `reg_ticker_task` added; increments `SCRATCH_A` per tick. -- New sysctls: `reg_data_in`, `reg_data_out`, `reg_intr_mask`, `reg_intr_status`, `reg_scratch_a`, `reg_scratch_b`, `reg_ticker_enabled`. -- New document: `HARDWARE.md`. -- Version tag: `0.9-mmio-stage2`. +- softc 中添加 `regs_tag`、`regs_handle`。 +- 访问器主体重写为使用 `bus_space_read_4` 和 `bus_space_write_4`。 +- 写入路径更新 `DATA_IN` 和 `STATUS.DATA_AV`。 +- 读取路径更新 `DATA_OUT` 并在缓冲区排空时清除 `STATUS.DATA_AV`。 +- 添加 `reg_ticker_task`;每次 tick 递增 `SCRATCH_A`。 +- 新 sysctl:`reg_data_in`、`reg_data_out`、`reg_intr_mask`、`reg_intr_status`、`reg_scratch_a`、`reg_scratch_b`、`reg_ticker_enabled`。 +- 新文档:`HARDWARE.md`。 +- 版本标签:`0.9-mmio-stage2`。 -### Stage 3 (Section 6) +### 第 3 阶段(第 6 节) -- `MYFIRST_ASSERT` added to accessors. -- All register access paths acquire `sc->mtx`. -- Access log and its sysctls added (`access_log_enabled`, `access_log`). -- `myfirst_reg_write_barrier` helper for barrier-aware writes. -- `HARDWARE.md` extended with per-register ownership. -- Version tag: `0.9-mmio-stage3`. +- 访问器添加 `MYFIRST_ASSERT`。 +- 所有寄存器访问路径获取 `sc->mtx`。 +- 添加访问日志及其 sysctl(`access_log_enabled`、`access_log`)。 +- `myfirst_reg_write_barrier` 辅助函数用于带屏障的写入。 +- `HARDWARE.md` 扩展了每寄存器所有权。 +- 版本标签:`0.9-mmio-stage3`。 -### Stage 4 (Section 8) +### 第 4 阶段(第 8 节) -- File split: `myfirst_hw.c`, `myfirst_hw.h`, `myfirst.c`. -- `struct myfirst_hw` grouping of hardware state. -- `myfirst_hw_attach`, `myfirst_hw_detach`, `myfirst_hw_add_sysctls` APIs. -- `CSR_READ_4`, `CSR_WRITE_4`, `CSR_UPDATE_4` macros. -- `HARDWARE.md` finalised. -- Full regression pass. -- Version tag: `0.9-mmio`. +- 文件拆分:`myfirst_hw.c`、`myfirst_hw.h`、`myfirst.c`。 +- `struct myfirst_hw` 分组硬件状态。 +- `myfirst_hw_attach`、`myfirst_hw_detach`、`myfirst_hw_add_sysctls` API。 +- `CSR_READ_4`、`CSR_WRITE_4`、`CSR_UPDATE_4` 宏。 +- `HARDWARE.md` 定稿。 +- 完整回归测试。 +- 版本标签:`0.9-mmio`。 -### Lines of Code +### 代码行数 -- Stage 1 adds about 80 lines (header, accessor helpers, sysctls). -- Stage 2 adds about 90 lines (accessor rewrite, data-path coupling, ticker task). -- Stage 3 adds about 70 lines (locking, access log, barrier helper). -- Stage 4 is a net reorganisation: lines move between files but the total is roughly unchanged. +- 第 1 阶段添加约 80 行(头文件、访问器辅助函数、sysctl)。 +- 第 2 阶段添加约 90 行(访问器重写、数据路径耦合、ticker 任务)。 +- 第 3 阶段添加约 70 行(加锁、访问日志、屏障辅助函数)。 +- 第 4 阶段是净重组:行在文件之间移动,但总数大致不变。 -Total additions, Chapter 16: roughly 240 to 280 lines across four small stages. +第 16 章总计添加:约 240 到 280 行,分布在四个小阶段中。 -## Reference: A Comparison with Linux Device Register Access +## 参考:与 Linux 设备寄存器访问的比较 -Because many readers come to FreeBSD from Linux, a short comparison of the register-access vocabulary clarifies what translates and what does not. +因为许多读者从 Linux 转向 FreeBSD,简短比较寄存器访问词汇可以澄清哪些可以对应、哪些不能。 -### Linux: `ioremap` + `readl` / `writel` +### Linux:`ioremap` + `readl` / `writel` -Linux uses a different shape. A driver obtains a virtual address through `ioremap` (for MMIO) or uses the raw I/O port number directly (for PIO). Register access is performed through `readl(addr)` and `writel(value, addr)`, with variants for different widths (`readb`, `readw`, `readl`, `readq`). The `addr` is a kernel virtual pointer cast to a specific marker type. +Linux 使用不同的形式。驱动程序通过 `ioremap`(用于 MMIO)获取虚拟地址,或直接使用原始 I/O 端口号(用于 PIO)。寄存器访问通过 `readl(addr)` 和 `writel(value, addr)` 执行,有不同宽度的变体(`readb`、`readw`、`readl`、`readq`)。`addr` 是一个转换为特定标记类型的内核虚拟指针。 -### FreeBSD: `bus_alloc_resource` + `bus_read_*` / `bus_write_*` +### FreeBSD:`bus_alloc_resource` + `bus_read_*` / `bus_write_*` -FreeBSD uses the tag-and-handle abstraction. A driver obtains a `struct resource *` through `bus_alloc_resource_any`, then uses `bus_read_4` and `bus_write_4` on it. The tag and handle are extracted by the macro from the resource; the driver does not see them directly in most code. +FreeBSD 使用标签和句柄抽象。驱动程序通过 `bus_alloc_resource_any` 获取 `struct resource *`,然后对其使用 `bus_read_4` 和 `bus_write_4`。标签和句柄由宏从资源中提取;驱动程序在大多数代码中不直接看到它们。 -### What Translates +### 可对应的内容 -- The mental model: registers at fixed offsets, accessed by width, with barriers for ordering. -- The idea of defining a header of register offsets and bit masks. -- The idea of wrapping access in driver-specific macros (Linux's `read_reg32`, FreeBSD's `CSR_READ_4`). -- The discipline of lock-protected access for shared state. +- 心智模型:固定偏移量处的寄存器,按宽度访问,用屏障保证排序。 +- 定义寄存器偏移量和位掩码头文件的想法。 +- 用驱动程序特定宏包装访问的想法(Linux 的 `read_reg32`,FreeBSD 的 `CSR_READ_4`)。 +- 共享状态受锁保护访问的规范。 -### What Differs +### 不同的内容 -- FreeBSD carries an explicit tag that encodes the address-space type. Linux does not; the function variants choose the address space implicitly. -- FreeBSD's resource abstraction is more explicit about ownership and lifecycle. Linux's `ioremap` is a thinner wrapper. -- FreeBSD's barrier function takes offset and length arguments that bus bridges can use for narrow barriers. Linux's `mb`, `rmb`, `wmb`, and `mmiowb` are CPU-wide. -- FreeBSD's `bus_space` is usable for simulation (as in this chapter); Linux's equivalent path is less friendly for that use. +- FreeBSD 携带编码地址空间类型的显式标签。Linux 没有;函数变体隐式选择地址空间。 +- FreeBSD 的资源抽象在所有权和生命周期方面更明确。Linux 的 `ioremap` 是更薄的包装。 +- FreeBSD 的屏障函数接受偏移量和长度参数,总线桥可以使用它们进行窄屏障。Linux 的 `mb`、`rmb`、`wmb` 和 `mmiowb` 是 CPU 范围的。 +- FreeBSD 的 `bus_space` 可用于模拟(如本章所示);Linux 的等效路径对该用途不太友好。 -Porting a driver from Linux to FreeBSD or vice versa involves rewriting the register-access layer but not the register map, because the map is defined by the device, not the OS. A well-organised driver that keeps its register access behind CSR-style macros can have its CSR macros replaced with minimal other code changes. +将驱动程序从 Linux 移植到 FreeBSD 或反之涉及重写寄存器访问层,但不涉及寄存器映射,因为映射由设备定义而非操作系统定义。一个将寄存器访问保持在 CSR 风格宏后面的组织良好的驱动程序,可以仅替换 CSR 宏,而其他代码几乎不需要更改。 -## Reference: A Worked Example: The Full `myfirst_hw.h` +## 参考:完整示例:`myfirst_hw.h` -For reference, the complete Stage 4 header. This is what lives at `examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.h`. +供参考,完整的第 4 阶段头文件。它位于 `examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.h`。 ```c /* myfirst_hw.h -- Chapter 16 Stage 4 simulated hardware interface. */ @@ -3376,13 +3377,13 @@ void myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, #endif /* _MYFIRST_HW_H_ */ ``` -This single header is what the rest of the driver includes to gain access to the hardware interface. A newcomer reads it once and understands what registers exist, how they are accessed, and which macros the driver body uses. +这个头文件就是驱动程序其余部分包含以获取硬件接口访问权限的全部内容。新来者读一遍就能理解存在哪些寄存器、如何访问它们以及驱动程序主体使用哪些宏。 -## Reference: A Worked Example: The `myfirst_hw.c` Accessor Functions +## 参考:完整示例:`myfirst_hw.c` 访问器函数 -Complementing the header, the implementations. For reference and as a template. +作为头文件的补充,这里是实现。供参考和作为模板。 ```c /* myfirst_hw.c -- Chapter 16 Stage 4 hardware access layer. */ @@ -3485,13 +3486,13 @@ myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, } ``` -This is a complete, working file. The `myfirst_hw_attach`, `myfirst_hw_detach`, and `myfirst_hw_add_sysctls` functions follow in the same file; they are longer but follow the same patterns as Section 4's worked text. +这是一个完整的、可工作的文件。`myfirst_hw_attach`、`myfirst_hw_detach` 和 `myfirst_hw_add_sysctls` 函数在同一文件中紧随其后;它们更长但遵循与第 4 节文字说明中相同的模式。 -## Reference: A Minimal Stand-Alone Test Module +## 参考:最小独立测试模块 -For readers who want to practise `bus_space(9)` in isolation from the `myfirst` driver, here is a minimal stand-alone kernel module that allocates a kernel-memory "device", exposes it through sysctls, and lets the reader experiment. Save as `hwsim.c`: +对于想独立于 `myfirst` 驱动程序练习 `bus_space(9)` 的读者,这里有一个最小的独立内核模块,它分配一个内核内存"设备",通过 sysctl 暴露它,让读者可以实验。保存为 `hwsim.c`: ```c /* hwsim.c -- Chapter 16 stand-alone bus_space(9) practice module. */ @@ -3588,7 +3589,7 @@ SRCS= hwsim.c .include ``` -Build, load, and play: +构建、加载并体验: ```text # make clean && make @@ -3601,117 +3602,117 @@ Build, load, and play: # kldunload hwsim ``` -The module demonstrates `bus_space(9)` in its simplest possible form: a memory buffer, a tag, a handle, two register slots, a pair of sysctls. A reader who types this in and runs it has the whole vocabulary of Section 3 in about 80 lines of C. +该模块以最简单的可能形式演示了 `bus_space(9)`:一个内存缓冲区、一个标签、一个句柄、两个寄存器槽位、一对 sysctl。亲手输入并运行的读者在大约 80 行 C 代码中就获得了第 3 节的全部词汇。 -## Reference: Why `volatile` Matters in `bus_space` +## 参考:为什么 `volatile` 在 `bus_space` 中很重要 -A note on a subtle detail the chapter touched on but did not expand. +关于本章提及但未展开的一个微妙细节的说明。 -When `bus_space_read_4` on x86 expands to `*(volatile u_int32_t *)(handle + offset)`, the `volatile` qualifier is not decorative. It is load-bearing. +当 x86 上的 `bus_space_read_4` 展开为 `*(volatile u_int32_t *)(handle + offset)` 时,`volatile` 限定符不是装饰性的。它是承重的。 -Without `volatile`, the compiler assumes that reading a memory location twice in sequence, with no intervening store to that location, must return the same value. It is free to reorder, coalesce, or elide reads based on that assumption. For ordinary memory, the assumption holds: RAM does not change underneath you. For device memory, the assumption is wrong. A read might consume an event; a write might have immediate and visible effects that a subsequent read sees. +没有 `volatile`,编译器假设连续两次读取同一内存位置(中间没有对该位置的存储)必须返回相同的值。它可以基于该假设自由地重排序、合并或省略读取。对于普通内存,该假设成立:RAM 不会在你下面改变。对于设备内存,该假设是错误的。一次读取可能消费一个事件;一次写入可能有后续读取能看到的即时且可见的效果。 -The `volatile` qualifier tells the compiler: treat this access as having observable side effects. Do not reorder it with other volatile accesses. Do not elide it. Do not cache its result. Emit a load (or store) every time, exactly as written. +`volatile` 限定符告诉编译器:将此访问视为具有可观察的副作用。不要与其他 volatile 访问重排序。不要省略它。不要缓存其结果。每次都按书写的方式发出加载(或存储)。 -On x86, this is enough. The CPU's memory model is strong enough that once the load is emitted in program order, it executes in program order. On arm64, additional barriers are needed to enforce program order across CPU-level reordering, which is why `bus_space_barrier` on arm64 emits DMB or DSB instructions and on x86 emits only a compiler fence. +在 x86 上,这就够了。CPU 的内存模型足够强,一旦加载按程序顺序发出,它就按程序顺序执行。在 arm64 上,需要额外的屏障来跨 CPU 级重排序强制程序顺序,这就是为什么 arm64 上的 `bus_space_barrier` 发出 DMB 或 DSB 指令,而 x86 上只发出编译器围栏。 -The short rule: every time you write a hand-rolled accessor for device memory, use `volatile`. Every time you use `bus_space_*` directly, the `volatile` is already there. Every time you cast a pointer to device memory through a non-volatile type, you have a bug waiting to happen. +简短规则:每次你为设备内存编写手工访问器时,使用 `volatile`。每次你直接使用 `bus_space_*` 时,`volatile` 已经在那里了。每次你通过非 volatile 类型将指向设备内存的指针进行类型转换时,你都有一个等待发生的 bug。 -## Reference: A Short Comparison of Access Patterns in Real FreeBSD Drivers +## 参考:真实 FreeBSD 驱动程序中访问模式的简短比较 -An informal survey of patterns used in real drivers. Each example cites the file and the characteristic pattern; read the files themselves to see the pattern in context. +对真实驱动程序所用模式的非正式调查。每个示例引用文件和特征模式;阅读文件本身以在上下文中看到模式。 -**`/usr/src/sys/dev/ale/if_ale.c`**: Uses `CSR_READ_4(sc, reg)` and `CSR_WRITE_4(sc, reg, val)` macros defined in `if_alevar.h` over `bus_read_4` and `bus_write_4`. Softc holds `ale_res[]`, an array of resources. The pattern is clean and scales well. +**`/usr/src/sys/dev/ale/if_ale.c`**:使用 `if_alevar.h` 中定义在 `bus_read_4` 和 `bus_write_4` 之上的 `CSR_READ_4(sc, reg)` 和 `CSR_WRITE_4(sc, reg, val)` 宏。softc 持有 `ale_res[]` 资源数组。该模式干净且可扩展。 -**`/usr/src/sys/dev/e1000/if_em.c`**: Uses `E1000_READ_REG(hw, reg)` and `E1000_WRITE_REG(hw, reg, val)` that wrap `bus_space_read_4` and `bus_space_write_4` on the `osdep` struct's tag and handle. More indirection than `ale`, justified by Intel's cross-OS shared-code model. +**`/usr/src/sys/dev/e1000/if_em.c`**:使用 `E1000_READ_REG(hw, reg)` 和 `E1000_WRITE_REG(hw, reg, val)`,它们包装了 `osdep` 结构标签和句柄上的 `bus_space_read_4` 和 `bus_space_write_4`。比 `ale` 更多间接层,由 Intel 的跨操作系统共享代码模型证明其合理性。 -**`/usr/src/sys/dev/uart/uart_bus_pci.c`**: A glue driver that allocates resources and hands them to the generic UART subsystem. The register access happens in subsystem code (`uart_dev_ns8250.c`), not in the PCI glue. +**`/usr/src/sys/dev/uart/uart_bus_pci.c`**:一个分配资源并将其交给通用 UART 子系统的粘合驱动程序。寄存器访问发生在子系统代码(`uart_dev_ns8250.c`)中,而非 PCI 粘合层中。 -**`/usr/src/sys/dev/uart/uart_dev_ns8250.c`**: Direct `bus_read_1` and `bus_write_1` on a `struct uart_bas *` that holds tag and handle. Legacy 8-bit register layout. +**`/usr/src/sys/dev/uart/uart_dev_ns8250.c`**:直接在持有标签和句柄的 `struct uart_bas *` 上使用 `bus_read_1` 和 `bus_write_1`。传统 8 位寄存器布局。 -**`/usr/src/sys/dev/virtio/pci/virtio_pci_modern.c`**: Uses `bus_read_4` and `bus_write_4` through `struct resource *` fields in the softc. Chapter 18 uses virtio as a test target for real-PCI exercises. +**`/usr/src/sys/dev/virtio/pci/virtio_pci_modern.c`**:通过 softc 中的 `struct resource *` 字段使用 `bus_read_4` 和 `bus_write_4`。第 18 章使用 virtio 作为真实 PCI 练习的测试目标。 -**`/usr/src/sys/dev/random/ivy.c`** (Intel Ivy Bridge RDRAND): Uses CPU instructions directly (`rdrand`) rather than `bus_space`; this is an unusual case because the "device" is the CPU itself, accessible through inline assembly. +**`/usr/src/sys/dev/random/ivy.c`**(Intel Ivy Bridge RDRAND):直接使用 CPU 指令(`rdrand`)而非 `bus_space`;这是一个不寻常的情况,因为"设备"是 CPU 本身,通过内联汇编访问。 -Across all of these, the pattern is "wrap `bus_*` or `bus_space_*` in driver-specific macros, keep register offsets in a header, access registers through the macros in the body". Chapter 16's Stage 4 matches this convention. +在所有这些中,模式都是"将 `bus_*` 或 `bus_space_*` 包装在驱动程序特定的宏中,将寄存器偏移量保留在头文件中,通过宏在主体中访问寄存器"。第 16 章的第 4 阶段匹配这一惯例。 -## Reference: The Road Ahead in Part 4 +## 参考:第四部分的路线图 -A preview of how Chapter 16's material feeds into later chapters, for readers who like a single-page map. +第 16 章材料如何汇入后续章节的预览,适合喜欢单页地图的读者。 -**Chapter 17 (Simulating Hardware)**: Extends the simulation with dynamic behaviour. Timers change `STATUS` bits. Writing `CTRL.GO` triggers a delayed update. Errors can be injected. The register vocabulary stays the same; the simulation becomes richer. +**第 17 章(模拟硬件)**:用动态行为扩展模拟。计时器改变 `STATUS` 位。写入 `CTRL.GO` 触发延迟更新。错误可以被注入。寄存器词汇保持不变;模拟变得更丰富。 -**Chapter 18 (Writing a PCI Driver)**: Replaces the simulation with real PCI. `bus_alloc_resource_any` enters in earnest. Vendor and device IDs, BAR mapping, `pci_enable_busmaster`, `pciconf`. The simulation path remains available behind a compile-time flag for continued testing. +**第 18 章(编写 PCI 驱动程序)**:用真实 PCI 替换模拟。`bus_alloc_resource_any` 正式登场。供应商和设备 ID、BAR 映射、`pci_enable_busmaster`、`pciconf`。模拟路径在编译时标志后保持可用以继续测试。 -**Chapter 19 (Handling Interrupts)**: Adds `bus_setup_intr`, filter vs ithread, interrupt acknowledgement, the `INTR_STATUS` register's read-to-clear semantics in a real context. The Chapter 16 access log becomes invaluable for debugging interrupt sequences. +**第 19 章(处理中断)**:添加 `bus_setup_intr`、过滤器与 ithread、中断确认、`INTR_STATUS` 寄存器在真实上下文中的读即清除语义。第 16 章的访问日志对于调试中断序列变得无价。 -**Chapter 20 and Chapter 21 (DMA)**: Add `bus_dma(9)`. Register accesses become the control surface for DMA operations: set up a descriptor, write a doorbell register, wait for completion. The `bus_space_barrier` story becomes essential. +**第 20 章和第 21 章(DMA)**:添加 `bus_dma(9)`。寄存器访问成为 DMA 操作的控制面:设置描述符、写入门铃寄存器、等待完成。`bus_space_barrier` 的故事变得不可或缺。 -**Chapter 22 (Power Management)**: Suspend, resume, dynamic power states. Registers that save and restore device state. Most of the Part 4 vocabulary applies; power management adds a few more idioms. +**第 22 章(电源管理)**:挂起、恢复、动态电源状态。保存和恢复设备状态的寄存器。第 4 部分的大部分词汇适用;电源管理添加了更多一些惯用法。 -Each chapter introduces a new layer; Chapter 16's layer (the register) is the foundation for all of them. A reader who leaves Chapter 16 comfortable with `bus_space(9)` will find each subsequent chapter adds a new vocabulary on top of familiar ground. +每一章引入一个新层;第 16 章的层(寄存器)是所有这些层的基础。一个带着对 `bus_space(9)` 的舒适感离开第 16 章的读者会发现每个后续章节都在熟悉的地面上添加新词汇。 -## Reference: How to Read a Datasheet +## 参考:如何阅读数据手册 -Every real driver starts with a datasheet: the document the device's manufacturer publishes describing the register interface, the programming model, and the operational behaviour. Chapter 16 works with a simulated device, so there is no datasheet to consult. Later chapters point at real devices, and a driver author who is comfortable with datasheets will learn faster. +每个真实驱动程序都从数据手册开始:设备制造商发布的描述寄存器接口、编程模型和操作行为的文档。第 16 章使用模拟设备,所以没有数据手册可查阅。后续章节指向真实设备,熟悉数据手册的驱动程序作者会学得更快。 -A brief primer follows. The reader can skip this on first pass and return when Chapter 18 or a later chapter points at a real device's specification. +以下是简要入门。读者可以在第一次阅读时跳过,在第 18 章或后续章节指向真实设备规格时再回来。 -### The Shape of a Datasheet +### 数据手册的形状 -A datasheet is usually a PDF of fifty to fifteen hundred pages. It covers: +数据手册通常是 50 到 1500 页的 PDF。它涵盖: -- A functional overview (what the device does, at a high level). -- Pinout or physical interface description (what signals the device has, what they mean). -- Register reference (the mapping Chapter 16 has been teaching you to read). -- Programming model (the sequence of operations a driver must perform for each high-level action). -- Electrical characteristics (voltages, timings, environmental ratings). -- Package dimensions (mechanical data for the circuit board designer). +- 功能概述(设备做什么,高层级描述)。 +- 引脚或物理接口描述(设备有哪些信号,它们意味着什么)。 +- 寄存器参考(第 16 章一直在教你阅读的映射)。 +- 编程模型(驱动程序必须为每个高层级操作执行的操作序列)。 +- 电气特性(电压、时序、环境评级)。 +- 封装尺寸(电路板设计者的机械数据)。 -Driver authors care primarily about the register reference and the programming model. Everything else is for hardware designers. +驱动程序作者主要关心寄存器参考和编程模型。其他一切都是给硬件设计者的。 -### Reading the Register Reference +### 阅读寄存器参考 -The register reference is usually a series of tables, one per register, with the following columns: +寄存器参考通常是一系列表格,每个寄存器一个,包含以下列: -- Offset. -- Width. -- Reset value (the value the register has after power-on or reset). -- Access type (R, W, RW, R/W1C for read with write-one-to-clear, and so on). -- Field names and bit ranges. -- Field descriptions. +- 偏移量。 +- 宽度。 +- 复位值(加电或复位后寄存器的值)。 +- 访问类型(R、W、RW、R/W1C 表示读并写一清除等)。 +- 字段名称和位范围。 +- 字段描述。 -A seasoned driver author reads this table first, notes any unusual access types, and translates the register map into a C header with named offsets and bit masks. The translation is mechanical; the care is in getting every bit right. +经验丰富的驱动程序作者首先阅读这个表格,记录任何不寻常的访问类型,然后将寄存器映射翻译为包含命名偏移量和位掩码的 C 头文件。翻译是机械的;关键在于让每个位都正确。 -A particular note on **reset values**. The reset value tells you what the register reads immediately after the device has been powered on or reset. If the driver writes a field and later reads it back, the read should return the value written (not the reset value). But if the driver has not written the register, the read returns the reset value. Getting this wrong produces surprising bugs: the driver "sees" a register it did not initialise and misinterprets the reset value as a state change. +关于**复位值**的特别说明。复位值告诉你设备加电或复位后寄存器立即读取的值。如果驱动程序写了一个字段然后回读,读取应返回写入的值(而非复位值)。但如果驱动程序没有写过该寄存器,读取返回复位值。搞错这个会产生令人惊讶的 bug:驱动程序"看到"一个它没有初始化的寄存器,并将复位值误解释为状态变化。 -### Reading the Programming Model +### 阅读编程模型 -The programming model section describes the sequences of register operations required to drive the device. A typical entry looks like: +编程模型部分描述了驱动设备所需的寄存器操作序列。一个典型条目看起来像: -> **Transmit one packet.** -> 1. Confirm `STATUS.TX_READY` is set. -> 2. Write the packet data to `TX_BUF[0..n-1]` in order. -> 3. Write the packet length to `TX_LEN`. -> 4. Write `CTRL.TX_START`. -> 5. Wait for `STATUS.TX_DONE` to assert (may take up to 100us). -> 6. Clear `STATUS.TX_DONE` by writing 1 to the same bit. +> **发送一个数据包。** +> 1. 确认 `STATUS.TX_READY` 已设置。 +> 2. 将数据包数据按顺序写入 `TX_BUF[0..n-1]`。 +> 3. 将数据包长度写入 `TX_LEN`。 +> 4. 写入 `CTRL.TX_START`。 +> 5. 等待 `STATUS.TX_DONE` 置位(可能需要最多 100us)。 +> 6. 通过向同一位写 1 来清除 `STATUS.TX_DONE`。 -This sequence is what a driver's transmit path implements. The order of steps is fixed; reordering can leave the device in an inconsistent state. The driver's job is to translate each step into a `bus_space_write_*` or `bus_space_read_*` call, with the proper barriers and locking. +这个序列就是驱动程序发送路径要实现的。步骤顺序是固定的;重排序可能使设备进入不一致状态。驱动程序的工作是将每个步骤翻译为 `bus_space_write_*` 或 `bus_space_read_*` 调用,带适当的屏障和加锁。 -Most datasheets have several such sequences. A network device might have receive, transmit, link initialisation, error recovery, and shutdown sequences. Each is documented independently. +大多数数据手册有几个这样的序列。一个网络设备可能有接收、发送、链路初始化、错误恢复和关闭序列。每个都被独立记录。 -### Extracting the C Header +### 提取 C 头文件 -A skilled driver author reads the register reference once and produces a C header something like: +熟练的驱动程序作者阅读寄存器参考一次后,会生成一个类似这样的 C 头文件: ```c /* foo_regs.h -- derived from Foo Corp. Foo-9000 datasheet, rev 3.2. */ @@ -3730,37 +3731,37 @@ A skilled driver author reads the register reference once and produces a C heade /* ... and so on ... */ ``` -The header is where the driver's knowledge of the device's register interface lives. Keep it up to date with the datasheet; reference the datasheet revision in the header so future contributors know which version the offsets match. +头文件是驱动程序对设备寄存器接口知识的存放处。保持它与数据手册同步;在头文件中引用数据手册修订版本,以便未来贡献者知道偏移量匹配哪个版本。 -### A Pattern for Each Type of Register +### 每种类型寄存器的模式 -Different access types imply different coding patterns. +不同的访问类型意味着不同的编码模式。 -**Read-only, no side effect.** Read whenever. Cache if convenient. No locking needed beyond "do not read a register from a region that has been freed". +**只读,无副作用。** 随时读取。如果方便可以缓存。除了"不要读取已释放区域中的寄存器"之外不需要加锁。 -**Read-only, with side effect (read-to-clear).** Read exactly as often as the protocol requires. Do not add debug reads that clear state. Do not re-read to "confirm" a value. +**只读,有副作用(读即清除)。** 只按协议要求的频率读取。不要添加会清除状态的调试读取。不要重新读取来"确认"一个值。 -**Write-only.** Write with whatever value the protocol requires. Do not read it back; the read returns garbage. +**只写。** 用协议要求的任何值写入。不要回读;读取返回垃圾。 -**Read/write, no side effect.** Safe read-modify-write sequences under lock. +**读/写,无副作用。** 在锁下安全的读-改-写序列。 -**Read/write, with side effect on write.** Be careful with read-modify-write: the write of an unchanged bit may still trigger the side effect. Sometimes a datasheet documents this by saying "writes of 0 to bit X have no effect"; sometimes it does not, and the driver must be conservative. +**读/写,写入时有副作用。** 小心读-改-写:未改变的位的写入仍可能触发副作用。有时数据手册会说"向位 X 写入 0 无效果";有时不会,驱动程序必须保守。 -**Write-one-to-clear (W1C).** Common for interrupt status registers. Writing 1 to a bit clears it; writing 0 has no effect. Use `CSR_WRITE_4(sc, REG, mask_of_bits_to_clear)`, not a read-modify-write. +**写一清除(W1C)。** 中断状态寄存器常见。向某位写 1 清除它;写 0 无效果。使用 `CSR_WRITE_4(sc, REG, mask_of_bits_to_clear)`,而非读-改-写。 -### An Exercise: Pretend the Chapter 16 Device Has a Datasheet +### 练习:假装第 16 章的设备有一份数据手册 -To close this reference, practise extracting a register header from a "datasheet" for the Chapter 16 simulated device. Write a fake datasheet in prose describing each register, its reset value, its access type, and its field layout. Then produce the corresponding `myfirst_hw.h`. Compare your version with the one Chapter 16 provided. +为结束这个参考章节,练习从第 16 章模拟设备的"数据手册"中提取寄存器头文件。用散文写一份假数据手册,描述每个寄存器、其复位值、访问类型和字段布局。然后生成对应的 `myfirst_hw.h`。将你的版本与第 16 章提供的版本进行比较。 -The exercise builds the muscle you will need for every real device later in the book. +这个练习建立你后续在书中处理每个真实设备时将需要的肌肉记忆。 -## Reference: A Case Study in Missing Barriers +## 参考:缺失屏障的案例研究 -A short cautionary tale to make the barrier story concrete, using only the MMIO vocabulary Chapter 16 has already introduced. +一个简短的警示故事,用第 16 章已经引入的 MMIO 词汇使屏障故事具体化。 -Imagine a real device whose datasheet says: "To send a command, write the 32-bit command word into `CMD_DATA`, then write the 32-bit command code into `CMD_GO`. The device picks up the command word when `CMD_GO` is written." The driver expresses this sequence naively: +想象一个真实设备,其数据手册说:"要发送命令,先将 32 位命令字写入 `CMD_DATA`,然后将 32 位命令码写入 `CMD_GO`。设备在 `CMD_GO` 被写入时拾取命令字。"驱动程序天真地表达这个序列: ```c /* Step 1: write the command payload. */ @@ -3770,11 +3771,11 @@ CSR_WRITE_4(sc, MYFIRST_REG_CMD_DATA, payload); CSR_WRITE_4(sc, MYFIRST_REG_CMD_GO, opcode); ``` -On x86 this works. The x86 memory model guarantees that stores retire in program order from the CPU's point of view, and the compiler's `volatile`-annotated write inside `bus_space_write_4` prevents it from reordering the two statements. By the time `CMD_GO` reaches the device, `CMD_DATA` has already been written. +在 x86 上这可以工作。x86 内存模型保证存储从 CPU 的角度按程序顺序完成,`bus_space_write_4` 内部 `volatile` 注解的写入阻止编译器重排序两条语句。到 `CMD_GO` 到达设备时,`CMD_DATA` 已经被写入。 -On arm64 the same code can fail. The CPU is free to reorder the two stores at the memory subsystem level. The device can observe `CMD_GO` first, grab whatever stale value still sits in `CMD_DATA`, and execute a command the driver did not intend. The symptom is intermittent, load-dependent, and only appears on arm64 hardware. A driver tested only on x86 would ship with this bug undetected. +在 arm64 上相同代码可能失败。CPU 可以在内存子系统层面重排序两次存储。设备可能先观察到 `CMD_GO`,获取 `CMD_DATA` 中仍然留存的陈旧值,并执行驱动程序不打算发送的命令。症状是间歇性的、依赖负载的,且只在 arm64 硬件上出现。只在 x86 上测试的驱动程序会带着这个 bug 发布而不被发现。 -The fix is a one-line change: +修复是一行更改: ```c CSR_WRITE_4(sc, MYFIRST_REG_CMD_DATA, payload); @@ -3786,29 +3787,29 @@ bus_space_barrier(sc->hw->regs_tag, sc->hw->regs_handle, 0, sc->hw->regs_size, CSR_WRITE_4(sc, MYFIRST_REG_CMD_GO, opcode); ``` -On x86, `bus_space_barrier` with `BUS_SPACE_BARRIER_WRITE` emits only a compiler fence, which is free in instruction terms and preserves the program order the x86 CPU was already going to preserve. On arm64, it emits a `dmb` or `dsb` that forces the CPU to drain its store buffer before the next store is issued. The same source code does the right thing on both. +在 x86 上,带 `BUS_SPACE_BARRIER_WRITE` 的 `bus_space_barrier` 只发出编译器围栏,在指令方面是免费的,并保留了 x86 CPU 本来就会保留的程序顺序。在 arm64 上,它发出 `dmb` 或 `dsb`,强制 CPU 在下一条存储发出之前排空其存储缓冲区。相同的源代码在两个平台上都做了正确的事情。 -The tale makes three points. +这个故事说明了三个要点。 -**First, x86 gives driver authors a false sense of security.** Code tested only on x86 may pass every test yet be broken on arm64 in ways that manifest only under specific load patterns. +**第一,x86 给驱动程序作者虚假的安全感。** 只在 x86 上测试的代码可能通过每个测试,但在 arm64 上以只在特定负载模式下才出现的方式损坏。 -**Second, portability costs are tiny if you build them in early.** Adding a `bus_space_barrier` at the right spot is a one-line change. Diagnosing the bug a year later on an arm64 deployment is a week of work. +**第二,如果及早构建,可移植性代价微乎其微。** 在正确的位置添加 `bus_space_barrier` 是一行更改。一年后在 arm64 部署上诊断 bug 是一周的工作。 -**Third, the cost of barriers on x86 is negligible for typical drivers.** A compiler fence is free in instruction terms; it constrains the compiler's reordering, which for a driver's cold paths matters not at all. +**第三,x86 上屏障的代价对典型驱动程序可以忽略。** 编译器围栏在指令方面是免费的;它约束编译器的重排序,对驱动程序的冷路径来说根本不重要。 -A related family of ordering bugs appears when the driver writes to memory the device reads through DMA (a descriptor ring, for example) and then rings a doorbell register. That pattern needs a `bus_dmamap_sync` call, not just a `bus_space_barrier`; Chapter 20 teaches the DMA path in depth. The vocabulary is different, but the intuition (writes must drain before the doorbell) is the same. +一类相关的排序 bug 出现在驱动程序写入设备通过 DMA 读取的内存(例如描述符环),然后敲响门铃寄存器时。那个模式需要 `bus_dmamap_sync` 调用,而不仅是 `bus_space_barrier`;第 20 章深入教授 DMA 路径。词汇不同,但直觉(写入必须在门铃之前排空)是相同的。 -The discipline Chapter 16 encourages, even when the immediate benefit is invisible, pays off when the code runs on hardware the author never saw. +第 16 章鼓励的规范,即使即时收益不可见,当代码运行在作者从未见过的硬件上时也会得到回报。 -## Reference: Reading `if_ale.c` Step By Step +## 参考:逐步阅读 `if_ale.c` -A guided walk through the attach path of a real driver so the vocabulary of Chapter 16 lands in production code. Open `/usr/src/sys/dev/ale/if_ale.c`, jump to `ale_attach`, and follow along. +引导式浏览真实驱动程序。 -### Step 1: The Attach Entry Point +### 第 1 步:Attach 入口点 -The `ale_attach` function begins: +`ale_attach` 函数开始: ```c static int @@ -3825,11 +3826,11 @@ ale_attach(device_t dev) sc->ale_dev = dev; ``` -`device_get_softc(dev)` is the same pattern Chapter 6 introduced. Nothing new here. +`device_get_softc(dev)` 是第 6 章引入的相同模式。这里没有新东西。 -### Step 2: Early Locking Setup +### 第 2 步:早期加锁设置 -The driver initialises its data-path mutex, its callout, and its first task: +驱动程序初始化其数据路径互斥锁、callout 和第一个任务: ```c mtx_init(&sc->ale_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK, @@ -3838,9 +3839,9 @@ callout_init_mtx(&sc->ale_tick_ch, &sc->ale_mtx, 0); NET_TASK_INIT(&sc->ale_int_task, 0, ale_int_task, sc); ``` -Every line here came straight out of Part 3. The mutex is the Chapter 11 primitive; the lock-aware callout is the Chapter 13 primitive; the task is the Chapter 14 primitive. A reader who has done Part 3 recognises all three immediately. +这里的每一行都直接来自第 3 部分。互斥锁是第 11 章的原语;感知锁的 callout 是第 13 章的原语;任务是第 14 章的原语。完成第 3 部分的读者立刻认出这三者。 -### Step 3: PCI Bus-Mastering and Resource Allocation +### 第 3 步:PCI 总线主控和资源分配 ```c pci_enable_busmaster(dev); @@ -3853,13 +3854,13 @@ if (error != 0) { } ``` -`pci_enable_busmaster` is PCI-specific; Chapter 18 covers it. The `ale_res_spec` is a `struct resource_spec` array (defined earlier in the file) that describes which resources the driver wants. `bus_alloc_resources` (plural) takes the spec and fills in the `sc->ale_res` array with the allocated resources. This is a slight convenience wrapper over calling `bus_alloc_resource_any` in a loop; either pattern is common, and the Chapter 18 discussion of PCI resource allocation covers both. +`pci_enable_busmaster` 是 PCI 特有的;第 18 章涵盖它。`ale_res_spec` 是一个 `struct resource_spec` 数组(在文件前面定义),描述驱动程序想要哪些资源。`bus_alloc_resources`(复数)接受规格并填充 `sc->ale_res` 数组。这是循环调用 `bus_alloc_resource_any` 的轻微便利包装;两种模式都很常见,第 18 章对 PCI 资源分配的讨论涵盖两者。 -After this call, `sc->ale_res[0]` holds a `struct resource *` for the device's MMIO region, and the `CSR_READ_*` / `CSR_WRITE_*` macros (defined in `/usr/src/sys/dev/ale/if_alevar.h`, right after the softc structure) can be used to access registers through it. +此调用之后,`sc->ale_res[0]` 持有设备 MMIO 区域的 `struct resource *`,`CSR_READ_*` / `CSR_WRITE_*` 宏(在 `/usr/src/sys/dev/ale/if_alevar.h` 中,紧接 softc 结构之后定义)可以通过它访问寄存器。 -### Step 4: Reading the First Register +### 第 4 步:读取第一个寄存器 -The driver reads the `PHY_STATUS` register to decide which chip variant it is running on: +驱动程序读取 `PHY_STATUS` 寄存器来决定它运行在哪种芯片变体上: ```c if ((CSR_READ_4(sc, ALE_PHY_STATUS) & PHY_STATUS_100M) != 0) { @@ -3871,13 +3872,13 @@ if ((CSR_READ_4(sc, ALE_PHY_STATUS) & PHY_STATUS_100M) != 0) { } ``` -This is the first register access in `ale_attach`. It is a single `CSR_READ_4` call that returns a 32-bit value, masked against the `PHY_STATUS_100M` bit, and used to select a code path. The `ALE_PHY_STATUS` constant is a register offset defined in `/usr/src/sys/dev/ale/if_alereg.h`. The bit mask `PHY_STATUS_100M` is defined in the same header. +这是 `ale_attach` 中的第一次寄存器访问。它是一个单次 `CSR_READ_4` 调用,返回 32 位值,与 `PHY_STATUS_100M` 位进行掩码,用于选择代码路径。`ALE_PHY_STATUS` 常量是在 `/usr/src/sys/dev/ale/if_alereg.h` 中定义的寄存器偏移量。位掩码 `PHY_STATUS_100M` 定义在同一个头文件中。 -Every element of that one line is Chapter 16 vocabulary. `CSR_READ_4` expands to `bus_read_4` over the first resource; `bus_read_4` expands to `bus_space_read_4` over the tag and handle inside the resource; on x86 memory space, `bus_space_read_4` compiles to a single `mov` instruction. +那一行的每个元素都是第 16 章的词汇。`CSR_READ_4` 展开为第一个资源上的 `bus_read_4`;`bus_read_4` 展开为资源内部标签和句柄上的 `bus_space_read_4`;在 x86 内存空间上,`bus_space_read_4` 编译为单条 `mov` 指令。 -### Step 5: Reading More Registers +### 第 5 步:读取更多寄存器 -A few lines later the driver reads three more registers to gather chip-identification data: +几行之后,驱动程序读取另外三个寄存器来收集芯片识别数据: ```c sc->ale_chip_rev = CSR_READ_4(sc, ALE_MASTER_CFG) >> @@ -3887,9 +3888,9 @@ txf_len = CSR_READ_4(sc, ALE_SRAM_TX_FIFO_LEN); rxf_len = CSR_READ_4(sc, ALE_SRAM_RX_FIFO_LEN); ``` -Same pattern, three more registers. Notice the uninitialised-hardware check a few lines down, guarded by `sc->ale_chip_rev == 0xFFFF`: if any of the returned values looks like `0xFFFFFFFF`, the driver assumes the hardware is not correctly initialised and bails out with `ENXIO`. This kind of sanity check is a common, quiet habit in production drivers: hardware that returns all-ones on every register typically means the mapping is wrong, the device is not responding, or the device was power-gated and never brought up. +相同模式,再多三个寄存器。注意几行之后的未初始化硬件检查,由 `sc->ale_chip_rev == 0xFFFF` 保护:如果任何返回值看起来像 `0xFFFFFFFF`,驱动程序假设硬件未正确初始化并以 `ENXIO` 退出。这种健全性检查是生产驱动程序中常见、安静的习惯:在每个寄存器上返回全 1 的硬件通常意味着映射错误、设备未响应,或设备被电源门控且从未启动。 -### Step 6: IRQ Setup +### 第 6 步:IRQ 设置 Further down: @@ -3897,176 +3898,176 @@ Further down: error = bus_alloc_resources(dev, sc->ale_irq_spec, sc->ale_irq); ``` -IRQ resources get their own allocation. Chapter 19 covers what happens next: `bus_setup_intr`, the filter-ithread split, and the interrupt handler. +IRQ 资源有自己的分配。第 19 章涵盖接下来发生的事:`bus_setup_intr`、过滤器-ithread 拆分和中断处理程序。 -### Step 7: Reading the Whole File +### 第 7 步:阅读整个文件 -After the IRQ allocation, `ale_attach` continues with DMA tag creation (Chapter 20), ifnet registration (Chapter 28 in Part 6), PHY attach, and so on. Each step uses patterns that will be introduced by later chapters in this book. What Chapter 16 gave you is the vocabulary to read every `CSR_*` macro call without stopping. +IRQ 分配之后,`ale_attach` 继续 DMA 标签创建(第 20 章)、ifnet 注册(第 6 部分第 28 章)、PHY attach 等等。每一步都使用本书后续章节将引入的模式。第 16 章给你的是阅读每个 `CSR_*` 宏调用而不用停下来的词汇。 -The exercise that consolidates the walk: pick three `CSR_READ_4` or `CSR_WRITE_4` calls from anywhere in `/usr/src/sys/dev/ale/if_ale.c`, look up the register offset in `if_alereg.h`, decode the bit mask in the same header, and write one sentence explaining what the driver is doing at that call site. If you can do that for three arbitrary calls, you have internalised the vocabulary this chapter taught. +巩固这次浏览的练习:从 `/usr/src/sys/dev/ale/if_ale.c` 的任意位置选择三个 `CSR_READ_4` 或 `CSR_WRITE_4` 调用,在 `if_alereg.h` 中查找寄存器偏移量,在同一个头文件中解码位掩码,写一句话解释驱动程序在那个调用点在做什么。如果你能为三个任意调用做到这一点,你就已经内化了本章教授的词汇。 -## Reference: An Honest Accounting of Chapter 16's Simplifications +## 参考:第 16 章简化处理的诚实说明 -A chapter that teaches a small slice of a large topic inevitably simplifies. For honesty with the reader, a catalogue of what Chapter 16 simplified and what the full story looks like. +教授大主题的一个小切片的章节不可避免地会简化。为了对读者诚实,这里列出第 16 章简化了什么以及完整故事是什么样的。 -### The Simulated Tag +### 模拟标签 -Chapter 16's simulation uses `X86_BUS_SPACE_MEM` as the tag and a kernel virtual address as the handle. On x86 this works because the x86 `bus_space_read_*` functions reduce to a `volatile` dereference of `handle + offset` for memory space. On other architectures the trick fails because the tag is not an integer; it is a pointer to a structure, and manufacturing one by hand requires reproducing the structure the platform's `bus_space` expects. +第 16 章的模拟使用 `X86_BUS_SPACE_MEM` 作为标签,使用内核虚拟地址作为句柄。在 x86 上这可以工作,因为 x86 的 `bus_space_read_*` 函数对于内存空间简化为 `handle + offset` 的 `volatile` 解引用。在其他架构上这个技巧失败,因为标签不是整数;它是指向结构的指针,手工构造一个需要复制平台 `bus_space` 期望的结构。 -The full story: real drivers never manufacture a tag; they receive one from the bus subsystem through `rman_get_bustag`. The Chapter 16 simulation shortcut is pedagogical, and the chapter explicitly marks it as x86-only. Chapter 17's richer simulation introduces a portable alternative, and Chapter 18's real PCI path retires the shortcut entirely. +完整故事:真实驱动程序从不手工制造标签;它们通过 `rman_get_bustag` 从总线子系统接收。第 16 章的模拟快捷方式是教学性的,本章明确将其标记为仅限 x86。第 17 章更丰富的模拟引入可移植的替代方案,第 18 章的真实 PCI 路径完全淘汰了这个快捷方式。 -### The Register Protocol +### 寄存器协议 -The simulated device's registers have no side effects on read or write. `STATUS` is set by the driver; it does not change autonomously. `DATA_IN` is written by the driver; it does not forward the write to an imaginary downstream consumer. `INTR_STATUS` is a plain register, not read-to-clear. +模拟设备的寄存器在读写时没有副作用。`STATUS` 由驱动程序设置;它不会自主改变。`DATA_IN` 由驱动程序写入;它不会将写入转发给想象的下游消费者。`INTR_STATUS` 是普通寄存器,不是读即清除的。 -The full story: real devices have protocols. Reading a status register may consume an event. Writing a command register may trigger a multi-cycle operation inside the device. The driver's job is to follow the protocol exactly; a single missed step produces a misbehaving device. Chapter 17 introduces some of this complexity by adding a callout-driven protocol: a write triggers a delayed status change. +完整故事:真实设备有协议。读取状态寄存器可能消费一个事件。写入命令寄存器可能触发设备内部的多周期操作。驱动程序的工作是精确遵循协议;单个遗漏的步骤产生行为不当的设备。第 17 章通过添加 callout 驱动的协议引入部分这种复杂性:一次写入触发延迟的状态改变。 -### Locking Granularity +### 加锁粒度 -Chapter 16 uses a single driver mutex (`sc->mtx`) for all register access. In practice, real drivers sometimes split locks: a fast-path lock for per-packet register writes (in a network driver) and a slower lock for configuration changes. Splitting increases concurrency at the cost of more locking discipline. +第 16 章对所有寄存器访问使用单个驱动程序互斥锁(`sc->mtx`)。在实践中,真实驱动程序有时拆分锁:网络驱动程序中用于每包寄存器写入的快速路径锁和用于配置更改的较慢锁。拆分以更多加锁规范为代价增加并发性。 -The full story: lock splitting is a performance tuning decision that belongs to later chapters on scaling and profiling. Chapter 16 uses a single lock because it is the simplest correct design, and because the driver's throughput requirements are nowhere near where lock contention matters. +完整故事:锁拆分是属于后续关于扩展和性能分析章节的性能调优决策。第 16 章使用单个锁是因为它是最简单的正确设计,而且驱动程序的吞吐量需求远未达到锁竞争有影响的地步。 -### Endianness +### 字节序 -Chapter 16 assumes host byte order for all register values. Real devices sometimes use a different byte order than the host CPU. The `_stream_` variants of `bus_space` handle this; Chapter 16 does not use them. +第 16 章假设所有寄存器值使用主机字节序。真实设备有时使用与主机 CPU 不同的字节序。`bus_space` 的 `_stream_` 变体处理这个;第 16 章不使用它们。 -The full story: FreeBSD's `bus_space` API supports per-tag byte-swap semantics. A driver whose device is big-endian on a little-endian CPU uses either a swap-aware tag or the `_stream_` variants plus explicit `htobe32`/`be32toh` conversions. Chapter 16's simulation is host-endian, so the issue does not arise; real drivers for big-endian devices handle it explicitly. +完整故事:FreeBSD 的 `bus_space` API 支持每标签字节交换语义。设备为大端序而 CPU 为小端序的驱动程序使用交换感知标签或 `_stream_` 变体加显式 `htobe32`/`be32toh` 转换。第 16 章的模拟是主机字节序的,所以问题不出现;大端序设备的真实驱动程序显式处理它。 -### Cache Attributes +### 缓存属性 -Chapter 16's `malloc(9)` allocation produces ordinary cacheable kernel memory. Real device memory is mapped with different cache attributes (uncached, write-combining, device-strongly-ordered) depending on the platform and the device's requirements. +第 16 章的 `malloc(9)` 分配产生普通可缓存内核内存。真实设备内存根据平台和设备要求使用不同的缓存属性(不可缓存、写合并、设备强序)映射。 -The full story: `bus_alloc_resource_any` with `RF_ACTIVE` on a real PCI BAR produces a mapping with the right cache attributes. The simulation does not go through this path; it uses plain cacheable memory. Under Chapter 16's patterns (serialised access, volatile accesses), the cache attribute difference does not manifest. In Chapter 18's real-PCI path, the allocation flow takes care of it. +完整故事:真实 PCI BAR 上带 `RF_ACTIVE` 的 `bus_alloc_resource_any` 产生具有正确缓存属性的映射。模拟不经过这个路径;它使用普通可缓存内存。在第 16 章的模式下(串行化访问、volatile 访问),缓存属性差异不会显现。在第 18 章的真实 PCI 路径中,分配流程负责处理它。 -### Error Handling +### 错误处理 -Chapter 16's simulated device never returns an error from a register access. Real hardware sometimes does: a read may time out, a write may be rejected, a bus may hang. The driver must handle these. +第 16 章的模拟设备从不在寄存器访问中返回错误。真实硬件有时会:读取可能超时、写入可能被拒绝、总线可能挂起。驱动程序必须处理这些。 -The full story: FreeBSD provides `bus_peek_*` and `bus_poke_*` variants (since FreeBSD 13) that return an error if the access faults. Chapter 16 does not use them because the simulation cannot fault. Chapter 19 introduces them in the context of interrupt handlers that may touch a device in an uncertain state. +完整故事:FreeBSD 提供 `bus_peek_*` 和 `bus_poke_*` 变体(自 FreeBSD 13 起),在访问出错时返回错误。第 16 章不使用它们因为模拟不会出错。第 19 章在中断处理程序可能触摸处于不确定状态设备的上下文中引入它们。 -### Interrupts +### 中断 -Chapter 16's driver polls registers through callouts and syscall paths. Real drivers typically use interrupts to know when to read a register. +第 16 章的驱动程序通过 callout 和系统调用路径轮询寄存器。真实驱动程序通常使用中断来知道何时读取寄存器。 -The full story: interrupts are Chapter 19's topic. Chapter 16's polling pattern is a stepping stone; after Chapter 19 the driver will have an interrupt handler that replaces much of the polling logic. +完整故事:中断是第 19 章的主题。第 16 章的轮询模式是垫脚石;第 19 章之后驱动程序将拥有替换大部分轮询逻辑的中断处理程序。 ### DMA -Chapter 16's driver does not use DMA. Every byte flowing through the driver is copied by the CPU, register by register. +第 16 章的驱动程序不使用 DMA。流经驱动程序的每个字节由 CPU 逐寄存器复制。 -The full story: real high-throughput devices use DMA for bulk data. The driver programs the device's DMA engine through registers, then the device reads or writes system RAM directly. Chapter 20 and Chapter 21 cover the DMA API. +完整故事:真实高吞吐量设备使用 DMA 进行批量数据传输。驱动程序通过寄存器编程设备的 DMA 引擎,然后设备直接读取或写入系统 RAM。第 20 章和第 21 章涵盖 DMA API。 -### Summary +### 总结 -Chapter 16 is an on-ramp. Every simplification it makes is deliberate, named, and picked up by a later chapter. The vocabulary Chapter 16 teaches is the vocabulary every later chapter extends; the discipline Chapter 16 builds is the discipline every later chapter relies on. The chapter is short of the full hardware story on purpose. Subsequent chapters fill in the rest. +第 16 章是一条入口匝道。它所做的每一个简化都是刻意的、有命名的,并由后续章节承接。第 16 章教授的词汇是每个后续章节扩展的词汇;第 16 章建立的规范是每个后续章节依赖的规范。本章故意没有讲述完整的硬件故事。后续章节填补其余部分。 -## Reference: A Quick Reference for Common MMIO Bugs +## 参考:常见 MMIO Bug 速查 -When a driver misbehaves, the bug is often in a small set of recurring categories. A quick reference to recognise each. +当驱动程序行为异常时,bug 通常在一小组反复出现的类别中。快速参考以识别每一个。 -### 1. Off-by-One in the Register Map +### 1. 寄存器映射中的差一错误 -**Symptom**: A read returns a plausible but wrong value, or a write has no effect. +**症状**:读取返回一个合理但错误的值,或写入没有效果。 -**Cause**: An offset in the driver's header is one or two or four bytes off from the datasheet. +**原因**:驱动程序头文件中的偏移量比数据手册差了一、两或四个字节。 -**Diagnosis**: Cross-check the header against the datasheet, register by register. +**诊断**:将头文件与数据手册逐寄存器交叉核对。 -**Fix**: Correct the offset. +**修复**:更正偏移量。 -### 2. Wrong Access Width +### 2. 错误的访问宽度 -**Symptom**: A read returns a value that looks like only part of the register, or a write affects only part of the register. +**症状**:读取返回的值看起来只是寄存器的一部分,或写入只影响寄存器的一部分。 -**Cause**: The driver uses `bus_read_4` on a 16-bit register or vice versa. +**原因**:驱动程序在 16 位寄存器上使用 `bus_read_4` 或反之。 -**Diagnosis**: Check the datasheet's width column against the accessor suffix. +**诊断**:将数据手册的宽度列与访问器后缀核对。 -**Fix**: Use the correct width. +**修复**:使用正确的宽度。 -### 3. Missing Volatile Qualifier in a Hand-Rolled Accessor +### 3. 手写访问器中缺少 Volatile 限定符 -**Symptom**: The compiler optimises away a register access, and the driver misses a state change. +**症状**:编译器优化掉了寄存器访问,驱动程序错过了状态变化。 -**Cause**: A driver that wraps `bus_space_*` in a non-volatile intermediate loses the volatile annotation. +**原因**:将 `bus_space_*` 包装在非 volatile 中间层的驱动程序丢失了 volatile 注解。 -**Diagnosis**: Audit any custom accessor that is not a direct `bus_space_*` call. +**诊断**:审计任何非直接 `bus_space_*` 调用的自定义访问器。 -**Fix**: Keep accessors as simple wrappers around `bus_space_*`; do not introduce intermediate variables without `volatile`. +**修复**:保持访问器为 `bus_space_*` 的简单包装;不要在没有 `volatile` 的情况下引入中间变量。 -### 4. Lost Update in Read-Modify-Write +### 4. 读-改-写中的更新丢失 -**Symptom**: A bit set by the driver disappears; another bit set by a second context disappears. +**症状**:驱动程序设置的位消失了;第二个上下文设置的另一个位也消失了。 -**Cause**: Two contexts do RMW on the same register without a lock; one clobbers the other. +**原因**:两个上下文在没有锁的情况下对同一寄存器进行 RMW;一个覆盖另一个。 -**Diagnosis**: Use the access log or DTrace to observe two writes in rapid succession. +**诊断**:使用访问日志或 DTrace 观察两次快速连续的写入。 -**Fix**: Protect RMW with the driver mutex, or use a write-one-to-clear idiom if the hardware supports it. +**修复**:用驱动程序互斥锁保护 RMW,或在硬件支持时使用写一清除惯用法。 -### 5. Missing Barrier Before a Doorbell +### 5. 门铃前缺少屏障 -**Symptom**: The device sometimes reads stale descriptor data or wrong command buffers. +**症状**:设备有时读取陈旧的描述符数据或错误的命令缓冲区。 -**Cause**: The descriptor writes are reordered past the doorbell register write (on arm64 or other weakly-ordered platforms). +**原因**:描述符写入被重排序到门铃寄存器写入之后(在 arm64 或其他弱序平台上)。 -**Diagnosis**: The symptom is often transient and load-dependent. +**诊断**:症状通常是瞬时和依赖负载的。 -**Fix**: Insert `bus_barrier` with `BUS_SPACE_BARRIER_WRITE` between the descriptor writes and the doorbell. +**修复**:在描述符写入和门铃之间插入带 `BUS_SPACE_BARRIER_WRITE` 的 `bus_barrier`。 -### 6. Reading a Write-Only Register +### 6. 读取只写寄存器 -**Symptom**: The driver reads a register and gets zero or garbage; based on that value, it takes the wrong action. +**症状**:驱动程序读取寄存器得到零或垃圾值;基于该值采取错误行动。 -**Cause**: The register is marked write-only in the datasheet; reads return a fixed value unrelated to state. +**原因**:寄存器在数据手册中标记为只写;读取返回与状态无关的固定值。 -**Diagnosis**: Check the access type in the datasheet. +**诊断**:检查数据手册中的访问类型。 -**Fix**: Do not read write-only registers. If you need to remember the last written value, cache it in the softc. +**修复**:不要读取只写寄存器。如果需要记住最后写入的值,在 softc 中缓存它。 -### 7. Unexpected Side Effect on Read +### 7. 读取时的意外副作用 -**Symptom**: A debug read changes driver behaviour. +**症状**:调试读取改变了驱动程序行为。 -**Cause**: The register has read-to-clear semantics and the debug read consumes an event. +**原因**:寄存器具有读即清除语义,调试读取消费了一个事件。 -**Diagnosis**: Disable the debug read; if the issue disappears, the read was the culprit. +**诊断**:禁用调试读取;如果问题消失,读取就是罪魁祸首。 -**Fix**: Cache the value in the softc on the protocol-driven read; expose the cached value through the debug interface. +**修复**:在协议驱动的读取中将值缓存在 softc 中;通过调试接口暴露缓存值。 -### 8. Dangling Tag or Handle +### 8. 悬空的标签或句柄 -**Symptom**: Kernel panic on the first register access, with a fault at an address that does not look like the mapped region. +**症状**:首次寄存器访问时内核 panic,故障地址看起来不像映射区域。 -**Cause**: The driver stored a tag and handle before allocation completed, or kept them after release. +**原因**:驱动程序在分配完成前存储了标签和句柄,或在释放后保留了它们。 -**Diagnosis**: `MYFIRST_ASSERT` firing; `regs_buf == NULL` in the panic. +**诊断**:`MYFIRST_ASSERT` 触发;panic 中 `regs_buf == NULL`。 -**Fix**: Set the tag and handle only after successful allocation; clear them (or null the `sc->hw` pointer) before release. +**修复**:仅在成功分配后设置标签和句柄;在释放前清除它们(或置空 `sc->hw` 指针)。 -### 9. Sysctl Handler Without Lock +### 9. 没有锁的 Sysctl 处理程序 -**Symptom**: WITNESS warning about an unprotected register access, or rare incorrect values observed from user space. +**症状**:WITNESS 警告未受保护的寄存器访问,或从用户空间观察到罕见的不正确值。 -**Cause**: A sysctl handler reads or writes a register without acquiring the driver lock. +**原因**:sysctl 处理程序在未获取驱动程序锁的情况下读取或写入寄存器。 -**Diagnosis**: The `MYFIRST_ASSERT` inside the accessor produces a WITNESS entry. +**诊断**:访问器内的 `MYFIRST_ASSERT` 产生 WITNESS 条目。 -**Fix**: Wrap the register access in `MYFIRST_LOCK`/`MYFIRST_UNLOCK`. +**修复**:将寄存器访问包装在 `MYFIRST_LOCK`/`MYFIRST_UNLOCK` 中。 -### 10. Detach Races +### 10. Detach 竞争 -**Symptom**: Kernel panic during `kldunload` with a stack that includes a register access. +**症状**:`kldunload` 期间内核 panic,栈中包含寄存器访问。 -**Cause**: A callout or task accesses registers after the register buffer has been freed. +**原因**:callout 或任务在寄存器缓冲区释放后访问寄存器。 -**Diagnosis**: `regs_buf == NULL` in the panic; the caller is a task or callout that was not drained before the free. +**诊断**:panic 中 `regs_buf == NULL`;调用者是释放前未排空的任务或 callout。 -**Fix**: Review detach ordering; drain all callouts and tasks before freeing `regs_buf`. +**修复**:审查 detach 排序;在释放 `regs_buf` 之前排空所有 callout 和任务。 -Each of these bugs has a short diagnostic path and a well-defined fix. Keeping the list nearby during development catches most issues on first contact. +这些 bug 中的每一个都有简短的诊断路径和明确定义的修复。在开发期间将此列表放在身边可以在首次接触时捕获大多数问题。 diff --git a/translations/zh_CN/chapters/part4/chapter-20.md b/translations/zh_CN/chapters/part4/chapter-20.md index 4655a0c..36d0d1f 100644 --- a/translations/zh_CN/chapters/part4/chapter-20.md +++ b/translations/zh_CN/chapters/part4/chapter-20.md @@ -1922,7 +1922,7 @@ fail_vectors: - `vmstat -i` 条目仍然存在意味着该向量没有调用 `bus_teardown_intr`。 - `vmstat -m` 泄漏意味着每向量任务没有被排空或任务队列没有被释放。 -- A `devinfo -v` entry remaining (rare) means the device's detach did not complete. +- `devinfo -v` 条目仍然存在(罕见)意味着设备的detach未完成。 ### 跨加载-卸载周期的MSI资源泄漏 @@ -1992,7 +1992,7 @@ Makefile - kmod build HARDWARE.md, LOCKING.md, SIMULATION.md, PCI.md, INTERRUPTS.md, MSIX.md (NEW) ``` -`myfirst_msix.c` and `myfirst_msix.h` are new. `MSIX.md` is new. The Chapter 19 `myfirst_intr.c` stays; it now handles the legacy-INTx fallback while `myfirst_msix.c` handles the MSI and MSI-X path. +`myfirst_msix.c` 和 `myfirst_msix.h` 是新文件。`MSIX.md` 是新文档。第19章的 `myfirst_intr.c` 保留;它现在处理 legacy-INTx 回退,而 `myfirst_msix.c` 处理 MSI 和 MSI-X 路径。 ### myfirst_msix.h头文件 @@ -2063,7 +2063,7 @@ SRCS 列表中增加一个源文件;版本字符串升级。 ### 版本字符串 -`1.2-intr` to `1.3-msi`. The bump reflects a significant capability addition: multi-vector interrupt handling. A minor-version bump is appropriate; the user-visible interface (the cdev) did not change. +`1.2-intr` 到 `1.3-msi`。版本升级反映了一项重要的能力添加:多向量中断处理。次版本号升级是合适的;用户可见的接口(cdev)未改变。 ### MSIX.md文档 @@ -2263,16 +2263,16 @@ vtpci_register_msix_vectors(struct vtpci_common *cn) } ``` -Two things match Chapter 20: +有两件事与第20章匹配: -- `rid = 1` for the first vector, incrementing per vector. -- The filter (here `NULL`) and handler (`vtpci_vq_handler`) pattern. Note that virtio uses an ithread-only handler (filter=NULL), not a filter-plus-task pipeline. This is a simpler option that works for virtio's per-vector work. +- 第一个向量的 `rid = 1`,每个向量递增。 +- 过滤器(此处为 `NULL`)和处理程序(`vtpci_vq_handler`)模式。注意 virtio 使用仅 ithread 的处理程序(filter=NULL),而不是过滤器加任务的管道。这是更简单的选项,适用于 virtio 的每向量工作。 -The `vtpci_vq_handler` function is the per-vector worker. Each vector gets its own argument (`&cn->vtpci_vectors[i]`), and the handler uses that argument to identify which virtqueue to service. +`vtpci_vq_handler` 函数是每向量的工作线程。每个向量获得自己的参数(`&cn->vtpci_vectors[i]`),处理程序使用该参数来识别要服务的虚拟队列。 ### 拆除 -Virtio's teardown follows the Chapter 20 pattern: +Virtio 的拆除遵循第20章的模式: ```c static void @@ -2298,51 +2298,51 @@ vtpci_release_intr_resources(struct vtpci_common *cn) } ``` -Per-vector teardown (bus_teardown_intr + bus_release_resource), then a single `pci_release_msi` at the end. The order matches Chapter 20's `myfirst_msix_teardown`. +每向量拆除(bus_teardown_intr + bus_release_resource),最后单个 `pci_release_msi`。该顺序与第20章的 `myfirst_msix_teardown` 匹配。 -A detail worth noting: virtio uses `rman_get_rid` to recover the rid from the resource, rather than storing it separately. Chapter 20's driver stores the rid in the per-vector struct; both approaches are fine, but the storage approach is clearer and easier to debug. +一个值得注意的细节:virtio 使用 `rman_get_rid` 从资源中恢复 rid,而不是单独存储它。第20章的驱动程序将 rid 存储在每向量结构中;两种方法都可以,但存储方法更清晰且更易于调试。 ### Virtio演示教学的内容 -Three lessons transfer directly to Chapter 20's design: +三个教训直接迁移到第20章的设计: -1. **The three-tier fallback ladder is the standard pattern**. Every driver that wants to work on a range of hardware implements it the same way. -2. **Per-vector resource management uses incrementing rids starting at 1**. This is universal in FreeBSD's PCI infrastructure. -3. **`pci_release_msi` is called once, regardless of the number of vectors**. The per-vector teardown releases IRQ resources; the device-level release handles the MSI state. +1. **三层回退阶梯是标准模式**。每个想在多种硬件上工作的驱动程序都以相同方式实现它。 +2. **每向量资源管理使用从1开始递增的rid**。这在FreeBSD的PCI基础设施中是通用的。 +3. **`pci_release_msi` 只调用一次,无论向量数量多少**。每向量拆除释放IRQ资源;设备级释放处理MSI状态。 -A reader who can follow `vtpci_alloc_intr_resources` end to end has internalised the Chapter 20 vocabulary. For a richer example, `/usr/src/sys/dev/nvme/nvme_ctrlr.c` shows the same pattern at scale, with one admin vector plus up to `NCPU` I/O vectors. +能够端到端理解 `vtpci_alloc_intr_resources` 的读者已经内化了第20章的词汇。对于更丰富的示例,`/usr/src/sys/dev/nvme/nvme_ctrlr.c` 展示了大规模下的相同模式,带有一个管理向量加上最多 `NCPU` 个I/O向量。 ## 深入了解向量到 CPU 放置 -Section 5 introduced `bus_bind_intr(9)` briefly. This section goes a level deeper into why CPU placement matters, how real drivers choose CPUs, and what the trade-offs are. +第5节简要介绍了 `bus_bind_intr(9)`。本节深入探讨为什么CPU放置很重要,真实驱动如何选择CPU,以及权衡是什么。 ### NUMA图景 -On a single-socket system, all CPUs share a single memory controller and a single cache hierarchy. Placement between CPUs matters only for cache affinity (the handler's code and data will be warm on whichever CPU last ran it). The performance difference between "CPU 0" and "CPU 3" is small. +在单插槽系统上,所有CPU共享单个内存控制器和单个缓存层次结构。CPU之间的放置仅对缓存亲和性重要(处理程序的代码和数据在上次运行它的CPU上会是热的)。"CPU 0"和"CPU 3"之间的性能差异很小。 -On a multi-socket NUMA system, the picture changes. Each socket has its own memory controller, its own L3 cache, and its own PCIe root complex. A PCIe device attached to socket 0 sits on that socket's root complex; its registers are memory-mapped to an address range handled by socket 0's controller. An interrupt from that device fires; the handler reads `INTR_STATUS`; the read goes to the device's BAR, which is on socket 0; the CPU that runs the handler must be on socket 0, or the read crosses the inter-socket interconnect. +在多插槽NUMA系统上,情况发生了变化。每个插槽有自己的内存控制器、自己的L3缓存和自己的PCIe根复合体。连接到插槽0的PCIe设备位于该插槽的根复合体上;其寄存器通过内存映射到由插槽0控制器处理的地址范围。来自该设备的中断触发;处理程序读取`INTR_STATUS`;读取访问设备的BAR,该BAR位于插槽0上;运行处理程序的CPU必须在插槽0上,否则读取会跨插槽间互连。 -The inter-socket interconnect (on Intel systems: UPI or earlier QPI; on AMD: Infinity Fabric) is much slower than intra-socket cache access. A handler running on the wrong socket sees register reads that take tens of nanoseconds instead of ones; a receive queue whose data lives on the wrong socket sees every packet crossing the interconnect on the way to user space. +插槽间互连(在Intel系统上:UPI或更早的QPI;在AMD上:Infinity Fabric)比插槽内缓存访问慢得多。在错误插槽上运行的处理程序看到寄存器读取耗时数十纳秒而不是个位数;数据位于错误插槽上的接收队列在数据包到达用户空间的路上每个包都要跨越互连。 -Well-placed vectors keep the handler's work on the socket the device lives on. +放置良好的向量将处理程序的工作保持在设备所在的插槽上。 ### 查询NUMA局部性 -FreeBSD exposes the NUMA topology to drivers through `bus_get_cpus(9)`. The API: +FreeBSD 通过 `bus_get_cpus(9)` 向驱动程序暴露 NUMA 拓扑。API: ```c int bus_get_cpus(device_t dev, enum cpu_sets op, size_t setsize, struct _cpuset *cpuset); ``` -The `op` argument selects which set to query: +`op` 参数选择要查询的集合: -- `LOCAL_CPUS`: CPUs in the same NUMA domain as the device. -- `INTR_CPUS`: CPUs suitable for handling device interrupts (usually `LOCAL_CPUS` unless the operator has excluded some). +- `LOCAL_CPUS`:与设备在同一 NUMA 域中的 CPU。 +- `INTR_CPUS`:适合处理设备中断的 CPU(通常是 `LOCAL_CPUS`,除非操作员排除了某些 CPU)。 -The `cpuset` is an output parameter; on success, it contains the bitmap of CPUs in the queried set. +`cpuset` 是输出参数;成功时,它包含所查询集合中 CPU 的位图。 Example use: @@ -2358,7 +2358,7 @@ if (bus_get_cpus(sc->dev, INTR_CPUS, sizeof(local_cpus), } ``` -The driver uses `CPU_FFS(&local_cpus)` to find the first CPU in the set, `CPU_CLR(cpu, &local_cpus)` to mark it used, and iterates. +驱动程序使用 `CPU_FFS(&local_cpus)` 查找集合中的第一个 CPU,使用 `CPU_CLR(cpu, &local_cpus)` 标记为已使用,并进行迭代。 A round-robin bind that respects NUMA locality: @@ -2391,13 +2391,13 @@ myfirst_msix_bind_vectors_numa(struct myfirst_softc *sc) } ``` -The code grabs the local CPU set, picks the lowest-numbered CPU, binds vector 0 to it, clears that CPU from the set, picks the next lowest, binds vector 1 to it, and so on. If the set is exhausted (more vectors than local CPUs), it refreshes and continues. +代码获取本地 CPU 集合,选择编号最小的 CPU,将向量 0 绑定到它,从集合中清除该 CPU,选择下一个最小的,将向量 1 绑定到它,以此类推。如果集合用尽(向量数多于本地 CPU 数),则刷新并继续。 -Chapter 20's driver does not include this NUMA-aware binding; a challenge exercise asks the reader to add it. +第20章的驱动程序未包含此 NUMA 感知绑定;挑战练习要求读者添加它。 ### 操作者视角 -An operator can override the kernel's placement with `cpuset`: +操作员可以使用 `cpuset` 覆盖内核的放置: ```sh # Get current placement for IRQ 257. @@ -2410,15 +2410,15 @@ sudo cpuset -l 3 -x 257 sudo cpuset -l 2,3 -x 257 ``` -These commands override whatever the driver set with `bus_bind_intr`. An operator might do this to pin critical interrupts away from user-workload CPUs (for real-time applications) or to concentrate traffic on specific CPUs (for diagnostic purposes). +这些命令覆盖驱动程序通过 `bus_bind_intr` 设置的任何放置。操作员可能会这样做,将关键中断从用户工作负载 CPU 上移开(用于实时应用),或将流量集中在特定 CPU 上(用于诊断目的)。 -The driver's `bus_bind_intr` call sets the initial placement; the operator can override. A well-behaved driver sets a sensible default and respects operator changes (which it does automatically, because `bus_bind_intr` just writes to an OS-managed CPU-affinity state that the operator then modifies). +驱动程序的 `bus_bind_intr` 调用设置初始放置;操作员可以覆盖。一个行为良好的驱动程序设置合理的默认值并尊重操作员的更改(它会自动这样做,因为 `bus_bind_intr` 只是写入操作系统管理的 CPU 亲和性状态,操作员随后可以修改)。 ### 测量效果 -A concrete way to see NUMA locality's value: run a high-interrupt-rate workload with the handler pinned to a local CPU, then to a remote CPU, and compare latencies. On a two-socket system, the remote CPU's handler typically takes 1.5x to 3x longer per interrupt, measured in CPU cycles. +查看 NUMA 局部性价值的具体方法:在处理程序绑定到本地 CPU 时运行高中断率工作负载,然后绑定到远程 CPU,比较延迟。在双插槽系统上,远程 CPU 的处理程序每次中断通常需要 1.5 到 3 倍的时间(以 CPU 周期计)。 -FreeBSD's DTrace provider can measure this: +FreeBSD 的 DTrace 提供者可以测量这一点: ```sh sudo dtrace -n ' @@ -2429,133 +2429,133 @@ fbt::myfirst_intr_filter:return /self->ts/ { }' ``` -The output is a per-CPU histogram of filter latencies. A reader can run this while observing vector placements and confirm the latency difference. +输出是过滤器延迟的每 CPU 直方图。读者可以在观察向量放置的同时运行此命令,确认延迟差异。 ### 向量放置何时重要 -- High interrupt rates (more than a few thousand per second per vector). -- Large cache-line footprint in the handler (the handler's code and data occupy multiple cache lines). -- Shared receive paths with downstream processing on the same socket. -- NUMA systems with more than one socket and PCIe devices attached to specific sockets. +- 高中断率(每向量每秒超过几千次)。 +- 处理程序中较大的缓存行占用(处理程序的代码和数据占据多个缓存行)。 +- 在同一插槽上具有下游处理流程的共享接收路径。 +- 具有多个插槽且 PCIe 设备连接到特定插槽的 NUMA 系统。 ### 向量放置何时不重要 -- Low-rate interrupts (dozens per second or fewer). -- Single-socket systems. -- Handlers that do minimal work (Chapter 20's admin vector). -- Drivers that run on a single CPU regardless (single-CPU embedded systems). +- 低速率中断(每秒几十次或更少)。 +- 单插槽系统。 +- 执行最少工作的处理程序(第20章的管理向量)。 +- 无论如何都在单个 CPU 上运行的驱动程序(单 CPU 嵌入式系统)。 -Chapter 20's driver is in the "does not really matter" category for normal testing, but the patterns the chapter teaches transfer directly to drivers where it does. +第20章的驱动程序在正常测试中属于"关系不大"的类别,但本章教授的模式直接迁移到确实需要它的驱动程序。 ## 深入了解向量分配策略 -Section 6 showed the fixed-assignment pattern (vector 0 = admin, 1 = rx, 2 = tx). This section explores other assignment strategies real drivers use. +第6节展示了固定分配模式(向量0 = admin,1 = rx,2 = tx)。本节探讨真实驱动程序使用的其他分配策略。 ### 每队列一向量 -The simplest strategy and the most common. Each queue (rx queue, tx queue, admin queue, etc.) has its own dedicated vector. The driver allocates `N+M+1` vectors for `N` receive queues, `M` transmit queues, and 1 admin. +最简单且最常见的策略。每个队列(接收队列、发送队列、管理队列等)有自己专用的向量。驱动程序为 `N` 个接收队列、`M` 个发送队列和 1 个管理队列分配 `N+M+1` 个向量。 -Pros: -- Simple per-vector handler logic. -- Each queue's interrupt rate is independent. -- CPU affinity is per-queue (easy to pin to the NUMA-local CPU). +优点: +- 每向量处理程序逻辑简单。 +- 每个队列的中断率独立。 +- CPU 亲和性是每队列的(易于固定到 NUMA 本地 CPU)。 -Cons: -- Consumes many vectors for drivers with many queues. -- Each queue's ithread adds overhead on low-rate queues. +缺点: +- 对于具有许多队列的驱动程序,消耗很多向量。 +- 每个队列的 ithread 在低速率队列上增加了开销。 -This is the pattern `nvme(4)` uses. +这是 `nvme(4)` 使用的模式。 ### 合并RX+TX向量 -Some drivers coalesce the RX and TX of a single queue-pair into a single vector. A NIC with 8 queue pairs would use 8 coalesced vectors plus a few for admin. When the vector fires, the filter checks both RX and TX status bits and dispatches accordingly. +一些驱动程序将单个队列对的 RX 和 TX 合并到一个向量中。具有 8 个队列对的 NIC 将使用 8 个合并向量加上几个用于管理。当向量触发时,过滤器检查 RX 和 TX 状态位并相应地分发。 -Pros: -- Half the vectors per queue-pair. -- RX and TX for the same queue pair tend to be NUMA-local to each other (they share the same descriptor-ring memory). +优点: +- 每队列对向量数量减半。 +- 同一队列对的 RX 和 TX 往往彼此 NUMA 本地(它们共享相同的描述符环内存)。 -Cons: -- The filter is slightly more complex. -- RX and TX can interfere under load (a burst of RX fills the handler's time, delaying TX completions). +缺点: +- 过滤器稍微复杂。 +- RX 和 TX 在负载下可能相互干扰(RX 突发填满处理程序时间,延迟 TX 完成)。 -This is a middle-ground design, used by some consumer NICs. +这是一种中间设计,被一些消费级 NIC 使用。 ### 所有队列共用一个向量 -Some very-constrained devices (low-cost NICs, small embedded devices) have only one or two MSI-X vectors total. The driver uses a single vector for all queues and dispatches to each queue based on a status register. +一些资源受限的设备(低成本 NIC、小型嵌入式设备)总共只有一两个 MSI-X 向量。驱动程序对所有队列使用单个向量,并根据状态寄存器分发到每个队列。 -Pros: -- Works on hardware with few vectors. -- Simple allocation. +优点: +- 在向量少的硬件上工作。 +- 分配简单。 -Cons: -- No per-queue affinity. -- The filter does more work to decide what to dispatch. +缺点: +- 没有每队列亲和性。 +- 过滤器要做更多工作来决定分发什么。 -This is the pattern a driver on very low-end hardware uses. +这是非常低端硬件上驱动程序使用的模式。 ### 动态每 CPU 分配 -A clever design: allocate one vector per CPU, and assign queues to vectors dynamically. An RX queue is "owned" by one CPU at a time; it processes on that CPU's vector. If the workload shifts, the driver can remap queues to different CPUs. +一个巧妙的设计:为每个 CPU 分配一个向量,并动态地将队列分配给向量。一个 RX 队列一次由一个 CPU "拥有";它在该 CPU 的向量上处理。如果工作负载变化,驱动程序可以将队列重新映射到不同的 CPU。 -Pros: -- Optimal per-CPU cache affinity. -- Adapts to workload changes. +优点: +- 最佳的每 CPU 缓存亲和性。 +- 适应工作负载变化。 -Cons: -- Complex allocation and remapping logic. -- Not easy to reason about. +缺点: +- 复杂的分配和重新映射逻辑。 +- 不容易推理。 -Some high-end NIC drivers (Mellanox ConnectX series, Intel 800 Series) use variants of this. +一些高端 NIC 驱动程序(Mellanox ConnectX 系列、Intel 800 系列)使用此变体。 ### 第 20 章的策略 -Chapter 20's driver uses the fixed-assignment strategy with three vectors. It is the simplest strategy that illustrates multi-vector design without getting into NUMA details or dynamic remapping. Real drivers often start with this design and evolve to more sophisticated patterns as requirements demand. +第20章的驱动程序使用三个向量的固定分配策略。这是说明多向量设计的最简单策略,不涉及 NUMA 细节或动态重新映射。真实驱动程序通常从这种设计开始,并根据需求演进到更复杂的模式。 -A challenge exercise asks the reader to implement the dynamic per-CPU-allocation strategy as an extension. +一个挑战练习要求读者实现动态每 CPU 分配策略作为扩展。 ## 深入了解中断调节和合并 -A concept adjacent to MSI-X that deserves a brief mention. Modern high-throughput devices often support **interrupt moderation** or **coalescing**: the device buffers events (incoming packets, completions) and fires a single interrupt for multiple events, either at a time threshold or a count threshold. +一个与 MSI-X 相邻的概念值得简单提及。现代高吞吐量设备通常支持**中断调节**或**合并**:设备缓冲事件(传入的数据包、完成通知),并在时间阈值或计数阈值处为多个事件触发单个中断。 ### 为什么调节重要 -A NIC receiving ten million packets per second would fire ten million interrupts if each packet triggered one. That is far too many; the CPU would spend all its time entering and exiting interrupt handlers. The solution is to batch: the NIC fires one interrupt every 50 microseconds, and during those 50 microseconds the NIC accumulates whatever packets arrived. The handler processes all the accumulated packets in one go. +每秒接收一千万数据包的 NIC 如果每个数据包触发一个中断,将触发一千万个中断。这太多了;CPU 将把所有时间花在进入和退出中断处理程序上。解决方案是批处理:NIC 每 50 微秒触发一次中断,在这 50 微秒内 NIC 累积到达的任何数据包。处理程序一次性处理所有累积的数据包。 -Coalescing trades latency for throughput: each packet takes up to 50 microseconds longer to be delivered to user space, but the CPU handles millions of packets per second with a manageable interrupt rate. +合并以延迟换取吞吐量:每个数据包交付到用户空间最多延迟 50 微秒,但 CPU 以可管理的中断率每秒处理数百万数据包。 ### 驱动程序如何控制调节 -The mechanism is device-specific. Common forms: +机制是设备特定的。常见形式: -- **Time-based:** the device fires after a configured interval (e.g., 50 microseconds). -- **Count-based:** the device fires after N events (e.g., 16 packets). -- **Combined:** whichever threshold is reached first. -- **Adaptive:** the device (or the driver) tunes the thresholds based on observed rates. +- **基于时间:**设备在配置的时间间隔后触发(例如 50 微秒)。 +- **基于计数:**设备在 N 个事件后触发(例如 16 个数据包)。 +- **组合:**先达到哪个阈值就触发哪个。 +- **自适应:**设备(或驱动程序)根据观察到的速率调整阈值。 -The driver typically programs the thresholds through device registers. The MSI-X mechanism itself does not provide moderation; it is a device feature that works with MSI-X because MSI-X allows per-vector assignment. +驱动程序通常通过设备寄存器编程阈值。MSI-X 机制本身不提供调节;它是一个与 MSI-X 配合使用的设备特性,因为 MSI-X 允许每向量分配。 ### 第 20 章的驱动程序不做调节 -The Chapter 20 driver has no moderation. Each simulated interrupt produces one filter call. On real hardware this would be a problem at high rates; on the lab it is fine. +第 20 章的驱动程序没有调节。每个模拟中断产生一次过滤器调用。在真实硬件上,这在高速率下会是个问题;在实验室中没问题。 -Real drivers like `em(4)`, `ix(4)`, `ixl(4)`, and `mgb(4)` all have moderation parameters. The `sysctl` interface exposes them as tunable values: +像 `em(4)`、`ix(4)`、`ixl(4)` 和 `mgb(4)` 这样的真实驱动程序都有调节参数。`sysctl` 接口将它们暴露为可调参数: ```sh sysctl dev.em.0 | grep itr ``` -A reader who adapts the chapter's driver to a real device should study the moderation controls for that device. The mechanism is orthogonal to MSI-X; the two combine to give high-performance interrupt handling. +将本章驱动程序适配到真实设备的读者应研究该设备的调节控制。该机制与 MSI-X 正交;两者结合提供高性能中断处理。 ## 来自真实 FreeBSD 驱动程序的模式 -A tour of the multi-vector patterns that appear in `/usr/src/sys/dev/`. Each pattern is a short snippet from a real driver, with a note on what it teaches for Chapter 20. +对 `/usr/src/sys/dev/` 中出现的多向量模式的一次巡览。每个模式都是来自真实驱动程序的简短代码片段,附有说明其对第20章的指导意义的注释。 ### 模式:nvme(4) 管理 + I/O 向量分离 @@ -2583,7 +2583,7 @@ for (i = 0; i < ctrlr->num_io_queues; i++) { } ``` -Why it matters: the admin-plus-N pattern is the right choice when one vector handles infrequent, high-priority work (errors, async events) and N vectors handle rate-limited, per-queue work. Chapter 20's admin/rx/tx split is a miniature version of this. +为什么重要:管理加 N 模式是一个向量处理不频繁的高优先级工作(错误、异步事件),N 个向量处理速率受限的每队列工作时的正确选择。第20章的管理/rx/tx 拆分是此模式的微型版本。 ### 模式:ixgbe 的队列对向量 @@ -2601,7 +2601,7 @@ link.rid = num_qpairs + 1; bus_setup_intr(..., ixgbe_msix_link, sc, ...); ``` -Why it matters: the coalesced RX+TX-per-queue-pair design halves the vector count without sacrificing per-queue affinity. Suitable when the device has many queues but few vectors. +为什么重要:合并的每队列对 RX+TX 设计在不牺牲每队列亲和性的情况下将向量计数减半。适用于设备具有许多队列但向量很少的情况。 ### 模式:virtio_pci 的每虚拟队列向量 @@ -2617,7 +2617,7 @@ for (i = 0; i < nvectors; i++) { } ``` -Why it matters: virtio's per-virtqueue assignment is the model for any paravirtualised device. The vector count equals the virtqueue count plus admin/config. +为什么重要:virtio 的每虚拟队列分配是任何半虚拟化设备的模型。向量数等于虚拟队列数加管理/配置。 ### 模式:ahci 的每端口向量 @@ -2630,11 +2630,11 @@ for (i = 0; i < ahci->nports; i++) { } ``` -Why it matters: storage controllers often use per-port vector assignments so that I/O completions on different ports can be processed concurrently on different CPUs. +为什么重要:存储控制器通常使用每端口向量分配,以便不同端口上的 I/O 完成可以在不同 CPU 上并发处理。 ### 模式:iflib 的隐藏向量管理 -Drivers using `iflib(9)` (such as `em(4)`, `igc(4)`, `ix(4)`, `ixl(4)`, `mgb(4)`) do not manage vectors directly. Instead, they register per-queue handler functions with iflib's registration table, and iflib does the allocation and binding: +使用 `iflib(9)` 的驱动程序(例如 `em(4)`、`igc(4)`、`ix(4)`、`ixl(4)`、`mgb(4)`)不直接管理向量。相反,它们向 iflib 的注册表注册每队列处理函数,由 iflib 进行分配和绑定: ```c static struct if_shared_ctx em_sctx_init = { @@ -2660,36 +2660,36 @@ em_if_msix_intr_assign(if_ctx_t ctx, int msix) } ``` -Why it matters: iflib abstracts MSI-X allocation and per-queue binding behind a clean API. Drivers using iflib are simpler than bare MSI-X drivers but give up some flexibility. The iflib pattern is the right choice for new FreeBSD network drivers; the bare MSI-X pattern is the right choice for non-network devices or when iflib does not fit. +为什么重要:iflib 在干净的 API 后面抽象了 MSI-X 分配和每队列绑定。使用 iflib 的驱动程序比裸 MSI-X 驱动程序更简单,但放弃了一些灵活性。iflib 模式是新的 FreeBSD 网络驱动程序的正确选择;裸 MSI-X 模式是非网络设备或 iflib 不合适时的正确选择。 ### 这些模式教会了什么 -All of these drivers follow the same structural pattern Chapter 20 teaches: +所有这些驱动程序都遵循第20章教授的相同结构模式: -1. Query vector count. -2. Allocate vectors. -3. For each vector: allocate IRQ resource at rid=i+1, register handler, describe. -4. Bind vectors to CPUs. -5. On teardown: per-vector teardown in reverse, then `pci_release_msi`. +1. 查询向量计数。 +2. 分配向量。 +3. 对每个向量:在 rid=i+1 分配 IRQ 资源,注册处理程序,描述。 +4. 将向量绑定到 CPU。 +5. 拆除时:逆序每向量拆除,然后 `pci_release_msi`。 -The differences among drivers are: +驱动程序之间的差异在于: -- How many vectors (1, a handful, dozens, or hundreds). -- How vectors are assigned (admin+N, queue-pair, per-port, per-virtqueue). -- Whether iflib handles the allocation. -- What each filter function does (admin vs data-path). +- 向量数量(1 个、少量、几十个或数百个)。 +- 向量如何分配(管理+N、队列对、每端口、每虚拟队列)。 +- iflib 是否处理分配。 +- 每个过滤器函数做什么(管理 vs 数据路径)。 -A reader who has Chapter 20's vocabulary can recognise these differences immediately. +拥有第20章词汇的读者可以立即识别这些差异。 ## 性能观察:测量 MSI-X 的收益 -A section that grounds the chapter's performance claims in a concrete measurement. +本节将本章的性能声明建立在具体的测量基础上。 ### 测试设置 -Suppose you have the Chapter 20 driver running on QEMU with `virtio-rng-pci` (so MSI-X is active) and a multi-CPU guest. The `intr_simulate_rx` sysctl lets you trigger interrupts from a user-space loop: +假设您在 QEMU 上使用 `virtio-rng-pci`(因此 MSI-X 处于活动状态)和多 CPU guest 运行第20章的驱动程序。`intr_simulate_rx` sysctl 让您从用户空间循环触发中断: ```sh # In one shell, drive simulated RX interrupts as fast as possible. @@ -2700,7 +2700,7 @@ done ### 使用 DTrace 测量 -In another shell, measure the filter's CPU-time per invocation and which CPU it runs on: +在另一个 shell 中,测量过滤器的每次调用 CPU 时间及其运行的 CPU: ```sh sudo dtrace -n ' @@ -2712,37 +2712,37 @@ fbt::myfirst_rx_filter:return /self->ts/ { }' ``` -The output is a per-CPU histogram of filter latencies. If `bus_bind_intr` placed the RX vector on CPU 1, the histogram should show all invocations on CPU 1, with latencies in the hundreds of nanoseconds to single-digit microseconds. +输出是过滤器延迟的每 CPU 直方图。如果 `bus_bind_intr` 将 RX 向量放置在 CPU 1 上,直方图应显示所有调用都在 CPU 1 上,延迟在数百纳秒到个位数微秒之间。 ### 结果显示什么 -On a well-placed MSI-X vector: +在放置良好的 MSI-X 向量上: -- Every invocation is on the same CPU (the bound CPU). -- Latencies are consistently short (the hot cache lines stay on one CPU). -- No cross-CPU cache bouncing. +- 每次调用都在同一个 CPU(绑定的 CPU)上。 +- 延迟一致地短(热缓存行保持在一个 CPU 上)。 +- 没有跨 CPU 缓存抖动。 -On a legacy INTx shared line: +在遗留 INTx 共享线上: -- Invocations spread across CPUs (the kernel routes randomly). -- Latencies are more variable (cold cache lines on each new CPU). -- Cross-CPU cache traffic appears in performance counters. +- 调用分散到各个 CPU(内核随机路由)。 +- 延迟更加多变(每个新 CPU 上的冷缓存行)。 +- 跨 CPU 缓存流量出现在性能计数器中。 -The difference can be measured in nanoseconds per invocation. For a driver handling a few hundred interrupts per second, the difference is invisible. For a driver handling a million interrupts per second, the difference is the difference between "works" and "does not work". +差异可以以每次调用纳秒为单位测量。对于每秒处理几百次中断的驱动程序,差异不可见。对于每秒处理一百万次中断的驱动程序,差异就是"工作"和"不工作"之间的差异。 ### 一般性教训 -Chapter 20's machinery is overkill for low-rate drivers. It is essential for high-rate drivers. The patterns the chapter teaches scale from "demo driver doing a hundred interrupts per second" to "production NIC doing ten million". Knowing where on that scale a specific driver lives determines how much of Chapter 20's advice matters in practice. +第20章的机制对于低速率驱动程序来说是过度的。对于高速率驱动程序来说它是必需的。本章教授的模式从"每秒执行一百次中断的演示驱动程序"扩展到"执行一千万次的生成 NIC"。知道特定驱动程序在哪个尺度上,决定了第20章的建议在实践中有多少重要性。 ## 深入了解多向量驱动程序的 sysctl 树设计 -Chapter 20's driver exposes its per-vector counters as flat sysctls (`vec0_fire_count`, `vec1_fire_count`, `vec2_fire_count`). For a driver with many vectors, a flat namespace becomes unwieldy. This section shows how to use `SYSCTL_ADD_NODE` to build a per-vector sysctl tree. +第20章的驱动程序将其每向量计数器暴露为扁平 sysctl(`vec0_fire_count`、`vec1_fire_count`、`vec2_fire_count`)。对于具有许多向量的驱动程序,扁平命名空间变得笨拙。本节展示如何使用 `SYSCTL_ADD_NODE` 构建每向量 sysctl 树。 ### 扁平与树形的权衡 -Flat namespace (what Chapter 20 uses): +扁平命名空间(第20章使用的): ```text dev.myfirst.0.vec0_fire_count: 42 @@ -2753,10 +2753,10 @@ dev.myfirst.0.vec1_stray_count: 0 dev.myfirst.0.vec2_stray_count: 0 ``` -Pros: simple, no `SYSCTL_ADD_NODE` calls. -Cons: many siblings at the top level; no grouping. +优点:简单,无需 `SYSCTL_ADD_NODE` 调用。 +缺点:顶层有许多同级节点;没有分组。 -Tree namespace: +树形命名空间: ```text dev.myfirst.0.vec.admin.fire_count: 42 @@ -2767,8 +2767,8 @@ dev.myfirst.0.vec.tx.fire_count: 4523 dev.myfirst.0.vec.tx.stray_count: 0 ``` -Pros: groups per-vector state; scales to many vectors; named rather than numbered. -Cons: more code to set up. +优点:对每向量状态进行分组;可扩展到许多向量;使用名称而非编号。 +缺点:需要更多代码来设置。 ### 构建树的代码 @@ -2812,7 +2812,7 @@ myfirst_msix_add_sysctls(struct myfirst_softc *sc) } ``` -The `SYSCTL_ADD_NODE` calls create the intermediate nodes; subsequent `SYSCTL_ADD_U64` calls attach leaf counters under them. The tree structure becomes visible in `sysctl` output automatically. +`SYSCTL_ADD_NODE` 调用创建中间节点;随后的 `SYSCTL_ADD_U64` 调用在其下附加叶计数器。树形结构在 `sysctl` 输出中自动可见。 ### 查询树 @@ -2827,258 +2827,258 @@ sysctl dev.myfirst.0.vec.rx sysctl -n dev.myfirst.0.vec.admin.fire_count dev.myfirst.0.vec.rx.fire_count dev.myfirst.0.vec.tx.fire_count ``` -The tree structure makes the sysctl namespace much more readable, especially for drivers with many vectors (NVMe with 32 I/O queues, or a NIC with 16 queue pairs). +树形结构使 sysctl 命名空间更易读,特别是对于具有许多向量的驱动程序(具有 32 个 I/O 队列的 NVMe,或具有 16 个队列对的 NIC)。 ### 何时使用树 -For Chapter 20's three-vector driver, the flat namespace is fine. For a driver with eight or more vectors, the tree becomes valuable. A reader writing a production driver should use the tree. +对于第20章的三向量驱动程序,扁平命名空间即可。对于具有八个或更多向量的驱动程序,树形结构变得有价值。编写生产驱动程序的读者应使用树形结构。 ### 常见错误 -- **Leaking the parent node.** `SYSCTL_ADD_NODE` registers the node in `sc->sysctl_ctx`; it is freed with the rest of the context. No explicit free needed. -- **Forgetting `NULL` for the handler argument.** `SYSCTL_ADD_NODE` is not a CTLPROC; it is a pure grouping node. The handler argument is `NULL`. -- **Wrong parent passed to child `SYSCTL_ADD_*` calls.** `SYSCTL_CHILDREN(vec_node)` for children of `vec_node`, not `SYSCTL_CHILDREN(parent)`. +- **泄露父节点。** `SYSCTL_ADD_NODE` 在 `sc->sysctl_ctx` 中注册节点;它与上下文的其他部分一起被释放。不需要显式释放。 +- **忘记为处理程序参数传入 `NULL`。** `SYSCTL_ADD_NODE` 不是 CTLPROC;它是一个纯分组节点。处理程序参数为 `NULL`。 +- **将错误父节点传递给子 `SYSCTL_ADD_*` 调用。** `vec_node` 的子节点应使用 `SYSCTL_CHILDREN(vec_node)`,而不是 `SYSCTL_CHILDREN(parent)`。 -This tree-design pattern is the cleanest way to expose multi-vector state. Chapter 20's challenge exercise suggests implementing it as an extension. +这种树形设计模式是暴露多向量状态的最干净方式。第20章的挑战练习建议将其作为扩展实现。 ## 深入了解 MSI-X 设置中的错误路径 -Section 3 and Section 5 showed the happy-path setup code. This section walks through what can go wrong and how to diagnose it. +第3节和第5节展示了快乐路径的设置代码。本节介绍可能出错的情况以及如何诊断。 ### 故障模式 1:pci_msix_count 返回 0 -Symptom: the MSI-X attempt is skipped because the count is 0. +症状:由于计数为 0,跳过了 MSI-X 尝试。 -Cause: the device has no MSI-X capability, or the PCI bus driver has not discovered it. +原因:设备没有 MSI-X 能力,或 PCI 总线驱动程序未发现它。 -Fix: Confirm with `pciconf -lvc`. If the device advertises MSI-X but `pci_msix_count` returns 0, the device's PCI configuration is broken or the kernel's probe did not find it; rare and hard to fix from the driver. +修复:用 `pciconf -lvc` 确认。如果设备公布有 MSI-X 但 `pci_msix_count` 返回 0,设备的 PCI 配置已损坏或内核的探测未找到它;这很少见且难以从驱动程序修复。 ### 故障模式 2:pci_alloc_msix 返回 EINVAL -Symptom: allocation fails with `EINVAL`. +症状:分配失败,返回 `EINVAL`。 -Cause: the driver is asking for a count greater than the device's advertised max, or it is asking for 0. +原因:驱动程序请求的计数大于设备公布的最大值,或者请求为 0。 -Fix: Clamp the requested count to `pci_msix_count`'s returned value. Always request at least 1. +修复:将请求计数限制在 `pci_msix_count` 返回的值以内。始终至少请求 1。 ### 故障模式 3:pci_alloc_msix 返回少于请求的向量数 -Symptom: `count` after the call is less than requested. +症状:调用后的 `count` 小于请求值。 -Cause: the kernel's vector pool was partially depleted; the device's allocation was given whatever remained. +原因:内核的向量池部分耗尽;设备分配得到了剩余的任何向量。 -Fix: Decide upfront whether to accept, adapt, or release. Chapter 20's driver releases and falls back to MSI. +修复:预先决定是接受、适应还是释放。第20章的驱动程序释放并回退到 MSI。 ### 故障模式 4:bus_alloc_resource_any 为 MSI-X 向量返回 NULL -Symptom: after `pci_alloc_msix` succeeded, the per-vector IRQ allocation fails. +症状:`pci_alloc_msix` 成功后,每向量 IRQ 分配失败。 -Causes: -- Wrong rid (using 0 instead of i+1). -- Already released previously (double-release). -- Out of IRQ resources at the bus layer. +原因: +- rid 错误(使用 0 而不是 i+1)。 +- 先前已释放(双重释放)。 +- 总线层的 IRQ 资源耗尽。 -Fix: Check the rid is i+1. Audit the release code. Log the error. +修复:检查 rid 是否为 i+1。审计释放代码。记录错误。 ### 故障模式 5:bus_setup_intr 为每向量处理程序返回 EINVAL -Symptom: `bus_setup_intr` fails. +症状:`bus_setup_intr` 失败。 -Causes: -- Filter and ithread both NULL. -- Missing `INTR_TYPE_*` flag. -- Already set up previously (double-setup). +原因: +- 过滤器和 ithread 均为 NULL。 +- 缺少 `INTR_TYPE_*` 标志。 +- 先前已设置(双重设置)。 -Fix: Ensure the filter argument is non-NULL. Include an `INTR_TYPE_*` flag. Audit the setup code for double-registration. +修复:确保过滤器参数非 NULL。包含 `INTR_TYPE_*` 标志。审计设置代码以防止双重注册。 ### 故障模式 6:bus_bind_intr 返回错误 -Symptom: `bus_bind_intr` returns non-zero. +症状:`bus_bind_intr` 返回非零值。 -Causes: -- Platform does not support rebinding. -- CPU out of range. -- Kernel configuration (NO_SMP, NUMA disabled). +原因: +- 平台不支持重新绑定。 +- CPU 超出范围。 +- 内核配置(NO_SMP、NUMA 禁用)。 -Fix: Treat as non-fatal (`device_printf` a warning and continue). The driver still works without binding. +修复:视为非致命(`device_printf` 警告并继续)。驱动程序在不绑定的情况下也能工作。 ### 故障模式 7:vmstat -i 显示向量但计数器不增加 -Symptom: the kernel sees the vectors but the filters never fire. +症状:内核看到向量但过滤器从未触发。 -Causes: -- The device's `INTR_MASK` is zero (chapter 19 problem). -- The device reset its interrupt state. -- Hardware bug or bhyve/QEMU configuration problem. +原因: +- 设备的 `INTR_MASK` 为零(第19章的问题)。 +- 设备重置了其中断状态。 +- 硬件 bug 或 bhyve/QEMU 配置问题。 -Fix: Verify the device's INTR_MASK. Use the simulated-interrupt sysctl to confirm the filter works at all. +修复:验证设备的 INTR_MASK。使用模拟中断 sysctl 确认过滤器是否至少能工作。 ### 故障模式 8:第二次 kldload 回退到较低层级 -Symptom: first load uses MSI-X; unload; second load uses legacy or MSI. +症状:第一次加载使用 MSI-X;卸载;第二次加载使用 legacy 或 MSI。 -Cause: `pci_release_msi` not called on teardown. +原因:拆除时未调用 `pci_release_msi`。 -Fix: Audit the teardown path. Make sure `pci_release_msi` runs on every successful allocation path. +修复:审计拆除路径。确保 `pci_release_msi` 在每条成功的分配路径上运行。 ### 故障模式 9:WITNESS 在多向量设置时崩溃 -Symptom: `WITNESS` reports a lock-order violation or a "lock held during sleep" in the per-vector setup. +症状:`WITNESS` 在每向量设置中报告锁顺序违规或"持锁睡眠"。 -Cause: holding `sc->mtx` across a `bus_setup_intr` call. The bus hooks may sleep, and holding a mutex across a sleep is illegal. +原因:在 `bus_setup_intr` 调用期间持有 `sc->mtx`。总线钩子可能睡眠,而在睡眠期间持有互斥锁是非法的。 -Fix: Release `sc->mtx` before calling `bus_setup_intr`. Reacquire afterwards if needed. +修复:在调用 `bus_setup_intr` 之前释放 `sc->mtx`。如有需要之后重新获取。 ### 故障模式 10:部分设置没有正确清理 -Symptom: attach fails; second attach fails with "resource in use". +症状:attach 失败;第二次 attach 失败,显示"资源正在使用"。 -Cause: the partial-failure goto cascade doesn't undo all the way. Some per-vector state lingers. +原因:部分失败的 goto 级联没有完全撤销。某些每向量状态残留。 -Fix: Ensure the cascade unwinds to the vector that failed, not past it. Use the per-vector helper consistently. +修复:确保级联回退到失败的向量处停止,而不是越过它。一致地使用每向量辅助函数。 ## 额外故障排除 -A handful of extra failure modes Chapter 20 readers might hit. +第20章的读者可能遇到的一些额外故障模式。 ### "QEMU guest 不暴露 MSI-X" -Causes: QEMU version too old, or the guest is booting with legacy virtio. +原因:QEMU 版本太旧,或 guest 使用 legacy virtio 启动。 -Fix: Update QEMU to a recent version. In the guest, check: +修复:更新 QEMU 到较新版本。在 guest 中检查: ```sh pciconf -lvc | grep -B 1 -A 2 'cap 11' ``` -If no `cap 11` lines appear, MSI-X is not available. Switch to QEMU's modern virtio-rng-pci with `-device virtio-rng-pci,disable-legacy=on`. +如果没有出现 `cap 11` 行,则 MSI-X 不可用。切换到 QEMU 的现代 virtio-rng-pci,使用 `-device virtio-rng-pci,disable-legacy=on`。 ### "intr_simulate_rx 增加 fire_count 但任务从不运行" -Cause: the task's `TASK_INIT` was not called, or the taskqueue was not started. +原因:任务的 `TASK_INIT` 未被调用,或任务队列未启动。 -Fix: Verify `TASK_INIT(&vec->task, 0, myfirst_rx_task_fn, vec)` in setup. Verify `taskqueue_start_threads(&sc->intr_tq, ...)`. +修复:验证设置中调用了 `TASK_INIT(&vec->task, 0, myfirst_rx_task_fn, vec)`。验证调用了 `taskqueue_start_threads(&sc->intr_tq, ...)`。 ### "每向量计数器增加但杂散计数成比例上升" -Cause: the filter's status check is wrong, or multiple vectors are triggering on the same bit. +原因:过滤器的状态检查错误,或多个向量在同一个位上触发。 -Fix: Each filter should check for its specific bit(s). If two filters both try to handle `DATA_AV`, one will win and the other will see stray. +修复:每个过滤器应检查其特定的位。如果两个过滤器都试图处理 `DATA_AV`,一个会赢,另一个会看到杂散。 ### "cpuset -g -x $irq 报告所有向量的掩码为 0" -Cause: `bus_bind_intr` has not been called, or it was called with CPU 0 (mask 1). +原因:`bus_bind_intr` 未被调用,或它被调用时指定了 CPU 0(掩码 1)。 -Fix: If intentionally unbound, "mask 0" might be platform-specific. If binding was attempted, check return value of `bus_bind_intr`. +修复:如果故意不绑定,"mask 0"可能是平台特定的。如果尝试了绑定,检查 `bus_bind_intr` 的返回值。 ### "驱动加载成功但 dmesg 没有显示 attach 横幅" -Cause: the `device_printf` came before the banner flush, or the banner is in a very early boot buffer. +原因:`device_printf` 在横幅刷新之前调用,或横幅位于非常早期的启动缓冲区中。 -Fix: `dmesg -a` shows the full message buffer. Verify `dmesg -a | grep myfirst`. +修复:`dmesg -a` 显示完整消息缓冲区。验证 `dmesg -a | grep myfirst`。 ### "Detach 在多向量设置后挂起" -Cause: a vector's handler is still running when teardown tries to proceed. `bus_teardown_intr` blocks waiting for it. +原因:拆除尝试继续时,向量的处理程序仍在运行。`bus_teardown_intr` 阻塞等待它完成。 -Fix: Make sure the device's `INTR_MASK` is cleared *before* `bus_teardown_intr`, so no new handlers can be dispatched. Make sure the filter does not loop forever; short-runtime discipline. +修复:确保在 `bus_teardown_intr` *之前*清除设备的 `INTR_MASK`,这样不会有新的处理程序被分发。确保过滤器不会永远循环;保持短运行时间纪律。 ### "pci_alloc_msix 成功但只有部分向量触发" -Cause: the device is not actually signalling on the vectors it should. Could be a driver bug (forgot to enable) or a device quirk. +原因:设备实际上没有在其应有的向量上发出信号。可能是驱动程序 bug(忘记启用)或设备问题。 -Fix: Use the simulated-interrupt sysctl to confirm the filter works for each vector. If the simulated path works but real events don't fire the vector, the issue is on the device side. +修复:使用模拟中断 sysctl 确认每个向量的过滤器是否工作。如果模拟路径工作但真实事件不触发向量,问题出在设备端。 ## 实例演练:追踪事件通过三个层级 -To make the fallback ladder concrete, here is a complete trace of the same event (a simulated DATA_AV interrupt) on each of the three tiers. +为了使回退阶梯具体化,以下是在三个层级上追踪同一事件(模拟的 DATA_AV 中断)的完整过程。 ### 第 3 层:遗留 INTx -On bhyve with virtio-rnd (no MSI-X exposed), the driver falls back to legacy INTx with one handler at rid 0. +在带有 virtio-rnd(不暴露 MSI-X)的 bhyve 上,驱动程序回退到在 rid 0 处有一个处理程序的 legacy INTx。 -1. User runs `sudo sysctl dev.myfirst.0.intr_simulate_admin=1` (or `intr_simulate_rx=1`, etc.). -2. The sysctl handler acquires `sc->mtx`, writes the bit to INTR_STATUS, releases, calls the filter. -3. The single `myfirst_intr_filter` (from Chapter 19) runs. It reads INTR_STATUS, sees the bit, acknowledges, and either enqueues the task (for DATA_AV) or handles inline (for ERROR/COMPLETE). -4. `intr_count` increments. -5. On legacy, there is only one vector, so all three simulated-interrupt sysctls go through the same filter. +1. 用户运行 `sudo sysctl dev.myfirst.0.intr_simulate_admin=1`(或 `intr_simulate_rx=1` 等)。 +2. sysctl 处理程序获取 `sc->mtx`,将位写入 INTR_STATUS,释放,调用过滤器。 +3. 单个 `myfirst_intr_filter`(来自第19章)运行。它读取 INTR_STATUS,看到该位,确认,并将任务入队(对于 DATA_AV)或内联处理(对于 ERROR/COMPLETE)。 +4. `intr_count` 递增。 +5. 在 legacy 上,只有一个向量,因此所有三个模拟中断 sysctl 通过同一个过滤器。 -Observations: -- `sysctl dev.myfirst.0.intr_mode` returns 0. -- `vmstat -i | grep myfirst` shows one line. -- The per-vector counters do not exist (legacy mode uses the Chapter 19 counters). +观察结果: +- `sysctl dev.myfirst.0.intr_mode` 返回 0。 +- `vmstat -i | grep myfirst` 显示一行。 +- 每向量计数器不存在(legacy 模式使用第19章的计数器)。 ### 第 2 层:MSI -On a system that supports MSI but not MSI-X, the driver allocates a single MSI vector. MSI requires a power-of-two vector count, so the driver cannot ask for 3 here; it requests 1 and uses the Chapter 19 single-handler pattern. +在支持 MSI 但不支持 MSI-X 的系统上,驱动程序分配单个 MSI 向量。MSI 要求向量计数为 2 的幂,因此驱动程序不能在此请求 3;它请求 1 并使用第19章的单处理程序模式。 -1. User runs `sudo sysctl dev.myfirst.0.intr_simulate_admin=1` (or `intr_simulate_rx=1`, or `intr_simulate_tx=4`). -2. Because only one vector is set up on the MSI tier, all three per-vector simulation sysctls route through the same Chapter 19 `myfirst_intr_filter`. -3. The filter reads INTR_STATUS, sees the bit, acknowledges, and either handles inline or enqueues the task. +1. 用户运行 `sudo sysctl dev.myfirst.0.intr_simulate_admin=1`(或 `intr_simulate_rx=1`,或 `intr_simulate_tx=4`)。 +2. 因为在 MSI 层级上只设置了一个向量,所有三个每向量模拟 sysctl 都通过第19章的同一个 `myfirst_intr_filter` 路由。 +3. 过滤器读取 INTR_STATUS,看到该位,确认,然后内联处理或将任务入队。 -Observations: -- `sysctl dev.myfirst.0.intr_mode` returns 1. -- `vmstat -i | grep myfirst` shows one line (the single MSI handler at rid=1, labelled "msi"). -- The per-vector counters on slots 1 and 2 stay at 0 because only slot 0 is in use; the Chapter 19 global counters (`intr_count`, `intr_data_av_count`, etc.) are the ones that move. +观察结果: +- `sysctl dev.myfirst.0.intr_mode` 返回 1。 +- `vmstat -i | grep myfirst` 显示一行(rid=1 处的单个 MSI 处理程序,标记为"msi")。 +- 槽位 1 和 2 的每向量计数器保持为 0,因为只有槽位 0 在使用;第19章的全局计数器(`intr_count`、`intr_data_av_count` 等)发生变化。 ### 第 1 层:MSI-X -On QEMU with virtio-rng-pci, the driver allocates MSI-X with 3 vectors, each bound to a CPU. +在带有 virtio-rng-pci 的 QEMU 上,驱动程序分配具有 3 个向量的 MSI-X,每个向量绑定到一个 CPU。 -1. User runs `sudo sysctl dev.myfirst.0.intr_simulate_rx=1`. -2. The sysctl calls the rx filter directly (simulated path does not go through the hardware). -3. `myfirst_rx_filter` runs (on whichever CPU the sysctl was invoked on, because simulation is not going through the kernel's interrupt dispatch). -4. Counters increment; task runs. +1. 用户运行 `sudo sysctl dev.myfirst.0.intr_simulate_rx=1`。 +2. sysctl 直接调用 rx 过滤器(模拟路径不经过硬件)。 +3. `myfirst_rx_filter` 运行(在调用 sysctl 的任何 CPU 上,因为模拟不经过内核的中断分发)。 +4. 计数器递增;任务运行。 -Observations: -- `sysctl dev.myfirst.0.intr_mode` returns 2. -- `vmstat -i | grep myfirst` shows three lines; each has a different IRQ number. -- `cpuset -g -x ` for each IRQ shows different CPU masks. +观察结果: +- `sysctl dev.myfirst.0.intr_mode` 返回 2。 +- `vmstat -i | grep myfirst` 显示三行;每行有不同的 IRQ 号。 +- 每个 IRQ 的 `cpuset -g -x ` 显示不同的 CPU 掩码。 -A real (non-simulated) MSI-X interrupt would dispatch on the bound CPU; the simulation bypass makes it run on the calling thread's CPU. This is a limitation of the simulation technique but does not affect correctness. +真实的(非模拟)MSI-X 中断会在绑定的 CPU 上分发;模拟旁路使其在调用线程的 CPU 上运行。这是模拟技术的局限性,但不影响正确性。 ### 教训 -All three tiers drive the same filter logic and the same task. The only differences are: +所有三个层级都驱动相同的过滤器逻辑和相同的任务。唯一的区别是: -- Which rid the IRQ resource uses (0 for legacy, 1+ for MSI/MSI-X). -- Whether `pci_alloc_msi` or `pci_alloc_msix` succeeded. -- How many filter functions are registered (1 for legacy, 3 for MSI/MSI-X). -- Which CPU real interrupts dispatch on. +- IRQ 资源使用哪个 rid(legacy 为 0,MSI/MSI-X 为 1+)。 +- `pci_alloc_msi` 还是 `pci_alloc_msix` 成功。 +- 注册了多少个过滤器函数(legacy 为 1,MSI/MSI-X 为 3)。 +- 真实中断在哪个 CPU 上分发。 -A well-written driver works identically on all three tiers. Chapter 20's fallback ladder ensures this. +编写良好的驱动程序在所有三个层级上工作方式相同。第20章的回退阶梯确保了这一点。 ## 实践实验:跨三个层级的回归测试 -A lab that exercises the fallback ladder to confirm all three tiers work. +一个练习回退阶梯以确认所有三个层级都能工作的实验。 ### 设置 -You need two test environments: +您需要两个测试环境: -- **Environment A**: bhyve with virtio-rnd. The driver falls back to legacy INTx. -- **Environment B**: QEMU with virtio-rng-pci. The driver uses MSI-X. +- **环境 A**:带有 virtio-rnd 的 bhyve。驱动程序回退到 legacy INTx。 +- **环境 B**:带有 virtio-rng-pci 的 QEMU。驱动程序使用 MSI-X。 -(A third environment with only MSI and no MSI-X is hard to construct reliably on modern platforms. The MSI path is exercised only if the reader has a system where MSI-X fails but MSI works.) +(第三个只有 MSI 而没有 MSI-X 的环境在现代平台上很难可靠构建。只有当读者拥有 MSI-X 失败但 MSI 工作的系统时,MSI 路径才会被练习。) ### 过程 -1. On Environment A, load `myfirst.ko`. Verify: +1. 在环境 A 上,加载 `myfirst.ko`。验证: ```sh sysctl dev.myfirst.0.intr_mode # returns 0 vmstat -i | grep myfirst # one line ``` -2. Exercise the pipeline via the simulated-interrupt sysctls. All three should work, though on legacy they all go through the same filter. +2. 通过模拟中断 sysctl 练习管道。所有三个都应该工作,虽然在 legacy 上它们都经过同一个过滤器。 ```sh sudo sysctl dev.myfirst.0.intr_simulate_admin=2 @@ -3087,9 +3087,9 @@ sudo sysctl dev.myfirst.0.intr_simulate_tx=4 sysctl dev.myfirst.0.intr_count # should be 3 ``` -3. Unload. Verify no leaks. +3. 卸载。验证无泄漏。 -4. On Environment B, repeat: +4. 在环境 B 上,重复: ```sh sysctl dev.myfirst.0.intr_mode # returns 2 @@ -3097,7 +3097,7 @@ vmstat -i | grep myfirst # three lines for irq in ; do cpuset -g -x $irq; done ``` -5. Exercise the per-vector pipeline. Each sysctl should increment its own vector's counter. +5. 练习每向量管道。每个 sysctl 应递增其自己向量的计数器。 ```sh sudo sysctl dev.myfirst.0.intr_simulate_admin=2 @@ -3106,75 +3106,75 @@ sysctl dev.myfirst.0.vec.rx.fire_count # 0 sysctl dev.myfirst.0.vec.tx.fire_count # 0 ``` -6. Unload. Verify no leaks. +6. 卸载。验证无泄漏。 ### 预期观察 -- Both environments attach cleanly. -- The dmesg summary line shows the correct mode for each. -- Per-vector counters tick independently on MSI-X. -- On legacy, a single counter covers all events. -- No leaks after unload in either environment. +- 两个环境都干净地附加。 +- dmesg 摘要行为每个环境显示正确的模式。 +- 在 MSI-X 上,每向量计数器独立跳动。 +- 在 legacy 上,单个计数器覆盖所有事件。 +- 两个环境中卸载后均无泄漏。 ### 如果某层失败该怎么办 -If the MSI-X tier fails on Environment B: +如果 MSI-X 层级在环境 B 上失败: -1. Verify QEMU is new enough. Older versions (pre-5.0) have quirks. -2. Check `pciconf -lvc` in the guest; MSI-X capability should be visible. -3. Check `dmesg` for errors from `pci_alloc_msix`. +1. 验证 QEMU 版本足够新。旧版本(5.0 之前)有 quirks。 +2. 在 guest 中检查 `pciconf -lvc`;MSI-X 能力应该可见。 +3. 检查 `dmesg` 中来自 `pci_alloc_msix` 的错误。 -If the legacy tier fails on Environment A: +如果 legacy 层级在环境 A 上失败: -1. Check `pciconf -lvc` for the device's interrupt line configuration. -2. Ensure `virtio_rnd` is not already attached (Chapter 18 caveat). -3. Look for `pci_alloc_resource` failures in `dmesg`. +1. 检查 `pciconf -lvc` 以确认设备的中断线配置。 +2. 确保 `virtio_rnd` 尚未附加(第18章注意事项)。 +3. 在 `dmesg` 中查找 `pci_alloc_resource` 失败。 ## 扩展挑战:构建生产级驱动程序 -An optional exercise for readers who want to practise multi-vector design on a realistic scale. +一个可选的练习,适合于希望在现实规模上练习多向量设计的读者。 ### 目标 -Take the Chapter 20 driver and extend it to handle N queues dynamically, where N is discovered at attach time based on the allocated MSI-X vector count. Each queue has: +采用第20章的驱动程序,扩展它以动态处理 N 个队列,其中 N 在附加时根据分配的 MSI-X 向量计数确定。每个队列具有: -- Its own vector (MSI-X vector 1+queue_id). -- Its own filter function (or a shared one that identifies the queue from the vector arg). -- Its own counters. -- Its own task on its own taskqueue. -- Its own NUMA-local CPU binding. +- 自己的向量(MSI-X 向量 1+queue_id)。 +- 自己的过滤器函数(或从向量参数识别队列的共享函数)。 +- 自己的计数器。 +- 自己任务队列上的自己的任务。 +- 自己的 NUMA 本地 CPU 绑定。 ### 实现大纲 -1. Replace `MYFIRST_MAX_VECTORS` with a runtime-chosen count. -2. Allocate the `vectors[]` array dynamically (using `malloc`). +1. 用运行时选择的计数替换 `MYFIRST_MAX_VECTORS`。 +2. 动态分配 `vectors[]` 数组(使用 `malloc`)。 3. Allocate a separate taskqueue per vector. 4. Use `bus_get_cpus(INTR_CPUS, ...)` to distribute vectors across NUMA-local CPUs. -5. Add sysctls that scale with the vector count. +5. 添加随向量计数扩展的 sysctl。 ### 测试 -Run the driver on a guest with varying MSI-X vector counts. For each count, verify: -- The fire counters tick for the simulated interrupts. -- The CPU affinity respects NUMA locality. -- Teardown is clean. +在具有不同 MSI-X 向量计数的 guest 上运行驱动程序。对每个计数,验证: +- 模拟中断的触发计数器跳动。 +- CPU 亲和性遵守 NUMA 局部性。 +- 拆除干净。 ### 本练习的内容 - Dynamic memory management in a driver. -- The `bus_get_cpus` API. -- Per-queue taskqueues (challenge 3 from earlier). -- Runtime sysctl tree construction (challenge 7 from earlier). +- `bus_get_cpus` API。 +- 每队列任务队列(之前的挑战3)。 +- 运行时 sysctl 树构建(之前的挑战7)。 -This is a significant exercise and will likely take several hours. The result is a driver recognisably similar to production NIC and NVMe drivers. +这是一个重要的练习,可能需要数小时。结果是一个在结构上类似于生产级 NIC 和 NVMe 驱动程序的驱动程序。 ## 参考:中断和任务工作的优先级值 -For quick reference, the priority constants a Chapter 20 driver might use (from `/usr/src/sys/sys/priority.h`): +快速参考,第20章驱动程序可能使用的优先级常量(来自 `/usr/src/sys/sys/priority.h`): ```text PI_REALTIME = PRI_MIN_ITHD + 0 (highest; rarely used) @@ -3187,13 +3187,13 @@ PI_DULL = PI_INTR (low-priority hardware) PI_SOFT = PRI_MIN_ITHD + 8 (soft interrupts) ``` -The common hardware priorities all map to `PI_INTR`; the names are distinctions of intent rather than of scheduling priority. Chapter 20's driver uses `PI_NET` for its taskqueue; any hardware-level priority would work equivalently. +常见的硬件优先级都映射到 `PI_INTR`;这些名称是意图的区别,而不是调度优先级的区别。第20章的驱动程序对其任务队列使用 `PI_NET`;任何硬件级优先级都可以等效工作。 ## 参考:MSI-X 驱动程序有用的 DTrace 单行命令 -For readers who want to observe the Chapter 20 driver's behaviour dynamically. +对于希望动态观察第20章驱动程序行为的读者。 ### 统计每个 CPU 的过滤器调用次数 @@ -3203,7 +3203,7 @@ fbt::myfirst_admin_filter:entry, fbt::myfirst_rx_filter:entry, fbt::myfirst_tx_filter:entry { @[probefunc, cpu] = count(); }' ``` -Shows which filter runs on which CPU. +显示哪个过滤器在哪个 CPU 上运行。 ### 每个过滤器花费的时间 @@ -3216,7 +3216,7 @@ fbt::myfirst_rx_filter:return /self->ts/ { }' ``` -Histogram of RX filter CPU time. +RX 过滤器 CPU 时间的直方图。 ### 模拟中断与真实中断的比率 @@ -3226,7 +3226,7 @@ fbt::myfirst_intr_simulate_vector_sysctl:entry { @sims = count(); } fbt::myfirst_rx_filter:entry { @filters = count(); }' ``` -If `filters > sims`, some real interrupts are firing. +如果 `filters > sims`,一些真实中断正在触发。 ### 任务延迟 @@ -3239,74 +3239,74 @@ fbt::myfirst_rx_task_fn:entry /self->ts/ { }' ``` -Histogram of time from filter to task invocation. Shows the taskqueue's scheduling latency. +从过滤器到任务调用的时间直方图。显示任务队列的调度延迟。 ## 参考:第四部分结束前的结束语 -Chapters 16 through 20 built the full interrupt and hardware story for the `myfirst` driver. Each chapter added one layer: +第16章到第20章为 `myfirst` 驱动程序构建了完整的中断和硬件故事。每章添加一层: -- Chapter 16: register access. -- Chapter 17: device behaviour simulation. -- Chapter 18: PCI attach. -- Chapter 19: single-vector interrupt handling. -- Chapter 20: multi-vector MSI/MSI-X. +- 第16章:寄存器访问。 +- 第17章:设备行为模拟。 +- 第18章:PCI 附加。 +- 第19章:单向量中断处理。 +- 第20章:多向量 MSI/MSI-X。 -Chapter 21 will add DMA, completing Part 4's hardware layer. At that point, the `myfirst` driver will be structurally a real driver: a PCI device with MSI-X interrupts and DMA-based data transfer. What distinguishes it from a production driver is the specific protocol it speaks (none, really; it is a demo) and the device it targets (a virtio-rnd abstraction). +第21章将添加 DMA,完成第4部分的硬件层。那时,`myfirst` 驱动程序在结构上将是一个真正的驱动程序:具有 MSI-X 中断和基于 DMA 的数据传输的 PCI 设备。它与生产驱动程序的区别在于它所说的特定协议(实际上没有;它是一个演示)和它针对的设备(一个 virtio-rnd 抽象)。 -A reader who has internalised these five chapters can open any FreeBSD driver in `/usr/src/sys/dev/` and recognise the patterns. That recognition is Part 4's deepest payoff. +已经内化这五章的读者可以打开 `/usr/src/sys/dev/` 中的任何 FreeBSD 驱动程序并识别这些模式。这种识别是第4部分最深的回报。 ## 动手实验 -The labs are graduated checkpoints. Each lab builds on the previous one and corresponds to one of the chapter's stages. A reader who works through all five has a complete multi-vector driver, a working QEMU test environment for MSI-X, and a regression script that validates all three tiers of the fallback ladder. +这些实验是分级的检查点。每个实验建立在前一个实验的基础上,对应于本章的一个阶段。完成所有五个实验的读者将拥有一个完整的多年驱动程序、一个用于 MSI-X 的工作 QEMU 测试环境,以及一个验证回退阶梯所有三个层级的回归脚本。 -Time budgets assume the reader has already read the relevant sections. +时间预算假设读者已经阅读了相关章节。 ### 实验 1:发现 MSI 和 MSI-X 能力 Time: thirty minutes. -Objective: Build an intuition for which devices on your system support MSI and MSI-X. +目标:建立对系统上哪些设备支持 MSI 和 MSI-X 的直觉。 Steps: -1. Run `sudo pciconf -lvc > /tmp/pci_caps.txt`. The `-c` flag includes capability lists. -2. Search for MSI capabilities: `grep -B 1 "cap 05" /tmp/pci_caps.txt`. -3. Search for MSI-X capabilities: `grep -B 1 "cap 11" /tmp/pci_caps.txt`. -4. For three devices that support MSI-X, note: - - The device's name (`pci0:B:D:F`). - - The number of MSI-X messages supported. - - Whether the driver is currently using MSI-X (check `vmstat -i` for multiple lines of the same device name). -5. Compare the total number of MSI-capable devices to the total number of MSI-X-capable devices. Modern systems typically have more MSI-X devices than MSI-only devices. +1. 运行 `sudo pciconf -lvc > /tmp/pci_caps.txt`。`-c` 标志包含能力列表。 +2. 搜索 MSI 能力:`grep -B 1 "cap 05" /tmp/pci_caps.txt`。 +3. 搜索 MSI-X 能力:`grep -B 1 "cap 11" /tmp/pci_caps.txt`。 +4. 对于三个支持 MSI-X 的设备,记录: + - 设备名称(`pci0:B:D:F`)。 + - 支持的 MSI-X 消息数。 + - 驱动程序当前是否正在使用 MSI-X(检查 `vmstat -i` 中同一设备名称的多行)。 +5. 比较支持 MSI 的设备总数与支持 MSI-X 的设备总数。现代系统通常有比仅 MSI 设备更多的 MSI-X 设备。 Expected observations: -- NICs usually advertise MSI-X with many vectors (4 to 64). -- SATA and NVMe controllers advertise MSI-X (NVMe often with dozens of vectors). -- Some legacy devices (an audio chip, a USB controller) advertise only MSI. -- A few very old devices advertise neither and rely on legacy INTx. +- NIC 通常公布具有许多向量的 MSI-X(4 到 64)。 +- SATA 和 NVMe 控制器公布 MSI-X(NVMe 通常有几十个向量)。 +- 一些遗留设备(音频芯片、USB 控制器)仅公布 MSI。 +- 少数非常老的设备既不公布,依赖 legacy INTx。 -This lab is about vocabulary. No code. The payoff is that Section 2 and 5's allocation calls become concrete. +本实验关乎词汇。没有代码。回报是第2节和第5节的分配调用变得具体。 ### 实验 2:阶段 1,MSI 回退阶梯 -Time: two to three hours. +时间:两到三小时。 -Objective: Extend Chapter 19's driver with the MSI-first fallback ladder. Version target: `1.3-msi-stage1`. +目标:用 MSI 优先的回退阶梯扩展第19章的驱动程序。版本目标:`1.3-msi-stage1`。 Steps: -1. Starting from Chapter 19 Stage 4, copy the driver source to a new working directory. -2. Add the `intr_mode` field and enum to `myfirst.h`. -3. Modify `myfirst_intr_setup` (in `myfirst_intr.c`) to attempt MSI allocation first, falling back to legacy INTx. -4. Modify `myfirst_intr_teardown` to call `pci_release_msi` when MSI was used. -5. Add the `dev.myfirst.N.intr_mode` sysctl. -6. Update the `Makefile` version string to `1.3-msi-stage1`. -7. Compile (`make clean && make`). -8. Load on a guest. Note which mode the driver reports: +1. 从第19章阶段4开始,将驱动程序源代码复制到新的工作目录。 +2. 向 `myfirst.h` 添加 `intr_mode` 字段和枚举。 +3. 修改 `myfirst_intr_setup`(在 `myfirst_intr.c` 中)以先尝试 MSI 分配,回退到 legacy INTx。 +4. 修改 `myfirst_intr_teardown` 以在使用 MSI 时调用 `pci_release_msi`。 +5. 添加 `dev.myfirst.N.intr_mode` sysctl。 +6. 将 `Makefile` 版本字符串更新为 `1.3-msi-stage1`。 +7. 编译(`make clean && make`)。 +8. 在 guest 上加载。注意驱动程序报告哪种模式: ```sh sudo kldload ./myfirst.ko @@ -3314,40 +3314,40 @@ sudo dmesg | tail -5 sysctl dev.myfirst.0.intr_mode ``` -On QEMU with virtio-rng-pci, the driver should report `MSI, 1 vector` (or similar). On bhyve with virtio-rnd, it should report `legacy INTx`. +在带有 virtio-rng-pci 的 QEMU 上,驱动程序应报告 `MSI, 1 vector`(或类似信息)。在带有 virtio-rnd 的 bhyve 上,应报告 `legacy INTx`。 -9. Unload and verify no leaks. +9. 卸载并验证无泄漏。 Common failures: -- Missing `pci_release_msi`: next load fails or falls back to legacy. -- Wrong rid (using 0 for MSI): `bus_alloc_resource_any` returns NULL. -- Not checking the returned count: driver proceeds with fewer vectors than expected. +- 缺少 `pci_release_msi`:下次加载失败或回退到 legacy。 +- rid 错误(对 MSI 使用 0):`bus_alloc_resource_any` 返回 NULL。 +- 未检查返回计数:驱动程序使用少于预期的向量继续运行。 ### 实验 3:阶段 2,多向量分配 (MSI) -Time: three to four hours. +时间:三到四小时。 -Objective: Extend to three MSI vectors with per-vector handlers. Version target: `1.3-msi-stage2`. +目标:扩展到具有每向量处理程序的三个 MSI 向量。版本目标:`1.3-msi-stage2`。 Steps: -1. Starting from Lab 2, add the `myfirst_vector` struct and per-vector array to `myfirst.h`. -2. Write three filter functions: `myfirst_admin_filter`, `myfirst_rx_filter`, `myfirst_tx_filter`. -3. Write the `myfirst_intr_setup_vector` and `myfirst_intr_teardown_vector` helpers. -4. Modify `myfirst_intr_setup` to try `pci_alloc_msi` for `MYFIRST_MAX_VECTORS` vectors, setting up each vector independently. -5. Modify `myfirst_intr_teardown` to loop per-vector. -6. Add per-vector counter sysctls (`vec0_fire_count`, `vec1_fire_count`, `vec2_fire_count`). -7. Add per-vector simulated-interrupt sysctls (`intr_simulate_admin`, `intr_simulate_rx`, `intr_simulate_tx`). -8. Bump the version to `1.3-msi-stage2`. -9. Compile, load, verify: +1. 从实验2开始,向 `myfirst.h` 添加 `myfirst_vector` 结构和每向量数组。 +2. 编写三个过滤器函数:`myfirst_admin_filter`、`myfirst_rx_filter`、`myfirst_tx_filter`。 +3. 编写 `myfirst_intr_setup_vector` 和 `myfirst_intr_teardown_vector` 辅助函数。 +4. 修改 `myfirst_intr_setup` 以尝试为 `MYFIRST_MAX_VECTORS` 向量调用 `pci_alloc_msi`,独立设置每个向量。 +5. 修改 `myfirst_intr_teardown` 以循环每向量。 +6. 添加每向量计数器 sysctl(`vec0_fire_count`、`vec1_fire_count`、`vec2_fire_count`)。 +7. 添加每向量模拟中断 sysctl(`intr_simulate_admin`、`intr_simulate_rx`、`intr_simulate_tx`)。 +8. 将版本提升到 `1.3-msi-stage2`。 +9. 编译,加载,验证: ```sh sysctl dev.myfirst.0.intr_mode # should be 1 on QEMU vmstat -i | grep myfirst # should show 3 lines ``` -10. Exercise each vector: +10. 练习每个向量: ```sh sudo sysctl dev.myfirst.0.intr_simulate_admin=2 # ERROR @@ -3356,33 +3356,33 @@ sudo sysctl dev.myfirst.0.intr_simulate_tx=4 # COMPLETE sysctl dev.myfirst.0 | grep vec ``` -Each vector's counter should increment independently. +每个向量的计数器应独立递增。 -11. Unload, verify no leaks. +11. 卸载,验证无泄漏。 ### 实验 4:阶段 3,带 CPU 绑定的 MSI-X -Time: three to four hours. +时间:三到四小时。 -Objective: Prefer MSI-X over MSI, bind each vector to a CPU. Version target: `1.3-msi-stage3`. +目标:优先使用 MSI-X 而非 MSI,将每个向量绑定到 CPU。版本目标:`1.3-msi-stage3`。 Steps: -1. Starting from Lab 3, change the fallback ladder to attempt MSI-X first (via `pci_msix_count` and `pci_alloc_msix`), MSI as second tier, legacy as last. -2. Add the `myfirst_msix_bind_vectors` helper that calls `bus_bind_intr` for each vector. -3. Call the bind helper after all vectors are registered. -4. Update the dmesg summary line to distinguish MSI-X from MSI. -5. Bump the version to `1.3-msi-stage3`. -6. Compile, load on QEMU with `virtio-rng-pci`. Verify: +1. 从实验3开始,更改回退阶梯以先尝试 MSI-X(通过 `pci_msix_count` 和 `pci_alloc_msix`),MSI 作为第二层,legacy 作为最后。 +2. 添加 `myfirst_msix_bind_vectors` 辅助函数,为每个向量调用 `bus_bind_intr`。 +3. 在所有向量注册后调用绑定辅助函数。 +4. 更新 dmesg 摘要行以区分 MSI-X 和 MSI。 +5. 将版本提升到 `1.3-msi-stage3`。 +6. 编译,在带有 `virtio-rng-pci` 的 QEMU 上加载。验证: ```sh -sysctl dev.myfirst.0.intr_mode # should be 2 on QEMU +sysctl dev.myfirst.0.intr_mode # 在 QEMU 上应为 2 sudo dmesg | grep myfirst | grep MSI-X ``` -The attach line should read `interrupt mode: MSI-X, 3 vectors`. +附加行应为 `interrupt mode: MSI-X, 3 vectors`。 -7. Check per-vector CPU bindings: +7. 检查每向量 CPU 绑定: ```sh # For each myfirst IRQ, show its CPU binding. @@ -3394,89 +3394,89 @@ for irq in ; do done ``` -On a multi-CPU guest, each vector should be bound to a different CPU. +在多 CPU guest 上,每个向量应绑定到不同的 CPU。 -8. Exercise each vector (same as Lab 3). +8. 练习每个向量(与实验3相同)。 -9. Detach and reattach: +9. 分离并重新附加: ```sh sudo devctl detach myfirst0 sudo devctl attach pci0:0:4:0 -sysctl dev.myfirst.0.intr_mode # should still be 2 +sysctl dev.myfirst.0.intr_mode # 应仍为 2 ``` -10. Unload, verify no leaks. +10. 卸载,验证无泄漏。 ### 实验 5:阶段 4,重构、回归、版本 -Time: three to four hours. +时间:三到四小时。 -Objective: Move the multi-vector code into `myfirst_msix.c`, write `MSIX.md`, run the regression. Version target: `1.3-msi`. +目标:将多向量代码移入 `myfirst_msix.c`,编写 `MSIX.md`,运行回归测试。版本目标:`1.3-msi`。 Steps: -1. Starting from Lab 4, create `myfirst_msix.c` and `myfirst_msix.h`. -2. Move the per-vector filter functions, helpers, setup, teardown, and sysctl registration into `myfirst_msix.c`. -3. Keep the legacy-INTx fallback in `myfirst_intr.c` (Chapter 19's file). -4. In `myfirst_pci.c`, replace the old interrupt setup/teardown calls with calls into `myfirst_msix.c`. -5. Update the `Makefile` to add `myfirst_msix.c` to SRCS. Bump the version to `1.3-msi`. -6. Write `MSIX.md` documenting the multi-vector design. -7. Compile, load, run the full regression script (from the companion examples). -8. Confirm all three tiers work (by testing on bhyve with virtio-rnd for legacy and QEMU with virtio-rng-pci for MSI-X). +1. 从实验4开始,创建 `myfirst_msix.c` 和 `myfirst_msix.h`。 +2. 将每向量过滤器函数、辅助函数、设置、拆除和 sysctl 注册移入 `myfirst_msix.c`。 +3. 将 legacy-INTx 回退保留在 `myfirst_intr.c`(第19章的文件)中。 +4. 在 `myfirst_pci.c` 中,用对 `myfirst_msix.c` 的调用替换旧的中断设置/拆除调用。 +5. 更新 `Makefile` 将 `myfirst_msix.c` 添加到 SRCS。将版本提升到 `1.3-msi`。 +6. 编写 `MSIX.md` 记录多向量设计。 +7. 编译、加载、运行完整的回归脚本(来自配套示例)。 +8. 确认所有三个层级都工作(通过在 bhyve 上使用 virtio-rnd 测试 legacy,在 QEMU 上使用 virtio-rng-pci 测试 MSI-X)。 Expected outcomes: -- The driver at `1.3-msi` works on both bhyve (legacy fallback) and QEMU (MSI-X). -- `myfirst_intr.c` now only contains the Chapter 19 single-handler fallback path. -- `myfirst_msix.c` contains the Chapter 20 multi-vector logic. -- `MSIX.md` documents the design clearly. +- `1.3-msi` 版本的驱动程序在 bhyve(legacy 回退)和 QEMU(MSI-X)上都能工作。 +- `myfirst_intr.c` 现在只包含第19章的单处理程序回退路径。 +- `myfirst_msix.c` 包含第20章的多向量逻辑。 +- `MSIX.md` 清晰地记录了该设计。 ## 挑战练习 -The challenges build on the labs and extend the driver in directions the chapter did not take. +这些挑战练习建立在实验的基础上,将驱动程序扩展至本章未涉及的方向。 ### 挑战 1:动态向量计数适配 -Modify the setup to adapt to whatever vector count the kernel actually allocates. If 3 are requested but 2 are allocated, the driver should still work with 2 (fold admin and tx into one combined vector). If 1 is allocated, fold everything into one. +修改设置以适应内核实际分配的任何向量计数。如果请求 3 个但只分配了 2 个,驱动程序仍应能使用 2 个工作(将 admin 和 tx 合并到一个向量中)。如果只分配了 1 个,将所有内容合并到一个中。 -This exercise teaches the "adapt" strategy from the fallback ladder. +此练习教授回退阶梯中的"适应"策略。 ### 挑战 2:NUMA 感知的 CPU 绑定 -Replace the round-robin CPU binding with a NUMA-aware binding using `bus_get_cpus(dev, INTR_CPUS, ...)`. Verify with `cpuset -g -x ` that vectors land on CPUs in the same NUMA domain as the device. +使用 `bus_get_cpus(dev, INTR_CPUS, ...)` 将轮询 CPU 绑定替换为 NUMA 感知绑定。用 `cpuset -g -x ` 验证向量落在与设备同一 NUMA 域的 CPU 上。 -On a single-socket system the exercise is academic; on a multi-socket test host it is measurable. +在单插槽系统上,此练习是理论性的;在多插槽测试主机上,效果是可测量的。 ### 挑战 3:每向量任务队列 -Each vector currently shares one taskqueue. Modify the driver so each vector has its own taskqueue (with its own worker thread). Measure the latency impact with DTrace. +目前每个向量共享一个任务队列。修改驱动程序,使每个向量有自己的任务队列(有自己的工作线程)。用 DTrace 测量延迟影响。 -This exercise introduces per-vector workers and shows when they help vs hurt. +此练习引入每向量工作者,并展示它们何时有帮助、何时有害。 ### 挑战 4:每向量 MSI-X 掩码控制 -The MSI-X table's vector-control register has a mask bit per vector. Add a sysctl that lets the operator mask an individual vector at runtime. Verify that a masked vector stops receiving interrupts. +MSI-X 表的向量控制寄存器每个向量有一个掩码位。添加一个 sysctl,让操作员在运行时掩码单个向量。验证被掩码的向量停止接收中断。 -Hint: the mask bit is programmed through direct MSI-X table access, which is a deeper topic than Chapter 20 covers. The FreeBSD MSI-X implementation may or may not expose this directly; a reader might need to use `bus_teardown_intr` and later `bus_setup_intr` as a higher-level "soft mask". +提示:掩码位通过直接 MSI-X 表访问编程,这是比第20章涵盖更深的话题。FreeBSD 的 MSI-X 实现可能直接暴露也可能不直接暴露这一点;读者可能需要使用 `bus_teardown_intr` 然后 `bus_setup_intr` 作为更高级别的"软掩码"。 ### 挑战5:实现中断调节 -For a simulated driver, moderation is easy to prototype: a sysctl that coalesces N simulated interrupts into one task run. Implement the coalescing, measure the latency-vs-throughput trade-off. +对于模拟驱动程序,调节很容易原型化:一个将 N 个模拟中断合并为一次任务运行的 sysctl。实现合并,测量延迟与吞吐量的权衡。 ### 挑战6:运行时向量重分配 -Add a sysctl that lets the operator reassign which vector handles which event class (e.g., swap RX and TX). Demonstrate that after the reassignment, simulated-interrupt-RX triggers the TX filter and vice versa. +添加一个 sysctl,让操作员重新分配哪个向量处理哪个事件类(例如,交换 RX 和 TX)。演示重新分配后,模拟中断 RX 触发 TX 过滤器,反之亦然。 ### 挑战7:每队列 Sysctl 树 -Restructure the per-vector sysctls into a proper tree: `dev.myfirst.N.vec.admin.fire_count`, `dev.myfirst.N.vec.rx.fire_count`, etc. Use `SYSCTL_ADD_NODE` to create the tree nodes. +将每向量 sysctl 重构为适当的树形结构:`dev.myfirst.N.vec.admin.fire_count`、`dev.myfirst.N.vec.rx.fire_count` 等。使用 `SYSCTL_ADD_NODE` 创建树节点。 ### 挑战8:DTrace 监测 -Write a DTrace script that shows the per-CPU distribution of each vector's filter invocations. Plot the per-CPU breakdown as a histogram. This is the diagnostic that confirms CPU binding is working. +编写一个 DTrace 脚本,显示每个向量过滤器调用的每 CPU 分布。将每 CPU 分解绘制为直方图。这是确认 CPU 绑定正在工作的诊断方法。 @@ -3484,47 +3484,47 @@ Write a DTrace script that shows the per-CPU distribution of each vector's filte ### "pci_alloc_msix 返回 EBUSY 或 ENXIO" -Possible causes: +可能的原因: -1. The device is not connected in a way that supports MSI-X (legacy virtio-rnd on bhyve, for example). Check `pciconf -lvc`. -2. A previous load of the driver did not call `pci_release_msi` at teardown. Reboot or try `kldunload` + `kldload` again. -3. The kernel ran out of interrupt vectors. Rare on modern x86, possible on low-vector platforms. +1. 设备未以支持 MSI-X 的方式连接(例如,bhyve 上的 legacy virtio-rnd)。检查 `pciconf -lvc`。 +2. 先前加载的驱动程序在拆除时未调用 `pci_release_msi`。重新启动或尝试再次 `kldunload` + `kldload`。 +3. 内核用尽了中断向量。在现代 x86 上很少见,在低向量平台上可能发生。 ### "vmstat -i 在 MSI-X guest 上只显示一行" -Likely cause: `pci_alloc_msix` succeeded but allocated only 1 vector. Check the returned count vs requested. Either accept (fold work into one) or release and fall back. +可能的原因:`pci_alloc_msix` 成功但只分配了 1 个向量。检查返回计数与请求计数。接受(将工作合并到一个)或释放并回退。 ### "过滤器触发但 vec->fire_count 保持为零" -Likely cause: the `sc` argument is confused with `vec`. The handler receives `vec`, not `sc`. Check `bus_setup_intr`'s argument. +可能的原因:`sc` 参数与 `vec` 混淆。处理程序接收 `vec`,而不是 `sc`。检查 `bus_setup_intr` 的参数。 ### "多次加载/卸载循环后 kldunload 时驱动崩溃" -Likely cause: `pci_release_msi` not called on teardown. The device-level MSI state leaks across loads; eventually the kernel's internal bookkeeping is confused. +可能的原因:拆除时未调用 `pci_release_msi`。设备级 MSI 状态在加载之间泄漏;最终内核的内部记账混乱。 ### "不同的向量都在同一个 CPU 上触发" -Likely cause: `bus_bind_intr` failed silently. Check the return value and log non-zero results. +可能的原因:`bus_bind_intr` 静默失败。检查返回值并记录非零结果。 ### "MSI-X 分配成功但 vmstat -i 不显示事件" -Likely cause: the device's `INTR_MASK` write targeted the wrong register or was skipped. Verify the mask is set (Chapter 17/Chapter 19 diagnostic). +可能的原因:设备的 `INTR_MASK` 写入针对了错误的寄存器或被跳过。验证掩码已设置(第17章/第19章诊断)。 ### "杂散中断在 MSI-X 管理向量上累积" -Likely cause: the admin filter's status check is wrong; the filter returns `FILTER_STRAY` when it should handle. Check the `status & MYFIRST_INTR_ERROR` check. +可能的原因:管理过滤器的状态检查错误;过滤器应该处理时返回了 `FILTER_STRAY`。检查 `status & MYFIRST_INTR_ERROR` 检查。 ### "legacy 回退上的共享 IRQ 行为与 MSI-X 不同" -Expected. On legacy INTx the single handler sees every event bit; on MSI-X each vector sees only its own event. Tests that exercise per-vector stray counts differ between the two modes. +这是预期的。在 legacy INTx 上,单个处理程序看到每个事件位;在 MSI-X 上,每个向量只看到自己的事件。练习每向量杂散计数的测试在这两种模式下不同。 ### "阶段 2 编译通过但阶段 3 在 `bus_get_cpus` 链接错误处失败" -Cause: `bus_get_cpus` may not be available in older FreeBSD versions or may require specific `#include ` placement. Check the include order. +原因:`bus_get_cpus` 可能在较旧的 FreeBSD 版本中不可用,或可能需要特定的 `#include ` 放置。检查 include 顺序。 ### "QEMU guest 不暴露 MSI-X 即使使用 virtio-rng-pci" -Likely cause: older QEMU versions use legacy virtio by default. Check `pciconf -lvc` in the guest; if MSI-X is not listed, the guest is using legacy. Update QEMU or use `-device virtio-rng-pci,disable-modern=off,disable-legacy=on`. +可能的原因:较旧的 QEMU 版本默认使用 legacy virtio。在 guest 中检查 `pciconf -lvc`;如果未列出 MSI-X,则 guest 正在使用 legacy。更新 QEMU 或使用 `-device virtio-rng-pci,disable-modern=off,disable-legacy=on`。 @@ -3562,7 +3562,7 @@ Likely cause: older QEMU versions use legacy virtio by default. Check `pciconf - ## 通往第21章的桥梁 -第 21 章标题为 *DMA 和高速数据传输*。其范围是第 20 章刻意未涉及的主题:设备直接读写 RAM 的能力,无需驱动程序参与每个字。 A NIC with a 64-entry receive descriptor ring populates those entries by DMA from the wire; a single interrupt signals "N entries are ready". The driver's handler walks the ring and processes the entries. Without DMA the driver would have to read each byte from a device register, which does not scale. +第 21 章标题为 *DMA 和高速数据传输*。其范围是第 20 章刻意未涉及的主题:设备直接读写 RAM 的能力,无需驱动程序参与每个字。 具有 64 条目接收描述符环的 NIC 通过 DMA 从线路上填充这些条目;单个中断信号表示"N 条目已就绪"。驱动程序的处理程序遍历环并处理条目。没有 DMA,驱动程序必须从设备寄存器读取每个字节,这无法扩展。 第 20 章以三种具体方式做好了准备。 @@ -3574,15 +3574,15 @@ Likely cause: older QEMU versions use legacy virtio by default. Check `pciconf - 第 21 章将涵盖的具体主题: -- What DMA is, the difference between memory-mapped I/O and DMA. -- `bus_dma(9)`: tags, maps, and the DMA state machine. -- `bus_dma_tag_create` to describe DMA requirements (alignment, boundaries, address range). -- `bus_dmamap_create` and `bus_dmamap_load` to set up DMA transfers. -- Synchronisation: `bus_dmamap_sync` around DMA. -- Bounce buffers: what they are and when they are used. -- Cache coherence: why CPUs and devices see different memory at different times. -- Scatter-gather lists: physical addresses that are not contiguous. -- Ring buffers: the producer-consumer descriptor ring pattern. +- DMA 是什么,内存映射 I/O 与 DMA 的区别。 +- `bus_dma(9)`:标签、映射和 DMA 状态机。 +- `bus_dma_tag_create` 描述 DMA 需求(对齐、边界、地址范围)。 +- `bus_dmamap_create` 和 `bus_dmamap_load` 设置 DMA 传输。 +- 同步:DMA 前后的 `bus_dmamap_sync`。 +- 反弹缓冲区:它们是什么以及何时使用。 +- 缓存一致性:为什么 CPU 和设备在不同时间看到不同的内容。 +- 分散-聚集列表:不连续的物理地址。 +- 环形缓冲区:生产者-消费者描述符环模式。 你不需要提前阅读。第 20 章已足够准备。带上你的 `myfirst` 驱动程序(`1.3-msi` 版本)、`LOCKING.md`、`INTERRUPTS.md`、`MSIX.md`、启用 `WITNESS` 的内核和回归脚本。第 21 章从第 20 章结束的地方开始。 diff --git a/translations/zh_CN/chapters/part4/chapter-22.md b/translations/zh_CN/chapters/part4/chapter-22.md index bb89fed..317351d 100644 --- a/translations/zh_CN/chapters/part4/chapter-22.md +++ b/translations/zh_CN/chapters/part4/chapter-22.md @@ -1039,39 +1039,39 @@ myfirst_pci_shutdown(device_t dev) 第2阶段驱动尚不做的是正确回来。恢复方法仍是第1阶段骨架;它记录日志并返回0而不恢复任何东西。如果挂起的设备有任何硬件丢失的状态,该状态已消失,后续传输将失败。第4节修复恢复路径使完整挂起-恢复周期将设备留在之前相同的状态。 -## Section 4: 恢复时恢复状态 +## 第4节:恢复时恢复状态 -Section 3 gave the driver a correct suspend path. Section 4 writes the matching resume. The resume is the complement of the suspend: every thing suspend stopped, resume restarts; every value suspend saved, resume writes back; every flag suspend set, resume clears. The sequence is not an exact mirror (resume runs in a different kernel context, with the PCI layer having already done work, and the device in a different state than where suspend left it), but the contents correspond one-to-one. Doing the resume correctly is a matter of respecting the contract the PCI layer has already partly fulfilled, and filling in the rest. +第3节给了驱动正确的挂起路径。第4节编写匹配的恢复。恢复是挂起的补集:挂起停止的一切,恢复重启;挂起保存的每个值,恢复写回;挂起设置的每个标志,恢复清除。顺序不是精确的镜像(恢复在不同的内核上下文中运行,PCI层已经做了一些工作,设备处于与挂起留下的不同状态),但内容一一对应。正确执行恢复意味着尊重PCI层已经部分完成的契约,并填补其余部分。 -### What the PCI Layer Has Already Done +### PCI层已经做了什么 -When the kernel's `DEVICE_RESUME` method is called on the driver, several things have already happened: +当内核在驱动上调用`DEVICE_RESUME`方法时,几件事已经发生: -1. The CPU has come out of the S-state (resumed from S3 or S4 back to S0). -2. Memory has been refreshed and the kernel has re-established its own state. -3. The parent bus has been resumed. For `myfirst`, that means the PCI bus driver has already handled the host bridge and the PCIe root complex. -4. The PCI layer has called `pci_set_powerstate(dev, PCI_POWERSTATE_D0)` on the device, transitioning it from whatever low-power state it was in (typically D3hot) back to full power. -5. The PCI layer has called `pci_cfg_restore(dev, dinfo)`, which writes the cached configuration space values (BARs, command register, cache-line size, etc.) back into the device. -6. The PCI layer has called `pci_clear_pme(dev)` to clear any pending power-management event bits. -7. The MSI or MSI-X configuration, which is part of the cached state, has been restored. The driver's interrupt vectors are usable again. +1. CPU已退出S状态(从S3或S4恢复到S0)。 +2. 内存已刷新,内核已重新建立自己的状态。 +3. 父总线已恢复。对于`myfirst`,这意味着PCI总线驱动已经处理了主机桥和PCIe根复合体。 +4. PCI层已在设备上调用`pci_set_powerstate(dev, PCI_POWERSTATE_D0)`,将其从任何低功耗状态(通常是D3hot)转回全功率。 +5. PCI层已调用`pci_cfg_restore(dev, dinfo)`,将缓存的配置空间值(BAR、命令寄存器、缓存行大小等)写回设备。 +6. PCI层已调用`pci_clear_pme(dev)`以清除任何待处理的电源管理事件位。 +7. MSI或MSI-X配置(作为缓存状态的一部分)已恢复。驱动的中断向量可再次使用。 -At this point the PCI bus driver calls into `myfirst`'s `DEVICE_RESUME`. The device is in D0, with its BARs mapped, its MSI/MSI-X table restored, and its generic PCI state intact. What the driver has to restore is the device-specific state that the PCI layer did not know about: the BAR-local registers the driver wrote during or after attach. +此时PCI总线驱动调用`myfirst`的`DEVICE_RESUME`。设备处于D0,其BAR已映射,其MSI/MSI-X表已恢复,其通用PCI状态完好。驱动需要恢复的是PCI层不知道的设备特定状态:驱动在挂载期间或之后写入的BAR局部寄存器。 -For the `myfirst` simulation, the relevant BAR-local registers are the interrupt mask (which the suspend path deliberately set to all-masked) and the DMA registers (which may have been left in an aborted state). The driver needs to put them back to values that reflect normal operation. +对于`myfirst`模拟,相关的BAR局部寄存器是中断掩码(挂起路径特意设置为全掩码)和DMA寄存器(可能已处于中止状态)。驱动需要将它们恢复为反映正常操作的值。 -### The Resume Discipline +### 恢复纪律 -A correct resume path does four things, in order: +正确的恢复路径按顺序做四件事: -1. **Re-enable bus-mastering**, in case the configuration-space restore did not do so or the PCI layer's automatic restore was disabled. This is `pci_enable_busmaster(dev)`. On modern FreeBSD it is usually redundant but harmless; older code paths or buggy BIOSes sometimes leave bus-mastering disabled. Calling it defensively is cheap. +1. **重新启用总线主控**,以防配置空间恢复未这样做或PCI层的自动恢复被禁用。这是`pci_enable_busmaster(dev)`。在现代FreeBSD上通常是冗余的但无害;旧代码路径或有缺陷的BIOS有时会让总线主控保持禁用。防御性调用成本低。 -2. **Restore any device-specific state** the driver saved during suspend. For `myfirst`, that means writing `saved_intr_mask` back to the INTR_MASK register. A real driver would also restore things like vendor-specific configuration bits, DMA engine programming, hardware timers, etc. +2. **恢复驱动在挂起期间保存的任何设备特定状态**。对于`myfirst`,这意味着将`saved_intr_mask`写回INTR_MASK寄存器。真实驱动还会恢复供应商特定配置位、DMA引擎编程、硬件定时器等。 -3. **Unmask interrupts and clear the suspended flag**, so the device can resume activity. This is the pivot point: before it, the device is still quiet; after it, the device can raise interrupts and accept work. +3. **取消掩码中断并清除挂起标志**,使设备可以恢复活动。这是转折点:在此之前,设备仍然安静;在此之后,设备可以引发中断并接受工作。 -4. **Log the transition and update counters**, for observability and regression testing. +4. **记录转换并更新计数器**,用于可观测性和回归测试。 -Here is what the pattern looks like in code: +以下是代码中的模式: ```c static int @@ -1099,33 +1099,33 @@ myfirst_pci_resume(device_t dev) } ``` -The helper `myfirst_restore` does the three real steps: +助手`myfirst_restore`执行三个实际步骤: ```c static int myfirst_restore(struct myfirst_softc *sc) { - /* Step 1: re-enable bus-master (defensive). */ + /* 步骤1:重新启用总线主控(防御性)。 */ pci_enable_busmaster(sc->dev); - /* Step 2: restore device-specific state. + /* 步骤2:恢复设备特定状态。 * - * For myfirst, this is just the interrupt mask. A real driver - * would restore more: DMA engine programming, hardware timers, - * vendor-specific configuration, etc. + * 对于myfirst,这只是中断掩码。真实驱动 + * 会恢复更多:DMA引擎编程、硬件定时器、 + * 供应商特定配置等。 */ if (sc->saved_intr_mask == 0xFFFFFFFF) { /* - * Suspend saved a fully-masked mask, which means the - * driver had no idea what the mask should be. Use the - * default: enable DMA completion, disable everything - * else. + * 挂起保存了一个全掩码的掩码,这意味着 + * 驱动不知道掩码应该是什么。使用 + * 默认值:启用DMA完成,禁用其他 + * 所有内容。 */ sc->saved_intr_mask = ~MYFIRST_INTR_COMPLETE; } CSR_WRITE_4(sc->dev, MYFIRST_REG_INTR_MASK, sc->saved_intr_mask); - /* Step 3: clear the suspended flag and unmask the device. */ + /* 步骤3:清除挂起标志并取消掩码设备。 */ MYFIRST_LOCK(sc); sc->suspended = false; MYFIRST_UNLOCK(sc); @@ -1134,41 +1134,41 @@ myfirst_restore(struct myfirst_softc *sc) } ``` -The function returns 0 because no step above can fail in the `myfirst` simulation. A real driver would check the return values of its hardware initialisation calls and propagate any errors. +该函数返回0,因为上述步骤在`myfirst`模拟中不会失败。真实驱动会检查其硬件初始化调用的返回值并传播任何错误。 -### Why pci_enable_busmaster Matters +### 为什么pci_enable_busmaster很重要 -Bus-mastering is a bit in the PCI command register that controls whether the device can issue DMA transactions. Without it, the device cannot read or write host memory; any DMA trigger would be silently ignored by the PCI host bridge. +总线主控是PCI命令寄存器中的一个位,控制设备是否可以发起DMA事务。没有它,设备无法读写主机内存;任何DMA触发都会被PCI主机桥静默忽略。 -Chapter 18 enabled bus-mastering during attach. The PCI layer's automatic config-space restore writes the command register back to its saved value, which includes the bus-master bit. So in principle the driver does not need to call `pci_enable_busmaster` again on resume. In practice, several things can go wrong: +第18章在挂载期间启用了总线主控。PCI层的自动配置空间恢复将命令寄存器写回其保存的值,其中包括总线主控位。因此原则上驱动不需要在恢复时再次调用`pci_enable_busmaster`。实际上,可能出几件事: -- The platform firmware may reset the command register as part of waking the device. -- The `hw.pci.do_power_suspend` sysctl may be 0, in which case the PCI layer does not save and restore the config space. -- A device-specific quirk might clear bus-mastering as a side effect of the D3-to-D0 transition. +- 平台固件可能在唤醒设备时重置命令寄存器。 +- `hw.pci.do_power_suspend` sysctl可能为0,此时PCI层不保存和恢复配置空间。 +- 设备特定的怪癖可能在D3到D0转换时清除总线主控作为副作用。 -Calling `pci_enable_busmaster` unconditionally defensively in resume is a low-cost safety net. Several production FreeBSD drivers follow this pattern; `if_re.c`'s resume path is one example. The call is idempotent: if bus-mastering is already on, the call just re-asserts it. +在恢复中无条件防御性地调用`pci_enable_busmaster`是低成本的安全网。几个生产FreeBSD驱动遵循此模式;`if_re.c`的恢复路径是一个例子。该调用是幂等的:如果总线主控已开启,调用只是重新断言它。 -### Restoring Device-Specific State +### 恢复设备特定状态 -The `myfirst` simulation does not have much state the driver needs to restore manually. The BAR-local registers are: +`myfirst`模拟没有太多驱动需要手动恢复的状态。BAR局部寄存器有: -- The interrupt mask (restored from `saved_intr_mask`). -- The interrupt status bits (were cleared in suspend; they should stay cleared until new activity arrives). -- The DMA engine registers (DMA_ADDR_LOW, DMA_ADDR_HIGH, DMA_LEN, DMA_DIR, DMA_CTRL, DMA_STATUS). These are transient: they hold the parameters of the current transfer. After resume, no transfer is in progress, so the values do not matter; the next transfer will overwrite them. +- 中断掩码(从`saved_intr_mask`恢复)。 +- 中断状态位(在挂起期间已清除;它们应保持清除直到新活动到达)。 +- DMA引擎寄存器(DMA_ADDR_LOW、DMA_ADDR_HIGH、DMA_LEN、DMA_DIR、DMA_CTRL、DMA_STATUS)。这些是瞬态的:它们持有当前传输的参数。恢复后没有传输在进行中,所以值不重要;下一次传输会覆盖它们。 -A real driver would have more. Consider a few examples: +真实驱动会更多。考虑几个例子: -- A storage driver might have a DMA descriptor ring whose base address the device learned during attach. After resume, the BAR-level register holding that base address may have been reset; the driver needs to reprogram it. -- A network driver might have filter tables (MAC addresses, multicast lists, VLAN tags) programmed into device registers. After resume, those tables may be empty; the driver rebuilds them from softc-side copies. -- A GPU driver might have register state for display timing, colour tables, hardware cursors. After resume, the driver restores the active mode. +- 存储驱动可能有一个DMA描述符环,其基址是设备在挂载期间学到的。恢复后,持有该基址的BAR级寄存器可能已被重置;驱动需要重新编程它。 +- 网络驱动可能有编程到设备寄存器中的过滤表(MAC地址、多播列表、VLAN标签)。恢复后,这些表可能为空;驱动从softc侧副本重建它们。 +- GPU驱动可能有显示定时、色彩表、硬件光标的寄存器状态。恢复后,驱动恢复活动模式。 -For `myfirst`, the interrupt mask is the only BAR-local state that needs restoring. The pattern shown above is the template a real driver would adapt to its device. +对于`myfirst`,中断掩码是需要恢复的唯一BAR局部状态。上面展示的模式是真实驱动会针对其设备调整的模板。 -### Validating Device Identity After Resume +### 恢复后验证设备身份 -Some devices are reset completely across a suspend-to-D3-cold cycle. The device that comes back is functionally the same, but its entire state has been reinitialised as if it had just powered on. A driver that assumed nothing changed would silently get wrong behaviour. +有些设备在挂起到D3cold的周期中完全重置。回来的设备功能上相同,但其整个状态已像刚上电一样重新初始化。假设什么都没改变的驱动会静默产生错误行为。 -A defensive resume path can detect this by reading a known register value and comparing to what it read at attach time. For a PCI device, the vendor ID and device ID in configuration space are always the same (the PCI layer restored them), but some device-private register (a revision ID, a self-test register, a firmware version) can be checked: +防御性的恢复路径可以通过读取已知寄存器值并与挂载时读取的值比较来检测这一点。对于PCI设备,配置空间中的供应商ID和设备ID始终相同(PCI层已恢复它们),但可以检查某些设备私有寄存器(修订ID、自检寄存器、固件版本): ```c static int @@ -1187,13 +1187,13 @@ myfirst_validate_device(struct myfirst_softc *sc) } ``` -For the `myfirst` simulation, there is no magic register (the simulation was not built with post-resume validation in mind). A reader who wants to add one as a challenge can extend the simulation backend's register map with a read-only `MAGIC` register, and have the driver check it. The chapter's Lab 3 includes this as an option. +对于`myfirst`模拟,没有魔术寄存器(模拟在构建时未考虑恢复后验证)。想要作为挑战添加一个的读者可以扩展模拟后端的寄存器映射,添加一个只读`MAGIC`寄存器,并让驱动检查它。本章的实验3将其作为选项包含。 -A real driver whose device truly does reset across D3cold needs this check, because without it a subtle failure can occur: the driver assumes the device's internal state machine is in state `IDLE`, but after the reset the state machine is actually in state `RESETTING`. Any command the driver sends is rejected, the driver interprets the rejection as a hardware fault, and the device is marked broken. Catching the reset explicitly and rebuilding state is cleaner. +真正在D3cold中重置的设备的真实驱动需要此检查,因为没有它可能发生微妙的故障:驱动假设设备的内部状态机处于`IDLE`状态,但重置后状态机实际处于`RESETTING`状态。驱动发送的任何命令都被拒绝,驱动将拒绝解释为硬件故障,设备被标记为损坏。显式捕获重置并重建状态更干净。 -### Detecting and Recovering from a Device Reset +### 检测和恢复设备重置 -If the validation finds a mismatch, the driver's recovery options depend on the hardware. For the `myfirst` simulation, the simplest response is to log, mark the device broken, and fail subsequent operations: +如果验证发现不匹配,驱动的恢复选项取决于硬件。对于`myfirst`模拟,最简单的响应是记录日志、标记设备为损坏、并使后续操作失败: ```c if (myfirst_validate_device(sc) != 0) { @@ -1204,43 +1204,43 @@ if (myfirst_validate_device(sc) != 0) { } ``` -The softc grows a `broken` flag, and any user-facing request checks the flag and fails with an error. The detach path still works (detach always succeeds, even on a broken device), so the user can unload the driver and reload it. +softc增加一个`broken`标志,任何面向用户的请求检查该标志并以错误失败。分离路径仍然有效(分离总是成功,即使设备损坏),所以用户可以卸载驱动并重新加载。 -A real driver that detects a reset has more options. A network driver might re-run its attach sequence from the point after `pci_alloc_msi` (which has been restored by the PCI layer). A storage driver might re-initialise its controller using the same code path attach used. The implementation depends heavily on the device; the pattern is "detect, then do whatever attach-time initialisation is still required". +检测到重置的真实驱动有更多选项。网络驱动可能从`pci_alloc_msi`之后的点重新运行其挂载序列(该序列已被PCI层恢复)。存储驱动可能使用挂载使用的相同代码路径重新初始化其控制器。实现严重依赖于设备;模式是"检测,然后执行仍然需要的任何挂载时初始化"。 -The chapter's `myfirst` driver takes the simpler approach: it does not implement reset detection for the simulation, and the resume path does not include the validation call by default. The code above is provided as reference for a reader who wants to extend the driver as an exercise. +本章的`myfirst`驱动采取更简单的方法:它不为模拟实现重置检测,恢复路径默认不包含验证调用。上面的代码作为参考提供给想要作为练习扩展驱动的读者。 -### Restoring DMA State +### 恢复DMA状态 -The Chapter 21 DMA setup allocates a tag, allocates memory, loads the map, and retains the bus address in the softc. None of that is visible in the BAR-local register map; the DMA engine learns the bus address only when the driver writes it to `DMA_ADDR_LOW` and `DMA_ADDR_HIGH` as part of starting a transfer. +第21章的DMA设置分配标签、分配内存、加载映射,并在softc中保留总线地址。这些都不在BAR局部寄存器映射中可见;DMA引擎仅在驱动作为启动传输的一部分将总线地址写入`DMA_ADDR_LOW`和`DMA_ADDR_HIGH`时才学习到它。 -This means the DMA state does not need restoration in the sense of "write registers". The tag, map, and memory are all kernel-side data structures; they survive suspend intact. The next transfer will program the DMA registers as part of its normal submission. +这意味着DMA状态不需要以"写入寄存器"的意义进行恢复。标签、映射和内存都是内核侧数据结构;它们在挂起中完好无损。下一次传输将作为正常提交的一部分编程DMA寄存器。 -What might need restoration on a real device is: +在真实设备上可能需要恢复的是: -- **The DMA descriptor ring base address**, if the device keeps a persistent pointer. A real NIC writes a base-address register once at attach and points the device at a ring of descriptors; after D3cold, that register may have been reset and the driver must reprogram it. -- **The DMA engine's enable bit**, if it is separate from individual transfers. -- **Any per-channel configuration** (burst size, priority, etc.) that is held in registers the PCI layer did not cache. +- **DMA描述符环基址**,如果设备保持持久指针。真实NIC在挂载时写入一次基址寄存器并将设备指向描述符环;D3cold后,该寄存器可能已被重置,驱动必须重新编程它。 +- **DMA引擎的启用位**,如果它与单个传输分开。 +- **任何PCI层未缓存的每通道配置**(突发大小、优先级等)。 -For `myfirst`, none of this applies. The DMA engine is programmed per transfer. Resume does not need any DMA-specific restoration beyond what the generic state restoration already covered. +对于`myfirst`,这些都不适用。DMA引擎是按传输编程的。恢复不需要任何DMA特定的恢复,除了通用状态恢复已覆盖的内容。 -### Re-Arming Interrupts +### 重新装备中断 -Masking interrupts was step 2 of suspend. Unmasking them is step 3 of resume. The Stage 3 resume writes `saved_intr_mask` back to the `INTR_MASK` register, which (by convention) writes 0 to the bits corresponding to enabled vectors and 1 to the bits for disabled vectors. After the write, the device is ready to assert interrupts on the enabled vectors as soon as there is reason to. +掩码中断是挂起的第2步。取消掩码是恢复的第3步。第3阶段恢复将`saved_intr_mask`写回`INTR_MASK`寄存器,它(按约定)将0写入对应启用向量的位,将1写入对应禁用向量的位。写入后,设备准备在有理由时在启用的向量上断言中断。 -There is a subtlety around ordering. The resume path unmasks interrupts before it clears the `suspended` flag. That means a very unfortunate interrupt could arrive, call the filter, and find `suspended == true`. The filter would refuse to handle it and return `FILTER_STRAY`, which would leave the interrupt asserted. +关于顺序有一个微妙之处。恢复路径在清除`suspended`标志之前取消掩码中断。这意味着一个非常不幸的中断可能在掩码清除后到达、调用过滤器、并发现`suspended == true`。过滤器会拒绝处理并返回`FILTER_STRAY`,这会使中断保持断言状态。 -To avoid that, the resume path takes the softc lock around the state change and does the unmask and the flag clear in the opposite order: clear `suspended` first, then unmask. That way any interrupt the device raises after the mask clears sees `suspended == false` and is handled normally. +为避免这种情况,恢复路径在状态更改周围获取softc锁,并以相反顺序执行取消掩码和标志清除:先清除`suspended`,然后取消掩码。这样设备在掩码清除后引发的任何中断都会看到`suspended == false`并被正常处理。 -The code in the previous snippet does this correctly: `myfirst_restore` writes the mask, then acquires the lock, clears the flag, and releases the lock. The order is important; reversing it creates a narrow window where interrupts could be lost. +前面代码片段中的代码正确执行了这一点:`myfirst_restore`写入掩码,然后获取锁、清除标志、释放锁。顺序很重要;反转它会创建一个可能丢失中断的狭窄窗口。 -### Wake Source Cleanup +### 唤醒源清理 -If the driver enabled a wake source during suspend (`pci_enable_pme`), the resume path should clear any pending wake event (`pci_clear_pme`). The PCI layer's `pci_resume_child` helper already calls `pci_clear_pme(child)` before the driver's `DEVICE_RESUME`, so the driver does not usually need to call it again. +如果驱动在挂起期间启用了唤醒源(`pci_enable_pme`),恢复路径应清除任何待处理的唤醒事件(`pci_clear_pme`)。PCI层的`pci_resume_child`助手已在驱动的`DEVICE_RESUME`之前调用`pci_clear_pme(child)`,所以驱动通常不需要再次调用它。 -The one case where the driver might want to call `pci_clear_pme` explicitly is in a runtime-PM context where the driver is resuming the device while the system stays in S0. In that case `pci_resume_child` was not involved, and the driver is responsible for clearing the PME status itself. +驱动可能想显式调用`pci_clear_pme`的一种情况是在运行时PM上下文中,驱动在系统保持S0时恢复设备。在这种情况下`pci_resume_child`未参与,驱动负责自己清除PME状态。 -A hypothetical sketch for a driver with wake-on-X: +支持wake-on-X的驱动的假设草图: ```c static int @@ -1249,37 +1249,37 @@ myfirst_pci_resume(device_t dev) struct myfirst_softc *sc = device_get_softc(dev); if (pci_has_pm(dev)) - pci_clear_pme(dev); /* defensive; PCI layer already did this */ + pci_clear_pme(dev); /* 防御性;PCI层已经做了 */ - /* ... rest of the resume path ... */ + /* ... 恢复路径的其余部分 ... */ } ``` -For `myfirst`, there is no wake source, so the call does nothing useful; the chapter omits it from the main code and mentions the pattern here for completeness. +对于`myfirst`,没有唤醒源,所以调用没有实际用途;本章从主代码中省略它并在此处提及模式以供完整性。 -### Updating the Stage 3 Driver +### 更新第3阶段驱动 -Stage 3 brings together everything above into a single working resume. The diff against Stage 2 is: +第3阶段将上述所有内容整合到单个可工作的恢复中。与第2阶段的差异是: -- `myfirst.h` grows a `saved_intr_mask` field (added for Stage 2) and a `broken` flag. -- `myfirst_pci.c` gets a `myfirst_restore` helper and a rewritten `myfirst_pci_resume`. -- The Makefile version bumps to `1.5-power-stage3`. +- `myfirst.h`增加`saved_intr_mask`字段(为第2阶段添加)和`broken`标志。 +- `myfirst_pci.c`获得`myfirst_restore`助手和重写的`myfirst_pci_resume`。 +- Makefile版本升级到`1.5-power-stage3`。 -Build and test: +构建并测试: ```sh cd /path/to/driver make clean && make -sudo kldunload myfirst # unload any previous version +sudo kldunload myfirst # 卸载任何先前版本 sudo kldload ./myfirst.ko -# Quiet baseline. +# 安静基线。 sysctl dev.myfirst.0.dma_transfers_read # 0 sysctl dev.myfirst.0.suspended # 0 -# Full cycle. +# 完整周期。 sudo devctl suspend myfirst0 sysctl dev.myfirst.0.suspended # 1 @@ -1288,12 +1288,12 @@ sudo devctl resume myfirst0 sysctl dev.myfirst.0.suspended # 0 -# A transfer after resume should work. +# 恢复后的传输应正常工作。 sudo sysctl dev.myfirst.0.dma_test_read=1 sysctl dev.myfirst.0.dma_transfers_read # 1 -# Do it several times to make sure the path is stable. +# 多次执行以确保路径稳定。 for i in 1 2 3 4 5; do sudo devctl suspend myfirst0 sudo devctl resume myfirst0 @@ -1303,46 +1303,46 @@ sysctl dev.myfirst.0.dma_transfers_read # 6 (1 + 5) sysctl dev.myfirst.0.power_suspend_count dev.myfirst.0.power_resume_count -# should be equal, around 6 each +# 应相等,各约6 ``` -If the counters drift (suspend count not equal to resume count) or if `dma_test_read` starts failing after a suspend, something in the restore path is not putting the device back into a usable state. The first debugging step is to read the INTR_MASK and compare against `saved_intr_mask`; the second is to trace the DMA engine's status register and see if it is reporting an error. +如果计数器漂移(挂起计数不等于恢复计数)或如果`dma_test_read`在挂起后开始失败,恢复路径中的某些东西没有将设备放回可用状态。第一个调试步骤是读取INTR_MASK并与`saved_intr_mask`比较;第二个是跟踪DMA引擎的状态寄存器看它是否报告错误。 -### Interaction with the Chapter 20 MSI-X Setup +### 与第20章MSI-X设置的交互 -The `myfirst` driver from Chapter 20 uses MSI-X when available, with a three-vector layout (admin, rx, tx). The MSI-X configuration lives in the device's MSI-X capability registers and in a kernel-side table. The PCI layer's config-space save-and-restore covers the capability registers; the kernel-side state is not affected by the D-state transition. +第20章的`myfirst`驱动在可用时使用MSI-X,采用三向量布局(admin、rx、tx)。MSI-X配置存在于设备的MSI-X能力寄存器和内核侧表中。PCI层的配置空间保存恢复覆盖能力寄存器;内核侧状态不受D状态转换影响。 -This means the `myfirst` driver does not need to do anything special to restore its MSI-X vectors. The interrupt resources (`irq_res`) remain allocated, the cookies remain registered, the CPU bindings remain in place. When the device raises an MSI-X vector on resume, the kernel delivers it to the filter that was registered at attach time. +这意味着`myfirst`驱动不需要做任何特殊操作来恢复其MSI-X向量。中断资源(`irq_res`)保持分配,cookie保持注册,CPU绑定保持不变。当设备在恢复时引发MSI-X向量时,内核将其传递给在挂载时注册的过滤器。 -A reader who wants to verify this can write to one of the simulate sysctls after resume and observe that the corresponding per-vector counter increments: +想要验证这一点的读者可以在恢复后写入一个模拟sysctl并观察相应的每向量计数器递增: ```sh sudo devctl suspend myfirst0 sudo devctl resume myfirst0 sudo sysctl dev.myfirst.0.intr_simulate_admin=1 sysctl dev.myfirst.0.vec0_fire_count -# should be incremented +# 应已递增 ``` -If the counter does not increment, the MSI-X path has been disturbed. The most likely cause is a bug in the driver's own state management (the `suspended` flag was not cleared, or the filter is rejecting the interrupt for a different reason). The chapter's troubleshooting section has more detail. +如果计数器未递增,MSI-X路径已被干扰。最可能的原因是驱动自身状态管理中的错误(`suspended`标志未清除,或过滤器因不同原因拒绝中断)。本章的故障排除部分有更多细节。 -### Handling a Failed Resume Gracefully +### 优雅处理恢复失败 -If some step of the resume fails, the driver has limited options. It cannot veto the resume (the kernel has no unwind path at this point). It cannot usually retry (the hardware state is uncertain). The best it can do is: +如果恢复的某个步骤失败,驱动选项有限。它不能否决恢复(内核此时没有展开路径)。通常不能重试(硬件状态不确定)。它能做的最好是: -1. Log the failure prominently with `device_printf` so the user sees it in dmesg. -2. Increment a counter (`power_resume_errors`) that a regression script or an observability tool can check. -3. Mark the device broken so that subsequent requests fail cleanly rather than silently corrupting data. -4. Keep the driver attached, so the device-tree state stays consistent and the user can eventually unload and reload the driver. -5. Return 0 from `DEVICE_RESUME`, because the kernel expects it to succeed. +1. 用`device_printf`显眼地记录失败,以便用户在dmesg中看到。 +2. 递增计数器(`power_resume_errors`),回归脚本或可观测性工具可以检查。 +3. 标记设备为损坏,以便后续请求干净地失败而非静默损坏数据。 +4. 保持驱动挂载,使设备树状态保持一致,用户最终可以卸载并重新加载驱动。 +5. 从`DEVICE_RESUME`返回0,因为内核期望它成功。 -The "mark broken, keep attached" pattern is common in production drivers. It moves the failure from "mysterious later corruption" to "immediate user-visible error", which is a better debugging experience. +"标记损坏、保持挂载"模式在生产驱动中常见。它将失败从"神秘的后续损坏"移动到"立即可见的用户错误",这是更好的调试体验。 -### A Short Detour: pci_save_state / pci_restore_state in Runtime PM +### 短暂弯路:运行时PM中的pci_save_state / pci_restore_state -Section 2 mentioned that `pci_save_state` and `pci_restore_state` are sometimes called by the driver itself, typically in a runtime power-management helper. This is worth a concrete sketch before Section 5 builds it out. +第2节提到`pci_save_state`和`pci_restore_state`有时由驱动自身调用,通常在运行时电源管理助手中。在第5节构建它之前,值得做一个具体的草图。 -A runtime PM helper that puts an idle device into D3 looks like: +将空闲设备放入D3的运行时PM助手如下: ```c static int @@ -1357,7 +1357,7 @@ myfirst_runtime_suspend(struct myfirst_softc *sc) pci_save_state(sc->dev); err = pci_set_powerstate(sc->dev, PCI_POWERSTATE_D3); if (err != 0) { - /* roll back */ + /* 回滚 */ pci_restore_state(sc->dev); myfirst_restore(sc); return (err); @@ -1380,59 +1380,59 @@ myfirst_runtime_resume(struct myfirst_softc *sc) } ``` -The pattern is similar to the system suspend/resume but uses the explicit PCI helpers because the PCI layer is not in the loop. Section 5 will turn this sketch into a real implementation and wire it to an idle-detection policy. +模式与系统挂起/恢复类似,但使用显式PCI助手,因为PCI层不在循环中。第5节将把这个草图变为真实实现并连接到空闲检测策略。 -### A Reality Check Against a Real Driver +### 与真实驱动的现实检验 -Before moving on, it is worth pausing and looking at a real driver's resume path. `/usr/src/sys/dev/re/if_re.c`'s `re_resume` function is about thirty lines. Its structure is: +继续之前,值得停下来看看真实驱动的恢复路径。`/usr/src/sys/dev/re/if_re.c`的`re_resume`函数大约三十行。其结构为: -1. Lock the softc. -2. If a MAC-sleep flag is set, take the chip out of sleep mode by writing a GPIO register. -3. Clear any wake-on-LAN patterns so normal receive filtering is not interfered with. -4. If the interface is administratively up, re-initialise it via `re_init_locked`. -5. Clear the `suspended` flag. -6. Unlock the softc. -7. Return 0. +1. 锁定softc。 +2. 如果MAC睡眠标志已设置,通过写GPIO寄存器将芯片从睡眠模式取出。 +3. 清除任何网络唤醒模式,以免正常接收过滤不被干扰。 +4. 如果接口在管理上已启动,通过`re_init_locked`重新初始化。 +5. 清除`suspended`标志。 +6. 解锁softc。 +7. 返回0。 -The `re_init_locked` call is the substantive work: it reprograms the MAC address, resets the receive and transmit descriptor rings, re-enables interrupts on the NIC, and starts the DMA engines. For `myfirst`, the equivalent work is much shorter because the device is much simpler, but the shape is the same: acquire state, do hardware-specific reinitialisation, unlock, return. +`re_init_locked`调用是实质工作:它重新编程MAC地址,重置接收和发送描述符环,重新启用NIC上的中断,并启动DMA引擎。对于`myfirst`,等效工作短得多因为设备简单得多,但形状相同:获取状态、执行硬件特定重新初始化、解锁、返回。 -A reader who reads `re_resume` after implementing `myfirst`'s resume will recognise the structure immediately. The vocabulary is the same; only the details differ. +在实现`myfirst`的恢复后阅读`re_resume`的读者会立即识别出结构。词汇相同;只有细节不同。 -### Wrapping Up Section 4 +### 第4节收尾 -Section 4 completed the resume path. It showed what the PCI layer has already done by the time `DEVICE_RESUME` is called (D0 transition, config-space restore, PME# clear, MSI-X restore), what the driver still has to do (re-enable bus-master, restore device-specific registers, clear the suspended flag, unmask interrupts), and why each step is important. The Stage 3 driver can now do a full suspend-resume cycle and continue operating normally; the regression test can run several cycles in a row and verify the counters are consistent. +第4节完成了恢复路径。它展示了到`DEVICE_RESUME`被调用时PCI层已经做了什么(D0转换、配置空间恢复、PME#清除、MSI-X恢复),驱动仍然需要做什么(重新启用总线主控、恢复设备特定寄存器、清除挂起标志、取消掩码中断),以及每个步骤为何重要。第3阶段驱动现在可以完成完整的挂起-恢复周期并继续正常操作;回归测试可以连续运行多个周期并验证计数器一致。 -With Sections 3 and 4 together, the driver is power-aware in the system-suspend sense: it handles S3 and S4 transitions cleanly. What it still does not do is any device-level power saving while the system is running. That is runtime power management, and Section 5 teaches it. +第3节和第4节一起,驱动在系统挂起意义上是电源感知的:它干净地处理S3和S4转换。它仍然不做的是系统运行时的任何设备级节能。那就是运行时电源管理,第5节教授它。 -## Section 5: 处理运行时电源管理 +## 第5节:处理运行时电源管理 -System suspend is a big, visible transition: the lid closes, the screen goes dark, the battery saves power for hours. Runtime power management is the opposite: dozens of small, invisible transitions a second, each saving a little, together saving much of the idle power a modern system draws. The user never notices them; the platform engineer lives or dies by their correctness. +系统挂起是一个大的、可见的转换:盖子关闭,屏幕变暗,电池节能数小时。运行时电源管理正好相反:每秒数十次小的、不可见的转换,每次节省一点,一起节省现代系统空闲功耗的大部分。用户从不注意它们;平台工程师因其正确性而生或死。 -This section is marked optional in the chapter outline because not every driver needs runtime PM. A driver for a device that is always active (a NIC on a busy server, a disk controller for the root filesystem) does not save power by attempting to suspend its device; the device is busy, and trying to suspend it wastes cycles setting up transitions that never complete. A driver for a device that is frequently idle (a webcam, a fingerprint reader, a WLAN card on a laptop) does benefit. Whether to add runtime PM is a policy decision driven by the device's usage profile. +本节在章节大纲中标记为可选,因为并非每个驱动都需要运行时PM。始终活跃的设备的驱动(繁忙服务器上的NIC、根文件系统的磁盘控制器)不通过尝试挂起其设备来节能;设备正忙,尝试挂起它浪费设置从不完成的转换的周期。经常空闲的设备的驱动(网络摄像头、指纹读取器、笔记本上的WLAN卡)确实受益。是否添加运行时PM是由设备使用配置文件驱动的策略决策。 -For Chapter 22, we implement runtime PM on the `myfirst` driver as a learning exercise. The device is already simulated; we can pretend it is idle whenever no sysctl has been written in the last few seconds, and watch the driver go through the motions. The implementation is short, and it teaches the PCI-level primitives that a real runtime-PM driver uses. +对于第22章,我们在`myfirst`驱动上实现运行时PM作为学习练习。设备已经是模拟的;我们可以假装它在最近几秒内没有sysctl写入时是空闲的,并观察驱动完成这些操作。实现很短,它教授真实运行时PM驱动使用的PCI级原语。 -### What Runtime PM Means in FreeBSD +### FreeBSD中运行时PM意味着什么 -FreeBSD does not currently have a centralised runtime-PM framework the way Linux does. There is no kernel-side "if the device has been idle for N milliseconds, call its idle hook" machinery. Instead, runtime PM is driver-local: the driver decides when to suspend and resume its device, using the same PCI-layer primitives (`pci_set_powerstate`, `pci_save_state`, `pci_restore_state`) it would use inside `DEVICE_SUSPEND` and `DEVICE_RESUME`. +FreeBSD目前没有像Linux那样的集中式运行时PM框架。没有内核侧的"如果设备已空闲N毫秒,调用其空闲钩子"机制。相反,运行时PM是驱动本地的:驱动决定何时挂起和恢复其设备,使用它在`DEVICE_SUSPEND`和`DEVICE_RESUME`内部会使用的相同PCI层原语(`pci_set_powerstate`、`pci_save_state`、`pci_restore_state`)。 -This has two consequences. First, every driver that wants runtime PM implements its own policy: how long the device must be idle before suspending, what counts as idle, how quickly the device must wake on demand. Second, the driver must integrate its runtime PM with its system PM; the two paths share a lot of code and must not step on each other. +这有两个后果。首先,每个想要运行时PM的驱动实现自己的策略:设备必须空闲多长时间才挂起、什么算空闲、设备按需求唤醒必须多快。其次,驱动必须将运行时PM与其系统PM集成;两条路径共享大量代码且不能互相冲突。 -The pattern Chapter 22 uses is straightforward: +第22章使用的模式很简单: -1. The driver adds a small state machine with states `RUNNING` and `RUNTIME_SUSPENDED`. -2. When the driver observes idleness (Section 5 uses a callout-based "no requests in the last 5 seconds" policy), it calls `myfirst_runtime_suspend`. -3. When the driver observes a new request while in `RUNTIME_SUSPENDED`, it calls `myfirst_runtime_resume` before processing the request. -4. On system suspend, if the device is in `RUNTIME_SUSPENDED`, the system-suspend path adjusts for it (the device is already quiesced; the system-suspend quiesce is a no-op, but the system resume has to bring the device back to D0). -5. On system resume, the driver returns to `RUNNING` unless it was explicitly runtime-suspended and wants to stay that way. +1. 驱动添加一个具有`RUNNING`和`RUNTIME_SUSPENDED`状态的小状态机。 +2. 当驱动观察到空闲(第5节使用基于callout的"最近5秒没有请求"策略)时,它调用`myfirst_runtime_suspend`。 +3. 当驱动在`RUNTIME_SUSPENDED`中观察到新请求时,它在处理请求之前调用`myfirst_runtime_resume`。 +4. 在系统挂起时,如果设备处于`RUNTIME_SUSPENDED`,系统挂起路径对其进行调整(设备已静默;系统挂起的静默是无操作,但系统恢复必须将设备带回D0)。 +5. 在系统恢复时,驱动返回`RUNNING`,除非它被显式运行时挂起并想保持那样。 -This is simpler than Linux's runtime PM framework, which has richer concepts (parent/child ref-counting, autosuspend timers, barriers). For a single driver on simple hardware, the FreeBSD approach is enough. +这比Linux的运行时PM框架更简单,后者有更丰富的概念(父/子引用计数、自动挂起定时器、屏障)。对于简单硬件上的单个驱动,FreeBSD方法足够了。 ### 运行时PM状态机 -The softc gains a state variable and a timestamp: +softc增加一个状态变量和一个时间戳: ```c enum myfirst_runtime_state { @@ -1451,13 +1451,13 @@ struct myfirst_softc { }; ``` -The `idle_threshold_seconds` is a policy knob exposed through a sysctl; defaulting to five seconds gives quick observability without being so aggressive as to cause unnecessary wake-ups during normal use. A production driver would tune this per-device; five seconds is a learning-friendly value that makes the transitions visible without requiring hours of waiting. +`idle_threshold_seconds`是通过sysctl暴露的策略旋钮;默认为五秒提供快速可观测性而不至于在正常使用中因过于激进导致不必要的唤醒。生产驱动会按设备调整此值;五秒是一个学习友好的值,使转换可见而不需要等待数小时。 -The `idle_watcher` callout fires once a second to check the idle time. If the device has been idle longer than `idle_threshold_seconds` and is currently in `RUNNING`, the callout triggers `myfirst_runtime_suspend`. +`idle_watcher` callout每秒触发一次检查空闲时间。如果设备空闲时间超过`idle_threshold_seconds`且当前处于`RUNNING`,callout触发`myfirst_runtime_suspend`。 -### Implementation +### 实现 -The attach path starts the idle watcher: +挂载路径启动空闲监视器: ```c static void @@ -1470,9 +1470,9 @@ myfirst_start_idle_watcher(struct myfirst_softc *sc) } ``` -The callout is initialised with the softc mutex, so it acquires the mutex automatically when firing. That simplifies the callback: it runs under the lock. +callout用softc互斥锁初始化,所以触发时自动获取互斥锁。这简化了回调:它在锁下运行。 -The callback checks the time since the last activity and suspends if needed: +回调检查自上次活动以来的时间并在需要时挂起: ```c static void @@ -1489,9 +1489,8 @@ myfirst_idle_watcher_cb(void *arg) if (diff.tv_sec >= sc->idle_threshold_seconds) { /* - * Release the lock while suspending. The - * runtime_suspend helper acquires it again as - * needed. + * 在挂起期间释放锁。运行时挂起助手 + * 根需要再次获取它。 */ MYFIRST_UNLOCK(sc); (void)myfirst_runtime_suspend(sc); @@ -1499,37 +1498,37 @@ myfirst_idle_watcher_cb(void *arg) } } - /* Reschedule. */ + /* 重新调度。 */ callout_reset(&sc->idle_watcher, hz, myfirst_idle_watcher_cb, sc); } ``` -Note the lock-drop around `myfirst_runtime_suspend`. The suspend helper calls `myfirst_quiesce`, which acquires the lock itself. Holding the lock across it would deadlock. +注意`myfirst_runtime_suspend`周围的锁释放。挂起助手调用`myfirst_quiesce`,它自己获取锁。跨它持有锁会死锁。 -Activity is recorded whenever the driver services a request. The Chapter 21 DMA path is a good hook: every time a user writes to `dma_test_read` or `dma_test_write`, the sysctl handler records activity: +活动在驱动服务请求时记录。第21章的DMA路径是一个好的钩子:每次用户写入`dma_test_read`或`dma_test_write`时,sysctl处理器记录活动: ```c static int myfirst_dma_sysctl_test_write(SYSCTL_HANDLER_ARGS) { struct myfirst_softc *sc = arg1; - /* ... existing code ... */ + /* ... 现有代码 ... */ - /* Mark the device active before processing. */ + /* 处理前标记设备为活跃。 */ myfirst_mark_active(sc); - /* If runtime-suspended, bring the device back before running. */ + /* 如果运行时已挂起,在运行前将设备带回。 */ if (sc->runtime_state == MYFIRST_RT_SUSPENDED) { int err = myfirst_runtime_resume(sc); if (err != 0) return (err); } - /* ... proceed with the transfer ... */ + /* ... 继续传输 ... */ } ``` -The `myfirst_mark_active` helper is a one-liner: +`myfirst_mark_active`助手是一行代码: ```c static void @@ -1541,9 +1540,9 @@ myfirst_mark_active(struct myfirst_softc *sc) } ``` -### The Runtime-Suspend and Runtime-Resume Helpers +### 运行时挂起和运行时恢复助手 -These were sketched in Section 4. Here are the fleshed-out versions: +这些在第4节中已做草图。以下是完整版本: ```c static int @@ -1624,26 +1623,26 @@ myfirst_runtime_resume(struct myfirst_softc *sc) } ``` -The shape is identical to system suspend/resume except that the driver explicitly calls `pci_set_powerstate` and `pci_save_state`/`pci_restore_state`. The PCI layer's automatic transitions are not in the loop for runtime PM because the kernel is not coordinating a system-wide power change; the driver is on its own. +形状与系统挂起/恢复相同,只是驱动显式调用`pci_set_powerstate`和`pci_save_state`/`pci_restore_state`。PCI层的自动转换不参与运行时PM,因为内核没有协调系统范围的电源更改;驱动独自处理。 -### Interaction Between Runtime PM and System PM +### 运行时PM和系统PM之间的交互 -The two paths have to cooperate. Consider what happens if the device is runtime-suspended (in D3) when the user closes the laptop lid: +两条路径必须协作。考虑当用户合上笔记本盖子时设备已运行时挂起(在D3中)会发生什么: -1. The kernel starts system suspend. -2. The PCI bus calls `myfirst_pci_suspend`. -3. Inside `myfirst_pci_suspend`, the driver notices that the device is already runtime-suspended. The quiesce is a no-op (nothing is happening). The PCI layer's automatic config-space save runs; it reads the config space (which is still accessible in D3) and caches it. -4. The PCI layer transitions the device from D3 to... wait, it is already in D3. The transition to D3 is a no-op. -5. The system sleeps. -6. On wake, the PCI layer transitions the device back to D0. The driver's `myfirst_pci_resume` runs. It restores state. But now the driver thinks the device is `RUNNING` (because system resume cleared the `suspended` flag), while conceptually it was runtime-suspended before. The next activity will use the device normally and set `last_activity`; the idle watcher will eventually re-suspend it if still idle. +1. 内核开始系统挂起。 +2. PCI总线调用`myfirst_pci_suspend`。 +3. 在`myfirst_pci_suspend`内部,驱动注意到设备已运行时挂起。静默是无操作(没有事情在发生)。PCI层的自动配置空间保存运行;它读取配置空间(在D3中仍可访问)并缓存它。 +4. PCI层将设备从D3转换到……等等,它已经在D3中。到D3的转换是无操作。 +5. 系统睡眠。 +6. 唤醒时,PCI层将设备转回D0。驱动的`myfirst_pci_resume`运行。它恢复状态。但现在驱动认为设备是`RUNNING`(因为系统恢复清除了`suspended`标志),而概念上它之前是运行时挂起的。下一个活动会正常使用设备并设置`last_activity`;空闲监视器最终会重新挂起它如果仍然空闲。 -The interaction is mostly benign; the worst that happens is that the device gets one extra trip through D0 before the idle watcher re-suspends it. A more polished implementation would remember the runtime-suspended state across the system suspend and restore it, but for a learning driver the simple approach is enough. +交互大多是良性的;最坏情况是设备在空闲监视器重新挂起它之前多经历一次D0。更完善的实现会在系统挂起间记住运行时挂起状态并恢复它,但对于学习驱动简单方法就足够了。 -The reverse (system-suspending a device that is already runtime-suspended) is already correct in our implementation because `myfirst_quiesce` checks `suspended` and returns 0 if already set. The runtime-suspended path set `suspended = true` as part of its quiesce, so the system suspend's quiesce sees the flag and skips. +反向(系统挂起已运行时挂起的设备)在我们的实现中已经正确,因为`myfirst_quiesce`检查`suspended`并在已设置时返回0。运行时挂起路径作为其静默的一部分设置了`suspended = true`,所以系统挂起的静默看到标志并跳过。 -### Exposing Runtime-PM Controls Through Sysctl +### 通过Sysctl暴露运行时PM控制 -The driver's runtime-PM policy can be controlled and observed through sysctls: +驱动的运行时PM策略可以通过sysctl控制和观察: ```c SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "idle_threshold_seconds", @@ -1660,101 +1659,101 @@ SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "runtime_state", "Runtime state: 0=running, 1=suspended"); ``` -A reader can now do this: +读者现在可以这样做: ```sh -# Watch the device idle out. +# 观察设备空闲。 while :; do sysctl dev.myfirst.0.runtime_state dev.myfirst.0.runtime_suspend_count sleep 1 done & ``` -After five seconds of inactivity, `runtime_state` flips from 0 to 1 and `runtime_suspend_count` increments. A write to any active sysctl triggers a resume and flips the state back: +五秒不活动后,`runtime_state`从0翻转到1,`runtime_suspend_count`递增。写入任何活动sysctl触发恢复并将状态翻转回来: ```sh sudo sysctl dev.myfirst.0.dma_test_read=1 -# The log shows: runtime resume, then the test read +# 日志显示:运行时恢复,然后测试读取 ``` -### Tradeoffs +### 权衡 -Runtime PM trades wake-up latency for idle power. Every D3-to-D0 transition costs time (tens of microseconds on a PCIe link, including the ASPM exit), and on some devices costs energy (the transition itself draws current). For a device that is idle most of the time with rare bursts of activity, the trade is favorable. For a device that is active most of the time with rare idle periods, the cost of the transitions dominates. +运行时PM用唤醒延迟换取空闲功耗。每次D3到D0转换花费时间(PCIe链路上数十微秒,包括ASPM退出),在某些设备上还花费能量(转换本身消耗电流)。对于大部分时间空闲、偶尔有活动突发的设备,交换是有利的。对于大部分时间活跃、偶尔有空闲期的设备,转换成本占主导。 -The `idle_threshold_seconds` knob lets the platform tune this. A value of 0 or 1 is aggressive and suitable for a webcam that is used for seconds at a time and idle for minutes. A value of 60 is conservative and suitable for a NIC whose idle periods are short but frequent. A value of 0 (if allowed) would disable runtime PM entirely, which is appropriate for devices that should stay on at all times. +`idle_threshold_seconds`旋钮让平台调整这一点。值为0或1是激进的,适合每次使用几秒、空闲几分钟的网络摄像头。值为60是保守的,适合空闲期短但频繁的NIC。值为0(如果允许)会完全禁用运行时PM,适合应始终保持开启的设备。 -A second tradeoff is in code complexity. Runtime PM adds a state machine, a callout, an idle watcher, two more kobj-like helpers, and additional ordering concerns between the runtime and system PM paths. Each of those is small, but together they increase the surface area for bugs. Many FreeBSD drivers deliberately omit runtime PM for this reason; they let the device stay in D0 and rely on the device's internal low-power states (clock gating, PCIe ASPM) to save power. That is a defensible choice, and for drivers where correctness matters more than milliwatts, it is the right one. +第二个权衡在代码复杂性方面。运行时PM添加状态机、callout、空闲监视器、两个额外类kobj助手,以及运行时和系统PM路径之间的额外排序关注。每个都很小,但它们一起增加了错误的攻击面。许多FreeBSD驱动因此故意省略运行时PM;它们让设备保持在D0并依赖设备自身的内部低功耗状态(时钟门控、PCIe ASPM)来节能。这是一个可辩护的选择,对于正确性比毫瓦更重要的驱动,这是正确的选择。 -Chapter 22's `myfirst` driver keeps runtime PM as an optional feature, gated by a build-time flag: +第22章的`myfirst`驱动将运行时PM保持为可选功能,由构建时标志控制: ```make CFLAGS+= -DMYFIRST_ENABLE_RUNTIME_PM ``` -A reader can build with or without the flag; the Section 5 code is only compiled in when the flag is defined. The default for Stage 3 is to leave runtime PM off; Stage 4 enables it in the consolidated driver. +读者可以在有或没有该标志的情况下构建;第5节代码仅在定义标志时编译。第3阶段的默认是关闭运行时PM;第4阶段在合并驱动中启用它。 -### A Word on Platform Runtime PM +### 关于平台运行时PM的说明 -Some platforms provide their own runtime-PM mechanism alongside the driver-local one. On arm64 and RISC-V embedded systems, the device tree may describe `power-domains` and `clocks` properties that the driver uses to turn off power domains and gate clocks. FreeBSD's `ext_resources/clk`, `ext_resources/regulator`, and `ext_resources/power` subsystems handle these. +一些平台在驱动本地的运行时PM之外提供自己的运行时PM机制。在arm64和RISC-V嵌入式系统上,设备树可能描述`power-domains`和`clocks`属性,驱动使用它们关闭电源域和门控时钟。FreeBSD的`ext_resources/clk`、`ext_resources/regulator`和`ext_resources/power`子系统处理这些。 -Runtime PM on such a platform is more capable than PCI-only runtime PM because the platform can turn off entire SoC blocks (a USB controller, a display engine, a GPU) rather than just moving the PCI device to D3. The driver uses the same pattern (mark idle, turn off resources on idle, turn back on for activity) but through different APIs. +此类平台上的运行时PM比仅PCI的运行时PM更强大,因为平台可以关闭整个SoC块(USB控制器、显示引擎、GPU)而不仅仅是将PCI设备移到D3。驱动使用相同的模式(标记空闲、空闲时关闭资源、活动时重新开启)但通过不同的API。 -Chapter 22 stays with the PCI path because that is where the `myfirst` driver lives. A reader who later works on an embedded platform will find the same conceptual structure with platform-specific APIs. The chapter mentions the distinction here so the reader knows the territory exists. +第22章停留在PCI路径上,因为那是`myfirst`驱动所在。之后在嵌入式平台上工作的读者会发现相同的概念结构和平台特定API。本章在此提及区别,以便读者知道该领域存在。 -### Wrapping Up Section 5 +### 第5节收尾 -Section 5 added runtime power management to the driver. It defined a two-state machine (`RUNNING`, `RUNTIME_SUSPENDED`), a callout-based idle watcher, a pair of helpers (`myfirst_runtime_suspend`, `myfirst_runtime_resume`) that use the PCI layer's explicit power-state and state-save APIs, the activity-recording hooks in the DMA sysctl handlers, and the sysctl knobs that expose the policy to user space. It also discussed the interaction between runtime PM and system PM, the latency-vs-power tradeoff, and the alternative of platform-level runtime PM on embedded systems. +第5节为驱动添加了运行时电源管理。它定义了两状态机(`RUNNING`、`RUNTIME_SUSPENDED`)、基于callout的空闲监视器、使用PCI层显式电源状态和状态保存API的一对助手(`myfirst_runtime_suspend`、`myfirst_runtime_resume`)、DMA sysctl处理器中的活动记录钩子,以及向用户空间暴露策略的sysctl旋钮。它还讨论了运行时PM和系统PM之间的交互、延迟与功耗的权衡,以及嵌入式系统上平台级运行时PM的替代方案。 -With Sections 2 through 5 in place, the driver now handles system suspend, system resume, system shutdown, runtime suspend, and runtime resume. What it does not yet do cleanly is explain how the reader tests all of these from user space. Section 6 turns to the user-space interface: `acpiconf`, `zzz`, `devctl suspend`, `devctl resume`, `devinfo -v`, and the regression test that wraps them together. +第2到5节就位后,驱动现在处理系统挂起、系统恢复、系统关机、运行时挂起和运行时恢复。它尚未干净地解释的是读者如何从用户空间测试所有这些。第6节转向用户空间接口:`acpiconf`、`zzz`、`devctl suspend`、`devctl resume`、`devinfo -v`,以及将它们组合在一起的回归测试。 -## Section 6: 与电源框架交互 +## 第6节:与电源框架交互 -A driver that handles suspend and resume correctly is only half of the story. The other half is being able to *test* that correctness, repeatedly and deliberately, from user space. Section 6 surveys the tools FreeBSD provides for that purpose, explains how each fits the driver's state model, and shows how to combine them into a regression script that exercises every path Sections 2 through 5 built. +正确处理挂起和恢复的驱动只是故事的一半。另一半是能够从用户空间*测试*这种正确性,重复地、有目的地。第6节调查FreeBSD为此目的提供的工具,解释每个如何适合驱动的状态模型,并展示如何将它们组合成回归脚本,练习第2到5节构建的每条路径。 -### The Four User-Space Entry Points +### 四个用户空间入口点 -Four commands cover almost everything a driver developer needs: +四个命令几乎覆盖驱动开发者需要的一切: -- **`acpiconf -s 3`** (and its variants) asks ACPI to put the whole system into sleep state S3. This is the most realistic test; it exercises the full path from user space through the kernel's suspend machinery through the PCI layer to the driver's methods. -- **`zzz`** is a thin wrapper around `acpiconf -s 3`. It reads `hw.acpi.suspend_state` (defaulting to S3) and enters the corresponding sleep state. For most users it is the most convenient way to suspend from a shell. -- **`devctl suspend myfirst0`** and **`devctl resume myfirst0`** trigger per-device suspend and resume through the `DEV_SUSPEND` and `DEV_RESUME` ioctls on `/dev/devctl2`. These only call the driver's methods; the rest of the system stays in S0. This is the fastest iteration target and what Chapter 22 uses for most development. -- **`devinfo -v`** lists all devices in the device tree with their current state. It shows whether a device is attached, suspended, or detached. +- **`acpiconf -s 3`**(及其变体)请求ACPI将整个系统置入睡眠状态S3。这是最真实的测试;它练习从用户空间通过内核挂起机制通过PCI层到驱动方法的完整路径。 +- **`zzz`**是`acpiconf -s 3`的薄包装器。它读取`hw.acpi.suspend_state`(默认为S3)并进入相应的睡眠状态。对于大多数用户,它是从shell挂起最方便的方式。 +- **`devctl suspend myfirst0`**和**`devctl resume myfirst0`**通过`/dev/devctl2`上的`DEV_SUSPEND`和`DEV_RESUME` ioctl触发每设备挂起和恢复。这些仅调用驱动的方法;系统其余部分保持在S0。这是最快的迭代目标,也是第22章大部分开发使用的。 +- **`devinfo -v`**列出设备树中所有设备及其当前状态。它显示设备是已挂载、已挂起还是已分离。 -Each has strengths and weaknesses. `acpiconf` is realistic but slow (one to three seconds per cycle on typical hardware) and disruptive (the system actually sleeps). `devctl` is fast (milliseconds per cycle) but exercises only the driver, not the ACPI or platform code. `devinfo -v` is passive and cheap; it observes without changing state. +每个都有优缺点。`acpiconf`真实但慢(典型硬件上每个周期一到三秒)且具有破坏性(系统实际睡眠)。`devctl`快(每个周期毫秒)但仅练习驱动,不练习ACPI或平台代码。`devinfo -v`是被动的且廉价的;它观察而不改变状态。 -A good regression strategy uses all three: `devctl` for unit testing of the driver's methods, `acpiconf` for integration testing of the full suspend path, and `devinfo -v` as a quick sanity check. +好的回归策略使用所有三个:`devctl`用于驱动方法的单元测试,`acpiconf`用于完整挂起路径的集成测试,`devinfo -v`用于快速健全性检查。 -### Using acpiconf to Suspend the System +### 使用acpiconf挂起系统 -On a machine with working ACPI, `acpiconf -s 3` is what Section 1 called a full system suspend. The command: +在有正常ACPI的机器上,`acpiconf -s 3`是第1节所称的完整系统挂起。命令: ```sh sudo acpiconf -s 3 ``` -does the following: +执行以下步骤: -1. It opens `/dev/acpi` and checks that the platform supports S3 via the `ACPIIO_ACKSLPSTATE` ioctl. -2. It sends the `ACPIIO_REQSLPSTATE` ioctl to request S3. -3. The kernel begins the suspend sequence: paused userland, frozen threads, device tree traversal with `DEVICE_SUSPEND` on each device. -4. Assuming no driver vetoes, the kernel enters S3. The machine sleeps. -5. A wake event (the lid opens, the power button is pressed, a USB device sends a remote-wakeup signal) wakes the platform. -6. The kernel runs the resume sequence: `DEVICE_RESUME` on each device, unfreezing threads, resuming userland. -7. The shell prompt returns. The machine is back in S0. +1. 打开`/dev/acpi`并通过`ACPIIO_ACKSLPSTATE` ioctl检查平台是否支持S3。 +2. 发送`ACPIIO_REQSLPSTATE` ioctl请求S3。 +3. 内核开始挂起序列:暂停用户态、冻结线程、以`DEVICE_SUSPEND`遍历设备树的每个设备。 +4. 假设没有驱动否决,内核进入S3。机器睡眠。 +5. 唤醒事件(盖子打开、电源按钮按下、USB设备发送远程唤醒信号)唤醒平台。 +6. 内核运行恢复序列:在每个设备上`DEVICE_RESUME`,解冻线程,恢复用户态。 +7. shell提示符返回。机器回到S0。 -For the `myfirst` driver to be exercised, the driver must be loaded before the suspend. The entire sequence from user perspective looks like: +要使`myfirst`驱动被测试,驱动必须在挂起之前加载。从用户角度看完整序列如下: ```sh sudo kldload ./myfirst.ko -sudo sysctl dev.myfirst.0.dma_test_read=1 # exercise it a bit +sudo sysctl dev.myfirst.0.dma_test_read=1 # 稍微锻炼一下 sudo acpiconf -s 3 -# [laptop sleeps; user opens lid] +# [笔记本睡眠;用户打开盖子] dmesg | grep myfirst ``` -The `dmesg` output should show two lines from Chapter 22's logging: +`dmesg`输出应显示第22章日志记录的两行: ```text myfirst0: suspend: starting @@ -1763,64 +1762,64 @@ myfirst0: resume: starting myfirst0: resume: complete ``` -If those lines are present and in that order, the driver's methods were called correctly by the full system path. +如果这些行存在且按此顺序,驱动的方法已被完整系统路径正确调用。 -If the machine does not come back, the suspend path broke at some layer below `myfirst`. If the machine comes back but the driver is in a strange state (the sysctls return errors, the counters have strange values, DMA transfers fail), the problem is in `myfirst`'s suspend or resume implementation. +如果机器未回来,挂起路径在`myfirst`之下的某层中断。如果机器回来了但驱动处于奇怪状态(sysctl返回错误、计数器有奇怪值、DMA传输失败),问题在`myfirst`的挂起或恢复实现中。 -### Using zzz +### 使用zzz -On FreeBSD, `zzz` is a small shell script that reads `hw.acpi.suspend_state` and calls `acpiconf -s `. It is not a binary; it is usually installed at `/usr/sbin/zzz` and is a few lines long. A typical invocation is: +在FreeBSD上,`zzz`是一个小型shell脚本,读取`hw.acpi.suspend_state`并调用`acpiconf -s `。它不是二进制文件;通常安装在`/usr/sbin/zzz`,只有几行长。典型调用是: ```sh sudo zzz ``` -The default `hw.acpi.suspend_state` is `S3` on machines that support it. A reader who wants to test S4 (hibernate) can: +在支持S3的机器上,默认`hw.acpi.suspend_state`是`S3`。想要测试S4(休眠)的读者可以: ```sh sudo sysctl hw.acpi.suspend_state=S4 sudo zzz ``` -S4 support on FreeBSD has historically been partial; whether it works depends on the platform firmware and the filesystem layout. For Chapter 22's purposes, S3 is sufficient, and `zzz` is the convenient shorthand. +FreeBSD上的S4支持历史上一直不完整;是否工作取决于平台固件和文件系统布局。对于第22章的目的,S3足够了,`zzz`是方便的简写。 -### Using devctl for Per-Device Suspend +### 使用devctl进行每设备挂起 -The `devctl(8)` command was built to let a user manipulate the device tree from user space. It supports attach, detach, enable, disable, suspend, resume, and more. For Chapter 22, `suspend` and `resume` are the two that matter. +`devctl(8)`命令是为了让用户从用户空间操作设备树而构建的。它支持挂载、分离、启用、禁用、挂起、恢复等。对于第22章,`suspend`和`resume`是两个重要的。 ```sh sudo devctl suspend myfirst0 sudo devctl resume myfirst0 ``` -The first command issues `DEV_SUSPEND` through `/dev/devctl2`; the kernel translates that into a call to `BUS_SUSPEND_CHILD` on the parent bus, which for a PCI device ends up calling `pci_suspend_child`, which saves config space, puts the device in D3, and calls the driver's `DEVICE_SUSPEND`. The reverse happens for resume. +第一个命令通过`/dev/devctl2`发出`DEV_SUSPEND`;内核将其转换为在父总线上调用`BUS_SUSPEND_CHILD`,对于PCI设备最终调用`pci_suspend_child`,它保存配置空间、将设备放入D3、并调用驱动的`DEVICE_SUSPEND`。恢复时反向发生。 -The key differences from `acpiconf`: +与`acpiconf`的主要区别: -- Only the target device and its children go through the transition. The rest of the system stays in S0. -- The CPU does not park. Userland does not freeze. The kernel does not sleep. -- The PCI device actually goes to D3hot (assuming `hw.pci.do_power_suspend` is 1). The reader can verify with `pciconf`: +- 只有目标设备及其子设备经历转换。系统其余部分保持在S0。 +- CPU不停车。用户态不冻结。内核不睡眠。 +- PCI设备实际进入D3hot(假设`hw.pci.do_power_suspend`为1)。读者可以用`pciconf`验证: ```sh -# Before suspend: device should be in D0 +# 挂起前:设备应在D0 pciconf -lvbc | grep -A 2 myfirst -# After devctl suspend myfirst0: device should be in D3 +# devctl suspend myfirst0后:设备应在D3 sudo devctl suspend myfirst0 pciconf -lvbc | grep -A 2 myfirst ``` -The power state is usually shown in the `powerspec` line of `pciconf -lvbc`. Moving from `D0` to `D3` is the observable signal that the transition really happened. +电源状态通常在`pciconf -lvbc`的`powerspec`行中显示。从`D0`到`D3`的变化是转换真正发生的可观察信号。 -### Using devinfo to Inspect Device State +### 使用devinfo检查设备状态 -The `devinfo(8)` utility lists the device tree with various levels of detail. The `-v` flag shows verbose information, including the device state (attached, suspended, or not present). +`devinfo(8)`工具以各种详细程度列出设备树。`-v`标志显示详细信息,包括设备状态(已挂载、已挂起或不存在)。 ```sh devinfo -v | grep -A 5 myfirst ``` -Typical output: +典型输出: ```text myfirst0 pnpinfo vendor=0x1af4 device=0x1005 subvendor=0x1af4 subdevice=0x0004 class=0x008880 at slot=5 function=0 dbsf=pci0:0:5:0 @@ -1830,22 +1829,22 @@ myfirst0 pnpinfo vendor=0x1af4 device=0x1005 subvendor=0x1af4 subdevice=0x0004 c 0xfeb80000-0xfeb80fff ``` -The state is implicit in the output: if the device is suspended, the line shows the device and its resources without the "active" marker. An explicit state query can be done through the softc sysctl; the `dev.myfirst.0.%parent` and `dev.myfirst.0.%desc` keys tell the user where the device sits. +状态在输出中是隐含的:如果设备已挂起,该行显示设备及其资源但没有"active"标记。显式状态查询可以通过softc sysctl完成;`dev.myfirst.0.%parent`和`dev.myfirst.0.%desc`键告诉用户设备在哪里。 -For Chapter 22, `devinfo -v` is most useful as a sanity check after a failed transition: if the device is missing from the output, the detach path ran; if the device is present but the resources are wrong, the attach or resume path left the device in an inconsistent state. +对于第22章,`devinfo -v`作为失败转换后的健全性检查最有用:如果设备从输出中缺失,分离路径已运行;如果设备存在但资源错误,挂载或恢复路径将设备留在了不一致状态。 -### Inspecting Power States Through sysctl +### 通过sysctl检查电源状态 -The PCI layer exposes power-state information through `sysctl` under `hw.pci`. Two variables are most relevant: +PCI层通过`hw.pci`下的`sysctl`暴露电源状态信息。两个变量最相关: ```sh sysctl hw.pci.do_power_suspend sysctl hw.pci.do_power_resume ``` -Both default to 1, meaning the PCI layer transitions devices to D3 on suspend and back to D0 on resume. Setting either to 0 disables the automatic transition for debugging. +两者默认为1,意味着PCI层在挂起时将设备转换到D3,在恢复时转回D0。将任一设为0可禁用自动转换用于调试。 -The ACPI layer exposes system-state information: +ACPI层暴露系统状态信息: ```sh sysctl hw.acpi.supported_sleep_state @@ -1853,36 +1852,36 @@ sysctl hw.acpi.suspend_state sysctl hw.acpi.s4bios ``` -The first lists which sleep states the platform supports (typically something like `S3 S4 S5`). The second is the state `zzz` enters (usually `S3`). The third says whether S4 is implemented through BIOS assistance. +第一个列出平台支持哪些睡眠状态(通常类似`S3 S4 S5`)。第二个是`zzz`进入的状态(通常是`S3`)。第三个表明S4是否通过BIOS辅助实现。 -For per-device observation, the driver exposes its own state through `dev.myfirst.N.*`. The Chapter 22 driver adds: +对于每设备观察,驱动通过`dev.myfirst.N.*`暴露自己的状态。第22章驱动添加: -- `dev.myfirst.N.suspended`: 1 if the driver considers itself suspended, 0 otherwise. -- `dev.myfirst.N.power_suspend_count`: number of times `DEVICE_SUSPEND` has been called. -- `dev.myfirst.N.power_resume_count`: number of times `DEVICE_RESUME` has been called. -- `dev.myfirst.N.power_shutdown_count`: number of times `DEVICE_SHUTDOWN` has been called. -- `dev.myfirst.N.runtime_state`: 0 for `RUNNING`, 1 for `RUNTIME_SUSPENDED`. -- `dev.myfirst.N.runtime_suspend_count`, `dev.myfirst.N.runtime_resume_count`: runtime-PM counters. -- `dev.myfirst.N.idle_threshold_seconds`: runtime-PM idle threshold. +- `dev.myfirst.N.suspended`:如果驱动认为自身已挂起则为1,否则为0。 +- `dev.myfirst.N.power_suspend_count`:`DEVICE_SUSPEND`被调用的次数。 +- `dev.myfirst.N.power_resume_count`:`DEVICE_RESUME`被调用的次数。 +- `dev.myfirst.N.power_shutdown_count`:`DEVICE_SHUTDOWN`被调用的次数。 +- `dev.myfirst.N.runtime_state`:0表示`RUNNING`,1表示`RUNTIME_SUSPENDED`。 +- `dev.myfirst.N.runtime_suspend_count`、`dev.myfirst.N.runtime_resume_count`:运行时PM计数器。 +- `dev.myfirst.N.idle_threshold_seconds`:运行时PM空闲阈值。 -Between these sysctls and `dmesg`, a reader can see in full detail what the driver did during any transition. +在这些sysctl和`dmesg`之间,读者可以完全详细地看到驱动在任何转换期间做了什么。 -### A Regression Script +### 回归脚本 -The labs directory grows a new script: `ch22-suspend-resume-cycle.sh`. The script: +labs目录新增一个脚本:`ch22-suspend-resume-cycle.sh`。该脚本: -1. Records the baseline values of every counter. -2. Runs one DMA transfer to confirm the device is working. -3. Calls `devctl suspend myfirst0`. -4. Verifies `dev.myfirst.0.suspended` is 1. -5. Verifies `dev.myfirst.0.power_suspend_count` has incremented by 1. -6. Calls `devctl resume myfirst0`. -7. Verifies `dev.myfirst.0.suspended` is 0. -8. Verifies `dev.myfirst.0.power_resume_count` has incremented by 1. -9. Runs one more DMA transfer to confirm the device still works. -10. Prints a PASS/FAIL summary. +1. 记录每个计数器的基线值。 +2. 运行一次DMA传输确认设备正常工作。 +3. 调用`devctl suspend myfirst0`。 +4. 验证`dev.myfirst.0.suspended`为1。 +5. 验证`dev.myfirst.0.power_suspend_count`增加了1。 +6. 调用`devctl resume myfirst0`。 +7. 验证`dev.myfirst.0.suspended`为0。 +8. 验证`dev.myfirst.0.power_resume_count`增加了1。 +9. 再运行一次DMA传输确认设备仍然正常工作。 +10. 打印PASS/FAIL摘要。 -The full script is in the examples directory; a short outline of the logic: +完整脚本在examples目录中;逻辑的简要大纲: ```sh #!/bin/sh @@ -1939,11 +1938,11 @@ fi echo "PASS: one suspend-resume cycle completed cleanly" ``` -Running the script repeatedly (say a hundred times in a tight loop) is a good stress test. A driver that passes one cycle but fails on the fiftieth usually has a resource leak or an edge case that only shows up under repetition. That class of bug is exactly what a regression script is meant to find. +重复运行脚本(比如在紧凑循环中运行一百次)是很好的压力测试。通过一次循环但在第五十次失败的驱动通常有资源泄漏或仅在重复下才出现的边缘情况。这类错误正是回归脚本要发现的。 -### Running the Stress Test +### 运行压力测试 -The chapter's `labs/` directory also includes `ch22-suspend-stress.sh`, which runs the cycle script a hundred times: +本章的`labs/`目录还包括`ch22-suspend-stress.sh`,它将循环脚本运行一百次: ```sh #!/bin/sh @@ -1959,11 +1958,11 @@ done echo "PASS: $N cycles" ``` -On a modern machine with the simulation-only myfirst driver, a hundred cycles takes about a second. If any iteration fails, the script stops and reports the iteration number. Running this after each change during development catches regressions immediately. +在带仅模拟myfirst驱动的现代机器上,一百次循环大约需要一秒。如果任何迭代失败,脚本停止并报告迭代号。在开发期间每次更改后运行它可以立即捕获回归。 -### Combining Runtime PM and User-Space Testing +### 结合运行时PM和用户空间测试 -The runtime-PM path needs a different test, because it is not triggered by user commands; it is triggered by idleness. The test looks like: +运行时PM路径需要不同的测试,因为它不是由用户命令触发的;它是由空闲触发的。测试如下: ```sh # Ensure runtime_state is running. @@ -1990,96 +1989,96 @@ sysctl dev.myfirst.0.runtime_resume_count # 1 ``` -A reader watching `dmesg` during this will see the "runtime suspend: starting" and "runtime suspend: device in D3" lines after about five seconds of inactivity, then "runtime resume: starting" when the sysctl write arrives. +在此期间观察`dmesg`的读者会在大约五秒不活动后看到"runtime suspend: starting"和"runtime suspend: device in D3"行,然后在sysctl写入到达时看到"runtime resume: starting"。 -The chapter's lab directory includes `ch22-runtime-pm.sh` to automate this sequence. +本章的lab目录包含`ch22-runtime-pm.sh`来自动化此序列。 -### Interpreting Failure Modes +### 解释失败模式 -When a user-space test fails, the diagnostic path depends on which layer failed: +当用户空间测试失败时,诊断路径取决于哪一层失败: -- **If `devctl suspend` returns a non-zero exit code**: the driver's `DEVICE_SUSPEND` returned a non-zero value, vetoing the suspend. Check `dmesg` for the driver's log output; the suspend method should be logging what went wrong. -- **If `devctl suspend` succeeds but `dev.myfirst.0.suspended` is 0 afterwards**: the driver's quiesce set the flag briefly but something cleared it. This usually means the quiesce is re-entering itself, or the detach path is racing the suspend. -- **If `devctl resume` succeeds but the next transfer fails**: the restore path did not fully reinitialise the device. Most commonly, an interrupt mask or a DMA register was not written; check the per-vector fire counters before and after resume to see whether interrupts are reaching the driver. -- **If `acpiconf -s 3` succeeds but the system does not come back**: a driver below `myfirst` in the tree is blocking resume. This is unusual in a test VM; it is the classic failure mode on real hardware with new drivers. -- **If `acpiconf -s 3` returns `EOPNOTSUPP`**: the platform does not support S3. Check `sysctl hw.acpi.supported_sleep_state`. +- **如果`devctl suspend`返回非零退出码**:驱动的`DEVICE_SUSPEND`返回了非零值,否决了挂起。检查`dmesg`中驱动的日志输出;挂起方法应该记录了出了什么问题。 +- **如果`devctl suspend`成功但之后`dev.myfirst.0.suspended`为0**:驱动的静默短暂设置了标志但某物清除了它。这通常意味着静默正在重入自身,或分离路径在与挂起竞争。 +- **如果`devctl resume`成功但下一次传输失败**:恢复路径没有完全重新初始化设备。最常见的是中断掩码或DMA寄存器未被写入;检查恢复前后的每向量触发计数器以查看中断是否到达驱动。 +- **如果`acpiconf -s 3`成功但系统没有回来**:设备树中`myfirst`下面的某个驱动阻止了恢复。这在测试VM中不常见;这是真实硬件上新驱动的典型故障模式。 +- **如果`acpiconf -s 3`返回`EOPNOTSUPP`**:平台不支持S3。检查`sysctl hw.acpi.supported_sleep_state`。 -In all cases, the first source of information is `dmesg`. The Chapter 22 driver logs every transition; if the log lines do not appear, the method was not called, and the problem is at a layer below the driver. +在所有情况下,第一个信息来源是`dmesg`。第22章驱动记录每个转换;如果日志行未出现,方法未被调用,问题在驱动以下的层。 -### A Minimal Troubleshooting Flow +### 最小故障排除流程 -A compact flowchart for a failed suspend-resume cycle: +失败挂起-恢复周期的紧凑流程图: -1. Is the driver loaded? `kldstat | grep myfirst`. -2. Is the device attached? `sysctl dev.myfirst.0.%driver`. -3. Do the suspend and resume methods log? `dmesg | tail`. -4. Did `dev.myfirst.0.suspended` toggle correctly? `sysctl dev.myfirst.0.suspended`. -5. Do the counters increment? `sysctl dev.myfirst.0.power_suspend_count dev.myfirst.0.power_resume_count`. -6. Does a post-resume transfer succeed? `sudo sysctl dev.myfirst.0.dma_test_read=1; dmesg | tail -2`. -7. Do the per-vector interrupt counters increment? `sysctl dev.myfirst.0.vec0_fire_count dev.myfirst.0.vec1_fire_count dev.myfirst.0.vec2_fire_count`. +1. 驱动已加载吗?`kldstat | grep myfirst`。 +2. 设备已挂载吗?`sysctl dev.myfirst.0.%driver`。 +3. 挂起和恢复方法有日志吗?`dmesg | tail`。 +4. `dev.myfirst.0.suspended`正确切换了吗?`sysctl dev.myfirst.0.suspended`。 +5. 计数器增加了吗?`sysctl dev.myfirst.0.power_suspend_count dev.myfirst.0.power_resume_count`。 +6. 恢复后传输成功吗?`sudo sysctl dev.myfirst.0.dma_test_read=1; dmesg | tail -2`。 +7. 每向量中断计数器增加了吗?`sysctl dev.myfirst.0.vec0_fire_count dev.myfirst.0.vec1_fire_count dev.myfirst.0.vec2_fire_count`。 -Any "no" answer points to a specific layer of the implementation. Section 7 goes deeper into the common failure modes and how to debug them. +任何"否"答案指向实现的特定层。第7节更深入地讨论常见故障模式及如何调试它们。 -### Wrapping Up Section 6 +### 第6节收尾 -Section 6 surveyed the user-space interface to the kernel's power-management machinery: `acpiconf`, `zzz`, `devctl suspend`, `devctl resume`, `devinfo -v`, and the relevant `sysctl` variables. It showed how to combine these tools into a regression script that exercises one suspend-resume cycle, and a stress script that runs a hundred cycles in a row. It discussed the runtime-PM test flow, the interpretation of the most common failure modes, and the minimal troubleshooting flowchart a reader can follow when a test fails. +第6节调查了内核电源管理机制的用户空间接口:`acpiconf`、`zzz`、`devctl suspend`、`devctl resume`、`devinfo -v`和相关`sysctl`变量。它展示了如何将这些工具组合成练习一次挂起-恢复周期的回归脚本,以及连续运行一百个周期的压力脚本。它讨论了运行时PM测试流程、最常见故障模式的解释,以及测试失败时读者可以遵循的最小故障排除流程图。 -With the user-space tools in hand, the next section dives into the characteristic failure modes the reader is likely to encounter while writing power-aware code, and how to debug each one. +有了用户空间工具,下一节深入探讨读者在编写电源感知代码时可能遇到的典型故障模式,以及如何调试每种故障。 -## Section 7: 调试电源管理问题 +## 第7节:调试电源管理问题 -Power management code has a special class of bugs. The machine sleeps; the machine wakes; the bug shows up an unknown time after the wake and looks like a generic malfunction rather than anything related to the power transition. The chain of cause and effect is longer than with most driver bugs, the reproduction is slower, and the user's bug report is usually "my laptop doesn't wake up sometimes", which contains almost no information the driver developer can use. +电源管理代码有一类特殊的错误。机器睡眠;机器唤醒;错误在唤醒后未知时间出现,看起来像通用故障而非与电源转换相关的任何东西。因果链比大多数驱动错误更长,重现更慢,用户的错误报告通常是"我的笔记本有时无法唤醒",其中几乎不包含驱动开发者可以使用的信息。 -Section 7 is about recognising the characteristic symptoms, tracing them back to their likely causes, and applying the matching debugging patterns. It draws on the Chapter 22 `myfirst` driver for concrete examples, but the patterns apply to any FreeBSD driver. +第7节关于识别典型症状、将其追溯到可能原因,并应用匹配的调试模式。它以第22章`myfirst`驱动为例,但模式适用于任何FreeBSD驱动。 ### Symptom 1: 恢复后设备冻结 -The most common power-management bug, both in learning drivers and in production ones, is a device that stops responding after resume. The driver attaches correctly at boot, works normally in S0, handles a suspend-resume cycle without visible error, and then on the next command it is silent. Interrupts do not fire. DMA transfers do not complete. Any read from a device register returns stale values or zeros. +最常见的电源管理错误,无论在学习驱动还是生产驱动中,都是恢复后设备停止响应。驱动在启动时正确挂载,在S0中正常工作,处理挂起-恢复周期没有可见错误,然后在下一个命令时沉默。中断不触发。DMA传输不完成。从设备寄存器读取返回陈旧值或零。 -The usual cause is that the device's registers were not written after resume. The device came back in a default state (interrupt mask all-masked, DMA engine disabled, whatever registers the hardware resets on D0 entry), the driver did not reprogram them, and so from the device's perspective nothing is configured to run. +通常原因是恢复后设备寄存器未被写入。设备以默认状态回来(中断掩码全掩码、DMA引擎禁用、硬件在D0入口时重置的任何寄存器),驱动未重新编程它们,所以从设备角度看没有配置运行的东西。 -**Debugging pattern.** Compare the device's register values before and after suspend. The `myfirst` driver exposes several of its registers through sysctls (if the reader adds them); otherwise, the reader can write a short kernel-space helper that reads each register and prints it. After a suspend-resume cycle: +**调试模式。** 比较挂起前后的设备寄存器值。`myfirst`驱动通过sysctl暴露几个寄存器(如果读者添加了它们);否则,读者可以写一个短内核空间助手读取每个寄存器并打印。在挂起-恢复周期后: -1. Read the interrupt mask register. If it is `0xFFFFFFFF` (all masked), the resume path did not restore the mask. -2. Read the DMA control register. If it has the ABORT bit set, the abort from the quiesce never cleared. -3. Read the device's configuration space via `pciconf -lvbc`. The command register should have the bus-master bit set; if not, `pci_enable_busmaster` was missed in the resume path. +1. 读取中断掩码寄存器。如果是`0xFFFFFFFF`(全掩码),恢复路径未恢复掩码。 +2. 读取DMA控制寄存器。如果ABORT位已设置,静默的中止从未清除。 +3. 通过`pciconf -lvbc`读取设备的配置空间。命令寄存器应有总线主控位设置;如果没有,恢复路径遗漏了`pci_enable_busmaster`。 -**Fix pattern.** The resume path should include an unconditional reprogram of every device-specific register the driver's normal operation depends on. Saving them at suspend time into the softc and restoring them at resume time is one approach; re-deriving them from softc state (the approach `re_resume` takes) is another. Either works; the choice depends on which is easier to prove correct for the specific device. +**修复模式。** 恢复路径应包括驱动正常操作依赖的每个设备特定寄存器的无条件重编程。在挂起时将它们保存到softc并在恢复时恢复是一种方法;从softc状态重新派生(`re_resume`采取的方法)是另一种。两者都有效;选择取决于哪个更容易为特定设备证明正确。 -### Symptom 2: Lost Interrupts +### 症状2:丢失中断 -A subtler variant of the frozen-device problem is lost interrupts: the device is responding to some calls, but its interrupts are not reaching the driver. The DMA engine accepts a START command, performs the transfer, raises the completion interrupt... and the interrupt count does not increment. The task queue does not get an entry. The CV does not broadcast. The transfer eventually times out, and the driver reports EIO. +冻结设备问题的更微妙变体是丢失中断:设备响应某些调用,但其中断未到达驱动。DMA引擎接受START命令,执行传输,引发完成中断……而中断计数不递增。任务队列未获得条目。CV不广播。传输最终超时,驱动报告EIO。 -Several things can cause this: +几种事情可能导致这个: -- The **interrupt mask** at the device is still all-masked. The device wants to raise the interrupt but the mask suppresses it. (Resume path bug.) -- The **MSI or MSI-X configuration** was not restored. The device is raising the interrupt, but the kernel does not route it to the driver's handler. (Unusual; the PCI layer should handle this automatically.) -- The **filter function pointer** was corrupted. Extremely unusual; usually indicates memory corruption somewhere else in the driver. -- The **suspended flag** is still true, and the filter is returning early. (Resume path bug: flag not cleared.) +- 设备处的**中断掩码**仍然全掩码。设备想要引发中断但掩码抑制了它。(恢复路径错误。) +- **MSI或MSI-X配置**未被恢复。设备正在引发中断,但内核未将其路由到驱动的处理器。(不常见;PCI层应自动处理。) +- **过滤器函数指针**被损坏。极不常见;通常指示驱动中其他地方的内存损坏。 +- **suspended标志**仍为true,过滤器提前返回。(恢复路径错误:标志未清除。) -**Debugging pattern.** Read the per-vector fire counters before and after the suspend-resume cycle. If the counter does not increment, the interrupt is not reaching the filter. Then check, in order: +**调试模式。** 读取挂起-恢复周期前后的每向量触发计数器。如果计数器未递增,中断未到达过滤器。然后按顺序检查: -1. Is the suspended flag cleared? `sysctl dev.myfirst.0.suspended`. -2. Is the interrupt mask at the device correct? Read the register. -3. Is the MSI-X table in the device correct? `pciconf -c` dumps the capability registers. -4. Is the kernel's MSI dispatch state consistent? `procstat -t` shows the interrupt threads. +1. 挂起标志是否已清除?`sysctl dev.myfirst.0.suspended`。 +2. 设备处的中断掩码是否正确?读取寄存器。 +3. 设备中的MSI-X表是否正确?`pciconf -c`转储能力寄存器。 +4. 内核的MSI调度状态是否一致?`procstat -t`显示中断线程。 -**Fix pattern.** Make sure the resume path (a) clears the suspended flag under the lock, (b) unmasks the device's interrupt register after clearing the flag, (c) does not rely on MSI-X restoration the driver must do itself (unless specifically disabled via sysctl). +**修复模式。** 确保恢复路径(a)在锁下清除挂起标志,(b)在清除标志后取消掩码设备的中断寄存器,(c)不依赖驱动必须自己做的MSI-X恢复(除非通过sysctl显式禁用)。 ### Symptom 3: 恢复后DMA错误 -A more dangerous class of bug is DMA that appears to work but produces wrong data. The driver programs the engine, the engine runs, the completion interrupt fires, the task runs, the sync is called, the driver reads the buffer... and the bytes are wrong. Not zeros, not garbage, just subtly incorrect: the pattern written previously, or the pattern from two cycles ago, or a pattern that indicates the DMA addressed the wrong page. +更危险的一类错误是DMA看起来正常工作但产生错误数据。驱动编程引擎,引擎运行,完成中断触发,任务运行,同步被调用,驱动读取缓冲区……但字节是错误的。不是零,不是垃圾,只是微妙地不正确:之前写入的模式,或两个周期前的模式,或指示DMA寻址错误页面的模式。 -Causes: +原因: -- The **bus address cached in the softc** is stale. This is unusual for a static allocation (the address is set once at attach and should not change), but it can happen if the driver re-allocates the DMA buffer at resume time (a bad idea; see below). -- The **DMA engine's base-address register** was not reprogrammed after resume, and it has a stale value that points elsewhere. -- The **`bus_dmamap_sync` calls are missing or mis-ordered**. This is the classic DMA-correctness bug, and it is worth being alert for in resume paths because the driver-side code adjacent to the sync calls is often edited during a refactor. -- The **IOMMU translation table** was not restored. Very rare on FreeBSD because the IOMMU configuration is per-session and survives suspend on most platforms; but if the driver is running on a system where `DEV_IOMMU` is unusual, this can bite. +- **softc中缓存的总线地址**过时了。这对于静态分配不常见(地址在挂载时设置一次不应改变),但如果驱动在恢复时重新分配DMA缓冲区(一个坏主意;见下文),可能发生。 +- 恢复后**DMA引擎的基址寄存器**未被重编程,它有过时值指向其他地方。 +- **`bus_dmamap_sync`调用缺失或顺序错误**。这是经典的DMA正确性错误,在恢复路径中值得警惕,因为同步调用附近的驱动侧代码在重构期间经常被编辑。 +- **IOMMU转换表**未被恢复。在FreeBSD上非常罕见,因为IOMMU配置是每会话的,在大多数平台上在挂起中存活;但如果驱动运行在`DEV_IOMMU`不常见的系统上,这可能发生。 -**Debugging pattern.** Add a known-pattern write before each DMA, a verify after each DMA, and log both. Reducing the cycle to "write 0xAA, sync, read, expect 0xAA" makes data-corruption bugs visible immediately. +**调试模式。** 在每次DMA前添加已知模式写入,在每次DMA后验证,并记录两者。将周期简化为"写0xAA、同步、读、期望0xAA"使数据损坏错误立即可见。 ```c memset(sc->dma_vaddr, 0xAA, MYFIRST_DMA_BUFFER_SIZE); @@ -2092,9 +2091,9 @@ if (((uint8_t *)sc->dma_vaddr)[0] != 0xAA) { } ``` -For the simulation, this should always succeed because the simulation does not modify the buffer on a write transfer. On real hardware, the pattern depends on the device. A reader debugging a real-hardware bug adapts the test. +对于模拟,这应始终成功因为模拟在写传输时不修改缓冲区。在真实硬件上,模式取决于设备。调试真实硬件错误的读者调整测试。 -**Fix pattern.** If the bus address is the problem, rebuild it on resume: +**修复模式。** 如果总线地址是问题,在恢复时重建它: ```c /* In resume, after PCI restore is complete. */ @@ -2104,24 +2103,24 @@ err = bus_dmamap_load(sc->dma_tag, sc->dma_map, BUS_DMA_NOWAIT); ``` -Only do this if the bus address actually changed, which is rare. More commonly, the fix is to write the base-address register at the start of every transfer (rather than relying on a persistent value) and to make sure the sync calls are in the right order. +只在总线地址实际改变时才这样做,这很罕见。更常见的是,修复是在每次传输开始时写入基址寄存器(而非依赖持久值)并确保同步调用顺序正确。 ### Symptom 4: Lost PME# Wake Events -On a device that supports wake-on-X, the symptom is "the device should have woken the system but did not". The driver reported a successful suspend; the system went to S3; the expected event (magic packet, button press, timer) happened; and the system stayed asleep. +在支持wake-on-X的设备上,症状是"设备应该唤醒系统但没有"。驱动报告了成功挂起;系统进入S3;预期事件(魔法数据包、按钮按下、定时器)发生了;系统保持睡眠。 -Causes: +原因: -- **`pci_enable_pme` was not called** in the suspend path. The device's PME_En bit is 0, so even when the device would normally assert PME#, the bit is suppressed. -- **The device's own wake logic is not configured**. For a NIC, the wake-on-LAN registers must be programmed before suspend. For a USB host controller, the remote-wakeup capability must be enabled per-port. -- **The platform's wake GPE is not enabled**. This is usually a firmware matter; the ACPI `_PRW` method should have registered the GPE, but on some machines the BIOS disables it by default. -- **The PME status bit is set at the time of suspend**, and a stale PME# is what triggers the wake (instead of the expected event). The system appears to wake immediately after sleeping. +- 挂起路径中**未调用`pci_enable_pme`**。设备的PME_En位为0,所以即使设备通常会断言PME#,该位也被抑制。 +- **设备自身的唤醒逻辑未配置**。对于NIC,网络唤醒寄存器必须在挂起前编程。对于USB主机控制器,远程唤醒能力必须按端口启用。 +- **平台的唤醒GPE未启用**。这通常是固件事务;ACPI `_PRW`方法应已注册GPE,但在某些机器上BIOS默认禁用它。 +- **挂起时PME状态位已设置**,陈旧的PME#是触发唤醒的东西(而非预期事件)。系统看起来在睡眠后立即唤醒。 -**Debugging pattern.** Read the PCI configuration space via `pciconf -lvbc`. The power-management capability's status/control register shows PME_En and the PME_Status bit. Before suspending, PME_Status should be 0 (no pending wake). After suspending with wake enabled, PME_En should be 1. +**调试模式。** 通过`pciconf -lvbc`读取PCI配置空间。电源管理能力的状态/控制寄存器显示PME_En和PME_Status位。挂起前,PME_Status应为0(无待处理唤醒)。启用唤醒挂起后,PME_En应为1。 -On a machine where the wake does not happen, check the BIOS settings for "wake on LAN", "wake on USB", etc. The driver can be perfect and the system still not wake if the platform is not configured. +在唤醒未发生的机器上,检查BIOS设置中的"网络唤醒"、"USB唤醒"等。驱动可以完美但如果平台未配置系统仍不会唤醒。 -**Fix pattern.** In the suspend path of a wake-capable driver: +**修复模式。** 在支持唤醒的驱动的挂起路径中: ```c static int @@ -2154,63 +2153,63 @@ myfirst_pci_resume(device_t dev) } ``` -The `myfirst` driver in Chapter 22 does not implement wake (the simulation has no wake logic). The pattern above is shown for reference. +第22章的`myfirst`驱动不实现唤醒(模拟没有唤醒逻辑)。上面的模式作为参考展示。 ### Symptom 5: 挂起期间WITNESS警告 -A debug kernel with `WITNESS` enabled often produces messages like: +启用`WITNESS`的调试内核经常产生如下消息: ```text witness: acquiring sleepable lock foo_mtx @ /path/to/driver.c:123 witness: sleeping with non-sleepable lock bar_mtx @ /path/to/driver.c:456 ``` -These are lock-order violations or sleep-while-locked violations, and they often show up in suspend code because suspend does things the driver does not normally do: acquire locks, sleep, and coordinate multiple threads. +这些是锁顺序违规或持锁睡眠违规,它们经常在挂起代码中出现因为挂起做驱动通常不做的事情:获取锁、睡眠、协调多个线程。 -Causes: +原因: -- The suspend path acquires a lock and then calls a function that sleeps without explicit tolerance for sleeping-with-that-lock-held. -- The suspend path acquires locks in a different order than the rest of the driver, and `WITNESS` notices the reversal. -- The suspend path calls `taskqueue_drain` or `callout_drain` while holding the softc lock, which causes a deadlock if the task or callout tries to acquire the same lock. +- 挂起路径获取锁然后调用在未显式容忍持该锁睡眠的情况下睡眠的函数。 +- 挂起路径以与驱动其余部分不同的顺序获取锁,`WITNESS`注意到逆转。 +- 挂起路径在持有softc锁时调用`taskqueue_drain`或`callout_drain`,如果任务或callout尝试获取同一个锁则导致死锁。 -**Debugging pattern.** Read the `WITNESS` message carefully. It includes the lock names and the source-line numbers where each was acquired. Trace the path from the acquisition to the sleep or lock reversal. +**调试模式。** 仔细阅读`WITNESS`消息。它包括锁名称和每个被获取的源代码行号。跟踪从获取到睡眠或锁逆转的路径。 -**Fix pattern.** The Chapter 22 `myfirst_quiesce` drops the softc lock before calling `myfirst_drain_workers` for exactly this reason. When extending the driver: +**修复模式。** 第22章的`myfirst_quiesce`正是因此原因在调用`myfirst_drain_workers`之前释放softc锁。扩展驱动时: -- Do not call `taskqueue_drain` with any driver lock held. -- Do not call `callout_drain` with the lock that the callout acquires. -- Sleep primitives (`pause`, `cv_wait`) must be called with only sleep-mutexes held (not spin-mutexes). -- If you need to drop a lock for a sleep, do so explicitly and reacquire after. +- 不要在持有任何驱动锁时调用`taskqueue_drain`。 +- 不要在持有callout获取的锁时调用`callout_drain`。 +- 睡眠原语(`pause`、`cv_wait`)必须在仅持有睡眠互斥锁时调用(不是自旋互斥锁)。 +- 如果需要为睡眠释放锁,显式这样做并在之后重新获取。 -### Symptom 6: Counters That Do Not Match +### 症状6:计数器不匹配 -The chapter's regression script expects `power_suspend_count == power_resume_count` after each cycle. When they drift, something is wrong. +本章的回归脚本期望每个周期后`power_suspend_count == power_resume_count`。当它们漂移时,出了问题。 -Causes: +原因: -- The driver's `DEVICE_SUSPEND` was called but the driver returned early before incrementing the counter. (Often because of a sanity check that fired.) -- The driver's `DEVICE_RESUME` was not called, because `DEVICE_SUSPEND` returned non-zero and the kernel unwound. -- The counters are not atomic and a concurrent update lost an increment. (Unlikely if the code uses `atomic_add_64`.) -- The driver was unloaded and reloaded between counts, resetting them. +- 驱动的`DEVICE_SUSPEND`被调用但驱动在递增计数器之前提前返回。(通常是因为健全性检查触发了。) +- 驱动的`DEVICE_RESUME`未被调用,因为`DEVICE_SUSPEND`返回非零且内核展开了。 +- 计数器不是原子的,并发更新丢失了一次递增。(如果代码使用`atomic_add_64`则不太可能。) +- 驱动在计数之间被卸载并重新加载,重置了它们。 -**Debugging pattern.** Run the regression script with `dmesg -c` cleared beforehand, and `dmesg` after each cycle. The log shows every method invocation; counting the log lines is an alternative to counting the counters, and any difference indicates a bug. +**调试模式。** 在运行回归脚本前清除`dmesg -c`,在每个周期后运行`dmesg`。日志显示每个方法调用;计数日志行是计数计数器的替代方案,任何差异指示错误。 -### Symptom 7: Hangs During Suspend +### 症状7:挂起期间挂起 -A hang during suspend is the worst diagnostic: the kernel is still running (the console still responds to break-to-DDB), but the suspend sequence is stuck in some driver's `DEVICE_SUSPEND`. Break into DDB and `ps` to see which thread is where: +挂起期间的挂起是最差的诊断:内核仍在运行(控制台仍响应break-to-DDB),但挂起序列卡在某个驱动的`DEVICE_SUSPEND`中。中断进入DDB并`ps`查看哪个线程在哪里: ```text db> ps ... 0 myfirst_drain_dma+0x42 myfirst_pci_suspend+0x80 ... ``` -**Debugging pattern.** Identify the hanging thread and the function it is stuck in. Usually it is a `cv_wait` or `cv_timedwait` that never completed, or a `taskqueue_drain` waiting on a task that will not finish. +**调试模式。** 识别挂起的线程及其卡在的函数。通常是`cv_wait`或`cv_timedwait`从未完成,或`taskqueue_drain`等待不会完成的任务。 -**Fix pattern.** Add a timeout to any wait the suspend path does. The `myfirst_drain_dma` function uses `cv_timedwait` with a one-second timeout; a variant that uses `cv_wait` (no timeout) can hang indefinitely. The chapter's implementation always uses timed variants for this reason. +**修复模式。** 为挂起路径的任何等待添加超时。`myfirst_drain_dma`函数使用带一秒超时的`cv_timedwait`;使用`cv_wait`(无超时)的变体可能无限期挂起。本章的实现始终使用定时变体因此原因。 -### Using DTrace to Trace Suspend and Resume +### 使用DTrace跟踪挂起和恢复 -DTrace is an excellent tool for observing the power-management path at fine granularity without adding print statements. A simple D script that times each call: +DTrace是以细粒度观察电源管理路径而不添加打印语句的优秀工具。一个计时每次调用的简单D脚本: ```d fbt::device_suspend:entry, @@ -2233,9 +2232,9 @@ fbt::device_resume:return } ``` -Save this as `trace-devpower.d` and run with `dtrace -s trace-devpower.d`. Any `devctl suspend` or `acpiconf -s 3` will produce output showing each device's suspend and resume times, and their return values. +将此保存为`trace-devpower.d`并用`dtrace -s trace-devpower.d`运行。任何`devctl suspend`或`acpiconf -s 3`都会产生显示每个设备挂起和恢复时间及其返回值的输出。 -For the `myfirst` driver specifically, `fbt::myfirst_pci_suspend:entry` and `fbt::myfirst_pci_resume:entry` are the probes. A D script focused on the driver: +对于`myfirst`驱动,`fbt::myfirst_pci_suspend:entry`和`fbt::myfirst_pci_resume:entry`是探针。专注于驱动的D脚本: ```d fbt::myfirst_pci_suspend:entry { @@ -2252,13 +2251,13 @@ fbt::myfirst_pci_suspend:return } ``` -The `stack()` call prints the call stack at entry, which is useful to confirm that the method is being called from where you expect (the PCI bus's `bus_suspend_child`, for example). +`stack()`调用在入口打印调用栈,这对于确认方法是否从您期望的位置被调用很有用(例如PCI总线的`bus_suspend_child`)。 -### A Note on Logging Discipline +### 关于日志纪律的说明 -The Chapter 22 code logs generously during suspend and resume: every method logs entry and exit, and each helper logs its own events. That verbosity is helpful during development but annoying in production (every laptop suspend prints half a dozen lines to dmesg). +第22章代码在挂起和恢复期间慷慨地记录日志:每个方法记录入口和出口,每个助手记录自己的事件。这种详细程度在开发期间有帮助但在生产中烦人(每次笔记本挂起向dmesg打印半打行)。 -A good production driver exposes a sysctl that controls log verbosity: +好的生产驱动暴露控制日志详细程度的sysctl: ```c static int myfirst_power_verbose = 1; @@ -2267,18 +2266,18 @@ SYSCTL_INT(_dev_myfirst, OID_AUTO, power_verbose, "Verbose power-management logging (0=off, 1=on, 2=debug)"); ``` -And the logging becomes conditional: +日志记录变得有条件: ```c if (myfirst_power_verbose >= 1) device_printf(dev, "suspend: starting\n"); ``` -A reader who wants to enable debugging on a production system can set `dev.myfirst.power_verbose=2` temporarily, trigger the problem, and reset the variable. The Chapter 22 driver does not implement this tiering; the learning driver logs everything and accepts the noise. +想要在生产系统上启用调试的读者可以临时设置`dev.myfirst.power_verbose=2`,触发问题,然后重置变量。第22章驱动不实现这种分层;学习驱动记录一切并接受噪音。 -### Using the INVARIANTS Kernel for Assertion Coverage +### 使用INVARIANTS内核进行断言覆盖 -A debug kernel with `INVARIANTS` compiled in causes `KASSERT` macros to actually evaluate their conditions and panic on failure. The `myfirst_dma.c` and `myfirst_pci.c` code uses several KASSERTs; the power-management code adds more. For example, the quiesce invariant: +编译了`INVARIANTS`的调试内核使`KASSERT`宏实际评估其条件并在失败时恐慌。`myfirst_dma.c`和`myfirst_pci.c`代码使用多个KASSERT;电源管理代码添加更多。例如,静默不变量: ```c static int @@ -2293,20 +2292,20 @@ myfirst_quiesce(struct myfirst_softc *sc) } ``` -On an `INVARIANTS` kernel, a bug that leaves `dma_in_flight` true causes an immediate panic with a useful message. On a production kernel, the assertion is compiled out and nothing happens. The learning driver deliberately runs on an `INVARIANTS` kernel to catch this class of bug. +在`INVARIANTS`内核上,让`dma_in_flight`为true的错误会导致立即恐慌并带有有用消息。在生产内核上,断言被编译掉,什么也不发生。学习驱动故意在`INVARIANTS`内核上运行以捕获这类错误。 -Similarly, the resume path can assert: +类似地,恢复路径可以断言: ```c KASSERT(sc->suspended == true, ("myfirst: resume called but not suspended")); ``` -This catches a bug where the driver somehow gets resume called without the matching suspend having happened (usually a bug in a parent bus driver, not in the `myfirst` driver itself). +这捕获驱动某种方式在匹配挂起未发生时被调用恢复的错误(通常是父总线驱动中的错误,不是`myfirst`驱动本身的)。 -### A Debugging Case Study +### 调试案例研究 -To bring the patterns together, consider a concrete scenario. The reader writes the Stage 2 suspend, runs a regression cycle, and sees: +将模式结合在一起,考虑一个具体场景。读者编写第2阶段挂起,运行回归周期,并看到: ```text myfirst0: suspend: starting @@ -2323,11 +2322,11 @@ sudo sysctl dev.myfirst.0.dma_test_read=1 # Returns EBUSY after a long delay ``` -The user-visible symptom is that the post-resume transfer does not work. The log shows a drain timeout during suspend, which is the first anomaly. +用户可见的症状是恢复后的传输不工作。日志显示挂起期间的排空超时,这是第一个异常。 -**Hypothesis.** The DMA engine did not honor the ABORT bit. The driver force-cleared `dma_in_flight`, but the engine is still running; when the user triggers a new transfer, the engine is not ready. +**假设。** DMA引擎未遵守ABORT位。驱动强制清除`dma_in_flight`,但引擎仍在运行;当用户触发新传输时,引擎未准备好。 -**Test.** Check the engine's status register before and after the abort: +**测试。** 检查中止前后的引擎状态寄存器: ```c /* In myfirst_drain_dma, after writing ABORT: */ @@ -2337,19 +2336,19 @@ uint32_t post_status = CSR_READ_4(sc->dev, MYFIRST_REG_DMA_STATUS); device_printf(sc->dev, "drain: status %#x -> %#x\n", pre_status, post_status); ``` -Running the cycle again produces: +再次运行周期产生: ```text myfirst0: drain: status 0x4 -> 0x4 ``` -Status 0x4 is RUNNING. The engine ignored the ABORT. That points to the simulation backend: the simulated engine might not implement abort, or might do so only when the simulation callout fires. +状态0x4是RUNNING。引擎忽略了ABORT。这指向模拟后端:模拟引擎可能未实现中止,或仅在模拟callout触发时才这样做。 -**Fix.** Look at the simulation's DMA engine code and verify the abort semantics. In this case, the simulation's engine handles the abort in its callout callback, which does not fire for a few milliseconds. Extend the drain timeout from 1 second (plenty) to... wait, 1 second is plenty for a callout that fires every few milliseconds. The real issue is elsewhere. +**修复。** 查看模拟的DMA引擎代码并验证中止语义。在这种情况下,模拟引擎在其callout回调中处理中止,回调几毫秒才触发一次。将排空超时从1秒(宽裕)扩展到……等等,1秒对于每几毫秒触发的callout已经宽裕。真正的问题在别处。 -Further investigation reveals that the simulation's callout was drained *before* the DMA drain completed. The order in `myfirst_drain_workers` (task first, callout second) was wrong; it should be callout first, task second, because the callout is what drives the abort completion. +进一步调查揭示模拟的callout在DMA排空完成*之前*就被排空了。`myfirst_drain_workers`中的顺序(先任务后callout)是错误的;应该是先callout后任务,因为callout驱动中止完成。 -**Resolution.** Reorder the drain: +**解决方案。** 重新排序排空: ```c static void @@ -2376,43 +2375,43 @@ myfirst_drain_workers(struct myfirst_softc *sc) } ``` -But wait: by the time `myfirst_drain_workers` is called from `myfirst_quiesce`, `myfirst_drain_dma` has already completed. The drain-dma wait is inside the drain-dma call; the drain-workers call only cleans up residual state. The order inside drain-workers is mostly aesthetic for suspend. +但是等等:到`myfirst_drain_workers`从`myfirst_quiesce`被调用时,`myfirst_drain_dma`已完成。排空DMA等待在排空DMA调用内部;排空工作者调用仅清理残余状态。排空工作者内部的顺序对挂起主要是美观的。 -The real fix is earlier: `myfirst_drain_dma` itself should not have timed out. The 1-second timeout should have been plenty. The actual cause is different: perhaps the simulation's callout was not firing because the driver held a sysctl lock that blocked it. Or the writing of the ABORT bit did not reach the simulation because the simulation's MMIO handler was also blocked. +真正的修复更早:`myfirst_drain_dma`本身不应超时。一秒超时应已宽裕。实际原因不同:也许模拟的callout未触发因为驱动持有阻塞它的sysctl锁。或ABORT位的写入未到达模拟因为模拟的MMIO处理器也被阻塞。 -**Lesson.** Debugging power management issues is iterative. Each symptom suggests a hypothesis; each test narrows it down; the fix is often in a different layer than the one the symptom pointed to. The patience to follow the chain is what distinguishes good power-aware code from code that mostly works. +**教训。** 调试电源管理问题是迭代的。每个症状提出假设;每个测试缩小范围;修复通常在症状指向的不同层中。遵循链条的耐心是区分好的电源感知代码和勉强工作的代码的关键。 ### Wrapping Up Section 7 -Section 7 walked through the characteristic failure modes of power-aware drivers: frozen devices, lost interrupts, bad DMA, missed wake events, WITNESS complaints, counter drift, and outright hangs. For each, it showed the typical cause, a debugging pattern that narrows the problem down, and the fix pattern that removes it. It also introduced DTrace for measurement, discussed log discipline, and showed how `INVARIANTS` and `WITNESS` catch the class of bug that only shows up under specific conditions. +第7节遍历了电源感知驱动的典型故障模式:冻结设备、丢失中断、错误DMA、错过唤醒事件、WITNESS抱怨、计数器漂移和完全挂起。对于每种,它展示了典型原因、缩小问题范围的调试模式,以及消除问题的修复模式。它还介绍了DTrace用于测量,讨论了日志纪律,并展示了`INVARIANTS`和`WITNESS`如何捕获仅在特定条件下出现的错误类。 -The debugging discipline in Section 7, like the quiesce discipline in Section 3 and the restore discipline in Section 4, is meant to stay with the reader beyond the `myfirst` driver. Every power-aware driver has some variation of these bugs lurking in its implementation; the patterns above are how to find them before they reach the user. +第7节的调试纪律,像第3节的静默纪律和第4节的恢复纪律一样,旨在留在读者身上超越`myfirst`驱动。每个电源感知驱动的实现中都潜伏着这些错误的某种变体;上面的模式是如何在它们到达用户之前找到它们。 -Section 8 brings Chapter 22 to a close by consolidating the Sections 2 through 7 code into a refactored `myfirst_power.c` file, bumping the version to `1.5-power`, adding a `POWER.md` document, and wiring up a final integration test. +第8节通过将第2到7节的代码整合到重构的`myfirst_power.c`文件中,将版本升级到`1.5-power`,添加`POWER.md`文档,并连接最终集成测试来结束第22章。 -## Section 8: 重构和版本化电源感知驱动程序 +## 第8节:重构和版本化电源感知驱动 -Stages 1 through 3 added the power-management code inline in `myfirst_pci.c`. That was convenient for teaching, because every change appeared next to the attach and detach code the reader already knew. It is less convenient for readability: `myfirst_pci.c` now has attach, detach, three power methods, and several helpers, and the file is long enough that a first-time reader has to scroll to find things. +第1到3阶段在`myfirst_pci.c`中内联添加了电源管理代码。这对教学方便,因为每个更改出现在读者已知的挂载和分离代码旁边。但对可读性不太方便:`myfirst_pci.c`现在有挂载、分离、三个电源方法和几个助手,文件足够长,首次读者需要滚动来找到东西。 -Stage 4, the final version of the Chapter 22 driver, pulls all of the power-management code out of `myfirst_pci.c` and into a new file pair, `myfirst_power.c` and `myfirst_power.h`. This follows the same pattern as Chapter 20's `myfirst_msix.c` split and Chapter 21's `myfirst_dma.c` split: the new file has a narrow, well-documented API, and the caller in `myfirst_pci.c` uses only that API. +第4阶段,第22章驱动的最终版本,将所有电源管理代码从`myfirst_pci.c`中拉出到新的文件对`myfirst_power.c`和`myfirst_power.h`中。这遵循与第20章`myfirst_msix.c`拆分和第21章`myfirst_dma.c`拆分相同的模式:新文件有狭窄的、良好文档化的API,`myfirst_pci.c`中的调用者仅使用该API。 -### The Target Layout +### 目标布局 -After Stage 4, the driver's source files are: +第4阶段后,驱动的源文件为: -- `myfirst.c` - top-level glue, shared state, sysctl tree. -- `myfirst_hw.c`, `myfirst_hw_pci.c` - register-access helpers. -- `myfirst_sim.c` - simulation backend. -- `myfirst_pci.c` - PCI attach, detach, method table, and thin forwarding to subsystem modules. -- `myfirst_intr.c` - single-vector interrupt (Chapter 19 legacy path). -- `myfirst_msix.c` - multi-vector interrupt setup (Chapter 20). -- `myfirst_dma.c` - DMA setup, teardown, transfer (Chapter 21). -- `myfirst_power.c` - power management (Chapter 22, new). -- `cbuf.c` - circular-buffer support. +- `myfirst.c` - 顶层粘合、共享状态、sysctl树。 +- `myfirst_hw.c`、`myfirst_hw_pci.c` - 寄存器访问助手。 +- `myfirst_sim.c` - 模拟后端。 +- `myfirst_pci.c` - PCI挂载、分离、方法表,以及到子系统的薄转发。 +- `myfirst_intr.c` - 单向量中断(第19章遗留路径)。 +- `myfirst_msix.c` - 多向量中断设置(第20章)。 +- `myfirst_dma.c` - DMA设置、拆除、传输(第21章)。 +- `myfirst_power.c` - 电源管理(第22章,新增)。 +- `cbuf.c` - 循环缓冲区支持。 -The new `myfirst_power.h` declares the public API of the power subsystem: +新的`myfirst_power.h`声明电源子系统的公共API: ```c #ifndef _MYFIRST_POWER_H_ @@ -2438,32 +2437,32 @@ void myfirst_power_add_sysctls(struct myfirst_softc *sc); #endif /* _MYFIRST_POWER_H_ */ ``` -The `_setup` and `_teardown` pair initialise and tear down the subsystem-level state (the callout, the sysctls). The per-transition functions wrap the same logic the Section 3 through Section 5 code built. The runtime-PM functions are compiled only when the build-time flag is defined. +`_setup`和`_teardown`对初始化和拆除子系统级状态(callout、sysctl)。每转换函数包装第3到5节代码构建的相同逻辑。运行时PM函数仅在定义构建时标志时编译。 -### The myfirst_power.c File +### myfirst_power.c文件 -The new file is about three hundred lines. Its structure mirrors `myfirst_dma.c`: header includes, static helpers, public functions, sysctl handlers, and `_add_sysctls`. +新文件大约三百行。其结构镜像`myfirst_dma.c`:头文件包含、静态助手、公共函数、sysctl处理器和`_add_sysctls`。 -The helpers are the three from Section 3: +助手是第3节的三个: - `myfirst_mask_interrupts` - `myfirst_drain_dma` - `myfirst_drain_workers` -Plus one from Section 4: +加上第4节的一个: - `myfirst_restore` -And, if runtime PM is enabled, two from Section 5: +以及,如果启用了运行时PM,第5节的两个: - `myfirst_idle_watcher_cb` - `myfirst_start_idle_watcher` -The public functions `myfirst_power_suspend`, `myfirst_power_resume`, and `myfirst_power_shutdown` become thin wrappers that call the helpers in the right order and update counters. The sysctl handlers expose the policy knobs and the observability counters. +公共函数`myfirst_power_suspend`、`myfirst_power_resume`和`myfirst_power_shutdown`成为以正确顺序调用助手并更新计数器的薄包装器。sysctl处理器暴露策略旋钮和可观测性计数器。 -### Updating myfirst_pci.c +### 更新myfirst_pci.c -The `myfirst_pci.c` file is now much shorter. Its three power methods each just forward to the power subsystem: +`myfirst_pci.c`文件现在短得多。它的三个电源方法每个仅转发到电源子系统: ```c static int @@ -2485,9 +2484,9 @@ myfirst_pci_shutdown(device_t dev) } ``` -The method table stays the same as Stage 1 set it up. The three prototypes above are now the only power-related code in `myfirst_pci.c`, apart from the call to `myfirst_power_setup` from attach and `myfirst_power_teardown` from detach. +方法表与第1阶段设置的相同。上面的三个原型现在是`myfirst_pci.c`中唯一的电源相关代码,除了从挂载调用`myfirst_power_setup`和从分离调用`myfirst_power_teardown`。 -The attach path grows one call: +挂载路径增加一个调用: ```c static int @@ -2510,7 +2509,7 @@ myfirst_pci_attach(device_t dev) } ``` -The detach path grows a matching call: +分离路径增加一个匹配调用: ```c static int @@ -2526,11 +2525,11 @@ myfirst_pci_detach(device_t dev) } ``` -`myfirst_power_setup` initialises the `saved_intr_mask`, the `suspended` flag, the counters, and (if runtime PM is enabled) the idle watcher callout. `myfirst_power_teardown` drains the callout and cleans up any subsystem-level state. The teardown must be done before the DMA teardown because the callout may still reference DMA state. +`myfirst_power_setup`初始化`saved_intr_mask`、`suspended`标志、计数器,以及(如果运行时PM启用)空闲监视器callout。`myfirst_power_teardown`排空callout并清理任何子系统级状态。拆除必须在DMA拆除之前完成,因为callout可能仍引用DMA状态。 -### Updating the Makefile +### 更新Makefile -The new source file goes into the `SRCS` list, and the version bumps: +新源文件放入`SRCS`列表,版本升级: ```make KMOD= myfirst @@ -2552,30 +2551,30 @@ CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.5-power\" .include ``` -The `MYFIRST_ENABLE_RUNTIME_PM` flag is off by default in Stage 4; the runtime-PM code compiles but is wrapped in `#ifdef`. A reader who wants to experiment enables the flag at build time. +`MYFIRST_ENABLE_RUNTIME_PM`标志在第4阶段默认关闭;运行时PM代码编译但被`#ifdef`包装。想要实验的读者在构建时启用标志。 -### Writing POWER.md +### 编写POWER.md -The Chapter 21 pattern set the precedent: every subsystem gets a markdown document that describes its purpose, its API, its state model, and its testing story. `POWER.md` is next. +第21章的模式确立了先例:每个子系统获得一个markdown文档描述其目的、API、状态模型和测试故事。`POWER.md`是下一个。 -A good `POWER.md` has these sections: +好的`POWER.md`有这些部分: -1. **Purpose**: a paragraph explaining what the subsystem does. -2. **Public API**: a table of function prototypes with one-line descriptions. -3. **State Model**: a diagram or text description of the states and transitions. -4. **Counters and Sysctls**: the read-only and read-write sysctls the subsystem exposes. -5. **Transition Flows**: what happens during each of suspend, resume, shutdown. -6. **Interaction with Other Subsystems**: how power management relates to DMA, interrupts, and the simulation. -7. **Runtime PM (optional)**: how runtime PM works and when it is enabled. -8. **Testing**: the regression and stress scripts. -9. **Known Limitations**: what the subsystem does not do yet. -10. **See Also**: cross-references to `bus(9)`, `pci(9)`, and the chapter text. +1. **目的**:一段解释子系统做什么的文字。 +2. **公共API**:函数原型及其一行描述的表格。 +3. **状态模型**:状态和转换的图表或文字描述。 +4. **计数器和Sysctl**:子系统暴露的只读和读写sysctl。 +5. **转换流程**:挂起、恢复、关机各期间发生什么。 +6. **与其他子系统的交互**:电源管理如何与DMA、中断和模拟相关。 +7. **运行时PM(可选)**:运行时PM如何工作以及何时启用。 +8. **测试**:回归和压力脚本。 +9. **已知限制**:子系统尚未做什么。 +10. **另见**:`bus(9)`、`pci(9)`和章节文本的交叉引用。 -The full document is in the examples directory (`examples/part-04/ch22-power/stage4-final/POWER.md`); the chapter does not reproduce it inline, but a reader who wants to check the expected structure can open it. +完整文档在examples目录(`examples/part-04/ch22-power/stage4-final/POWER.md`);本章不在正文中复制它,但想检查预期结构的读者可以打开它。 -### Regression Script +### 回归脚本 -The Stage 4 regression script exercises every path: +第4阶段回归脚本练习每条路径: ```sh #!/bin/sh @@ -2606,39 +2605,39 @@ sudo kldunload myfirst echo "FULL REGRESSION PASSED" ``` -Each sub-script is a few dozen lines and tests one thing. Running the full regression after each change catches regressions immediately. +每个子脚本几十行测试一件事。每次更改后运行完整回归可以立即捕获回归。 -### Integration With the Existing Regression Tests +### 与现有回归测试的集成 -The Chapter 21 regression script checked: +第21章回归脚本检查了: -- `dma_complete_intrs == dma_complete_tasks` (the task always sees every interrupt). -- `dma_complete_intrs == dma_transfers_write + dma_transfers_read + dma_errors + dma_timeouts`. +- `dma_complete_intrs == dma_complete_tasks`(任务总是看到每个中断)。 +- `dma_complete_intrs == dma_transfers_write + dma_transfers_read + dma_errors + dma_timeouts`。 -The Chapter 22 script adds: +第22章脚本添加: -- `power_suspend_count == power_resume_count` (every suspend has a matching resume). -- The `suspended` flag is 0 outside of a transition. -- After a suspend-resume cycle, the DMA counters still add up to the expected total (no phantom transfers). +- `power_suspend_count == power_resume_count`(每个挂起有匹配的恢复)。 +- `suspended`标志在转换之外为0。 +- 挂起-恢复周期后,DMA计数器仍加到预期总数(无幻影传输)。 -The combined regression is the Chapter 22 full script. It exercises DMA, interrupts, MSI-X, and power management together. A driver that passes it is in good shape. +组合回归是第22章的完整脚本。它一起练习DMA、中断、MSI-X和电源管理。通过它的驱动状态良好。 -### Version History +### 版本历史 -The driver has now evolved through several versions: +驱动现在已通过多个版本演进: -- `1.0` - Chapter 16: MMIO-only driver, simulation backend. -- `1.1` - Chapter 18: PCI attach, real BAR. -- `1.2-intx` - Chapter 19: single-vector interrupt with filter+task. -- `1.3-msi` - Chapter 20: multi-vector MSI-X with fallback. -- `1.4-dma` - Chapter 21: `bus_dma` setup, simulated DMA engine, interrupt-driven completion. -- `1.5-power` - Chapter 22: suspend/resume/shutdown, refactored into `myfirst_power.c`, optional runtime PM. +- `1.0` - 第16章:仅MMIO驱动、模拟后端。 +- `1.1` - 第18章:PCI挂载、真实BAR。 +- `1.2-intx` - 第19章:带过滤器+任务的单向量中断。 +- `1.3-msi` - 第20章:带回退的多向量MSI-X。 +- `1.4-dma` - 第21章:`bus_dma`设置、模拟DMA引擎、中断驱动完成。 +- `1.5-power` - 第22章:挂起/恢复/关机、重构到`myfirst_power.c`、可选运行时PM。 -Each version builds on the previous one. A reader who has the Chapter 21 driver working can apply the Chapter 22 changes incrementally and end up at `1.5-power` without having to rewrite any earlier code. +每个版本建立在前一个之上。有第21章驱动工作的读者可以增量应用第22章更改并最终达到`1.5-power`而无需重写任何先前代码。 -### A Final Integration Test on Real Hardware +### 真实硬件上的最终集成测试 -If the reader has access to real hardware (a machine with a working S3 implementation), the Chapter 22 driver can be exercised through a full system suspend: +如果读者有真实硬件(有正常S3实现的机器),第22章驱动可以通过完整系统挂起来测试: ```sh sudo kldload ./myfirst.ko @@ -2649,44 +2648,44 @@ sudo acpiconf -s 3 sudo sysctl dev.myfirst.0.dma_test_read=1 ``` -On most platforms where ACPI S3 works, the driver survives the full cycle. The `dmesg` output shows the suspend and resume lines just as `devctl` would trigger, confirming that the same method code runs in both contexts. +在ACPI S3工作的大多数平台上,驱动在完整周期中存活。`dmesg`输出显示挂起和恢复行,正如`devctl`会触发的那样,确认相同方法代码在两个上下文中运行。 -If the full-system test fails where the per-device test succeeded, the extra work that system suspend does (ACPI sleep-state transitions, CPU parking, RAM self-refresh) has exposed something the per-device test missed. The usual culprits are device-specific register values that the system's low-power state resets but the per-device D3 does not. A driver that tests only with `devctl` can miss these; a driver that tests with `acpiconf -s 3` at least once before claiming correctness is more reliable. +如果全系统测试在每设备测试成功的地方失败,系统挂起做的额外工作(ACPI睡眠状态转换、CPU停车、RAM自刷新)暴露了每设备测试遗漏的东西。通常罪魁祸首是系统低功耗状态重置但每设备D3不重置的设备特定寄存器值。仅用`devctl`测试的驱动可能遗漏这些;在声称正确性之前至少用`acpiconf -s 3`测试一次的驱动更可靠。 -### The Chapter 22 Code in One Place +### 第22章代码一览 -A compact summary of what the Stage 4 driver added: +第4阶段驱动添加内容的紧凑摘要: -- **One new file**: `myfirst_power.c`, about three hundred lines. -- **One new header**: `myfirst_power.h`, about thirty lines. -- **One new markdown document**: `POWER.md`, about two hundred lines. -- **Five new softc fields**: `suspended`, `saved_intr_mask`, `power_suspend_count`, `power_resume_count`, `power_shutdown_count`, plus the runtime-PM fields when that feature is enabled. -- **Three new `DEVMETHOD` lines**: `device_suspend`, `device_resume`, `device_shutdown`. -- **Three new helper functions**: `myfirst_mask_interrupts`, `myfirst_drain_dma`, `myfirst_drain_workers`. -- **Two new subsystem entry points**: `myfirst_power_setup`, `myfirst_power_teardown`. -- **Three new transition functions**: `myfirst_power_suspend`, `myfirst_power_resume`, `myfirst_power_shutdown`. -- **Six new sysctls**: the counter nodes and the suspended flag. -- **Several new lab scripts**: cycle, stress, transfer-across-cycle, runtime-PM. +- **一个新文件**:`myfirst_power.c`,约三百行。 +- **一个新头文件**:`myfirst_power.h`,约三十行。 +- **一个新markdown文档**:`POWER.md`,约二百行。 +- **五个新softc字段**:`suspended`、`saved_intr_mask`、`power_suspend_count`、`power_resume_count`、`power_shutdown_count`,加上启用该功能时的运行时PM字段。 +- **三行新`DEVMETHOD`**:`device_suspend`、`device_resume`、`device_shutdown`。 +- **三个新助手函数**:`myfirst_mask_interrupts`、`myfirst_drain_dma`、`myfirst_drain_workers`。 +- **两个新子系统入口点**:`myfirst_power_setup`、`myfirst_power_teardown`。 +- **三个新转换函数**:`myfirst_power_suspend`、`myfirst_power_resume`、`myfirst_power_shutdown`。 +- **六个新sysctl**:计数器节点和suspended标志。 +- **几个新实验脚本**:cycle、stress、transfer-across-cycle、runtime-PM。 -The overall line increment is about seven hundred lines of code, plus a couple of hundred lines of documentation and script. For the capability the chapter added (a driver that correctly handles every power transition the kernel can throw at it), that is a proportionate investment. +总行增量约为七百行代码,加上几百行文档和脚本。对于本章添加的能力(一个正确处理内核可能抛出的每个电源转换的驱动),这是成比例的投入。 ### Wrapping Up Section 8 -Section 8 closed the Chapter 22 driver's construction by splitting the power code into its own file, bumping the version to `1.5-power`, adding a `POWER.md` document, and wiring the final regression test. The pattern was familiar from Chapters 20 and 21: take the inline code, extract it into a subsystem with a small API, document the subsystem, and integrate it into the rest of the driver through function calls rather than direct field access. +第8节通过将电源代码拆分为自己的文件、将版本升级到`1.5-power`、添加`POWER.md`文档并连接最终回归测试来结束第22章驱动的构建。模式与第20和21章熟悉:取内联代码、用小API将其提取为子系统、文档化子系统,并通过函数调用而非直接字段访问将其集成到驱动其余部分。 -The resulting driver is power-aware in every sense the chapter introduced: it handles `DEVICE_SUSPEND`, `DEVICE_RESUME`, and `DEVICE_SHUTDOWN`; it quiesces the device cleanly; it restores state correctly on resume; it optionally implements runtime power management; it exposes its state through sysctls; it has a regression test; and it survives full-system suspend on real hardware when the platform supports it. +产生的驱动在本章引入的每个意义上都是电源感知的:它处理`DEVICE_SUSPEND`、`DEVICE_RESUME`和`DEVICE_SHUTDOWN`;它干净地静默设备;它在恢复时正确恢复状态;它可选地实现运行时电源管理;它通过sysctl暴露状态;它有回归测试;当平台支持时它在真实硬件上存活完整系统挂起。 -## Deep Look: Power Management in /usr/src/sys/dev/re/if_re.c +## 深入理解:/usr/src/sys/dev/re/if_re.c中的电源管理 -The Realtek 8169 and compatible gigabit NICs are handled by the `re(4)` driver. It is an informative driver to read for Chapter 22 purposes because it implements the full suspend-resume-shutdown trio with wake-on-LAN support, and its code has been stable enough to represent a canonical FreeBSD pattern. A reader who has worked through Chapter 22 can open `/usr/src/sys/dev/re/if_re.c` and recognise the structure immediately. +Realtek 8169和兼容的千兆NIC由`re(4)`驱动处理。对于第22章目的来说,它是一个值得阅读的信息性驱动,因为它实现了带网络唤醒支持的完整挂起-恢复-关机三重奏,其代码已足够稳定代表规范的FreeBSD模式。完成第22章的读者可以打开`/usr/src/sys/dev/re/if_re.c`并立即识别结构。 -> **Reading this walkthrough.** The paired `re_suspend()` and `re_resume()` listings in the subsections below are taken from `/usr/src/sys/dev/re/if_re.c`, and the method-table excerpt abbreviates the full `re_methods[]` array with a `/* ... other methods ... */` comment so the three power-related `DEVMETHOD` entries stand out. We kept the signatures, the lock-acquire and lock-release pattern, and the order of device-specific calls (`re_stop`, `re_setwol`, `re_clrwol`, `re_init_locked`) intact; the real method table has many more entries, and the surrounding file carries the helper implementations. Every symbol the listings name is a real FreeBSD identifier in `if_re.c` that you can find with a symbol search. +> **阅读本演练。** 下面小节中成对的`re_suspend()`和`re_resume()`清单取自`/usr/src/sys/dev/re/if_re.c`,方法表摘录用`/* ... other methods ... */`注释缩写了完整的`re_methods[]`数组,使三个电源相关的`DEVMETHOD`条目突出。我们保持了签名、锁获取和锁释放模式,以及设备特定调用(`re_stop`、`re_setwol`、`re_clrwol`、`re_init_locked`)的顺序不变;真实方法表有更多条目,周围文件包含助手实现。清单中命名的每个符号都是`if_re.c`中的真实FreeBSD标识符,可以通过符号搜索找到。 -### The Method Table +### 方法表 -The `re(4)` driver's method table includes the three power methods near the top: +`re(4)`驱动的方法表在顶部附近包含三个电源方法: ```c static device_method_t re_methods[] = { @@ -2700,11 +2699,11 @@ static device_method_t re_methods[] = { }; ``` -This is exactly the pattern Chapter 22 teaches. The `myfirst` driver's method table looks the same. +这正是第22章教授的模式。`myfirst`驱动的方法表看起来一样。 ### re_suspend -The suspend function is about a dozen lines: +挂起函数大约十几行: ```c static int @@ -2724,9 +2723,9 @@ re_suspend(device_t dev) } ``` -Three calls do the work: `re_stop` quiesces the NIC (disables interrupts, halts DMA, stops the RX and TX engines), `re_setwol` programs the wake-on-LAN logic and calls `pci_enable_pme` if WoL is enabled, and `sc->suspended = 1` sets the softc flag. +三个调用完成工作:`re_stop`静默NIC(禁用中断、停止DMA、停止RX和TX引擎),`re_setwol`编程网络唤醒逻辑并在WoL启用时调用`pci_enable_pme`,`sc->suspended = 1`设置softc标志。 -Compare to `myfirst_power_suspend`: +与`myfirst_power_suspend`比较: ```c int @@ -2742,11 +2741,11 @@ myfirst_power_suspend(struct myfirst_softc *sc) } ``` -The structure is identical. `re_stop` and `re_setwol` together are the equivalent of `myfirst_quiesce`; the chapter's driver does not have wake-on-X, so there is no analogue of `re_setwol`. +结构是相同的。`re_stop`和`re_setwol`一起等效于`myfirst_quiesce`;本章驱动没有wake-on-X,所以没有`re_setwol`的类似物。 ### re_resume -The resume function is about thirty lines: +恢复函数大约三十行: ```c static int @@ -2784,14 +2783,14 @@ re_resume(device_t dev) } ``` -The steps map cleanly to Chapter 22's discipline: +这些步骤干净地映射到第22章的纪律: -1. **Take the controller out of sleep mode** (MAC sleep bit on some Realtek parts). This is a device-specific restore step. -2. **Clear any WOL patterns** via `re_clrwol`, which reverses what `re_setwol` did. This also calls `pci_clear_pme` implicitly through the clear. -3. **Re-initialise the interface** if it was up before suspend. `re_init_locked` is the same function attach calls to bring up the NIC; it reprograms the MAC, resets the descriptor rings, enables interrupts, and starts the DMA engines. -4. **Clear the suspended flag** under the lock. +1. **将控制器从睡眠模式取出**(某些Realtek部件上的MAC睡眠位)。这是设备特定的恢复步骤。 +2. **通过`re_clrwol`清除任何WOL模式**,它逆转`re_setwol`所做的。这还通过清除隐式调用`pci_clear_pme`。 +3. **如果挂起前接口已启动,重新初始化接口**。`re_init_locked`与挂载调用以启动NIC的函数相同;它重新编程MAC、重置描述符环、启用中断、启动DMA引擎。 +4. **在锁下清除suspended标志**。 -The `myfirst_power_resume` equivalent: +`myfirst_power_resume`的等效: ```c int @@ -2807,11 +2806,11 @@ myfirst_power_resume(struct myfirst_softc *sc) } ``` -Again the structure is identical. `myfirst_restore` corresponds to the combination of the MAC-sleep exit, `re_clrwol`, `re_init_locked`, and the flag clear. +结构再次相同。`myfirst_restore`对应MAC睡眠退出、`re_clrwol`、`re_init_locked`和标志清除的组合。 ### re_shutdown -The shutdown function is: +关机函数为: ```c static int @@ -2836,11 +2835,11 @@ re_shutdown(device_t dev) } ``` -Similar to `re_suspend`, plus the interface-flag clear (shutdown is final; marking the interface down prevents spurious activity). The pattern is nearly identical; `re_shutdown` is essentially a more defensive version of `re_suspend`. +与`re_suspend`类似,加上接口标志清除(关机是最终的;标记接口为down防止虚假活动)。模式几乎相同;`re_shutdown`本质上是`re_suspend`的更具防御性的版本。 ### re_setwol -The wake-on-LAN setup is worth looking at because it shows how a real driver calls the PCI PM APIs: +网络唤醒设置值得一看,因为它展示了真实驱动如何调用PCI PM API: ```c static void @@ -2862,13 +2861,13 @@ re_setwol(struct rl_softc *sc) } ``` -Three key patterns appear here that are worth copying into any power-aware driver that supports wake-on-X: +这里出现三个关键模式,值得复制到任何支持wake-on-X的电源感知驱动中: -1. **`pci_has_pm(dev)` guard.** The function returns early if the device does not support power management. This prevents writes to registers that do not exist. -2. **Device-specific wake programming.** The bulk of the function writes Realtek-specific registers through `CSR_WRITE_1`. A driver for a different device would write different registers, but the placement (inside the suspend path, before `pci_enable_pme`) is the same. -3. **Conditional `pci_enable_pme`.** Only enable PME# if the user has actually asked for wake-on-X. If the user has not, the function still sets the relevant configuration bits (for consistency with the driver's interface capabilities) but does not call `pci_enable_pme`. +1. **`pci_has_pm(dev)`守卫。** 如果设备不支持电源管理,函数提前返回。这防止写入不存在的寄存器。 +2. **设备特定唤醒编程。** 函数主体通过`CSR_WRITE_1`写入Realtek特定寄存器。不同设备的驱动会写入不同寄存器,但位置(在挂起路径内,`pci_enable_pme`之前)相同。 +3. **条件`pci_enable_pme`。** 仅在用户实际请求了wake-on-X时启用PME#。如果用户没有,函数仍设置相关配置位(为与驱动接口能力一致)但不调用`pci_enable_pme`。 -The inverse is `re_clrwol`: +逆向是`re_clrwol`: ```c static void @@ -2885,23 +2884,23 @@ re_clrwol(struct rl_softc *sc) } ``` -Note that `re_clrwol` does not explicitly call `pci_clear_pme`; the PCI layer's `pci_resume_child` has already called it before the driver's `DEVICE_RESUME`. `re_clrwol` is responsible for undoing the driver-visible side of WoL configuration, not the kernel-visible PME status. +注意`re_clrwol`不显式调用`pci_clear_pme`;PCI层的`pci_resume_child`已在驱动的`DEVICE_RESUME`之前调用了它。`re_clrwol`负责撤销WoL配置的驱动可见侧,而非内核可见的PME状态。 -### What the Deep Look Shows +### 深入理解展示了什么 -The Realtek driver is more complex than `myfirst` by every measure (more registers, more state, more device variants), and yet its power-management discipline is less complex. That is because complexity of the *device* does not map one-to-one to complexity of the *power-management code*. Chapter 22's discipline scales down as well as it scales up: a simple device has a simple power path; a complex device has a modestly more complex power path. The structure is the same. +Realtek驱动在各方面都比`myfirst`更复杂(更多寄存器、更多状态、更多设备变体),但其电源管理纪律却不太复杂。这是因为*设备*的复杂性不一对一映射到*电源管理代码*的复杂性。第22章的纪律向下扩展和向上扩展一样好:简单设备有简单电源路径;复杂设备有适度更复杂的电源路径。结构是相同的。 -A reader who has finished Chapter 22 can now open `if_re.c`, recognise every function and every pattern, and understand why each exists. That comprehension transfers: the same recognition applies to `if_xl.c`, `virtio_blk.c`, and hundreds of other FreeBSD drivers. Chapter 22 is not teaching a `myfirst`-specific API; it is teaching the FreeBSD power-management idiom, and the `myfirst` driver is the vehicle that made it concrete. +完成第22章的读者现在可以打开`if_re.c`,识别每个函数和每个模式,并理解每个为什么存在。这种理解力可以迁移:相同的识别适用于`if_xl.c`、`virtio_blk.c`和数百个其他FreeBSD驱动。第22章不是在教授`myfirst`特定的API;它在教授FreeBSD电源管理惯用法,`myfirst`驱动是使之具体的载体。 -## Deep Look: Simpler Patterns in if_xl.c and virtio_blk.c +## 深入理解:if_xl.c和virtio_blk.c中的更简单模式 -For contrast, two other FreeBSD drivers implement power management in even simpler ways. +作为对比,另外两个FreeBSD驱动以更简单的方式实现电源管理。 -### if_xl.c: Shutdown Calls Suspend +### if_xl.c:关机调用挂起 -The 3Com EtherLink III driver in `/usr/src/sys/dev/xl/if_xl.c` has the minimal three-method setup: +/usr/src/sys/dev/xl/if_xl.c`中的3Com EtherLink III驱动有最小的三方法设置: ```c static int @@ -2947,16 +2946,16 @@ xl_resume(device_t dev) } ``` -Two things stand out: +两件事引人注目: -1. `xl_shutdown` is one line: it just calls `xl_suspend`. For this driver, shutdown and suspend do the same work, and the code does not need two copies. -2. There is no `suspended` flag in the softc. The driver assumes the normal lifecycle of attach → run → suspend → resume, and uses the `IFF_DRV_RUNNING` flag (which the TX path already checks) as the equivalent. This is a perfectly valid approach for a NIC whose main user-visible state is the interface's running state. +1. `xl_shutdown`是一行:它只调用`xl_suspend`。对于此驱动,关机和挂起做相同工作,代码不需要两份副本。 +2. softc中没有`suspended`标志。驱动假设正常的挂载→运行→挂起→恢复生命周期,并使用TX路径已检查的`IFF_DRV_RUNNING`标志作为等效。这对于主要用户可见状态是接口运行状态的NIC是完全有效的方法。 -For the `myfirst` driver, the explicit `suspended` flag is preferred because the driver has no natural equivalent of `IFF_DRV_RUNNING`. A NIC driver can reuse what it already has; a learning driver declares what it needs. +对于`myfirst`驱动,显式`suspended`标志更受偏好因为驱动没有`IFF_DRV_RUNNING`的自然等效。NIC驱动可以重用它已有的;学习驱动声明它需要的。 -### virtio_blk.c: Minimal Quiesce +### virtio_blk.c:最小静默 -The virtio block driver in `/usr/src/sys/dev/virtio/block/virtio_blk.c` has an even shorter suspend path: +/usr/src/sys/dev/virtio/block/virtio_blk.c`中的virtio块驱动有更短的挂起路径: ```c static int @@ -2994,203 +2993,203 @@ vtblk_resume(device_t dev) } ``` -The comment `/* XXX BMV: virtio_stop(), etc needed here? */` is an honest acknowledgement that the author was not sure how thorough the quiesce should be. The existing code sets a flag, waits for the queue to drain (that is what `vtblk_quiesce` does), and returns. On resume, it clears the flag and restarts I/O. +注释`/* XXX BMV: virtio_stop(), etc needed here? */`是作者不确定静默应该多彻底的诚实承认。现有代码设置标志、等待队列排空(这就是`vtblk_quiesce`做的),然后返回。恢复时,它清除标志并重启I/O。 -For a virtio block device, this is enough because the virtio host (the hypervisor) implements its own quiesce when the guest says it is suspending. The driver only needs to stop submitting new requests; the host deals with the rest. +对于virtio块设备,这足够了因为virtio主机(虚拟机监控程序)在客户说它正在挂起时实现自己的静默。驱动只需停止提交新请求;主机处理其余。 -This shows an important pattern: **the driver's quiesce depth depends on how much of the hardware's state is the driver's responsibility**. A bare-metal driver (like `re(4)`) has to program hardware registers carefully because the hardware has no other ally. A virtio driver has the hypervisor as an ally; the host can handle most of the state for the guest. The `myfirst` driver, running on a simulated backend, is in a similar position: the simulation is an ally, and the driver's quiesce can be correspondingly simpler. +这展示了一个重要模式:**驱动的静默深度取决于硬件状态有多少是驱动的责任**。裸机驱动(如`re(4)`)必须小心编程硬件寄存器因为硬件没有其他盟友。virtio驱动有虚拟机监控程序作为盟友;主机可以为客户处理大部分状态。`myfirst`驱动运行在模拟后端上,处于类似位置:模拟是盟友,驱动的静默可以相应更简单。 ### 比较显示了什么 -Reading multiple drivers' power-management code side by side is one of the best ways to build fluency. Each driver adapts the Chapter 22 pattern to its context: `re(4)` handles wake-on-LAN, `xl(4)` reuses `xl_shutdown = xl_suspend`, `virtio_blk(4)` trusts the hypervisor. The common thread is the structure: stop activity, save state, flag suspended, return 0 from suspend; on resume, clear flag, restore state, restart activity, return 0. +并排阅读多个驱动的电源管理代码是建立流利度的最佳方式之一。每个驱动将第22章模式适应其上下文:`re(4)`处理网络唤醒,`xl(4)`重用`xl_shutdown = xl_suspend`,`virtio_blk(4)`信任虚拟机监控程序。共同线索是结构:停止活动、保存状态、标记已挂起、从挂起返回0;恢复时,清除标志、恢复状态、重启活动、返回0。 -A reader who has Chapter 22 in memory can open any FreeBSD driver, find its `device_suspend` and `device_resume` in the method table, and read the two functions. Within a few minutes the driver's power policy is clear. That skill transfers to every driver the reader will ever work on; it is the single most useful takeaway from the chapter. +心中有第22章的读者可以打开任何FreeBSD驱动,在方法表中找到其`device_suspend`和`device_resume`,阅读这两个函数。几分钟内驱动的电源策略就清楚了。这项技能迁移到读者将来工作的每个驱动;它是本章最有用的单一收获。 ## 深入理解:ACPI睡眠状态详解 -Section 1 introduced the ACPI S-states as a list. It is worth revisiting them with the driver's point of view in focus, because the driver sees slightly different things depending on which S-state the kernel is entering. +第1节以列表形式介绍了ACPI S状态。值得以驱动的视角重新审视它们,因为驱动看到的东西略有不同,取决于内核正在进入哪个S状态。 ### S0:工作状态 -S0 is the state the reader has worked in throughout Chapters 16 to 21. The CPU is executing, RAM is refreshed, the PCIe links are up. From the driver's point of view, S0 is continuous; everything is normal. +S0是读者在第16到21章中一直工作的状态。CPU执行中,RAM刷新中,PCIe链路已启动。从驱动角度看,S0是连续的;一切正常。 -Within S0, however, there can still be fine-grained power transitions. The CPU may enter idle states (C1, C2, C3, etc.) between scheduler ticks. The PCIe link may enter L0s or L1 based on ASPM. Devices may enter D3 based on runtime PM. None of these require the driver to do anything beyond its own runtime-PM logic; they are transparent. +然而在S0内,仍可以有细粒度电源转换。CPU可以在调度器节拍之间进入空闲状态(C1、C2、C3等)。PCIe链路可以基于ASPM进入L0s或L1。设备可以基于运行时PM进入D3。这些都不需要驱动做任何超出自身运行时PM逻辑的事情;它们是透明的。 ### S1:待机 -S1 is historically the lightest sleep state. The CPU stops executing but its registers are preserved; RAM stays powered; device power stays at D0 or D1. Wake latency is fast (under a second). +S1历史上是最轻的睡眠状态。CPU停止执行但其寄存器被保留;RAM保持供电;设备电源保持D0或D1。唤醒延迟快(一秒以内)。 -On modern hardware, S1 is rarely supported. The platform's BIOS advertises only S3 and deeper. If the platform does advertise S1 and the user enters it, the driver's `DEVICE_SUSPEND` is still called; the driver does its usual quiesce. The difference is that the PCI layer typically does not transition to D3 for S1 (because the bus stays powered), so the device stays in D0 through the transition. The driver's save and restore are largely unused. +在现代硬件上,S1很少被支持。平台的BIOS只广播S3及更深的状态。如果平台确实广播S1且用户进入它,驱动的`DEVICE_SUSPEND`仍被调用;驱动做其通常的静默。区别是PCI层通常不为S1转换到D3(因为总线保持供电),所以设备在转换期间保持D0。驱动的保存和恢复大部分未使用。 -A driver that supports S1 cleanly also supports S3, because the driver-side work is a subset. No driver written for Chapter 22 needs to treat S1 specially. +干净支持S1的驱动也支持S3,因为驱动侧工作是子集。为第22章编写的驱动不需要特殊处理S1。 ### S2:保留 -S2 is defined in the ACPI specification but almost never implemented. A driver can safely ignore it; FreeBSD's ACPI layer treats S2 as S1 or S3 depending on platform support. +S2在ACPI规范中定义但几乎从未实现。驱动可以安全忽略它;FreeBSD的ACPI层根据平台支持将S2视为S1或S3。 ### S3:挂起到内存 -S3 is the canonical sleep state Chapter 22 targets. When the user enters S3: +S3是第22章瞄准的规范睡眠状态。当用户进入S3时: -1. The kernel's suspend sequence traverses the device tree, calling `DEVICE_SUSPEND` on each driver. -2. The PCI layer's `pci_suspend_child` caches configuration space for each PCI device. -3. The PCI layer transitions each PCI device to D3hot. -4. Higher-level subsystems (ACPI, the CPU's idle machinery) enter their own sleep states. -5. The CPU's context is saved to RAM; the CPU halts. -6. RAM enters self-refresh; the memory controller maintains the contents with minimal power. -7. The platform's wake circuitry is armed: the power button, lid switch, and any configured wake sources. -8. The system waits for a wake event. +1. 内核的挂起序列遍历设备树,在每个驱动上调用`DEVICE_SUSPEND`。 +2. PCI层的`pci_suspend_child`为每个PCI设备缓存配置空间。 +3. PCI层将每个PCI设备转换到D3hot。 +4. 更高级子系统(ACPI、CPU的空闲机制)进入自己的睡眠状态。 +5. CPU的上下文保存到RAM;CPU停止。 +6. RAM进入自刷新;内存控制器以最小功率维持内容。 +7. 平台的唤醒电路装备就绪:电源按钮、盖子开关和任何配置的唤醒源。 +8. 系统等待唤醒事件。 -When a wake event arrives: +当唤醒事件到达时: -1. The CPU resumes; its context is restored from RAM. -2. Higher-level subsystems resume. -3. The PCI layer walks the device tree and calls `pci_resume_child` for each device. -4. Each device is transitioned to D0; its configuration is restored; pending PME# is cleared. -5. Each driver's `DEVICE_RESUME` is called. -6. User space unfreezes. +1. CPU恢复;其上下文从RAM恢复。 +2. 更高级子系统恢复。 +3. PCI层遍历设备树并为每个设备调用`pci_resume_child`。 +4. 每个设备转换到D0;其配置恢复;待处理的PME#被清除。 +5. 每个驱动的`DEVICE_RESUME`被调用。 +6. 用户空间解冻。 -The driver sees only steps 1 (suspend) and 5 (resume) of each sequence. The rest is kernel and platform machinery. +驱动只看到每个序列的步骤1(挂起)和步骤5(恢复)。其余是内核和平台机制。 -A subtle point: during S3, RAM is refreshed but the kernel is not running. This means any kernel-side state (the softc, the DMA buffer, the pending tasks) survives S3 unchanged. The only thing that may be lost is hardware state: configuration registers in the device may be reset; BAR-mapped registers may return to default values. The driver's job on resume is to re-program the hardware from the preserved kernel state. +一个微妙的点:在S3期间,RAM被刷新但内核未运行。这意味着任何内核侧状态(softc、DMA缓冲区、待处理任务)在S3中不变地存活。唯一可能丢失的是硬件状态:设备中的配置寄存器可能被重置;BAR映射寄存器可能返回默认值。驱动在恢复时的工作是从保留的内核状态重新编程硬件。 ### S4:挂起到磁盘(休眠) -S4 is the "hibernate" state. The kernel writes the full contents of RAM to a disk image, then enters S5. On wake, the platform boots, the kernel reads the image back, and the system continues from where it left off. +S4是"休眠"状态。内核将RAM的全部内容写入磁盘映像,然后进入S5。唤醒时,平台启动,内核读取映像回,系统从它离开的地方继续。 -On FreeBSD, S4 has historically been partial. The kernel can produce the hibernation image on some platforms, but the restore path is not as mature as Linux's. For driver purposes, S4 is the same as S3: the `DEVICE_SUSPEND` and `DEVICE_RESUME` methods are called; the driver's quiesce and restore paths work without change. The extra platform-level work (writing the image) is transparent. +在FreeBSD上,S4历史上一直不完整。内核可以在某些平台上产生休眠映像,但恢复路径不如Linux成熟。对于驱动目的,S4与S3相同:`DEVICE_SUSPEND`和`DEVICE_RESUME`方法被调用;驱动的静默和恢复路径无需更改即可工作。额外的平台级工作(写入映像)是透明的。 -The one difference the driver might notice is that after S4 resume, the PCI configuration space is always restored from scratch (the platform has fully rebooted), so even if the driver were relying on `hw.pci.do_power_suspend` being 0 to keep the device in D0, after S4 the device will still have been through a full power cycle. This matters only for drivers that do platform-specific tricks during suspend; most drivers are oblivious. +驱动可能注意到的一个区别是S4恢复后,PCI配置空间始终从头恢复(平台已完全重启),所以即使驱动依赖`hw.pci.do_power_suspend`为0保持设备在D0,S4后设备仍会经历完整电源周期。这仅对在挂起期间做平台特定技巧的驱动有影响;大多数驱动对此无感知。 ### S5:软关机 -S5 is system power-off. The power button, the battery (if any), and the wake circuitry still receive power; everything else is off. +S5是系统断电。电源按钮、电池(如果有)和唤醒电路仍接收电源;其他一切关闭。 -From the driver's point of view, S5 looks like a shutdown: `DEVICE_SHUTDOWN` is called (not `DEVICE_SUSPEND`), the driver places the device in a safe state for power-off, and the system halts. There is no resume corresponding to S5; if the user presses the power button, the system boots from scratch. +从驱动角度看,S5看起来像关机:`DEVICE_SHUTDOWN`被调用(不是`DEVICE_SUSPEND`),驱动将设备置于安全断电状态,系统停止。S5没有对应的恢复;如果用户按电源按钮,系统从头启动。 -Shutdown is not a power transition in the reversible sense; it is a termination. The driver's `DEVICE_SHUTDOWN` method is called once, and the driver does not expect to run again until the next boot. The chapter's `myfirst_power_shutdown` handles this correctly by quiescing the device (same as suspend) and not trying to save any state (because there is no resume to save for). +关机不是可逆意义上的电源转换;它是终止。驱动的`DEVICE_SHUTDOWN`方法被调用一次,驱动不期望在下次启动前再次运行。本章的`myfirst_power_shutdown`通过静默设备(与挂起相同)且不尝试保存任何状态(因为没有恢复需要保存)来正确处理这一点。 ### 观察平台支持的状态 -On any FreeBSD 14.3 system with ACPI, the supported states are exposed through a sysctl: +在任何带ACPI的FreeBSD 14.3系统上,支持的状态通过sysctl暴露: ```sh sysctl hw.acpi.supported_sleep_state ``` -Typical outputs: +典型输出: -- A modern laptop: `S3 S4 S5` -- A server: `S5` (suspend not supported on many server platforms) -- A VM on bhyve: varies; usually `S5` only -- A VM on QEMU/KVM with `-machine q35`: often `S3 S4 S5` +- 现代笔记本:`S3 S4 S5` +- 服务器:`S5`(许多服务器平台不支持挂起) +- bhyve上的VM:各不相同;通常只有`S5` +- 带有`-machine q35`的QEMU/KVM上的VM:通常`S3 S4 S5` -If a driver is meant to work on a specific platform, the supported-state list tells you which transitions you need to test. A driver that only runs on servers does not need S3 testing; a driver meant for laptops does. +如果驱动要在特定平台上工作,支持状态列表告诉您需要测试哪些转换。仅在服务器上运行的驱动不需要S3测试;为笔记本设计的驱动需要。 ### 测试内容 -For Chapter 22's purposes, the minimum test is: +对于第22章的目的,最低测试是: -- `devctl suspend` / `devctl resume`: always possible; tests the driver-side code path. -- `acpiconf -s 3` (if supported): tests the full system suspend. -- System shutdown (`shutdown -p now`): tests the `DEVICE_SHUTDOWN` method. +- `devctl suspend` / `devctl resume`:始终可能;测试驱动侧代码路径。 +- `acpiconf -s 3`(如果支持):测试完整系统挂起。 +- 系统关机(`shutdown -p now`):测试`DEVICE_SHUTDOWN`方法。 -S4 and runtime PM are optional; they exercise less-used code paths. A driver that passes the minimum test on a platform that supports S3 is in good shape; extensions are icing. +S4和运行时PM是可选的;它们练习较少使用的代码路径。在支持S3的平台上通过最低测试的驱动状态良好;扩展是锦上添花。 ### 睡眠状态到驱动程序方法的映射 -A compact table of which kobj method is called for each transition: +每种转换调用哪个kobj方法的紧凑表格: -| Transition | Method | Driver Action | +| 转换 | 方法 | 驱动操作 | |---------------------|--------------------|--------------------------------------------------| -| S0 → S1 | DEVICE_SUSPEND | Quiesce; save state | -| S0 → S3 | DEVICE_SUSPEND | Quiesce; save state (device likely goes to D3) | -| S0 → S4 | DEVICE_SUSPEND | Quiesce; save state (followed by hibernate) | -| S0 → S5 (shutdown) | DEVICE_SHUTDOWN | Quiesce; leave in safe state for power-off | -| S1/S3 → S0 | DEVICE_RESUME | Restore state; unmask interrupts | -| S4 → S0 (resume) | (attach from boot) | Normal attach, because the kernel booted fresh | -| devctl suspend | DEVICE_SUSPEND | Quiesce; save state (device goes to D3) | -| devctl resume | DEVICE_RESUME | Restore state; unmask interrupts | +| S0 → S1 | DEVICE_SUSPEND | 静默;保存状态 | +| S0 → S3 | DEVICE_SUSPEND | 静默;保存状态(设备可能进入D3) | +| S0 → S4 | DEVICE_SUSPEND | 静默;保存状态(随后休眠) | +| S0 → S5(关机) | DEVICE_SHUTDOWN | 静默;使设备处于断电安全状态 | +| S1/S3 → S0 | DEVICE_RESUME | 恢复状态;取消屏蔽中断 | +| S4 → S0(恢复) | (从启动挂载) | 正常挂载,因为内核是全新引导的 | +| devctl suspend | DEVICE_SUSPEND | 静默;保存状态(设备进入D3) | +| devctl resume | DEVICE_RESUME | 恢复状态;取消屏蔽中断 | -The driver does not distinguish S1, S3, and S4 from its own code; it always does the same work. The differences are at the platform and kernel levels. That uniformity is what makes the pattern scalable: one suspend path, one resume path, multiple contexts. +驱动不从自己的代码中区分S1、S3和S4;它总是做相同的工作。差异在平台和内核层。这种统一性使模式可扩展:一个挂起路径,一个恢复路径,多个上下文。 ## 深入理解:PCIe链路状态和ASPM实战 -Section 1 sketched the PCIe link states (L0, L0s, L1, L1.1, L1.2, L2). It is worth seeing how they behave in practice, because understanding them helps the driver developer interpret latency measurements and power observations. +第1节概述了PCIe链路状态(L0、L0s、L1、L1.1、L1.2、L2)。值得在实践中看看它们的行为,因为理解它们有助于驱动开发者解释延迟测量和功耗观察。 ### 为什么链路有自己的状态 -A PCIe link is a pair of high-speed differential lanes between two endpoints (root complex and device, or root complex and switch). Each lane has a transmitter and a receiver; each lane's transmitter consumes power to keep the channel in a known state. When traffic is low, the transmitters can be turned off in various degrees, and the link can be re-established quickly when traffic resumes. The L-states describe those degrees. +PCIe链路是两个端点(根复合体和设备,或根复合体和交换器)之间的一对高速差分通道。每个通道有发送器和接收器;每个通道的发送器消耗功率保持通道在已知状态。当流量低时,发送器可以不同程度关闭,链路可以在流量恢复时快速重新建立。L状态描述这些程度。 -The link's state is separate from the device's D-state. A device in D0 can have its link in L1 (the link is idle; the device is not transmitting or receiving). A device in D3 has its link in L2 or similar (the link is off). A device in D0 with a busy link is in L0. +链路的状态独立于设备的D状态。D0中的设备可以使其链路处于L1(链路空闲;设备不在传输或接收)。D3中的设备使其链路处于L2或类似状态(链路关闭)。D0中带繁忙链路的设备处于L0。 ### L0:活动 -L0 is the normal operating state. Both sides of the link are active; data can flow in either direction; latency is at its minimum (a few hundred nanoseconds round-trip on a modern PCIe). +L0是正常操作状态。链路两侧都活跃;数据可以双向流动;延迟最小(现代PCIe上往返几百纳秒)。 -When a DMA transfer is running or an MMIO read is pending, the link is in L0. The device's own logic and the PCIe host bridge both require L0 for the transaction. +当DMA传输正在运行或MMIO读取待处理时,链路处于L0。设备自身的逻辑和PCIe主机桥都需要L0进行事务。 ### L0s:发送器待机 -L0s is a low-power state where one side of the link's transmitter is turned off. The receiver stays on; the link can be brought back to L0 in under a microsecond. +L0s是链路一侧发送器关闭的低功耗状态。接收器保持开启;链路可以在一微秒内回到L0。 -L0s is entered automatically by the link logic when no traffic has been sent for a few microseconds. The platform's PCIe host bridge and the device's PCIe interface cooperate: when the transmit FIFO is empty and ASPM is enabled, the transmitter goes off. When new traffic arrives, the transmitter comes back on. +L0s在几微秒没有发送流量时由链路逻辑自动进入。平台的PCIe主机桥和设备的PCIe接口协作:当发送FIFO为空且ASPM启用时,发送器关闭。当新流量到达时,发送器重新开启。 -L0s is "asymmetric": each side independently enters and exits the state. A device's transmitter can be in L0s while the root complex's transmitter is in L0. This is useful because traffic is typically bursty: the CPU sends a DMA trigger, then does not send anything else for a while; the CPU's transmitter enters L0s quickly, while the device's transmitter stays in L0 because it is actively sending the DMA response. +L0s是"非对称的":每侧独立进入和退出状态。设备的发送器可以在L0s中而根复合体的发送器在L0中。这很有用因为流量通常是突发的:CPU发送DMA触发,然后一段时间不发送任何东西;CPU的发送器快速进入L0s,而设备的发送器保持在L0因为它正在积极发送DMA响应。 ### L1:双方待机 -L1 is a deeper state where both transmitters are off. Neither side can send anything until the link is brought back to L0; the latency is measured in microseconds (5 to 65, depending on platform). +L1是更深的状态,两侧发送器都关闭。在链路回到L0之前,任何一方都不能发送任何东西;延迟以微秒计(5到65,取决于平台)。 -L1 is entered after a longer idle period than L0s. The exact threshold is configurable through ASPM settings; typical values are tens of microseconds of inactivity. L1 saves more power than L0s but costs more to exit. +L1在比L0s更长的空闲期后进入。确切阈值通过ASPM设置配置;典型值是数十微秒不活动。L1比L0s节省更多功率但退出成本更高。 ### L1.1和L1.2:更深的L1子状态 -PCIe 3.0 and later define sub-states of L1 that turn off additional parts of the physical layer. L1.1 (also called "L1 PM Substate 1") keeps the clock running but turns off more circuitry; L1.2 turns off the clock as well. The wake latencies increase (tens of microseconds for L1.1; hundreds for L1.2), but the idle power draws decrease. +PCIe 3.0及更高版本定义了关闭物理层额外部分的L1子状态。L1.1(也称为"L1 PM子状态1")保持时钟运行但关闭更多电路;L1.2也关闭时钟。唤醒延迟增加(L1.1数十微秒;L1.2数百微秒),但空闲功耗降低。 -Most modern laptops use L1.1 and L1.2 aggressively to extend battery life. A laptop that stays in L1.2 most of the idle time can have PCIe power draw in the single-digit milliwatts, compared to hundreds of milliwatts in L0. +大多数现代笔记本积极使用L1.1和L1.2以延长电池寿命。大部分空闲时间保持在L1.2的笔记本PCIe功耗可以是个位毫瓦,而L0中是数百毫瓦。 ### L2:近关闭 -L2 is the state the link enters when the device is in D3cold. The link is effectively off; re-establishing it requires a full link-training sequence (tens of milliseconds). L2 is entered as part of the full-system suspend sequence; the driver does not manage it directly. +L2是设备处于D3cold时链路进入的状态。链路实际上关闭;重新建立它需要完整链路训练序列(数十毫秒)。L2作为完整系统挂起序列的一部分进入;驱动不直接管理它。 ### 谁控制ASPM -ASPM is a per-link feature configured through the PCIe Link Capability and Link Control registers in both the root complex and the device. The configuration specifies: +ASPM是通过根复合体和设备两端的PCIe链路能力和链路控制寄存器配置的每链路特性。配置指定: -- Whether L0s is enabled (one-bit field). -- Whether L1 is enabled (one-bit field). -- The exit latency thresholds the platform considers acceptable. +- 是否启用L0s(一位字段)。 +- 是否启用L1(一位字段)。 +- 平台认为可接受的退出延迟阈值。 -On FreeBSD, ASPM is usually controlled by the platform firmware through ACPI's `_OSC` method. The firmware tells the OS which capabilities to manage; if the firmware keeps ASPM control, the OS does not touch it. If the firmware hands over control, the OS may enable or disable ASPM per link based on policy. +在FreeBSD上,ASPM通常由平台固件通过ACPI的`_OSC`方法控制。固件告诉操作系统管理哪些能力;如果固件保持ASPM控制,操作系统不触碰它。如果固件移交控制,操作系统可以基于策略按链路启用或禁用ASPM。 -For Chapter 22's `myfirst` driver, ASPM is the platform's job. The driver does not configure ASPM; it does not need to know whether the link is in L0 or L1 at any moment. The link's state is invisible to the driver from a functional standpoint (latency is the only observable effect). +对于第22章的`myfirst`驱动,ASPM是平台的工作。驱动不配置ASPM;它不需要知道链路在任何时刻处于L0还是L1。从功能角度看,链路的状态对驱动是不可见的(延迟是唯一可观察的效果)。 ### ASPM何时对驱动程序重要 -There are specific situations where a driver does have to worry about ASPM: +在特定情况下驱动确实需要关注ASPM: -1. **Known errata.** Some PCIe devices have bugs in their ASPM implementation that cause the link to wedge or produce corrupted transactions. The driver may need to explicitly disable ASPM for those devices. The kernel provides the PCIe Link Control register access through `pcie_read_config` and `pcie_write_config` for this purpose. +1. **已知勘误。** 某些PCIe设备的ASPM实现有缺陷,会导致链路卡死或产生损坏的事务。驱动可能需要为这些设备显式禁用ASPM。内核通过`pcie_read_config`和`pcie_write_config`提供PCIe链路控制寄存器访问用于此目的。 -2. **Latency-sensitive devices.** A real-time audio or video device may not tolerate the microsecond-scale latency of L1. The driver may disable L1 while keeping L0s enabled. +2. **延迟敏感设备。** 实时音频或视频设备可能无法容忍L1的微秒级延迟。驱动可以在保持L0s启用的同时禁用L1。 -3. **Power-sensitive devices.** A battery-powered device may want L1.2 always enabled. The driver may force L1.2 if the platform's default is less aggressive. +3. **功耗敏感设备。** 电池供电的设备可能希望L1.2始终启用。如果平台默认不够激进,驱动可以强制L1.2。 -For the `myfirst` driver, none of these apply. The simulated device does not have a link at all; the real PCIe link (if any) is handled by the platform. The chapter mentions ASPM for completeness and moves on. +对于`myfirst`驱动,这些都不适用。模拟设备根本没有链路;真实PCIe链路(如果有)由平台处理。本章为完整性提及ASPM后继续。 ### 观察链路状态 -On a system where the platform supports ASPM observation, the link state is exposed through `pciconf -lvbc`: +在平台支持ASPM观察的系统上,链路状态通过`pciconf -lvbc`暴露: ```sh pciconf -lvbc | grep -A 20 myfirst ``` -Look for lines like: +查找如下行: ```text cap 10[ac] = PCI-Express 2 endpoint max data 128(512) FLR NS @@ -3200,15 +3199,15 @@ cap 10[ac] = PCI-Express 2 endpoint max data 128(512) FLR NS slot 0 ``` -The "ASPM disabled" on this line says ASPM is not currently active. "disabled(L0s/L1)" says the device supports both L0s and L1 but neither is enabled. On a system with aggressive ASPM, the line would read "ASPM L1" or similar. +此行上的"ASPM disabled"表示ASPM当前不活跃。"disabled(L0s/L1)"表示设备支持L0s和L1但两者都未启用。在有激进ASPM的系统上,该行会显示"ASPM L1"或类似内容。 -The exit latencies tell the driver how long the transition back to L0 takes; a latency-sensitive driver can decide whether L1 is tolerable by looking at this number. +退出延迟告诉驱动回到L0的转换需要多长时间;延迟敏感的驱动可以通过查看此数字决定L1是否可容忍。 ### 链路状态和功耗 -A rough table of PCIe power draws (typical values; actual depend on implementation): +PCIe功耗粗略表格(典型值;实际取决于实现): -| State | Power (x1 link) | Exit Latency | +| 状态 | 功耗(x1链路) | 退出延迟 | |-------|-----------------|--------------| | L0 | 100-200 mW | 0 | | L0s | 50-100 mW | <1 µs | @@ -3217,29 +3216,29 @@ A rough table of PCIe power draws (typical values; actual depend on implementati | L1.2 | <1 mW | 50-500 µs | | L2 | near 0 | 1-100 ms | -For a laptop with a dozen PCIe links all in L1.2 during idle, the aggregate savings relative to all-L0 can be in the watts. For a server with high-throughput links always in L0, ASPM is disabled and the power saving is zero. +对于空闲时所有12条PCIe链路都在L1.2的笔记本,相对于全L0的总节省可以达到瓦特级别。对于高吞吐量链路始终在L0的服务器,ASPM被禁用,节能为零。 -Chapter 22 does not implement ASPM for `myfirst`. The chapter mentions it because understanding the link state machine is part of understanding the full power-management picture. A reader who later works on a driver with known ASPM errata will know where to look. +第22章不为`myfirst`实现ASPM。本章提及它因为理解链路状态机是理解完整电源管理图景的一部分。之后在有已知ASPM勘误的驱动上工作的读者会知道去哪里查找。 ## 深入理解:唤醒源详解 -Wake sources are the mechanisms that bring a suspended system or device back to active. Chapter 1 mentioned them briefly; this deeper look walks through the most common ones. +唤醒源是将挂起的系统或设备带回活动状态的机制。第1节简要提及了它们;这个深入理解遍历最常见的几种。 ### PCIe上的PME# -The PCI spec defines the `PME#` signal (Power Management Event). When asserted, it tells the upstream root complex that the device has an event worth waking for. The root complex converts PME# into an ACPI GPE or interrupt, which the kernel handles. +PCI规范定义`PME#`信号(电源管理事件)。断言时,它告诉上游根复合体设备有值得唤醒的事件。根复合体将PME#转换为ACPI GPE或中断,由内核处理。 -A device that supports PME# has a PCI power-management capability (checked via `pci_has_pm`). The capability's control register includes: +支持PME#的设备有PCI电源管理能力(通过`pci_has_pm`检查)。能力的控制寄存器包括: -- **PME_En** (bit 8): enable PME# generation. -- **PME_Status** (bit 15): set by the device when PME# is raised, cleared by software. -- **PME_Support** (read-only, bits 11-15 in PMC register): which D-states the device can raise PME# from (D0, D1, D2, D3hot, D3cold). +- **PME_En**(位8):启用PME#生成。 +- **PME_Status**(位15):设备在PME#被引发时设置,由软件清除。 +- **PME_Support**(只读,PMC寄存器中的位11-15):设备可以从哪些D状态引发PME#(D0、D1、D2、D3hot、D3cold)。 -The driver's job is to set PME_En at the right time (usually before suspend) and to clear PME_Status at the right time (usually after resume). The `pci_enable_pme(dev)` and `pci_clear_pme(dev)` helpers do both jobs. +驱动的工作是在正确的时间设置PME_En(通常在挂起前)和在正确的时间清除PME_Status(通常在恢复后)。`pci_enable_pme(dev)`和`pci_clear_pme(dev)`助手完成这两个工作。 -On a typical laptop, the root complex routes PME# to an ACPI GPE, which the kernel's ACPI driver picks up as a wake event. The chain looks like: +在典型笔记本上,根复合体将PME#路由到ACPI GPE,内核的ACPI驱动将其作为唤醒事件拾取。链如下: ```text device asserts PME# @@ -3251,94 +3250,94 @@ device asserts PME# → eventually: DEVICE_RESUME on the device that woke ``` -The whole chain takes one to three seconds. The driver's role is minimal: it enabled PME# before suspend, and it will clear PME_Status after resume. Everything else is platform. +整个链需要一到三秒。驱动的角色很小:它在挂起前启用PME#,它将在恢复后清除PME_Status。其余是平台的工作。 ### USB远程唤醒 -USB has its own wake mechanism called "remote wakeup". A USB device requests wake capability through its standard descriptor; the host controller enables the capability at enumeration time; when the device asserts a resume signal on its upstream port, the host controller propagates it. +USB有自己的唤醒机制称为"远程唤醒"。USB设备通过其标准描述符请求唤醒能力;主机控制器在枚举时启用该能力;当设备在其上游端口上断言恢复信号时,主机控制器传播它。 -From a FreeBSD driver perspective, USB remote wakeup is almost entirely handled by the USB host controller driver (`xhci`, `ohci`, `uhci`). Individual USB device drivers (for keyboards, storage, audio, etc.) participate through the USB framework's suspend and resume callbacks, but they do not deal with PME# directly. The USB host controller's own PME# is what actually wakes the system. +从FreeBSD驱动角度看,USB远程唤醒几乎完全由USB主机控制器驱动(`xhci`、`ohci`、`uhci`)处理。单个USB设备驱动(用于键盘、存储、音频等)通过USB框架自己的挂起和恢复回调参与,但它们不直接处理PME#。USB主机控制器自身的PME#是实际唤醒系统的东西。 -For Chapter 22 purposes, USB wake is a black box that works through the USB host controller driver. A reader who eventually writes a USB device driver will learn the framework's conventions then. +对于第22章的目的,USB唤醒是通过USB主机控制器驱动工作的黑盒。最终编写USB设备驱动的读者将在那时学习框架的约定。 ### 嵌入式平台上的GPIO唤醒 -On embedded platforms (arm64, RISC-V), wake sources are typically GPIO pins connected to the SoC's wake logic. The device tree describes which pins are wake sources via `wakeup-source` properties and `interrupts-extended` pointing to the wake controller. +在嵌入式平台(arm64、RISC-V)上,唤醒源通常是连接到SoC唤醒逻辑的GPIO引脚。设备树通过`wakeup-source`属性和指向唤醒控制器的`interrupts-extended`描述哪些引脚是唤醒源。 -FreeBSD's GPIO intr framework handles these. A device driver whose hardware is wake-capable reads the device-tree `wakeup-source` property during attach, registers the GPIO as a wake source with the framework, and the framework does the rest. The mechanism is very different from PCIe PME#, but the driver-side API (mark wake enabled, clear wake status) is conceptually similar. +FreeBSD的GPIO intr框架处理这些。硬件具有唤醒能力的设备驱动在挂载期间读取设备树`wakeup-source`属性,用框架将GPIO注册为唤醒源,框架做其余的工作。该机制与PCIe PME#非常不同,但驱动侧API(标记唤醒启用、清除唤醒状态)在概念上相似。 -Chapter 22 does not exercise GPIO wake; the `myfirst` driver is a PCI device. Part 7 revisits embedded platforms and covers the GPIO path in detail. +第22章不练习GPIO唤醒;`myfirst`驱动是PCI设备。第七部分重新审视嵌入式平台并详细覆盖GPIO路径。 ### 局域网唤醒(WoL) -Wake on LAN is a specific implementation pattern for a network controller. The controller watches incoming packets for a "magic packet" (a specific pattern containing the controller's MAC address repeated many times) or for user-configured patterns. When a match is detected, the controller asserts PME# upstream. +局域网唤醒是网络控制器的特定实现模式。控制器监视传入数据包中的"魔法数据包"(包含控制器MAC地址重复多次的特定模式)或用户配置的模式。当检测到匹配时,控制器向上游断言PME#。 -From the driver's perspective, WoL requires: +从驱动角度看,WoL需要: -1. Configuring the NIC's wake logic (magic-packet filter, pattern filters) before suspend. -2. Enabling PME# via `pci_enable_pme`. -3. On resume, disabling the wake logic (because normal packet processing would otherwise be influenced by the filters). +1. 在挂起前配置NIC的唤醒逻辑(魔法数据包过滤器、模式过滤器)。 +2. 通过`pci_enable_pme`启用PME#。 +3. 在恢复时,禁用唤醒逻辑(因为否则正常数据包处理会被过滤器影响)。 -The `re(4)` driver's `re_setwol` is the canonical FreeBSD example. A reader building a NIC driver copies its structure and adapts the device-specific register programming. +`re(4)`驱动的`re_setwol`是规范的FreeBSD例子。构建NIC驱动的读者复制其结构并适应设备特定的寄存器编程。 ### 盖子、电源按钮等唤醒 -The laptop's lid switch, power button, keyboard (in some cases), and other platform inputs are wired to the platform's wake logic through ACPI. The ACPI driver handles the wake; individual device drivers are not involved. +笔记本的盖子开关、电源按钮、键盘(在某些情况下)和其他平台输入通过ACPI连接到平台的唤醒逻辑。ACPI驱动处理唤醒;单个设备驱动不参与。 -The ACPI `_PRW` method on a device's object in the ACPI namespace declares which GPE that device's wake event uses. The OS reads `_PRW` during boot to configure the wake routing. The `myfirst` driver, as a simple PCI endpoint with no platform-specific wake source, does not have a `_PRW` method; its wake capability (if any) is purely through PME#. +ACPI命名空间中设备对象上的ACPI `_PRW`方法声明该设备的唤醒事件使用哪个GPE。操作系统在启动时读取`_PRW`以配置唤醒路由。`myfirst`驱动作为没有平台特定唤醒源的简单PCI端点,没有`_PRW`方法;其唤醒能力(如果有)纯粹通过PME#。 ### 驱动程序何时必须启用唤醒 -A simple heuristic: the driver must enable wake if the user has asked for it (through an interface capability flag like `IFCAP_WOL` for NICs) and the hardware supports it (`pci_has_pm` returns true, the device's own wake logic is operational). Otherwise, the driver leaves wake disabled. +简单的启发式:驱动必须在用户请求时(通过接口能力标志如NIC的`IFCAP_WOL`)且硬件支持时(`pci_has_pm`返回true,设备自身唤醒逻辑可操作)启用唤醒。否则,驱动保持唤醒禁用。 -A driver that enables wake for every device by default wastes platform power; the wake circuitry and PME# routing cost a few milliwatts continuously. A driver that never enables wake frustrates users who want their laptop to wake on a network packet. The policy is "enable only when asked". +默认为每个设备启用唤醒的驱动浪费平台功率;唤醒电路和PME#路由持续消耗几毫瓦。从不启用唤醒的驱动让希望笔记本在收到网络数据包时唤醒的用户沮丧。策略是"仅在请求时启用"。 -FreeBSD's interface capabilities (set via `ifconfig em0 wol wol_magic`) are the standard way users express the desire. The NIC driver reads the flags and configures WoL accordingly. +FreeBSD的接口能力(通过`ifconfig em0 wol wol_magic`设置)是用户表达愿望的标准方式。NIC驱动读取标志并相应配置WoL。 ### 测试唤醒源 -Testing wake is harder than testing suspend and resume, because testing wake requires the system to actually sleep and then an external event to wake it. Common approaches: +测试唤醒比测试挂起和恢复更难,因为测试唤醒需要系统实际睡眠然后外部事件唤醒它。常见方法: -- **Magic packet from another machine.** Send a WoL magic packet to the suspended machine's MAC address. If WoL is working, the machine wakes in a few seconds. -- **Lid switch.** Close the lid, wait, open the lid. If the platform's wake routing is working, the machine wakes on open. -- **Power button.** Press the power button briefly while suspended. The machine should wake. +- **从另一台机器发送魔法数据包。** 向挂起机器的MAC地址发送WoL魔法数据包。如果WoL工作,机器在几秒内唤醒。 +- **盖子开关。** 关闭盖子、等待、打开盖子。如果平台的唤醒路由工作,机器在打开时唤醒。 +- **电源按钮。** 在挂起时短暂按电源按钮。机器应唤醒。 -For a learning driver like `myfirst`, there is no meaningful wake source to test against. The chapter mentions wake mechanics for pedagogical completeness, not because the driver exercises them. +对于像`myfirst`这样的学习驱动,没有有意义的唤醒源可以测试。本章出于教学完整性提及唤醒机制,不是因为驱动练习它们。 ## 深入理解:hw.pci.do_power_suspend可调参数 -One of the most important tunables for power-management debugging is `hw.pci.do_power_suspend`. It controls whether the PCI layer automatically transitions devices to D3 during system suspend. Understanding what it does and when to change it is worth a dedicated look. +电源管理调试中最重要的可调参数之一是`hw.pci.do_power_suspend`。它控制PCI层是否在系统挂起期间自动将设备转换到D3。理解它做什么以及何时更改它值得专门看一下。 ### 默认值的作用 -With `hw.pci.do_power_suspend=1` (the default), the PCI layer's `pci_suspend_child` helper, after calling the driver's `DEVICE_SUSPEND`, transitions the device to D3hot by calling `pci_set_power_child(dev, child, PCI_POWERSTATE_D3)`. On resume, `pci_resume_child` transitions back to D0. +`hw.pci.do_power_suspend=1`(默认)时,PCI层的`pci_suspend_child`助手在调用驱动的`DEVICE_SUSPEND`后,通过调用`pci_set_power_child(dev, child, PCI_POWERSTATE_D3)`将设备转换到D3hot。恢复时,`pci_resume_child`转回D0。 -This is the "power-save" mode. A device that supports D3 uses its lowest-power idle state during suspend. A laptop benefits because battery life during sleep is extended; a device that can sleep at a few milliwatts instead of a few hundred is worth the extra D-state transition. +这是"节能"模式。支持D3的设备在挂起期间使用其最低功耗空闲状态。笔记本受益因为睡眠期间电池寿命延长;能以几毫瓦而非几百毫瓦睡眠的设备值得额外的D状态转换。 ### hw.pci.do_power_suspend=0的作用 -With the tunable set to 0, the PCI layer does not transition the device to D3. The device stays in D0 throughout the suspend. The driver's `DEVICE_SUSPEND` runs; the driver quiesces activity; the device stays powered. +可调参数设为0时,PCI层不将设备转换到D3。设备在整个挂起期间保持在D0。驱动的`DEVICE_SUSPEND`运行;驱动静默活动;设备保持供电。 -From a power-saving perspective, this is worse: the device continues to draw its D0 power budget during sleep. From a correctness perspective, it can be better for some devices: +从节能角度看,这更差:设备在睡眠期间继续消耗D0功率预算。从正确性角度看,对某些设备可以更好: -- A device with broken D3 implementation may misbehave when transitioned. Staying in D0 avoids the transition bug. -- A device whose context is expensive to save and restore may prefer to stay in D0 during a short suspend. If the suspend is only a few seconds, the context-save cost exceeds the power-saving benefit. -- A device that is critical to the machine's core function (a console keyboard, for example) may need to stay alert even during suspend. +- 有损坏D3实现的设备在转换时可能行为异常。保持D0避免转换错误。 +- 上下文保存和恢复代价昂贵的设备在短暂挂起期间可能偏好保持D0。如果挂起仅几秒,上下文保存成本超过节能收益。 +- 对机器核心功能关键的设备(例如控制台键盘)可能需要在挂起期间保持警觉。 ### 何时更改 -For development and debugging, setting `hw.pci.do_power_suspend=0` can isolate bugs: +对于开发和调试,设置`hw.pci.do_power_suspend=0`可以隔离错误: -- If a resume bug appears only with the tunable at 1, the bug is in the D3-to-D0 transition (either in the PCI layer's config restore, or in the driver's handling of a device that has been reset). -- If a resume bug appears with the tunable at 0 as well, the bug is in the driver's `DEVICE_SUSPEND` or `DEVICE_RESUME` code, not in the D-state machinery. +- 如果恢复错误仅在可调参数为1时出现,错误在D3到D0转换中(在PCI层的配置恢复中,或在驱动处理已重置设备中)。 +- 如果恢复错误在可调参数为0时也出现,错误在驱动的`DEVICE_SUSPEND`或`DEVICE_RESUME`代码中,不在D状态机制中。 -For production, the default (1) is almost always right. Changing it globally affects every PCI device on the system; a better approach is a per-device override if one is needed, which typically lives in the driver itself. +对于生产,默认(1)几乎总是正确的。全局更改它影响系统上的每个PCI设备;更好的方法是如果需要则按设备覆盖,通常位于驱动自身中。 ### 验证可调参数生效 -A quick way to verify is to check the device's power state with `pciconf` before and after a suspend: +快速验证方法是在挂起前后用`pciconf`检查设备的电源状态: ```sh # Before suspend (device should be in D0): @@ -3361,85 +3360,85 @@ sudo sysctl hw.pci.do_power_suspend=1 sudo devctl resume myfirst0 ``` -The `powerspec` line in `pciconf -lvbc` output shows the current power state. Watching it change between D0 and D3 confirms the automatic transition is happening. +`pciconf -lvbc`输出中的`powerspec`行显示当前电源状态。观察它在D0和D3之间变化确认自动转换正在发生。 ### 与pci_save_state的交互 -When `hw.pci.do_power_suspend` is 1, the PCI layer automatically calls `pci_cfg_save` before transitioning to D3. When it is 0, the PCI layer does not call `pci_cfg_save`. +当`hw.pci.do_power_suspend`为1时,PCI层在转换到D3之前自动调用`pci_cfg_save`。当为0时,PCI层不调用`pci_cfg_save`。 -This has a subtle implication: if the driver wants to save configuration explicitly in the 0 case, it must call `pci_save_state` itself. The Chapter 22 pattern assumes the default (1) and does not call `pci_save_state` explicitly; a driver that wants to support both modes would need additional logic. +这有一个微妙的含义:如果驱动想在0情况下显式保存配置,它必须自己调用`pci_save_state`。第22章的模式假设默认(1)并且不显式调用`pci_save_state`;想要支持两种模式的驱动需要额外逻辑。 ### 可调参数影响系统挂起还是devctl挂起? -Both. `pci_suspend_child` is called for both `acpiconf -s 3` and `devctl suspend`, and the tunable gates the D-state transition in both cases. A reader debugging with `devctl suspend` will see the same behavior as with a full system suspend, modulo the other platform work (CPU park, ACPI sleep state entry). +两者都影响。`pci_suspend_child`既为`acpiconf -s 3`也为`devctl suspend`调用,可调参数在两种情况下都控制D状态转换。用`devctl suspend`调试的读者将看到与完整系统挂起相同的行为,除了其他平台工作(CPU停车、ACPI睡眠状态进入)。 ### 具体调试场景 -Suppose the `myfirst` driver's resume fails intermittently: sometimes it works, sometimes `dma_test_read` after resume returns EIO. The counters are consistent (suspend count = resume count), the logs show both methods ran, but the post-resume DMA fails. +假设`myfirst`驱动的恢复间歇性失败:有时工作,有时恢复后`dma_test_read`返回EIO。计数器一致(挂起计数=恢复计数),日志显示两个方法都运行了,但恢复后DMA失败。 -**Hypothesis 1.** The D3-to-D0 transition is producing an inconsistent device state. Verify by setting `hw.pci.do_power_suspend=0` and retrying. +**假设1。** D3到D0转换产生了不一致的设备状态。通过设置`hw.pci.do_power_suspend=0`并重试验证。 -If the bug disappears with the tunable at 0, the D-state machinery is involved. The fix might be in the driver's resume path (add a delay after the transition to let the device stabilise), in the PCI layer's config restore, or in the device itself. +如果错误在可调参数为0时消失,D状态机制涉及其中。修复可能在驱动的恢复路径中(在转换后添加延迟让设备稳定)、在PCI层的配置恢复中、或在设备本身中。 -**Hypothesis 2.** The bug is in the driver's own suspend/resume code, independent of D3. Verify by setting the tunable to 0 and retrying. +**假设2。** 错误在驱动自己的挂起/恢复代码中,独立于D3。通过设置可调参数为0并重试验证。 -If the bug persists with the tunable at 0, the driver's code is the problem. The D3 transition is innocent. +如果错误在可调参数为0时持续,驱动的代码是问题。D3转换是清白的。 -This kind of bisection is common in power-management debugging. The tunable is the tool that lets you isolate the variable. +这种二分法在电源管理调试中很常见。可调参数是让您隔离变量的工具。 ## 深入理解:DEVICE_QUIESCE和何时需要它 -Section 2 briefly mentioned `DEVICE_QUIESCE` as the third power-management method alongside `DEVICE_SUSPEND` and `DEVICE_SHUTDOWN`. It is rarely implemented explicitly in FreeBSD drivers; a search of `/usr/src/sys/dev/` shows only a handful of drivers define their own `device_quiesce`. Understanding when you do need it and when you do not is worth a short section. +第2节简要提及`DEVICE_QUIESCE`作为`DEVICE_SUSPEND`和`DEVICE_SHUTDOWN`旁边的第三个电源管理方法。它在FreeBSD驱动中很少被显式实现;搜索`/usr/src/sys/dev/`显示只有少数驱动定义了自己的`device_quiesce`。理解何时需要它何时不需要值得一小节。 ### DEVICE_QUIESCE的用途 -The `device_quiesce` wrapper in `/usr/src/sys/kern/subr_bus.c` is called in several places: +`/usr/src/sys/kern/subr_bus.c`中的`device_quiesce`包装器在几个地方被调用: -- `devclass_driver_deleted`: when a driver is being unloaded, the framework calls `device_quiesce` on every instance before calling `device_detach`. -- `DEV_DETACH` via devctl: when the user runs `devctl detach myfirst0`, the kernel calls `device_quiesce` before `device_detach` unless the `-f` (force) flag is given. -- `DEV_DISABLE` via devctl: when the user runs `devctl disable myfirst0`, the kernel calls `device_quiesce` similarly. +- `devclass_driver_deleted`:当驱动被卸载时,框架在调用`device_detach`之前在每个实例上调用`device_quiesce`。 +- 通过devctl的`DEV_DETACH`:当用户运行`devctl detach myfirst0`时,内核在`device_detach`之前调用`device_quiesce`,除非给出`-f`(强制)标志。 +- 通过devctl的`DEV_DISABLE`:当用户运行`devctl disable myfirst0`时,内核类似地调用`device_quiesce`。 -In each case, the quiesce is a pre-check: "can the driver safely stop what it is doing?". A driver that returns EBUSY from `DEVICE_QUIESCE` prevents the subsequent detach or disable. The user gets an error, and the driver stays attached. +在每种情况下,静默是预检查:"驱动能安全停止正在做的事情吗?"。从`DEVICE_QUIESCE`返回EBUSY的驱动阻止后续分离或禁用。用户得到错误,驱动保持挂载。 ### 默认值的作用 -If a driver does not implement `DEVICE_QUIESCE`, the default (`null_quiesce` in `device_if.m`) returns 0 unconditionally. The kernel proceeds with detach or disable. +如果驱动不实现`DEVICE_QUIESCE`,默认(`device_if.m`中的`null_quiesce`)无条件返回0。内核继续分离或禁用。 -For most drivers, this is fine. The driver's detach path handles any in-flight work, so there is nothing the quiesce would do that detach does not also do. +对于大多数驱动,这没问题。驱动的分离路径处理任何进行中的工作,所以静默能做的分离也都做。 ### 何时应该实现它 -A driver implements `DEVICE_QUIESCE` explicitly when: +驱动在以下情况下显式实现`DEVICE_QUIESCE`: -1. **Returning EBUSY is more informative than waiting.** If the driver has a concept of "busy" (a transfer in flight, an open file descriptor count, a filesystem mount), and the user can wait for it to become non-busy, the driver might refuse quiesce until busy is zero. `DEVICE_QUIESCE` returning EBUSY tells the user "the device is busy; wait and retry". +1. **返回EBUSY比等待更有信息量。** 如果驱动有"忙碌"的概念(传输进行中、打开的文件描述符计数、文件系统挂载),且用户可以等待它变为非忙碌,驱动可以拒绝静默直到忙碌为零。`DEVICE_QUIESCE`返回EBUSY告诉用户"设备正忙;请等待并重试"。 -2. **The quiesce can be done faster than a full detach.** If detach is expensive (frees large resource tables, drains slow queues) but the device can be stopped cheaply, `DEVICE_QUIESCE` lets the kernel probe for readiness without paying detach's cost. +2. **静默可以比完整分离更快完成。** 如果分离代价高昂(释放大型资源表、排空慢速队列)但设备可以廉价停止,`DEVICE_QUIESCE`让内核在不付出分离成本的情况下探测就绪状态。 -3. **The driver wants to distinguish quiesce from suspend.** If the driver wants to stop activity but not save state (because no resume is coming), implementing quiesce separately from suspend is a way to express that distinction in code. +3. **驱动想区分静默和挂起。** 如果驱动想停止活动但不保存状态(因为不会有恢复),将静默与挂起分开实现是在代码中表达这种区别的方式。 -For the `myfirst` driver, none of these apply. The Chapter 21 detach path already handles in-flight work; the Chapter 22 suspend path handles quiesce in the power-management sense. Adding a separate `DEVICE_QUIESCE` would be redundant. +对于`myfirst`驱动,这些都不适用。第21章的分离路径已处理进行中的工作;第22章的挂起路径在电源管理意义上处理静默。添加单独的`DEVICE_QUIESCE`是冗余的。 ### 来自bce(4)的示例 -The Broadcom NetXtreme driver in `/usr/src/sys/dev/bce/if_bce.c` has a commented-out `DEVMETHOD(device_quiesce, bce_quiesce)` entry in its method table. The comment suggests the author considered implementing quiesce but did not. This is common: many drivers keep the line commented as a TODO that never gets implemented, because the default handles their use case. +/usr/src/sys/dev/bce/if_bce.c`中的Broadcom NetXtreme驱动在其方法表中有注释掉的`DEVMETHOD(device_quiesce, bce_quiesce)`条目。注释表明作者考虑了实现静默但没有。这很常见:许多驱动将该行作为TODO注释保留,因为默认处理了它们的用例。 -The implementation, if the driver enabled it, would stop the NIC's TX and RX paths without freeing the hardware resources. A subsequent `device_detach` would then do the actual freeing. The split between "stop" and "free" is what `DEVICE_QUIESCE` would express. +如果驱动启用它,实现会停止NIC的TX和RX路径而不释放硬件资源。后续的`device_detach`然后做实际释放。"停止"和"释放"之间的分割是`DEVICE_QUIESCE`要表达的。 ### 与DEVICE_SUSPEND的关系 -`DEVICE_QUIESCE` and `DEVICE_SUSPEND` do similar things: they stop the device's activity. The differences: +`DEVICE_QUIESCE`和`DEVICE_SUSPEND`做类似的事:它们停止设备的活动。区别: -- **Lifecycle**: quiesce is between run and detach; suspend is between run and eventual resume. -- **Resources**: quiesce does not require the driver to save any state; suspend does. -- **Ability to veto**: both can return EBUSY; the consequences differ (quiesce prevents detach; suspend prevents the power transition). +- **生命周期**:静默在运行和分离之间;挂起在运行和最终恢复之间。 +- **资源**:静默不要求驱动保存任何状态;挂起需要。 +- **否决能力**:两者都可以返回EBUSY;后果不同(静默阻止分离;挂起阻止电源转换)。 -A driver that implements both usually shares code: `foo_quiesce` might do "stop activity" and `foo_suspend` might do "call quiesce; save state; return". The `myfirst` driver's `myfirst_quiesce` helper is the shared code; the chapter does not wire it to a `DEVICE_QUIESCE` method, but doing so would be a small addition. +实现两者的驱动通常共享代码:`foo_quiesce`可能做"停止活动",`foo_suspend`可能做"调用静默;保存状态;返回"。`myfirst`驱动的`myfirst_quiesce`助手是共享代码;本章不将其连接到`DEVICE_QUIESCE`方法,但这样做是一个小的添加。 ### myfirst的可选添加 -As a challenge, the reader can add `DEVICE_QUIESCE` to `myfirst`: +作为挑战,读者可以向`myfirst`添加`DEVICE_QUIESCE`: ```c static int @@ -3455,27 +3454,27 @@ myfirst_pci_quiesce(device_t dev) } ``` -And the matching method-table entry: +以及匹配的方法表条目: ```c DEVMETHOD(device_quiesce, myfirst_pci_quiesce), ``` -Testing it: `devctl detach myfirst0` calls quiesce before detach; the reader can verify by reading `dev.myfirst.0.power_quiesce_count` immediately before the detach takes effect. +测试它:`devctl detach myfirst0`在分离前调用静默;读者可以在分离生效前立即读取`dev.myfirst.0.power_quiesce_count`来验证。 -The challenge is short and does not change the driver's overall structure; it just wires one more method. Chapter 22's consolidated Stage 4 does not include it by default, but the reader who wants the method can add it in a few lines. +挑战很短且不改变驱动的整体结构;它只是连接了一个更多方法。第22章的合并第4阶段默认不包含它,但想要该方法的读者可以在几行中添加。 -## Hands-On Labs +## 动手实验 -Chapter 22 includes three hands-on labs that exercise the power-management path in progressively harder ways. Each lab has a script in `examples/part-04/ch22-power/labs/` that the reader can run as-is, plus extension ideas. +第22章包括三个动手实验,以逐步加难的方式练习电源管理路径。每个实验在`examples/part-04/ch22-power/labs/`中有脚本,读者可以按原样运行,还有扩展想法。 ### 实验1:单周期挂起-恢复 -The first lab is the simplest: one clean suspend-resume cycle with counter verification. +第一个实验最简单:带计数器验证的一次干净挂起-恢复周期。 -**Setup.** Load the Chapter 22 Stage 4 driver: +**设置。** 加载第22章第4阶段驱动: ```sh cd examples/part-04/ch22-power/stage4-final @@ -3483,7 +3482,7 @@ make clean && make sudo kldload ./myfirst.ko ``` -Verify attach: +验证挂载: ```sh sysctl dev.myfirst.0.%driver @@ -3492,19 +3491,19 @@ sysctl dev.myfirst.0.suspended # Should return: 0 ``` -**Run.** Execute the cycle script: +**运行。** 执行周期脚本: ```sh sudo sh ../labs/ch22-suspend-resume-cycle.sh ``` -Expected output: +预期输出: ```text PASS: one suspend-resume cycle completed cleanly ``` -**Verify.** Inspect the counters: +**验证。** 检查计数器: ```sh sysctl dev.myfirst.0.power_suspend_count @@ -3513,79 +3512,79 @@ sysctl dev.myfirst.0.power_resume_count # Should return: 1 ``` -Check `dmesg`: +检查`dmesg`: ```sh dmesg | tail -6 ``` -Should show four lines (suspend start, suspend complete, resume start, resume complete) plus the pre-and-post transfer log lines. +应显示四行(挂起开始、挂起完成、恢复开始、恢复完成)加上前后传输日志行。 -**Extension.** Modify the cycle script to run two suspend-resume cycles instead of one, and verify that the counters increment by exactly 2 each. +**扩展。** 修改周期脚本运行两次挂起-恢复周期而非一次,并验证计数器各精确递增2。 ### 实验2:百周期压力测试 -The second lab runs the cycle script one hundred times in a row and checks that nothing drifts. +第二个实验连续运行周期脚本一百次并检查没有任何漂移。 -**Run.** +**运行。** ```sh sudo sh ../labs/ch22-suspend-stress.sh ``` -Expected output after a few seconds: +几秒后的预期输出: ```text PASS: 100 cycles ``` -**Verify.** After the stress run, the counters should each be 100 (or 100 plus whatever was there before): +**验证。** 压力运行后,计数器应各为100(或100加上之前已有的): ```sh sysctl dev.myfirst.0.power_suspend_count # 100 (or however many cycles were added) ``` -**Observations to make.** +**观察内容。** -- How long does one cycle take? On the simulation, it should be a few milliseconds. On real hardware with D-state transitions, expect a few hundred microseconds to a few milliseconds. -- Does the system's load average change during the stress? The simulation is cheap; a hundred cycles on a modern machine should barely register. -- What happens if you run the DMA test during the stress? (`sudo sysctl dev.myfirst.0.dma_test_read=1` concurrently with the cycle loop.) A well-written driver should handle this gracefully; the DMA test succeeds if it happens during a `RUNNING` window and fails with EBUSY or similar if it happens during a transition. +- 一个周期需要多长时间?在模拟上,应为几毫秒。在带D状态转换的真实硬件上,预期几百微秒到几毫秒。 +- 压力期间系统的负载平均值是否变化?模拟代价低;现代机器上一百个周期几乎不应有影响。 +- 如果在压力期间运行DMA测试会怎样?(`sudo sysctl dev.myfirst.0.dma_test_read=1`与周期循环并发。)编写良好的驱动应优雅处理;DMA测试如果在`RUNNING`窗口期间发生则成功,如果在转换期间发生则以EBUSY或类似方式失败。 -**Extension.** Run the stress script with `dmesg -c` before to clear the log, then afterwards: +**扩展。** 运行压力脚本前用`dmesg -c`清除日志,之后: ```sh dmesg | wc -l ``` -Should be close to 400 (four log lines per cycle, times 100 cycles). A log-line-per-cycle count lets you verify that every cycle actually executed through the driver. +应接近400(每个周期四行日志,乘以100个周期)。每周期日志行计数让您验证每个周期实际通过驱动执行了。 ### 实验3:跨周期传输 -The third lab is the hardest: it starts a DMA transfer and immediately suspends in the middle of it, then resumes and verifies that the driver recovers. +第三个实验最难:它启动DMA传输并立即在中间挂起,然后恢复并验证驱动恢复了。 -**Setup.** The lab script is `ch22-transfer-across-cycle.sh`. It runs a DMA transfer in the background, sleeps a few milliseconds, calls `devctl suspend`, sleeps, calls `devctl resume`, and then starts another transfer. +**设置。** 实验脚本是`ch22-transfer-across-cycle.sh`。它在后台运行DMA传输,睡眠几毫秒,调用`devctl suspend`,睡眠,调用`devctl resume`,然后启动另一次传输。 -**Run.** +**运行。** ```sh sudo sh ../labs/ch22-transfer-across-cycle.sh ``` -**Observations to make.** +**观察内容。** -- Does the first transfer complete, error out, or time out? The expected behavior is that the quiesce aborts it cleanly; the transfer reports EIO or ETIMEDOUT. -- Does the counter `dma_errors` or `dma_timeouts` increment? One of them should. -- Does `dma_in_flight` go back to false after the suspend? -- Does the post-resume transfer succeed normally? If yes, the driver's state is consistent and the cycle worked. +- 第一次传输是完成、出错还是超时?预期行为是静默干净地中止它;传输报告EIO或ETIMEDOUT。 +- 计数器`dma_errors`或`dma_timeouts`是否递增?其中之一应该。 +- 挂起后`dma_in_flight`是否回到false? +- 恢复后传输是否正常成功?如果是,驱动状态一致,周期工作正常。 -**Extension.** Reduce the sleep between the transfer start and the suspend to hit the corner case where the transfer is mid-execution at the moment of the suspend. That is where race conditions live; a driver that passes this test under aggressive timing has a solid quiesce implementation. +**扩展。** 减少传输开始和挂起之间的睡眠以命中传输在挂起时刻正在执行中的角落情况。那是竞态条件存在的地方;在激进时序下通过此测试的驱动有坚实的静默实现。 ### 实验4:运行时PM(可选) -For readers building with `MYFIRST_ENABLE_RUNTIME_PM`, a fourth lab exercises the runtime-PM path. +对于用`MYFIRST_ENABLE_RUNTIME_PM`构建的读者,第四个实验练习运行时PM路径。 -**Setup.** Rebuild with runtime PM enabled: +**设置。** 启用运行时PM重新构建: ```sh cd examples/part-04/ch22-power/stage4-final @@ -3595,337 +3594,337 @@ make clean && make sudo kldload ./myfirst.ko ``` -**Run.** +**运行。** ```sh sudo sh ../labs/ch22-runtime-pm.sh ``` -The script: +脚本: -1. Sets the idle threshold to 3 seconds (instead of the default 5). -2. Records baseline counters. -3. Waits 5 seconds without any activity. -4. Verifies `runtime_state` is `RUNTIME_SUSPENDED`. -5. Triggers a DMA transfer. -6. Verifies `runtime_state` is back to `RUNNING`. -7. Prints PASS. +1. 将空闲阈值设为3秒(而非默认的5)。 +2. 记录基线计数器。 +3. 等待5秒无任何活动。 +4. 验证`runtime_state`为`RUNTIME_SUSPENDED`。 +5. 触发DMA传输。 +6. 验证`runtime_state`回到`RUNNING`。 +7. 打印PASS。 -**Observations to make.** +**观察内容。** -- During the idle wait, `dmesg` should show the "runtime suspend" log line approximately 3 seconds in. -- The `runtime_suspend_count` and `runtime_resume_count` should each be 1 at the end. -- The DMA transfer should succeed normally after the runtime resume. +- 在空闲等待期间,`dmesg`应在大约3秒后显示"runtime suspend"日志行。 +- `runtime_suspend_count`和`runtime_resume_count`在结束时各自应为1。 +- DMA传输在运行时恢复后应正常成功。 -**Extension.** Set the idle threshold to 1 second. Run the DMA test repeatedly in a tight loop. You should see no runtime-suspend transitions during the loop (because each test resets the idle timer), but as soon as the loop stops, the runtime suspend fires. +**扩展。** 将空闲阈值设为1秒。在紧凑循环中重复运行DMA测试。循环期间不应看到运行时挂起转换(因为每次测试重置空闲定时器),但循环一停止,运行时挂起就触发。 ### 实验说明 -All of the labs assume the driver is loaded and the system is idle enough that transitions happen on-demand. If another process is actively using the device (unlikely for `myfirst`, but common in real setups), the counters drift by unexpected amounts and the scripts' exact-increment checks fail. The scripts are designed for a quiet test environment, not a noisy one. +所有实验假设驱动已加载且系统足够空闲使转换按需发生。如果另一个进程正在积极使用设备(对`myfirst`不太可能,但在真实设置中常见),计数器会以意外数量漂移,脚本的精确增量检查失败。脚本是为安静测试环境设计的,不是嘈杂的。 -For realistic testing of the `re(4)` driver or other production drivers, the same script structure applies with the device name adjusted. The `devctl suspend`/`devctl resume` dance works for any PCI device the kernel manages. +对于`re(4)`驱动或其他生产驱动的真实测试,相同的脚本结构适用,只需调整设备名称。`devctl suspend`/`devctl resume`舞蹈适用于内核管理的任何PCI设备。 ## Challenge Exercises -The Chapter 22 challenge exercises push the reader beyond the baseline driver into territory that real-world drivers eventually have to handle. Each exercise is scoped to be achievable with the chapter's material and a few hours of work. +第22章的挑战练习将读者推到基线驱动之外,进入现实世界驱动最终必须处理的领域。每个练习的范围都可以通过本章材料和几小时的工作完成。 ### 挑战1:实现sysctl唤醒机制 -Extend the `myfirst` driver with a simulated wake source. The simulation already has a callout that can fire; add a new simulation feature that sets a "wake" bit on the device while it is in D3, and have the driver's `DEVICE_RESUME` path log the wake event. +用模拟的唤醒源扩展`myfirst`驱动。模拟已有可以触发的callout;添加一个新的模拟功能,在设备处于D3时在设备上设置"wake"位,并让驱动的`DEVICE_RESUME`路径记录唤醒事件。 **Hints.** -- Add a `MYFIRST_REG_WAKE_STATUS` register to the simulation backend. -- Add a `MYFIRST_REG_WAKE_ENABLE` register the driver writes during suspend. -- Have the simulation callout set the wake status bit after a random delay. -- On resume, the driver reads the register and logs whether a wake was observed. +- 向模拟后端添加`MYFIRST_REG_WAKE_STATUS`寄存器。 +- 添加驱动在挂起期间写入的`MYFIRST_REG_WAKE_ENABLE`寄存器。 +- 让模拟callout在随机延迟后设置唤醒状态位。 +- 恢复时,驱动读取寄存器并记录是否观察到唤醒。 -**Verification.** After `devctl suspend; sleep 1; devctl resume`, the log should show the wake status. A follow-up `sysctl dev.myfirst.0.wake_events` should increment. +**验证。** 执行`devctl suspend; sleep 1; devctl resume`后,日志应显示唤醒状态。后续的`sysctl dev.myfirst.0.wake_events`应增加。 -**Why this matters.** Wake source handling is one of the trickiest parts of real-hardware power management. Building it into the simulation lets the reader exercise the full contract without needing hardware. +**为什么重要。** 唤醒源处理是真实硬件电源管理中最棘手的部分之一。将其构建到模拟中让读者在不需要硬件的情况下练习完整的契约。 ### 挑战2:保存和恢复描述符环 -The Chapter 21 simulation does not yet use a descriptor ring (transfers are one-at-a-time). Extend the simulation with a small descriptor ring, program its base address through a register at attach, and have the suspend path save the ring's base address into softc state. Have the resume path write the saved base address back. +第21章的模拟尚不使用描述符环(传输是逐个进行的)。用小型描述符环扩展模拟,在挂载时通过寄存器编程其基地址,让挂起路径将环的基地址保存到softc状态中。让恢复路径将保存的基地址写回。 **Hints.** -- The ring's base address is a `bus_addr_t` held in the softc. -- The register is `MYFIRST_REG_RING_BASE_LOW`/`_HIGH`. -- Saving and restoring is trivial; the point is to verify that *not* saving and restoring would break things. +- 环的基地址是保存在softc中的`bus_addr_t`。 +- 寄存器为`MYFIRST_REG_RING_BASE_LOW`/`_HIGH`。 +- 保存和恢复是微不足道的;关键是要验证*不*保存和恢复会导致问题。 -**Verification.** After suspend-resume, the ring base register should hold the same value as before. Without the restore, it should hold zero. +**验证。** 挂起-恢复后,环基寄存器应保持与之前相同的值。如果不恢复,它应保持为零。 -**Why this matters.** Descriptor rings are what real high-throughput drivers use; a power-aware driver with a ring has to restore the base address on every resume. This exercise is a stepping stone to the kind of state management that production drivers like `re(4)` and `em(4)` perform. +**为什么重要。** 描述符环是真实高吞吐量驱动使用的;带环的电源感知驱动必须在每次恢复时恢复基地址。此练习是通往`re(4)`和`em(4)`等生产驱动执行的状态管理类型的跳板。 ### 挑战3:实现否决策略 -Extend the suspend path with a policy knob that lets the user specify whether the driver should veto a suspend when the device is busy. Specifically: +用策略旋钮扩展挂起路径,让用户指定驱动是否应在设备忙碌时否决挂起。具体来说: -- Add `dev.myfirst.0.suspend_veto_if_busy` as a read-write sysctl. -- If the sysctl is 1 and a DMA transfer is in flight, `myfirst_power_suspend` returns EBUSY without quiescing. -- If the sysctl is 0 (default), suspend always succeeds. +- 添加`dev.myfirst.0.suspend_veto_if_busy`作为读写sysctl。 +- 如果sysctl为1且有DMA传输进行中,`myfirst_power_suspend`返回EBUSY而不静默。 +- 如果sysctl为0(默认),挂起始终成功。 -**Hints.** Set `suspend_veto_if_busy` to 1. Start a long DMA transfer (add a `DELAY` to the simulation's engine to make it last a second or two). Call `devctl suspend myfirst0` during the transfer. Verify that the suspend returns an error and `dev.myfirst.0.suspended` stays 0. +**提示。** 将`suspend_veto_if_busy`设为1。启动一次长DMA传输(向模拟引擎添加`DELAY`使其持续一两秒)。在传输期间调用`devctl suspend myfirst0`。验证挂起返回错误且`dev.myfirst.0.suspended`保持为0。 -**Verification.** The kernel's unwind path runs; the driver is still in `RUNNING`; the transfer completes normally. +**验证。** 内核的展开路径运行;驱动仍处于`RUNNING`;传输正常完成。 -**Why this matters.** Vetoing is an effective tool and a dangerous one. Real-world policy decisions about whether to veto are nuanced (storage drivers often veto; NIC drivers usually do not). Implementing the mechanism makes the policy question tangible. +**为什么重要。** 否决是有效的工具,也是危险的工具。关于是否否决的现实世界策略决策是微妙的(存储驱动通常否决;NIC驱动通常不否决)。实现机制使策略问题变得具体。 ### 挑战4:添加恢复后自检 -After resume, do a minimum-viable test of the device: write a known pattern to the DMA buffer, trigger a write transfer, read it back with a read transfer, and verify. If the test fails, mark the device broken and fail subsequent operations. +恢复后,对设备进行最小可行测试:向DMA缓冲区写入已知模式,触发写传输,用读传输读回并验证。如果测试失败,标记设备为损坏并使后续操作失败。 **Hints.** -- Add the self-test as a helper that runs from `myfirst_power_resume` after `myfirst_restore`. -- Use a well-known pattern like `0xDEADBEEF`. -- Use the existing DMA path; the self-test is just one write and one read. +- 将自检添加为从`myfirst_power_resume`中`myfirst_restore`之后运行的助手。 +- 使用熟知的模式如`0xDEADBEEF`。 +- 使用现有DMA路径;自检只是一次写入和一次读取。 -**Verification.** Under normal operation, the self-test always passes. To verify it catches failures, add an artificial "fail once" mechanism to the simulation and trigger it; the driver should log the failure and mark itself broken. +**验证。** 正常操作下,自检始终通过。要验证它能捕获故障,向模拟添加人为的"fail once"机制并触发它;驱动应记录故障并将自身标记为损坏。 -**Why this matters.** Self-tests are a lightweight form of reliability engineering. A driver that catches its own failures at well-defined points is easier to debug than one that silently corrupts data until a user notices. +**为什么重要。** 自检是可靠性工程的轻量级形式。在定义明确的点捕获自身故障的驱动比静默损坏数据直到用户注意到的驱动更容易调试。 ### 挑战5:实现手动pci_save_state/pci_restore_state -Most drivers let the PCI layer handle config-space save-and-restore automatically. Extend the Chapter 22 driver to optionally do it manually, gated by a sysctl `dev.myfirst.0.manual_pci_save`. +大多数驱动让PCI层自动处理配置空间的保存和恢复。扩展第22章驱动以可选地手动执行,通过sysctl `dev.myfirst.0.manual_pci_save`控制。 **Hints.** -- Read `hw.pci.do_power_suspend` and `hw.pci.do_power_resume` and set them to 0 when manual mode is enabled. -- Call `pci_save_state` explicitly in the suspend path, `pci_restore_state` in the resume path. -- Verify that the device still works after suspend-resume. +- 读取`hw.pci.do_power_suspend`和`hw.pci.do_power_resume`并在手动模式启用时将它们设为0。 +- 在挂起路径中显式调用`pci_save_state`,在恢复路径中调用`pci_restore_state`。 +- 验证设备在挂起-恢复后仍然正常工作。 -**Verification.** The device should function identically whether or not manual mode is enabled. Set the sysctl before a stress test and verify no drift. +**验证。** 无论是否启用手动模式,设备功能应相同。在压力测试前设置sysctl并验证无漂移。 -**Why this matters.** Some real drivers need manual save/restore because the PCI layer's automatic handling interferes with device-specific quirks. Knowing when and how to take over the save/restore is a useful intermediate skill. +**为什么重要。** 某些真实驱动需要手动保存/恢复,因为PCI层的自动处理会干扰设备特定的怪异行为。了解何时以及如何接管保存/恢复是有用的中级技能。 ## Troubleshooting Reference -This section collects the common problems a reader may encounter while working through Chapter 22, with a short diagnostic and fix for each. The list is meant to be skimmable; if a problem matches, skip to the corresponding entry. +本节收集读者在学习第22章时可能遇到的常见问题,每个都有简短的诊断和修复。列表设计为可快速浏览;如果问题匹配,跳到相应条目。 ### "devctl: DEV_SUSPEND failed: Operation not supported" -The driver does not implement `DEVICE_SUSPEND`. Either the method table is missing the `DEVMETHOD(device_suspend, ...)` line, or the driver has not been rebuilt and reloaded. +驱动未实现`DEVICE_SUSPEND`。要么方法表缺少`DEVMETHOD(device_suspend, ...)`行,要么驱动尚未重新构建和重新加载。 -**Fix.** Check the method table. Rebuild with `make clean && make`. Unload and reload. +**修复。** 检查方法表。用`make clean && make`重新构建。卸载并重新加载。 ### "devctl: DEV_SUSPEND failed: Device busy" -The driver returned `EBUSY` from `DEVICE_SUSPEND`, probably because of the veto logic from Challenge 3, or because the device is genuinely busy (DMA in flight, task running) and the driver chose to veto. +驱动从`DEVICE_SUSPEND`返回`EBUSY`,可能因为挑战3的否决逻辑,或因为设备确实忙碌(DMA进行中、任务运行中)且驱动选择否决。 -**Fix.** Check whether the `suspend_veto_if_busy` knob is set. Check `dma_in_flight`. Wait for activity to complete before suspending. +**修复。** 检查`suspend_veto_if_busy`旋钮是否已设置。检查`dma_in_flight`。等待活动完成后再挂起。 ### "devctl: DEV_RESUME failed" -`DEVICE_RESUME` returned non-zero. The log should have more detail. +`DEVICE_RESUME`返回非零。日志应有更多细节。 -**Fix.** Check `dmesg | tail`. The resume log line should tell you what failed. Usually it is a hardware-specific init step that did not succeed. +**修复。** 检查`dmesg | tail`。恢复日志行应告诉您什么失败了。通常是硬件特定的初始化步骤未成功。 ### Device is suspended but `dev.myfirst.0.suspended` reads 0 -The driver's flag is out of sync with the kernel's state. Probably a bug in the quiesce path: the flag was never set, or was cleared prematurely. +驱动的标志与内核状态不同步。可能是静默路径中的错误:标志从未被设置,或被过早清除。 -**Fix.** Add a `KASSERT(sc->suspended == true)` at the top of the resume path; run under `INVARIANTS` to catch the bug. +**修复。** 在恢复路径顶部添加`KASSERT(sc->suspended == true)`;在`INVARIANTS`下运行以捕获错误。 ### `power_suspend_count != power_resume_count` -A cycle got one side but not the other. Check `dmesg` for errors; the log should show where the sequence broke. +一个周期获得了一侧但没有另一侧。检查`dmesg`中的错误;日志应显示序列在哪里中断。 -**Fix.** Fix the code path that is missing. Usually an early return without the counter update. +**修复。** 修复缺失的代码路径。通常是缺少计数器更新的提前返回。 ### DMA transfers fail after resume -The restore path did not reinitialise the DMA engine. Check the INTR_MASK register, the DMA control registers, the `saved_intr_mask` value. Enable verbose logging to see the resume path's restoration sequence. +恢复路径没有重新初始化DMA引擎。检查INTR_MASK寄存器、DMA控制寄存器、`saved_intr_mask`值。启用详细日志以查看恢复路径的恢复序列。 -**Fix.** Add a missing register write to `myfirst_restore`. +**修复。** 向`myfirst_restore`添加缺失的寄存器写入。 ### WITNESS complains about a lock held during suspend -The suspend path acquired a lock and then called a function that sleeps or tries to acquire another lock. Read the WITNESS message for the offending lock names. +挂起路径获取了锁然后调用了睡眠或尝试获取另一个锁的函数。阅读WITNESS消息中的违规锁名称。 -**Fix.** Drop the lock before the sleeping call, or restructure the code so the lock is acquired only when needed. +**修复。** 在睡眠调用之前释放锁,或重构代码使锁仅在需要时获取。 ### System does not wake from S3 -A driver below `myfirst` is blocking resume. Unlikely to be `myfirst` itself unless the logs show an error from the driver specifically. +`myfirst`下面的某个驱动阻止了恢复。不太可能是`myfirst`本身,除非日志特别显示来自驱动的错误。 -**Fix.** Boot into single-user mode, or load fewer drivers, and bisect. Check `dmesg` in the live system for the offending driver. +**修复。** 引导进入单用户模式,或加载更少驱动,并二分查找。在活动系统中检查`dmesg`中的违规驱动。 ### Runtime PM never fires -The idle watcher callout is not running, or the `last_activity` timestamp is being updated too often. +空闲监视器callout未运行,或`last_activity`时间戳更新太频繁。 -**Fix.** Verify `callout_reset` is being called from the attach path. Verify `myfirst_mark_active` is not being called from unexpected code paths. Add logging to the callout callback to confirm it fires. +**修复。** 验证`callout_reset`正在从挂载路径调用。验证`myfirst_mark_active`未从意外代码路径调用。向callout回调添加日志以确认它触发。 ### Kernel panic during suspend -A KASSERT failed (on an `INVARIANTS` kernel) or a lock is held incorrectly. The panic message identifies the offending file and line. +KASSERT失败(在`INVARIANTS`内核上)或锁被不正确持有。恐慌消息标识了违规的文件和行号。 -**Fix.** Read the panic message. Match the file and line to the code. The fix is usually straightforward once the location is identified. +**修复。** 阅读恐慌消息。将文件和行号匹配到代码。一旦识别了位置,修复通常很简单。 ## Wrapping Up -Chapter 22 closes Part 4 by giving the `myfirst` driver the discipline of power management. At the start, `myfirst` at version `1.4-dma` was a capable driver: it attached to a PCI device, handled multi-vector interrupts, moved data through DMA, and cleaned up its resources on detach. What it lacked was the ability to participate in the system's power transitions. It would crash, leak, or silently fail if the user closed the laptop lid or asked the kernel to suspend the device. At the end, `myfirst` at version `1.5-power` handles every power transition the kernel can throw at it: system suspend to S3 or S4, per-device suspend through `devctl`, system shutdown, and optional runtime power management. +第22章通过赋予`myfirst`驱动电源管理纪律来结束第4部分。开始时,`myfirst`在`1.4-dma`版本已是一个有能力的驱动:它挂载到PCI设备、处理多向量中断、通过DMA移动数据、并在分离时清理资源。它缺少的是参与系统电源转换的能力。如果用户合上笔记本盖子或要求内核挂起设备,它会崩溃、泄漏或静默失败。最终,`myfirst`在`1.5-power`版本处理内核可能抛出的每个电源转换:系统挂起到S3或S4、通过`devctl`的每设备挂起、系统关机和可选的运行时电源管理。 -The eight sections walked the full progression. Section 1 established the big picture: why a driver cares about power, what ACPI S-states and PCI D-states are, what PCIe L-states and ASPM add, and what wake sources look like. Section 2 introduced FreeBSD's concrete APIs: the `DEVICE_SUSPEND`, `DEVICE_RESUME`, `DEVICE_SHUTDOWN`, and `DEVICE_QUIESCE` methods, the `bus_generic_suspend` and `bus_generic_resume` helpers, and the PCI layer's automatic config-space save and restore. The Stage 1 skeleton made the methods log and count transitions without doing any real work. Section 3 turned the suspend skeleton into a real quiesce: mask interrupts, drain DMA, drain workers, in that order, with helper functions shared between suspend and detach. Section 4 wrote the matching resume path: re-enable bus-master, restore device-specific state, clear the suspended flag, unmask interrupts. Section 5 added optional runtime power management with an idle-watcher callout and explicit `pci_set_powerstate` transitions. Section 6 surveyed the user-space interface: `acpiconf`, `zzz`, `devctl suspend`, `devctl resume`, `devinfo -v`, and the matching sysctls. Section 7 catalogued the characteristic failure modes and their debugging patterns. Section 8 refactored the code into `myfirst_power.c`, bumped the version to `1.5-power`, added `POWER.md`, and wired the final regression test. +八个部分走完了完整的进程。第1节建立了全局视图:为什么驱动关心电源、ACPI S状态和PCI D状态是什么、PCIe L状态和ASPM添加了什么、唤醒源长什么样。第2节介绍了FreeBSD的具体API:`DEVICE_SUSPEND`、`DEVICE_RESUME`、`DEVICE_SHUTDOWN`和`DEVICE_QUIESCE`方法,`bus_generic_suspend`和`bus_generic_resume`助手,以及PCI层的自动配置空间保存和恢复。第1阶段骨架让方法记录日志和计数转换而不做任何实际工作。第3节将挂起骨架变成真正的静默:屏蔽中断、排空DMA、排空工作线程,按此顺序,共享挂起和分离之间的助手函数。第4节编写了匹配的恢复路径:重新启用总线主控、恢复设备特定状态、清除挂起标志、取消屏蔽中断。第5节添加了带空闲监视器callout和显式`pci_set_powerstate`转换的可选运行时电源管理。第6节调查了用户空间接口:`acpiconf`、`zzz`、`devctl suspend`、`devctl resume`、`devinfo -v`和匹配的sysctl。第7节编目了特征性故障模式及其调试模式。第8节将代码重构到`myfirst_power.c`,将版本升级到`1.5-power`,添加了`POWER.md`,并连接了最终回归测试。 -What Chapter 22 did not do is scatter-gather power management for multi-queue drivers (that is a Part 6 topic, Chapter 28), hotplug and surprise-removal integration (a Part 7 topic), embedded-platform power domains (Part 7 again), or the internals of ACPI's AML interpreter (never covered in this book). Each of those is a natural extension built on Chapter 22's primitives, and each belongs in a later chapter where the scope matches. The foundation is in place; the specialisations add vocabulary without needing a new foundation. +第22章没有做的是多队列驱动的分散-收集电源管理(那是第6部分第28章的话题)、热插拔和意外移除集成(第7部分话题)、嵌入式平台电源域(也是第7部分)、或ACPI的AML解释器内部机制(本书不涉及)。每一个都是基于第22章原语的自然扩展,每一个都属于范围匹配的后续章节。基础已就位;专业化添加词汇而无需新基础。 -The file layout has grown: 16 source files (including `cbuf`), 8 documentation files (`HARDWARE.md`, `LOCKING.md`, `SIMULATION.md`, `PCI.md`, `INTERRUPTS.md`, `MSIX.md`, `DMA.md`, `POWER.md`), and an extended regression suite that covers every subsystem. The driver is structurally parallel to production FreeBSD drivers; a reader who has worked through Chapters 16 through 22 can open `if_re.c`, `if_xl.c`, or `virtio_blk.c` and recognise every architectural part: register accessors, simulation backend, PCI attach, interrupt filter and task, per-vector machinery, DMA setup and teardown, sync discipline, power suspend, power resume, clean detach. +文件布局已经增长:16个源文件(包括`cbuf`)、8个文档文件(`HARDWARE.md`、`LOCKING.md`、`SIMULATION.md`、`PCI.md`、`INTERRUPTS.md`、`MSIX.md`、`DMA.md`、`POWER.md`),以及覆盖每个子系统的扩展回归套件。驱动在结构上与生产FreeBSD驱动平行;学完第16至22章的读者可以打开`if_re.c`、`if_xl.c`或`virtio_blk.c`并识别每个架构部分:寄存器访问器、模拟后端、PCI挂载、中断过滤器和任务、每向量机制、DMA设置和拆卸、同步纪律、电源挂起、电源恢复、干净分离。 ### A Reflection Before Chapter 23 -Chapter 22 is the last chapter of Part 4, and Part 4 is the part that taught the reader how a driver talks to hardware. Chapters 16 through 21 introduced the primitives: MMIO, simulation, PCI, interrupts, multi-vector interrupts, DMA. Chapter 22 introduced the discipline: how those primitives survive power transitions. Together, the seven chapters take the reader from "no idea what a driver is" to "a working multi-subsystem driver that handles every hardware event the kernel can throw at it". +第22章是第4部分的最后一章,第4部分教授读者驱动如何与硬件对话。第16至21章介绍了原语:MMIO、模拟、PCI、中断、多向量中断、DMA。第22章介绍了纪律:这些原语如何在电源转换中存活。这七章一起将读者从"不知道驱动是什么"带到"一个处理内核可能抛出的每个硬件事件的工作中的多子系统驱动"。 -Chapter 22's teaching generalises. A reader who has internalised the suspend-quiesce-save-restore pattern, the interaction between driver and PCI layer, the runtime-PM state machine, and the debugging patterns will find similar shapes in every power-aware FreeBSD driver. The specific hardware differs; the structure does not. A driver for a NIC, a storage controller, a GPU, or a USB host controller applies the same vocabulary to its own hardware. +第22章的教学是可推广的。内化了挂起-静默-保存-恢复模式、驱动与PCI层的交互、运行时PM状态机和调试模式的读者会在每个电源感知的FreeBSD驱动中找到相似的形状。具体硬件不同;结构不变。NIC、存储控制器、GPU或USB主机控制器的驱动将相同的词汇应用于自己的硬件。 -Part 5, which begins with Chapter 23, shifts focus. Part 4 was about the driver-to-hardware direction: how the driver talks to the device. Part 5 is about the driver-to-kernel direction: how the driver is debugged, traced, tooled, and stressed by the humans who maintain it. Chapter 23 starts that shift with debugging and tracing techniques that apply across every driver subsystem. +从第23章开始的第5部分转移了重点。第4部分是关于驱动到硬件的方向:驱动如何与设备对话。第5部分是关于驱动到内核的方向:驱动如何被维护它的人类调试、追踪、工具化和压力测试。第23章用适用于每个驱动子系统的调试和追踪技术开始这一转变。 ### What to Do If You Are Stuck Three suggestions. -First, focus on the Stage 2 suspend and Stage 3 resume paths. If `devctl suspend myfirst0` followed by `devctl resume myfirst0` succeeds and a subsequent DMA transfer works, the core of the chapter is working. Every other piece of the chapter is optional in the sense that it decorates the pipeline, but if the pipeline fails, the chapter is not working and Section 3 or Section 4 is the right place to diagnose. +首先,专注于第2阶段挂起和第3阶段恢复路径。如果`devctl suspend myfirst0`后跟`devctl resume myfirst0`成功且后续DMA传输工作,本章的核心就在工作。本章的其他部分在装饰管道的意义上是可选的,但如果管道失败,本章就不在工作,第3节或第4节是诊断的正确位置。 -Second, open `/usr/src/sys/dev/re/if_re.c` and re-read `re_suspend`, `re_resume`, and `re_setwol`. Each function is about thirty lines. Every line maps to a Chapter 22 concept. Reading them once after completing the chapter should feel like familiar territory; the real driver's patterns will look like elaborations of the chapter's simpler ones. +其次,打开`/usr/src/sys/dev/re/if_re.c`并重读`re_suspend`、`re_resume`和`re_setwol`。每个函数大约三十行。每一行映射到第22章的一个概念。完成本章后阅读它们应该感觉像熟悉的领域;真实驱动的模式看起来像是本章更简单模式的详细阐述。 -Third, skip the challenges on the first pass. The labs are calibrated for Chapter 22's pace; the challenges assume the chapter's material is solid. Come back to them after Chapter 23 if they feel out of reach now. +第三,第一遍跳过挑战。实验为第22章的节奏校准;挑战假设本章的材料已扎实。如果现在觉得难以触及,第23章后再回来。 -Chapter 22's goal was to give the driver power-management discipline. If it has, Chapter 23's debugging and tracing machinery becomes a generalisation of what you already do instinctively rather than a new topic. +第22章的目标是给驱动电源管理纪律。如果做到了,第23章的调试和追踪机制就成为您已本能所做之事的推广,而非新话题。 ## 第4部分检查点 -Part 4 has been the longest and densest stretch of the book so far. Seven chapters covered hardware resources, register I/O, PCI attach, interrupts, MSI and MSI-X, DMA, and power management. Before Part 5 changes the mode from "writing drivers" to "debugging and tracing them," confirm that the hardware-facing story is internalized. +第4部分是本书迄今为止最长最密集的段落。七章涵盖了硬件资源、寄存器I/O、PCI挂载、中断、MSI和MSI-X、DMA和电源管理。在第5部分将模式从"编写驱动"变为"调试和追踪它们"之前,确认硬件面向的故事已内化。 -By the end of Part 4 you should be able to do each of the following without searching: +到第4部分结束时,您应该能够在不查找的情况下完成以下每一项: -- Claim a hardware resource with `bus_alloc_resource_any` or `bus_alloc_resource_anywhere`, access it through the `bus_space(9)` read/write and barrier primitives, and release it cleanly in detach. -- Read and write device registers through the `bus_space(9)` abstraction rather than raw pointer dereferences, with correct barrier discipline around sequences that must not be reordered. -- Match a PCI device through vendor, device, subvendor, and subdevice IDs; claim its BARs; and survive a forced detach without leaking resources. -- Register a top-half filter together with a bottom-half task or ithread via `bus_setup_intr`, in the order the kernel requires, and tear them down in reverse order under detach. -- Set up MSI or MSI-X vectors with a graceful fallback ladder from MSI-X to MSI to legacy INTx, and bind vectors to specific CPUs when the workload calls for it. -- Allocate, map, sync, and release DMA buffers using `bus_dma(9)` including the bounce-buffer case. -- Implement `device_suspend` and `device_resume` with register save and restore, I/O quiescing, and a post-resume self-test. +- 用`bus_alloc_resource_any`或`bus_alloc_resource_anywhere`声明硬件资源,通过`bus_space(9)`读/写和屏障原语访问它,并在分离时干净地释放。 +- 通过`bus_space(9)`抽象而非原始指针解引用读写设备寄存器,在不得重排序的序列周围有正确的屏障纪律。 +- 通过供应商、设备、子供应商和子设备ID匹配PCI设备;声明其BAR;并在强制分离后存活而不泄漏资源。 +- 通过`bus_setup_intr`注册上半部过滤器连同下半部任务或ithread,按内核要求的顺序,并在分离时以相反顺序拆卸。 +- 设置MSI或MSI-X向量,具有从MSI-X到MSI到传统INTx的优雅回退阶梯,并在工作负载需要时将向量绑定到特定CPU。 +- 使用`bus_dma(9)`分配、映射、同步和释放DMA缓冲区,包括弹跳缓冲区情况。 +- 实现带寄存器保存和恢复、I/O静默和恢复后自检的`device_suspend`和`device_resume`。 -If any of those still requires a lookup, the labs to revisit are: +如果其中任何一项仍需查找,值得重做的实验是: -- Registers and barriers: Lab 1 (Observe the Register Dance) and Lab 8 (The Watchdog-Meets-Register Scenario) in Chapter 16. -- Simulated hardware under load: Lab 6 (Inject Stuck-Busy and Watch the Driver Wait) and Lab 10 (Inject a Memory-Corruption Attack) in Chapter 17. -- PCI attach and detach: Lab 4 (Claim the BAR and Read a Register) and Lab 5 (Exercise the cdev and Verify Detach Cleanup) in Chapter 18. -- Interrupt handling: Lab 3 (Stage 2, Real Filter and Deferred Task) in Chapter 19. -- MSI and MSI-X: Lab 4 (Stage 3, MSI-X With CPU Binding) in Chapter 20. -- DMA: Lab 4 (Stage 3, Interrupt-Driven Completion) and Lab 5 (Stage 4, Refactor and Regression) in Chapter 21. -- Power management: Lab 2 (One-Hundred-Cycle Stress) and Lab 3 (Transfer Across a Cycle) in Chapter 22. +- 寄存器和屏障:第16章实验1(观察寄存器之舞)和实验8(看门狗遇上寄存器场景)。 +- 负载下的模拟硬件:第17章实验6(注入卡住忙碌并观察驱动等待)和实验10(注入内存损坏攻击)。 +- PCI挂载和分离:第18章实验4(声明BAR并读取寄存器)和实验5(练习cdev并验证分离清理)。 +- 中断处理:第19章实验3(第2阶段,真实过滤器和延迟任务)。 +- MSI和MSI-X:第20章实验4(第3阶段,带CPU绑定的MSI-X)。 +- DMA:第21章实验4(第3阶段,中断驱动完成)和实验5(第4阶段,重构和回归)。 +- 电源管理:第22章实验2(百周期压力)和实验3(跨周期传输)。 -Part 5 will expect the following as a baseline: +第5部分期望以下作为基线: -- A hardware-capable driver with observability already baked in: counters, sysctls, and `devctl_notify` calls at the important transitions. Chapter 23's debugging machinery works best when the driver already reports on itself. -- A regression script that can cycle the driver reliably, since Part 5 turns reproducibility into a first-class skill. -- A kernel built with `INVARIANTS` and `WITNESS`. Part 5 leans on both even more heavily than Part 4, especially in Chapter 23. -- The understanding that a bug in driver code is a bug in kernel code, which means user-space debuggers alone will not be enough and Part 5 will teach the kernel-space tools. +- 一个已内置可观测性的硬件能力驱动:计数器、sysctl和在重要转换处的`devctl_notify`调用。第23章的调试机制在驱动已自我报告时效果最佳。 +- 能够可靠循环驱动的回归脚本,因为第5部分将可重现性变成一等技能。 +- 用`INVARIANTS`和`WITNESS`构建的内核。第5部分比第4部分更依赖两者,特别是在第23章。 +- 理解驱动代码中的错误就是内核代码中的错误,这意味着仅用户空间调试器不够用,第5部分将教授内核空间工具。 -If those hold, Part 5 is ready for you. If one still looks shaky, a short lap through the relevant lab will pay back its time several times over. +如果这些成立,第5部分为您准备好了。如果某一项仍不稳定,短时间重做相关实验将获得数倍回报。 ## 通往第23章的桥梁 -Chapter 23 is titled *Debugging and Tracing*. Its scope is the professional practice of finding bugs in drivers: tools like `ktrace`, `ddb`, `kgdb`, `dtrace`, and `procstat`; techniques for analysing panics, deadlocks, and data corruption; strategies for turning vague user reports into reproducible test cases; and the mindset of a driver developer who has to debug code running in kernel space with limited visibility. +第23章题为*调试与追踪*。其范围是查找驱动中错误的专业实践:`ktrace`、`ddb`、`kgdb`、`dtrace`和`procstat`等工具;分析恐慌、死锁和数据损坏的技术;将模糊用户报告转化为可重现测试用例的策略;以及在有限可见性下必须调试内核空间运行代码的驱动开发者心态。 -Chapter 22 prepared the ground in four specific ways. +第22章以四种具体方式准备了基础。 -First, **you have observability counters everywhere**. The Chapter 22 driver exposes suspend, resume, shutdown, and runtime-PM counters through sysctls. Chapter 23's debugging techniques rely on observability; a driver that already tracks its own state is much easier to debug than one that does not. +首先,**您到处都有可观测性计数器**。第22章驱动通过sysctl暴露挂起、恢复、关机和运行时PM计数器。第23章的调试技术依赖可观测性;已跟踪自身状态的驱动比不跟踪的更容易调试。 -Second, **you have a regression test**. The cycle and stress scripts from Section 6 are a first taste of what Chapter 23 expands: the ability to reproduce a bug on demand. A bug you cannot reproduce is a bug you cannot fix; Chapter 22's scripts are a foundation for the heavier testing Chapter 23 adds. +其次,**您有回归测试**。第6节的循环和压力脚本是第23章扩展内容的初体验:按需重现错误的能力。无法重现的错误是无法修复的错误;第22章的脚本是第23章添加的更重测试的基础。 -Third, **you have a working INVARIANTS / WITNESS debug kernel**. Chapter 22 leaned on both throughout; Chapter 23 builds on the same kernel for `ddb` sessions, post-mortem analysis, and kernel-crash reproduction. +第三,**您有可工作的INVARIANTS/WITNESS调试内核**。第22章全程依赖两者;第23章在同一内核上构建`ddb`会话、事后分析和内核崩溃重现。 -Fourth, **you understand that bugs in driver code are bugs in kernel code**. Chapter 22 ran into hangs, frozen devices, lost interrupts, and WITNESS complaints. Each of those is a kernel bug in the user-visible sense; each requires a kernel-space debugging approach. Chapter 23 teaches that approach systematically. +第四,**您理解驱动代码中的错误就是内核代码中的错误**。第22章遇到了挂起、冻结设备、丢失中断和WITNESS警告。每一个在用户可见意义上都是内核错误;每一个都需要内核空间调试方法。第23章系统地教授该方法。 -Specific topics Chapter 23 will cover: +第23章将涵盖的具体主题: -- Using `ktrace` and `kdump` to observe a process's system call trace in real time. -- Using `ddb` to break into the kernel debugger for post-mortem analysis or live inspection. -- Using `kgdb` with a core dump to recover the state of a crashed kernel. -- Using `dtrace` for in-kernel tracing without modifying the source. -- Using `procstat`, `top`, `pmcstat`, and related tools for performance observation. -- Strategies for minimising a bug: shrinking a reproducer, bisecting a regression, hypothesising and testing. -- Patterns for instrumenting a driver in production without disturbing behaviour. +- 使用`ktrace`和`kdump`实时观察进程的系统调用追踪。 +- 使用`ddb`进入内核调试器进行事后分析或实时检查。 +- 使用`kgdb`配合核心转储恢复崩溃内核的状态。 +- 使用`dtrace`在不修改源代码的情况下进行内核内追踪。 +- 使用`procstat`、`top`、`pmcstat`及相关工具进行性能观察。 +- 最小化错误的策略:缩小重现器、二分回归、假设和测试。 +- 在生产环境中检测驱动而不干扰行为的模式。 -You do not need to read ahead. Chapter 22 is sufficient preparation. Bring your `myfirst` driver at `1.5-power`, your `LOCKING.md`, your `INTERRUPTS.md`, your `MSIX.md`, your `DMA.md`, your `POWER.md`, your `WITNESS`-enabled kernel, and your regression script. Chapter 23 starts where Chapter 22 ended. +您不需要提前阅读。第22章已是充分准备。带上您的`myfirst`驱动`1.5-power`版本、`LOCKING.md`、`INTERRUPTS.md`、`MSIX.md`、`DMA.md`、`POWER.md`、启用`WITNESS`的内核和回归脚本。第23章从第22章结束的地方开始。 -Part 4 is complete. Chapter 23 opens Part 5 by adding the observability and debugging discipline that separates a driver you wrote last week from a driver you can maintain for years. +第4部分已完成。第23章通过添加可观测性和调试纪律来开启第5部分,这将上周写的驱动与可以维护多年的驱动区分开来。 -The vocabulary is yours; the structure is yours; the discipline is yours. Chapter 23 adds the next missing piece: the ability to find and fix bugs that only show up in production. +词汇是您的;结构是您的;纪律是您的。第23章添加下一个缺失的部分:查找和修复仅在生产环境中出现的错误的能力。 ## Reference: 第22章快速参考卡 -A compact summary of the vocabulary, APIs, flags, and procedures Chapter 22 introduced. +第22章引入的词汇、API、标志和过程的紧凑摘要。 ### Vocabulary -- **Suspend:** a transition from D0 (full operation) to a lower-power state from which the device can be brought back. -- **Resume:** the transition back from the lower-power state to D0. -- **Shutdown:** the transition to a final state from which the device will not return. -- **Quiesce:** to bring a device to a state with no activity and no pending work. -- **System sleep state (S0, S1, S3, S4, S5):** ACPI-defined levels of system power. -- **Device power state (D0, D1, D2, D3hot, D3cold):** PCI-defined levels of device power. -- **Link state (L0, L0s, L1, L1.1, L1.2, L2):** PCIe-defined levels of link power. -- **ASPM (Active-State Power Management):** automatic transitions between L0 and L0s/L1. -- **PME# (Power Management Event):** a signal a device asserts when it wants to wake the system. -- **Wake source:** a mechanism by which a suspended device can request wakeup. -- **Runtime PM:** device-level power saving while the system stays in S0. +- **挂起(Suspend):** 从D0(完全操作)到设备可以恢复的较低功耗状态的转换。 +- **恢复(Resume):** 从较低功耗状态回到D0的转换。 +- **关机(Shutdown):** 到设备不会返回的最终状态的转换。 +- **静默(Quiesce):** 将设备带到无活动且无待处理工作的状态。 +- **系统睡眠状态(S0、S1、S3、S4、S5):** ACPI定义的系统功耗级别。 +- **设备电源状态(D0、D1、D2、D3hot、D3cold):** PCI定义的设备功耗级别。 +- **链路状态(L0、L0s、L1、L1.1、L1.2、L2):** PCIe定义的链路功耗级别。 +- **ASPM(活动状态电源管理):** L0和L0s/L1之间的自动转换。 +- **PME#(电源管理事件):** 设备在想要唤醒系统时断言的信号。 +- **唤醒源:** 挂起设备可以通过其请求唤醒的机制。 +- **运行时PM:** 系统保持在S0时的设备级节能。 ### Essential Kobj Methods -- `DEVMETHOD(device_suspend, foo_suspend)`: called to quiesce the device before a power transition. -- `DEVMETHOD(device_resume, foo_resume)`: called to restore the device after the power transition. -- `DEVMETHOD(device_shutdown, foo_shutdown)`: called to leave the device in a safe state for reboot. -- `DEVMETHOD(device_quiesce, foo_quiesce)`: called to stop activity without tearing down resources. +- `DEVMETHOD(device_suspend, foo_suspend)`:在电源转换前调用来静默设备。 +- `DEVMETHOD(device_resume, foo_resume)`:在电源转换后调用来恢复设备。 +- `DEVMETHOD(device_shutdown, foo_shutdown)`:调用来使设备处于重启的安全状态。 +- `DEVMETHOD(device_quiesce, foo_quiesce)`:调用来停止活动而不拆除资源。 ### Essential PCI APIs -- `pci_has_pm(dev)`: true if the device has a power-management capability. -- `pci_set_powerstate(dev, state)`: transition to `PCI_POWERSTATE_D0`, `D1`, `D2`, or `D3`. -- `pci_get_powerstate(dev)`: current power state. -- `pci_save_state(dev)`: cache the configuration space. -- `pci_restore_state(dev)`: write the cached configuration space back. -- `pci_enable_pme(dev)`: enable PME# generation. -- `pci_clear_pme(dev)`: clear pending PME status. -- `pci_enable_busmaster(dev)`: re-enable bus-master after a reset. +- `pci_has_pm(dev)`:如果设备有电源管理能力则返回true。 +- `pci_set_powerstate(dev, state)`:转换到`PCI_POWERSTATE_D0`、`D1`、`D2`或`D3`。 +- `pci_get_powerstate(dev)`:当前电源状态。 +- `pci_save_state(dev)`:缓存配置空间。 +- `pci_restore_state(dev)`:将缓存的配置空间写回。 +- `pci_enable_pme(dev)`:启用PME#生成。 +- `pci_clear_pme(dev)`:清除待处理的PME状态。 +- `pci_enable_busmaster(dev)`:重置后重新启用总线主控。 ### Essential Bus Helpers -- `bus_generic_suspend(dev)`: suspend all children in reverse order. -- `bus_generic_resume(dev)`: resume all children in forward order. -- `device_quiesce(dev)`: call the driver's `DEVICE_QUIESCE`. +- `bus_generic_suspend(dev)`:以相反顺序挂起所有子设备。 +- `bus_generic_resume(dev)`:以正向顺序恢复所有子设备。 +- `device_quiesce(dev)`:调用驱动的`DEVICE_QUIESCE`。 ### Essential Sysctls -- `hw.acpi.supported_sleep_state`: list of S-states the platform supports. -- `hw.acpi.suspend_state`: default S-state for `zzz`. -- `hw.pci.do_power_suspend`: automatic D0->D3 transition on suspend. -- `hw.pci.do_power_resume`: automatic D3->D0 transition on resume. -- `dev.N.M.suspended`: driver's own suspended flag. -- `dev.N.M.power_suspend_count`, `power_resume_count`, `power_shutdown_count`. -- `dev.N.M.runtime_state`, `runtime_suspend_count`, `runtime_resume_count`. +- `hw.acpi.supported_sleep_state`:平台支持的S状态列表。 +- `hw.acpi.suspend_state`:`zzz`的默认S状态。 +- `hw.pci.do_power_suspend`:挂起时自动D0->D3转换。 +- `hw.pci.do_power_resume`:恢复时自动D3->D0转换。 +- `dev.N.M.suspended`:驱动自身的挂起标志。 +- `dev.N.M.power_suspend_count`、`power_resume_count`、`power_shutdown_count`。 +- `dev.N.M.runtime_state`、`runtime_suspend_count`、`runtime_resume_count`。 ### Useful Commands -- `acpiconf -s 3`: enter S3. -- `zzz`: wrapper around `acpiconf`. -- `devctl suspend `: per-device suspend. -- `devctl resume `: per-device resume. -- `devinfo -v`: device tree with state. -- `pciconf -lvbc`: PCI devices with power state. -- `sysctl -a | grep acpi`: all ACPI-related variables. +- `acpiconf -s 3`:进入S3。 +- `zzz`:`acpiconf`的包装器。 +- `devctl suspend `:每设备挂起。 +- `devctl resume `:每设备恢复。 +- `devinfo -v`:带状态的设备树。 +- `pciconf -lvbc`:带电源状态的PCI设备。 +- `sysctl -a | grep acpi`:所有ACPI相关变量。 ### Common Procedures @@ -3985,13 +3984,13 @@ int foo_runtime_resume(struct foo_softc *sc) { ### 需要收藏的文件 -- `/usr/src/sys/kern/device_if.m`: the kobj method definitions. -- `/usr/src/sys/kern/subr_bus.c`: `bus_generic_suspend`, `bus_generic_resume`, `device_quiesce`. -- `/usr/src/sys/dev/pci/pci.c`: `pci_suspend_child`, `pci_resume_child`, `pci_save_state`, `pci_restore_state`. -- `/usr/src/sys/dev/pci/pcivar.h`: `PCI_POWERSTATE_*` constants and inline API. -- `/usr/src/sys/dev/re/if_re.c`: production reference for suspend/resume with WoL. -- `/usr/src/sys/dev/xl/if_xl.c`: minimal suspend/resume pattern. -- `/usr/src/sys/dev/virtio/block/virtio_blk.c`: virtio-style quiesce. +- `/usr/src/sys/kern/device_if.m`:kobj方法定义。 +- `/usr/src/sys/kern/subr_bus.c`:`bus_generic_suspend`、`bus_generic_resume`、`device_quiesce`。 +- `/usr/src/sys/dev/pci/pci.c`:`pci_suspend_child`、`pci_resume_child`、`pci_save_state`、`pci_restore_state`。 +- `/usr/src/sys/dev/pci/pcivar.h`:`PCI_POWERSTATE_*`常量和内联API。 +- `/usr/src/sys/dev/re/if_re.c`:带WoL的挂起/恢复生产参考。 +- `/usr/src/sys/dev/xl/if_xl.c`:最小挂起/恢复模式。 +- `/usr/src/sys/dev/virtio/block/virtio_blk.c`:virtio风格的静默。 diff --git a/translations/zh_CN/chapters/part6/chapter-26.md b/translations/zh_CN/chapters/part6/chapter-26.md index 932b86d..d734844 100644 --- a/translations/zh_CN/chapters/part6/chapter-26.md +++ b/translations/zh_CN/chapters/part6/chapter-26.md @@ -17,188 +17,188 @@ language: "zh-CN" ## 引言 -第25章 closed 第5部分 with a 驱动程序 that the rest of the system could talk to. The `myfirst` 驱动程序 at version `1.8-maintenance` had a rate-limited logging macro, a careful errno vocabulary, loader tunables and writable sysctls, a three-way version split, a labelled-goto cleanup chain in 附加 and 分离, a clean modular source layout, `MODULE_DEPEND` and `MODULE_PNP_INFO` metadata, a `MAINTENANCE.md` document, a `shutdown_pre_sync` event handler, and a regression script that could load and unload the 驱动程序 a hundred times without leaking a single resource. What the 驱动程序 did not have was any contact with real hardware. The 字符设备 backed a 缓冲区 in 内核 memory. The sysctl counters tracked operations against that 缓冲区. The `MYFIRSTIOC_GETCAPS` ioctl announced capabilities that were implemented entirely in software. Everything the 驱动程序 did, it did without ever reading a byte off a wire. +第25章以一个系统其余部分可以与之通信的驱动程序结束了第5部分。版本为 `1.8-maintenance` 的 `myfirst` 驱动程序具备了速率受限的日志宏、完善的 errno 词汇表、加载器可调参数和可写 sysctl、三路版本拆分、attach 和 detach 中的标签化 goto 清理链、整洁的模块化源代码布局、`MODULE_DEPEND` 和 `MODULE_PNP_INFO` 元数据、`MAINTENANCE.md` 文档、`shutdown_pre_sync` 事件处理器,以及一个能够连续加载和卸载驱动程序一百次而不泄漏任何资源的回归测试脚本。但这个驱动程序没有的是与真实硬件的任何接触。字符设备背后是内核内存中的缓冲区。sysctl 计数器追踪的是针对该缓冲区的操作。`MYFIRSTIOC_GETCAPS` ioctl 公布的能力完全由软件实现。驱动程序所做的一切,都没有从线缆上读取过哪怕一个字节。 -第26章 begins the step outward. Instead of serving a 缓冲区 in RAM, the 驱动程序 will 附加 to a real 总线 and service a real 设备. The 总线 will be the Universal Serial Bus, because USB is the most approachable transport in FreeBSD: it is ubiquitous, its subsystem is extremely well organised, the 内核 接口 is designed around a small handful of structures and macros, and every FreeBSD developer already has a dozen USB 设备 on their desk. After USB, the chapter pivots to the subject that historically preceded USB and still lives alongside it everywhere from debug consoles to GPS modules: the 串行端口, in its classical form as a UART-driven RS-232 接口 and in its modern form as a USB-to-serial bridge. By the end of the chapter, the `myfirst` 驱动程序 family has grown a new transport-specific sibling, `myfirst_usb`, at version `1.9-usb`. That sibling knows how to 附加 to a real USB 设备, how to set up a bulk-in and a bulk-out transfer, how to echo received bytes through a `/dev` node, and how to survive the 设备 being yanked out of the port while the 驱动程序 is in use. +第26章开始向外迈出一步。驱动程序将不再服务于 RAM 中的缓冲区,而是附加到真实的总线上并服务于真实的设备。这条总线将是通用串行总线(USB),因为 USB 是 FreeBSD 中最易于上手的传输层:它无处不在,其子系统组织得极为完善,内核接口围绕少量结构和宏设计而成,每位 FreeBSD 开发者的桌面上都有十几个 USB 设备。在 USB 之后,本章转向历史上先于 USB 出现、至今仍与 USB 并存于从调试控制台到 GPS 模块等各处的主题:串行端口——其经典形式为 UART 驱动的 RS-232 接口,现代形式为 USB 转串行桥接器。到本章结束时,`myfirst` 驱动程序家族将增加一个新的特定传输层兄弟成员 `myfirst_usb`,版本为 `1.9-usb`。这个兄弟成员知道如何附加到真实的 USB 设备、如何设置批量输入和批量输出传输、如何通过 `/dev` 节点回显接收到的字节,以及如何在驱动程序仍在使用时应对设备被从端口拔出的情况。 -第26章 is the opening chapter of 第6部分. 第6部分 is organised around the observation that up to this point the book has been teaching the parts of FreeBSD 驱动程序 development that are *transport-neutral*: the New总线 model, the 字符设备 接口, synchronisation, interrupts, DMA, power management, debugging, integration, and maintenance. All of those disciplines apply to every 驱动程序 regardless of how the 设备 is 附加ed. 第6部分 shifts the focus. USB, storage, and networking each have their own 总线, their own lifecycle, their own data-flow pattern, and their own idiomatic way of integrating with the rest of the 内核. The disciplines you have built in Parts 1 through 5 carry over unchanged; what is new is the shape of the 接口 between your 驱动程序 and the specific subsystem it plugs into. 第26章 teaches that shape for USB and for serial 设备. 第27章 teaches it for storage 设备 and the VFS layer. 第28章 teaches it for 网络接口. Each of the three chapters is structurally parallel: the transport is introduced, the subsystem is mapped, a minimal 驱动程序 is built, and the reader is shown how to test without the specific hardware everyone happens not to have. +第26章是第6部分的开篇章节。第6部分的编排基于这样一个观察:到目前为止,本书一直在教授FreeBSD驱动程序开发中*与传输层无关*的部分——Newbus模型、字符设备接口、同步、中断、DMA、电源管理、调试、集成和维护。所有这些规范适用于每一个驱动程序,无论设备以何种方式附加。第6部分转移了重点。USB、存储和网络各自拥有自己的总线、自己的生命周期、自己的数据流模式,以及与内核其余部分集成的惯用方式。你在第1到第5部分中建立的规范保持不变;新的东西是你的驱动程序与它所插入的特定子系统之间接口的形态。第26章为USB和串行设备教授这种形态。第27章为存储设备和VFS层教授这种形态。第28章为网络接口教授这种形态。这三个章节在结构上是平行的:引入传输层、映射子系统、构建最小驱动程序,并向读者展示如何在缺乏特定硬件的情况下进行测试。 -There is a deliberate pairing of USB and serial in this chapter. The two topics sit together because they are both first-class citizens of the same larger mental model: a transport is a *protocol plus a lifecycle*, and the 驱动程序 is the piece of code that carries data across the protocol boundary and keeps the lifecycle consistent with the 内核's view of the 设备. USB is a protocol with a rich four-transfer-type vocabulary and a 热插拔 lifecycle. A UART is a protocol with a much simpler byte-framing vocabulary and a statically-附加ed lifecycle. Studying them together makes the pattern visible. A student who has seen the USB 回调 state machine and the UART 中断处理程序 side by side understands that "FreeBSD's 驱动程序 model" is not a single shape but a family of shapes, each one adapted to the demands of its own transport. +本章有意将USB和串行放在一起讨论。这两个主题并列是因为它们都是同一个更大思维模型的一等公民:传输层是一个*协议加生命周期*,而驱动程序是跨越协议边界传递数据并使生命周期与内核对设备的视图保持一致的代码。USB是一个拥有丰富四类传输类型词汇和热插拔生命周期的协议。UART是一个拥有简单得多的字节成帧词汇和静态附加生命周期的协议。将它们放在一起学习可以使模式变得清晰。一个同时看过USB回调状态机和UART中断处理程序的学生会理解,"FreeBSD的驱动程序模型"不是单一的形态,而是一个形态家族,每一种都适应其自身传输层的需求。 -The second reason to pair USB and serial is historical and practical. A very large number of what the operating system calls "USB 设备" are in fact 串行端口s in disguise. The FTDI FT232R chip, the Prolific PL2303, the Silicon Labs CP210x, and the WCH CH340 all expose a standard serial-port API to user space, but physically they sit on the USB 总线. FreeBSD handles that with the `ucom(4)` 框架: a USB驱动程序 寄存器 回调 with `ucom`, and `ucom` produces the user-visible `/dev/ttyU0` and `/dev/cuaU0` 设备 nodes and arranges for the termios-aware line discipline to operate correctly on top of a USB bulk-in and bulk-out pair. The reader who is about to write a USB驱动程序 is likely, sooner or later, to write a USB-to-串行驱动程序, and that 驱动程序 will be an intersection of the two worlds the chapter introduces. Putting the material into a single chapter makes the intersection visible. +将USB和串行配对的第二个原因是历史和实践层面的。操作系统所称的"USB设备"中,有很大一部分实际上是伪装的串行端口。FTDI FT232R芯片、Prolific PL2303、Silicon Labs CP210x和WCH CH340都向用户空间暴露了标准的串行端口API,但在物理上它们连接在USB总线上。FreeBSD通过 `ucom(4)` 框架来处理这种情况:一个USB驱动程序向 `ucom` 注册回调,`ucom` 生成用户可见的 `/dev/ttyU0` 和 `/dev/cuaU0` 设备节点,并安排支持termios的线路规程在USB批量输入和批量输出对之上正确运行。即将编写USB驱动程序的读者,迟早会编写USB转串行驱动程序,而该驱动程序将是本章介绍的两个世界的交汇点。将这些材料放在同一章中使这种交汇变得可见。 -A third reason is pedagogical. The `myfirst` 驱动程序 so far has been a pseudo-设备. The transition to real hardware is a conceptual step, not just a coding step. Many readers will find their first attempt at a hardware-backed 驱动程序 unsettling: interrupts arrive without asking, transfers can stall or time out, the 设备 can be unplugged mid-operation, and the 内核 has opinions about how fast you are allowed to respond. USB is the friendliest possible 引言 to that world because the USB subsystem does an unusually large 挂载 of work on the 驱动程序's behalf. Setting up a 批量传输 in USB is not the same kind of problem as setting up a DMA ring on a PCI Express NIC. The USB core manages the low-level DMA bookkeeping; your 驱动程序 works at the level of "tell me when this transfer completes". Learning the USB pattern first makes the later hardware chapters (storage, networking, embedded 总线es in Part 7) less intimidating because by then the basic shape of a transport-specific 驱动程序 is familiar. +第三个原因是教学方面的。到目前为止,`myfirst` 驱动程序一直是一个伪设备。向真实硬件的过渡是一个概念上的步骤,而不仅仅是编码步骤。许多读者会发现他们第一次尝试编写基于硬件的驱动程序时会感到不安:中断不请自来,传输可能停滞或超时,设备可能在操作中途被拔出,而内核对你允许以多快的速度响应有自己的要求。USB是对这个世界最友好的入门方式,因为USB子系统替驱动程序承担了异常大量的工作。在USB中设置批量传输与在PCI Express网卡上设置DMA环不是同一类问题。USB核心管理底层的DMA簿记工作;你的驱动程序工作在"告诉我这个传输什么时候完成"的层面。先学习USB模式使后面的硬件章节(存储、网络、第7部分中的嵌入式总线)不那么令人生畏,因为到那时,特定传输层驱动程序的基本形态已经为人所熟悉。 -The `myfirst` 驱动程序's path through this chapter is concrete. It picks up at version `1.8-maintenance` from the end of 第25章. It adds a new source file, `myfirst_usb.c`, compiled into a new 内核模块, `myfirst_usb.ko`. The new module declares itself dependent on `usb`, lists a single vendor and product identifier in its 匹配表, 探测 and 附加 on 热插拔, allocates one bulk-in and one bulk-out transfer, exposes a `/dev/myfirst_usb0` node, echoes incoming bytes to the 内核 log and copies them back out on a read, handles 分离 cleanly when the cable is pulled, and carries forward every 第25章 discipline without exception. The labs exercise each piece in turn. By the end of the chapter, there is a second 驱动程序 in the family, a new source layout to accommodate it, and a working example of a FreeBSD USB驱动程序 that the reader has typed themselves. +`myfirst` 驱动程序在本章中的路径是具体的。它从第25章末尾的版本 `1.8-maintenance` 继续。它添加了一个新的源文件 `myfirst_usb.c`,编译为一个新的内核模块 `myfirst_usb.ko`。新模块声明自己依赖于 `usb`,在其匹配表中列出一个供应商和产品标识符,在热插拔时进行探测和附加,分配一个批量输入和一个批量输出传输,暴露一个 `/dev/myfirst_usb0` 节点,将传入的字节回显到内核日志并在读取时将其复制回去,在拔出线缆时干净地处理分离,并无一例外地继承了第25章的所有规范。实验环节依次练习每个部分。到本章结束时,家族中将拥有第二个驱动程序、一个新的源代码布局来容纳它,以及一个读者亲手编写的可工作的FreeBSD USB驱动程序示例。 -Because this is also a chapter about serial 设备, the chapter spends time on the serial half of its scope even though `myfirst_usb` itself is not a 串行驱动程序. The serial material teaches how `uart(4)` is laid out, how `ucom(4)` fits in, how termios carries 波特率 and 奇偶校验 and 流控制 from user space down to hardware, and how to test serial 接口 without physical hardware using `nmdm(4)`. The serial material does not build a new UART hardware 驱动程序 from scratch. Writing a UART hardware 驱动程序 is a specialised undertaking that is almost never the right choice in a modern environment: the existing `ns8250` 驱动程序 in the base system already handles every PC-compatible 串行端口, every common PCI serial card, and the ARM PL011 that most virtualised platforms present. The chapter teaches the serial subsystem at the level the reader actually needs: how it is organised, how to read existing 驱动程序, how termios reaches a 驱动程序's `param` method, how to use the subsystem from user space, and what to do when the goal is a USB-to-串行驱动程序 (the common case) rather than a new hardware 驱动程序 (the rare case). +由于本章也是关于串行设备的章节,因此本章花时间在串行方面的内容上,尽管 `myfirst_usb` 本身不是串行驱动程序。串行部分教授 `uart(4)` 是如何布局的、`ucom(4)` 如何融入其中、termios如何将波特率、奇偶校验和流控制从用户空间传递到硬件,以及如何使用 `nmdm(4)` 在没有物理硬件的情况下测试串行接口。串行部分不会从头构建一个新的UART硬件驱动程序。编写UART硬件驱动程序是一项专门的工作,在现代环境中几乎从来不是正确的选择:基本系统中现有的 `ns8250` 驱动程序已经处理了所有PC兼容的串行端口、所有常见的PCI串行卡,以及大多数虚拟化平台所提供的ARM PL011。本章在读者实际需要的层面上教授串行子系统:它是如何组织的、如何阅读现有的驱动程序、termios如何到达驱动程序的 `param` 方法、如何从用户空间使用该子系统,以及当目标是USB转串行驱动程序(常见情况)而非新硬件驱动程序(罕见情况)时该怎么做。 -The rhythm of 第26章 is the rhythm of pattern recognition. The reader will leave the chapter knowing what a USB驱动程序 looks like, what a 串行驱动程序 looks like, where the two overlap, where they differ from the pseudo-驱动程序 of Parts 2 through 5, and how to test both without a lab full of adapters. Those are the foundations of transport-specific 驱动程序 development. 第27章 will then apply the same discipline to storage, and 第28章 will apply it to networking, each time taking the same general pattern and bending it to a new transport's rules. +第26章的节奏是模式识别的节奏。读者离开本章时将知道USB驱动程序是什么样的,串行驱动程序是什么样的,两者在哪里重叠,它们与第2到第5部分的伪驱动程序有何不同,以及如何在没有满实验室适配器的情况下测试两者。这些是特定传输层驱动程序开发的基础。第27章随后将把同样的规范应用于存储,第28章将把它应用于网络,每次都采用相同的通用模式并将其弯曲到新传输层的规则中。 -### Where 第25章 Left the Driver +### 第25章为驱动程序留下的起点 -A short checkpoint before the new work starts. 第26章 extends the 驱动程序 family produced at the end of 第25章, tagged as version `1.8-maintenance`. If any of the items below is uncertain, return to 第25章 and resolve it before starting this chapter, because the new material assumes every 第25章 primitive is working and every habit is in place. +在开始新工作之前做一个简短的检查。第26章扩展了第25章末尾生成的驱动程序家族,标记为版本 `1.8-maintenance`。如果以下任何项目不确定,请在开始本章之前返回第25章并解决它,因为新材料假定第25章的每个原语都在工作,每个习惯都已养成。 -- Your 驱动程序 source matches 第25章 Stage 4. `myfirst.ko` compiles cleanly, identifies itself as `1.8-maintenance` in `kldstat -v`, and carries the full `MYFIRST_VERSION`, `MODULE_VERSION`, and `MYFIRST_IOCTL_VERSION` triple. -- The source layout is split: `myfirst_总线.c`, `myfirst_cdev.c`, `myfirst_ioctl.c`, `myfirst_sysctl.c`, `myfirst_debug.c`, `myfirst_log.c`, with `myfirst.h` as the shared private header. -- The rate-limited log macro `DLOG_RL` is in place and tied to a `struct myfirst_ratelimit` inside the softc. -- The `goto fail;` cleanup chain in `myfirst_附加` is working and exercised by a deliberate failure lab. -- The regression script passes a hundred consecutive `kldload`/`kldunload` cycles with no residual OIDs, no orphaned cdev nodes, and no leaked memory. -- Your lab machine runs FreeBSD 14.3 with `/usr/src` on disk, a debug 内核 with `INVARIANTS`, `WITNESS`, `WITNESS_SKIPSPIN`, `DDB`, `KDB`, `KDB_UNATTENDED`, `KDTRACE_HOOKS`, and `DDB_CTF`, and a VM snapshot at the `1.8-maintenance` state you can revert to. +- 你的驱动程序源代码与第25章第4阶段匹配。`myfirst.ko` 编译干净,在 `kldstat -v` 中标识为 `1.8-maintenance`,并携带完整的 `MYFIRST_VERSION`、`MODULE_VERSION` 和 `MYFIRST_IOCTL_VERSION` 三元组。 +- 源代码布局已拆分:`myfirst_bus.c`、`myfirst_cdev.c`、`myfirst_ioctl.c`、`myfirst_sysctl.c`、`myfirst_debug.c`、`myfirst_log.c`,以及作为共享私有头文件的 `myfirst.h`。 +- 速率受限的日志宏 `DLOG_RL` 已就位,并与softc中的 `struct myfirst_ratelimit` 绑定。 +- `myfirst_attach` 中的 `goto fail;` 清理链正常工作,并通过一个有意的失败实验进行了验证。 +- 回归测试脚本通过一百次连续的 `kldload`/`kldunload` 循环,没有残留的OID、没有孤立的cdev节点、没有内存泄漏。 +- 你的实验机器运行FreeBSD 14.3,磁盘上有 `/usr/src`,一个启用了 `INVARIANTS`、`WITNESS`、`WITNESS_SKIPSPIN`、`DDB`、`KDB`、`KDB_UNATTENDED`、`KDTRACE_HOOKS` 和 `DDB_CTF` 的调试内核,以及一个可以回退到的 `1.8-maintenance` 状态的VM快照。 -That 驱动程序, those files, and those habits are what 第26章 extends. The additions introduced in this chapter live almost entirely in a new file, `myfirst_usb.c`, which becomes a second 内核模块 sharing the same conceptual family as `myfirst.ko` but building a separate `myfirst_usb.ko`. The chapter's labs exercise each stage of the new module: 探测, 附加, transfer setup, 回调 handling, /dev exposure, and 分离. The chapter does not modify `myfirst.ko` itself; the existing 驱动程序 remains a reference implementation of Parts 2 through 5, and the new 驱动程序 is its USB-transport sibling. +那个驱动程序、那些文件和那些习惯正是第26章要扩展的内容。本章引入的新增内容几乎全部位于一个新文件 `myfirst_usb.c` 中,它成为第二个内核模块,与 `myfirst.ko` 共享相同的概念家族,但构建一个独立的 `myfirst_usb.ko`。本章的实验练习新模块的每个阶段:探测、附加、传输设置、回调处理、/dev暴露和分离。本章不修改 `myfirst.ko` 本身;现有驱动程序仍然是第2到第5部分的参考实现,新驱动程序是其USB传输层的兄弟。 -### What You Will Learn +### 你将学到什么 -By the end of this chapter you will be able to: +到本章结束时,你将能够: -- Explain what makes a transport-specific 驱动程序 different from the pseudo-驱动程序 built in Parts 2 through 5, and name the three broad categories of work a transport-specific 驱动程序 has to add to its New总线 foundation: matching rules, transfer mechanics, and lifecycle 热插拔 handling. -- Describe the USB mental model at the level needed to write a 驱动程序: host versus 设备 roles, hubs and ports, 设备 classes (CDC, HID, Mass Storage, Vendor), the 描述符 hierarchy (设备, configuration, 接口, 端点), the four transfer types (control, bulk, interrupt, isochronous), and the 热插拔 lifecycle. -- Read the output of `usbconfig` and `dmesg` for a USB 设备 and identify its vendor identifier, product identifier, 接口 class, 端点 addresses, 端点 types, and 数据包 sizes. -- Describe the serial mental model at the level needed to write a 驱动程序: the UART as a shift 注册 with a baud generator, RS-232 framing, start and 停止位, 奇偶校验, hardware 流控制 via RTS and CTS, software 流控制 via XON and XOFF, and the relationship between `struct termios`, `tty(9)`, and the 驱动程序's `param` 回调. -- Explain the difference between FreeBSD's `uart(4)` subsystem for real UART hardware and the `ucom(4)` 框架 for USB-to-serial bridges, and name the two worlds a serial-驱动程序 author must never confuse. -- Write a USB 设备驱动程序 that 附加 to `uhub`, declares a `STRUCT_USB_HOST_ID` 匹配表, implements `探测` and `附加` and `分离` methods, uses `usbd_transfer_setup` to configure a bulk-in and a bulk-out transfer, and unwinds cleanly through a labelled-goto chain. -- Write a USB 传输回调 that follows the `USB_GET_STATE` state machine, handles `USB_ST_SETUP` and `USB_ST_TRANSFERRED` correctly, distinguishes `USB_ERR_CANCELLED` from other errors, and responds to a stalled 端点 with `usbd_xfer_set_stall`. -- Expose a USB 设备 to user space through the `usb_fifo` 框架 or through a custom `make_dev_s`-注册ed `cdevsw`, and know when each is the right choice. -- Read an existing UART 驱动程序 in `/usr/src/sys/dev/uart/` with a pattern vocabulary that makes the code's intent clear on first pass, including the `uart_class`/`uart_ops` split, the method dispatch, the baud-divisor calculation, and the tty-side wakeup machinery. -- Translate a `struct termios` into the four arguments of a UART `param` method (baud, databits, stopbits, 奇偶校验), and know which termios flags belong to the hardware layer and which belong to the line discipline. -- Test a USB驱动程序 against a simulated 设备 using QEMU USB redirection or `usb_template(4)`, and test a 串行驱动程序 against a `nmdm(4)` null-modem pair without any hardware at all. -- Use `cu(1)`, `tip(1)`, `stty(1)`, `comcontrol(8)`, and `usbconfig(8)` to drive, configure, and inspect serial and USB 设备 from user space. -- Handle 热拔出 cleanly in a USB驱动程序's 分离 path: cancel outstanding transfers, drain callouts and taskqueues, release 总线 resources, and destroy cdev nodes, all while knowing that the 设备 may already be gone by the time the 分离 method runs. +- 解释是什么使特定传输层的驱动程序与第2到第5部分构建的伪驱动程序不同,并指出特定传输层驱动程序必须在其Newbus基础上增加的三大类工作:匹配规则、传输机制和生命周期热插拔处理。 +- 描述编写驱动程序所需的USB思维模型:主机与设备角色、集线器和端口、设备类(CDC、HID、大容量存储、Vendor)、描述符层次结构(设备、配置、接口、端点)、四种传输类型(控制、批量、中断、等时)以及热插拔生命周期。 +- 读取USB设备的 `usbconfig` 和 `dmesg` 输出,并识别其供应商标识符、产品标识符、接口类、端点地址、端点类型和数据包大小。 +- 描述编写驱动程序所需的串行思维模型:UART作为带有波特率发生器的移位寄存器、RS-232成帧、起始位和停止位、奇偶校验、通过RTS和CTS的硬件流控制、通过XON和XOFF的软件流控制,以及 `struct termios`、`tty(9)` 和驱动程序的 `param` 回调之间的关系。 +- 解释FreeBSD的 `uart(4)` 子系统(用于真实UART硬件)与 `ucom(4)` 框架(用于USB转串行桥接器)之间的区别,并指出串行驱动程序作者绝不能混淆的两个世界。 +- 编写一个附加到 `uhub` 的USB设备驱动程序,声明一个 `STRUCT_USB_HOST_ID` 匹配表,实现 `probe` 和 `attach` 及 `detach` 方法,使用 `usbd_transfer_setup` 配置一个批量输入和一个批量输出传输,并通过标签化goto链进行干净的展开。 +- 编写一个遵循 `USB_GET_STATE` 状态机的USB传输回调,正确处理 `USB_ST_SETUP` 和 `USB_ST_TRANSFERRED`,区分 `USB_ERR_CANCELLED` 和其他错误,并使用 `usbd_xfer_set_stall` 响应停滞的端点。 +- 通过 `usb_fifo` 框架或通过自定义的 `make_dev_s` 注册的 `cdevsw` 将USB设备暴露给用户空间,并知道何时选择哪种方式。 +- 使用模式词汇阅读 `/usr/src/sys/dev/uart/` 中现有的UART驱动程序,使代码的意图在第一次阅读时就清楚,包括 `uart_class`/`uart_ops` 拆分、方法分派、波特率除数计算和tty侧的唤醒机制。 +- 将 `struct termios` 转换为UART `param` 方法的四个参数(波特率、数据位、停止位、奇偶校验),并知道哪些termios标志属于硬件层,哪些属于线路规程。 +- 使用QEMU USB重定向或 `usb_template(4)` 针对模拟设备测试USB驱动程序,并使用 `nmdm(4)` 空调制解调器对在完全没有硬件的情况下测试串行驱动程序。 +- 使用 `cu(1)`、`tip(1)`、`stty(1)`、`comcontrol(8)` 和 `usbconfig(8)` 从用户空间驱动、配置和检查串行及USB设备。 +- 在USB驱动程序的分离路径中干净地处理热拔出:取消未完成的传输、排空callout和任务队列、释放总线资源并销毁cdev节点,同时要知道在分离方法运行时设备可能已经不存在了。 -The list is long because transport-specific 驱动程序 touch many surfaces at once. Each item is narrow and teachable. The chapter's work is making the set of items into a coherent, reusable mental picture. +这个列表很长,因为特定传输层的驱动程序同时涉及许多方面。每个项目都是狭窄且可教的。本章的工作是将这些项目集合成一个连贯的、可重用的思维图景。 -### What This Chapter Does Not Cover +### 本章不涵盖的内容 -Several adjacent topics are explicitly deferred to later chapters so 第26章 stays focused on the foundations of USB and 串行驱动程序 development. +几个相邻的主题被明确推迟到后面的章节,以便第26章专注于USB和串行驱动程序开发的基础。 -- **USB 等时传输 and high-bandwidth video/audio streaming** are mentioned at a conceptual level in Section 1 but not developed. Isochronous transfers are the most complex of the four transfer types and are almost always used through higher-level 框架 (audio, video capture) that deserve their own treatment. 第26章 focuses on control, bulk, and 中断传输, which together cover the vast majority of USB驱动程序 work. -- **USB 设备-mode and gadget programming** through `usb_template(4)` is introduced briefly for testing purposes but not built out. Writing a custom USB gadget is a specialised project outside the scope of a first transport-specific chapter. -- **The internals of the USB 主机控制器 驱动程序** (`xhci`, `ehci`, `ohci`, `uhci`) are outside scope. These 驱动程序 implement the low-level protocol machinery that `usbd_transfer_setup` eventually calls; a 驱动程序 author almost never has to modify them. The chapter treats them as a stable platform. -- **Writing a new UART hardware 驱动程序 from scratch** is outside scope. The existing `ns8250` 驱动程序 handles every common PC 串行端口, the `pl011` 驱动程序 handles most ARM platforms, and the embedded SoC 驱动程序 handle the rest. Writing a new UART 驱动程序 is the specialised work of porting FreeBSD to a new system-on-chip, which is its own topic (touched on in Part 7 alongside Device Tree and ACPI). 第26章 teaches the reader how to *read* and *understand* a UART 驱动程序 rather than how to write one. -- **Storage 驱动程序** (GEOM providers, 块设备, VFS integration) are the subject of 第27章. USB mass storage is touched on only as an example of a USB 设备 class, not as a 驱动程序 target. -- **Network 驱动程序** (`ifnet(9)`, mbufs, RX/TX ring bookkeeping) are the subject of 第28章. USB network adapters are mentioned as an example of CDC 以太网, not as a 驱动程序 target. -- **USB/IP for remote USB 设备 testing over a network** is mentioned as an option for readers who truly cannot obtain any USB pass-through, but is not developed. The standard testing pathway in this chapter is a local VM with 设备 redirection. -- **Quirks and vendor-specific workarounds** through `usb_quirk(4)` are mentioned but not developed. A 驱动程序 author who needs quirks is already past the level this chapter teaches. -- **Bluetooth, Wi-Fi, and other wireless transports that happen to use USB** as their physical 总线 are outside scope. Those stacks involve protocols well beyond USB itself and are their own bodies of work. -- **Transport-agnostic abstraction for multi-总线 驱动程序** (the same 驱动程序 logic plugging into PCI, USB, and serial via a common 接口) is deferred to Part 7's portability chapter. +- **USB等时传输和高带宽数字视频/音频流**在第1节中在概念层面提及但未展开。等时传输是四种传输类型中最复杂的,几乎总是通过更高级别的框架(音频、视频捕获)来使用,这些框架值得单独讨论。第26章专注于控制、批量和中断传输,它们共同覆盖了绝大多数USB驱动程序工作。 +- **USB设备模式和gadget编程**通过 `usb_template(4)` 为测试目的做了简要介绍但未展开。编写自定义USB gadget是一个专门的项目,超出了第一个特定传输层章节的范围。 +- **USB主机控制器驱动程序的内部机制**(`xhci`、`ehci`、`ohci`、`uhci`)不在范围内。这些驱动程序实现了 `usbd_transfer_setup` 最终调用的底层协议机制;驱动程序作者几乎不需要修改它们。本章将它们视为稳定平台。 +- **从头编写新的UART硬件驱动程序**不在范围内。现有的 `ns8250` 驱动程序处理所有常见的PC串行端口,`pl011` 驱动程序处理大多数ARM平台,嵌入式SoC驱动程序处理其余的。编写新的UART驱动程序是将FreeBSD移植到新片上系统的专门工作,这是一个独立的主题(在第7部分中与设备树和ACPI一起涉及)。第26章教读者如何*阅读*和*理解*UART驱动程序,而不是如何编写一个。 +- **存储驱动程序**(GEOM提供者、块设备、VFS集成)是第27章的主题。USB大容量存储仅作为USB设备类的示例提及,而非驱动程序目标。 +- **网络驱动程序**(`ifnet(9)`、mbuf、RX/TX环簿记)是第28章的主题。USB网络适配器仅作为CDC以太网示例提及,而非驱动程序目标。 +- **通过网络进行远程USB设备测试的USB/IP**作为真正无法获得任何USB直通的读者的选项提及,但未展开。本章的标准测试路径是带有设备重定向的本地VM。 +- **通过 `usb_quirk(4)` 的quirk和供应商特定的变通方法**已提及但未展开。需要quirk的驱动程序作者已经超出了本章所教授的水平。 +- **恰好使用USB作为物理总线的蓝牙、Wi-Fi和其他无线传输**不在范围内。这些协议栈涉及远超USB本身的协议,是独立的工作领域。 +- **多总线驱动程序的传输无关抽象**(通过公共接口将相同驱动程序逻辑插入PCI、USB和串行)推迟到第7部分的可移植性章节。 -Staying inside those lines keeps 第26章 a chapter about *the USB and serial transports*, not a chapter about every technique a senior transport-specific 内核 developer might use on a senior transport-specific 内核 problem. +保持在这些界限内使得第26章成为一本关于*USB和串行传输层*的章节,而不是关于高级特定传输层内核开发者在高级特定传输层内核问题上可能使用的每一种技术的章节。 -### Where We Are in 第6部分 +### 我们在第6部分的位置 -第6部分 has three chapters. 第26章 is the opening chapter and teaches transport-specific 驱动程序 development through USB and serial 设备. 第27章 teaches transport-specific 驱动程序 development through storage 设备 and the VFS layer. 第28章 teaches it through 网络接口. The three chapters are structurally parallel in the sense that each introduces a transport, maps the subsystem, builds a minimal 驱动程序, and teaches hardware-free testing. +第6部分有三个章节。第26章是开篇章节,通过USB和串行设备教授特定传输层驱动程序开发。第27章通过存储设备和VFS层教授特定传输层驱动程序开发。第28章通过网络接口教授这些内容。这三个章节在结构上是平行的,即每个章节都引入一个传输层、映射子系统、构建最小驱动程序,并教授无硬件测试。 -第26章 is the right place to start 第6部分 for three reasons. The first is that USB is the most gentle 引言 to hardware-backed 驱动程序: its core abstractions are smaller than storage's (no GEOM graph, no VFS), smaller than networking's (no mbuf chains, no 环形缓冲区 with head/tail pointers and interrupts mitigation), and the subsystem handles a large share of the hard parts on the 驱动程序's behalf. The second is that USB appears everywhere. Even a reader who will never write a storage or 网络驱动程序 will probably write a USB驱动程序 at some point: a thermometer, a data logger, a custom serial adapter, a factory test fixture. The third is pedagogical. The pattern USB teaches, a subsystem with 探测-and-附加 lifecycles, transfer setup through a config array, 回调-based completion, and a clean 分离 on unplug, is the same pattern (with different specifics) that storage and networking teach. Seeing it first in USB makes the next two chapters recognisable. +第26章是开始第6部分的正确位置,有三个原因。第一,USB是对基于硬件的驱动程序最温和的入门方式:其核心抽象比存储的更小(没有GEOM图、没有VFS),比网络的更小(没有mbuf链、没有带头/尾指针和中断缓解的环形缓冲区),并且子系统代表驱动程序处理了很大一部分困难的工作。第二,USB无处不在。即使是一个永远不会编写存储或网络驱动程序的读者也可能在某个时候编写USB驱动程序:温度计、数据记录器、自定义串行适配器、工厂测试夹具。第三是教学方面的。USB教授的模式——一个具有探测和附加生命周期的子系统、通过配置数组进行传输设置、基于回调的完成以及拔出时的干净分离——与存储和网络教授的模式相同(具体细节不同)。先在USB中看到它使接下来的两章变得容易辨认。 -第26章 bridges forward to 第27章 by closing on a note about lifecycle: the USB 分离 path is a dress rehearsal for the storage-设备 hot-removal path, and the patterns the reader has just practised will come back the moment an external USB disk is pulled in 第27章. It also bridges backward to 第25章 by carrying every 第25章 discipline forward: `MODULE_DEPEND`, `MODULE_PNP_INFO`, the labelled-goto pattern, the errno vocabulary, rate-limited logging, version discipline, and a regression script that exercises the new module as rigorously as 第25章 exercised the old one. +第26章通过以关于生命周期的注释作为结尾来向第27章过渡:USB分离路径是存储设备热移除路径的预演,读者刚刚练习过的模式将在第27章中拉出外部USB磁盘的那一刻回来。它还通过继承第25章的每一项规范来向第25章回溯:`MODULE_DEPEND`、`MODULE_PNP_INFO`、标签化goto模式、errno词汇表、速率受限的日志记录、版本规范,以及一个像第25章一样严格测试新模块的回归测试脚本。 -### A Small Note on Difficulty +### 关于难度的一点说明 -If the transition from pseudo-驱动程序 to real hardware looks daunting on the first reading, that feeling is entirely normal. Every experienced FreeBSD developer had a first USB驱动程序 that did not 附加, a first serial session where `cu` refused to talk, and a first debug session where `dmesg` stayed silent. The chapter is structured to ease you into each of those moments with labs, troubleshooting notes, and exit points. If a section starts to feel overwhelming, the right move is not to push through but to stop, read the corresponding real 驱动程序 in `/usr/src`, and return when the real code makes the concept visible. The existing FreeBSD 驱动程序 are the single best teaching resource this chapter can point to, and the chapter will point to them often. +如果从伪驱动程序到真实硬件的过渡在第一次阅读时看起来令人生畏,这种感觉是完全正常的。每一位有经验的FreeBSD开发者都有一个无法附加的第一个USB驱动程序,一个 `cu` 拒绝通信的第一个串行会话,以及一个 `dmesg` 保持沉默的第一个调试会话。本章的结构旨在通过实验、故障排除注释和退出点来缓解这些时刻。如果某个部分开始让你感到不知所措,正确的做法不是硬着头皮继续,而是停下来,阅读 `/usr/src` 中相应的真实驱动程序,然后在真实代码使概念变得可见时再回来。现有的FreeBSD驱动程序是本章能指向的最好的教学资源,本章会经常指向它们。 -## 读者指南: How to Use This Chapter +## 读者指南:如何使用本章 -第26章 has three layers of engagement, and you can pick the layer that fits your current situation. The layers are independent enough that you can read for understanding now and return for hands-on practice later without losing continuity. +第26章有三个参与层次,你可以选择适合你当前情况的层次。这些层次之间足够独立,你可以现在为了理解而阅读,以后再回来进行实践练习而不失去连贯性。 -**Reading only.** Three to four hours. Reading gives you the USB and serial mental models, the shape of the FreeBSD subsystems, and pattern recognition for reading existing 驱动程序. If you are not yet in a position to load 内核模块 (because your lab VM is unavailable, you are reading on a commute, or you have a planning meeting in thirty minutes), a reading-only pass is a worthwhile investment. The chapter is written so that the prose carries the teaching load; the code 块 are there to anchor the prose, not to replace it. +**仅阅读。**三到四个小时。阅读为你提供USB和串行的思维模型、FreeBSD子系统的形态以及阅读现有驱动程序的模式识别能力。如果你目前还无法加载内核模块(因为你的实验VM不可用、你正在通勤时阅读,或者你在三十分钟后有一个计划会议),一次纯阅读的投入是值得的。本章的编写方式是让正文承担教学负荷;代码块是为了锚定正文,而不是替代它。 -**Reading plus the hands-on labs.** Eight to twelve hours over two or three sessions. The labs guide you through building `myfirst_usb.ko`, exploring real USB 设备 with `usbconfig`, setting up a simulated serial link with `nmdm(4)`, talking to it with `cu`, and running a 热拔出 stress test. The labs are where the chapter turns from explanation into reflex. If you can spare eight to twelve hours across two or three sessions, do the labs. The cost of skipping them is that the patterns stay abstract instead of becoming habit. +**阅读加上动手实验。**两到三次会话,每次八到十二小时。实验引导你构建 `myfirst_usb.ko`、使用 `usbconfig` 探索真实的USB设备、使用 `nmdm(4)` 建立模拟串行链路、使用 `cu` 与其通信,以及运行热拔出压力测试。实验是本章从解释转化为条件反射的地方。如果你能在两到三次会话中抽出八到十二个小时,请做实验。跳过它们的代价是模式停留在抽象层面而不是变成习惯。 -**Reading plus the labs plus the challenge exercises.** Fifteen to twenty hours over three or four sessions. The challenge exercises push beyond the chapter's worked example into the territory where you have to adapt the pattern to a new requirement: add a control-transfer ioctl, port the 驱动程序 to the `usb_fifo` 框架, read an unfamiliar USB驱动程序 end-to-end, simulate a flaky cable with failure injection, or extend the regression script to cover the new module. The challenge material does not introduce new foundations; it stretches the ones the chapter has just taught. Spend time on the challenges in proportion to how much autonomy you expect to have on your next 驱动程序 project. +**阅读加上实验加上挑战练习。**三到四次会话,十五到二十小时。挑战练习推动你超越本章的示例,进入你必须将模式适应新需求的领域:添加控制传输ioctl、将驱动程序移植到 `usb_fifo` 框架、从头到尾阅读一个陌生的USB驱动程序、使用故障注入模拟不稳定的线缆,或扩展回归测试脚本以覆盖新模块。挑战材料不引入新的基础;它拉伸本章刚刚教授的基础。在挑战上花费的时间与你期望在下一个驱动程序项目中拥有多少自主权成正比。 -Do not rush. This is the first chapter in the book whose material depends on real hardware or convincing simulation. Set aside a 块 of time when you can watch `dmesg` after `kldload` and read it slowly. A USB驱动程序 that 附加 without errors is usually right; a USB驱动程序 whose 附加 messages you have not actually read is often wrong in a way that will cost you an hour of debugging two days later. The small discipline of reading the 附加 output as it happens, rather than assuming it, is a habit worth forming in 第26章 because every subsequent transport-specific chapter depends on it. +不要急于求成。这是本书中第一个其材料依赖于真实硬件或令人信服的模拟的章节。留出一块时间,这样你可以在 `kldload` 之后观看 `dmesg` 并慢慢阅读它。一个没有错误地附加的USB驱动程序通常是正确的;一个你没有实际阅读过其附加消息的USB驱动程序往往是错误的,这种错误会在两天后花费你一个小时的调试时间。在附加输出发生时阅读它而不是假设它的小纪律,是在第26章中值得养成的习惯,因为每个后续的特定传输层章节都依赖于它。 -### Recommended Pacing +### 推荐的学习节奏 -Three sitting structures work well for this chapter. +三种学习时段结构适合本章。 -- **Two long sittings of four to six hours each.** First sitting: 引言, 读者指南, How to Get the Most Out of This Chapter, Section 1, Section 2, and Lab 1. Second sitting: Section 3, Section 4, Section 5, Labs 2 through 5, and the 总结. The advantage of long sittings is that you stay in the mental model long enough to connect Section 1's vocabulary to Section 3's 回调 code. +- **两次长时间学习,每次四到六小时。**第一次:引言、读者指南、如何从本章获得最大收益、第1节、第2节和实验1。第二次:第3节、第4节、第5节、实验2到5和总结。长时间学习的优势是你能停留在思维模型中足够长的时间,将第1节的词汇与第3节的回调代码联系起来。 -- **Four medium sittings of two to three hours each.** Sitting 1: 引言 through Section 1 and Lab 1. Sitting 2: Section 2 and Lab 2. Sitting 3: Section 3 and Labs 3 and 4. Sitting 4: Section 4, Section 5, Lab 5, and 总结. The advantage is that each sitting has a crisp milestone. +- **四次中等时间学习,每次两到三小时。**学习1:引言到第1节和实验1。学习2:第2节和实验2。学习3:第3节和实验3、4。学习4:第4节、第5节、实验5和总结。优势是每次学习都有一个明确的里程碑。 -- **A linear reading pass followed by a hands-on pass.** Day one: read the entire chapter start to finish without running any code, to get the full mental model in place. Day two or day three: return to the chapter with a 内核 source tree and a lab VM open and work through the labs in sequence. The advantage of this approach is that the mental model is fully loaded before you touch code, which catches concept-level mistakes early. +- **一次线性阅读后跟一次动手实践。**第一天:从头到尾阅读整章而不运行任何代码,以建立完整的思维模型。第二天或第三天:带着内核源代码树和打开的实验VM回到本章,按顺序完成实验。这种方法的优势是在你接触代码之前思维模型已经完全加载,这可以及早发现概念层面的错误。 -Do not attempt the whole chapter in a single marathon session. The material is dense, and the USB 回调 state machine in particular does not reward tired reading. +不要试图在一次马拉松式的会话中完成整章。材料很密集,特别是USB回调状态机不适合疲劳阅读。 -### What a Good Study Session Looks Like +### 一个好的学习时段是什么样的 -A good study session for this chapter has five elements visible at once. Put the book chapter on one side of your screen. Put the relevant FreeBSD source files in a second pane: `/usr/src/sys/dev/usb/usbdi.h`, `/usr/src/sys/dev/usb/misc/uled.c`, and `/usr/src/sys/dev/uart/uart_总线.h` are the three most useful to keep open. Put a terminal on your lab VM in a third pane. Put `man 4 usb`, `man 4 uart`, and `man 4 ucom` in a fourth pane for quick reference. Finally, keep a small note file open for questions you will want to answer later. If a term comes up you cannot define, write it in the note file and keep reading; if the same term comes up twice, look it up before continuing. This is the study posture that gets the most out of a long technical chapter. +本章的一个好的学习时段需要同时看到五个元素。将书中的章节放在屏幕的一侧。将相关的FreeBSD源文件放在第二个窗格中:`/usr/src/sys/dev/usb/usbdi.h`、`/usr/src/sys/dev/usb/misc/uled.c` 和 `/usr/src/sys/dev/uart/uart_bus.h` 是保持打开的三个最有用的文件。将实验VM上的终端放在第三个窗格中。将 `man 4 usb`、`man 4 uart` 和 `man 4 ucom` 放在第四个窗格中以供快速参考。最后,保持打开一个小笔记文件,用于记录你以后想要回答的问题。如果出现一个你无法定义的术语,把它写在笔记文件中然后继续阅读;如果同一个术语出现两次,在继续之前查一下它。这是从一个长技术章节中获得最大收益的学习姿态。 -### If You Do Not Have a USB Device to Test With +### 如果你没有USB设备可供测试 -Many readers will not have a spare USB 设备 that matches the vendor/product identifiers in the worked example. That is fine. Section 5 teaches three ways to proceed: QEMU USB 设备 redirection from a host to a guest, `usb_template(4)` for FreeBSD-as-USB-设备, and the simulated-设备 approach that tests 驱动程序 logic without a real 总线 at all. The chapter's worked example is written so that the 驱动程序's 匹配表 can be swapped for one matching any USB 设备 you do have on your desk. A USB flash drive will do. A mouse will do. A keyboard will do. The chapter explains how to point the 驱动程序 at whatever 设备 you happen to have, at the cost of temporarily stealing that 设备 from the 内核's built-in 驱动程序, which the chapter also covers. +许多读者不会有一个与示例中的供应商/产品标识符匹配的备用USB设备。这没关系。第5节教授了三种继续的方法:从主机到客户机的QEMU USB设备重定向、用于FreeBSD作为USB设备的 `usb_template(4)`,以及完全不需要真实总线的模拟设备方法来测试驱动程序逻辑。本章的示例编写方式使得驱动程序的匹配表可以替换为与你桌上任何USB设备匹配的表。一个USB闪存盘就可以。一个鼠标就可以。一个键盘就可以。本章解释了如何将驱动程序指向你碰巧拥有的任何设备,代价是暂时从内核的内置驱动程序中夺取该设备,本章也涵盖了这一点。 -## How to Get the Most Out of This Chapter +## 如何从本章获得最大收益 -Five habits pay off in this chapter more than in any of the earlier chapters. +五个习惯在本章中的回报比在前面任何章节中都大。 -First, **keep four short manual-page files open in a browser tab or a terminal pane**: `usb(4)`, `usb_quirk(4)`, `uart(4)`, and `ucom(4)`. These four pages together are the tightest overview the FreeBSD project has of the subsystems this chapter introduces. None of them is long. `usb(4)` describes the subsystem from the user's perspective and lists the `/dev` entries that appear. `usb_quirk(4)` lists the quirks table and explains what a quirk is, which will save you puzzlement later when you see quirk code in real 驱动程序. `uart(4)` describes the serial subsystem from the user's perspective. `ucom(4)` describes the USB-to-serial 框架. Skim each once at the start of the chapter. When the prose refers to "consult the manual page for details," return to the appropriate page. The manual pages are authoritative; this book is commentary. +第一,**在浏览器标签页或终端窗格中保持打开四个简短的手册页文件**:`usb(4)`、`usb_quirk(4)`、`uart(4)` 和 `ucom(4)`。这四个页面合在一起是FreeBSD项目对 本章引入的子系统最精炼的概述。它们都不长。`usb(4)` 从用户的角度描述子系统并列出出现的 `/dev` 条目。`usb_quirk(4)` 列出quirk表并解释什么是quirk,这将在你以后在真实驱动程序中看到quirk代码时为你节省困惑。`uart(4)` 从用户的角度描述串行子系统。`ucom(4)` 描述USB转串行框架。在本章开始时快速浏览每一个。当正文提到"详情请参阅手册页"时,返回相应的页面。手册页是权威的;本书是评论。 -Second, **keep three real 驱动程序 close to hand**. `/usr/src/sys/dev/usb/misc/uled.c` is a very small USB驱动程序 that talks to a USB-附加ed LED. It uses the `usb_fifo` 框架, which is one of the two user-visible patterns the chapter teaches, and its entire 附加 function is smaller than a page. `/usr/src/sys/dev/usb/misc/ugold.c` is a slightly larger USB驱动程序 that reads temperature data from a TEMPer thermometer through 中断传输. It demonstrates the other common transfer type and shows how a 驱动程序 uses a callout to pace its reads. `/usr/src/sys/dev/uart/uart_dev_ns8250.c` is the canonical 16550 UART 驱动程序; every PC 串行端口 in the world uses it. Read each of these three files once at the start of the chapter and once more at the end. The first read will feel largely opaque; the second will feel almost obvious. That change is the measure of progress this chapter offers. +第二,**随时保持三个真实的驱动程序在手边**。`/usr/src/sys/dev/usb/misc/uled.c` 是一个非常小的USB驱动程序,与一个USB连接的LED通信。它使用 `usb_fifo` 框架,这是本章教授的两种用户可见模式之一,其整个附加函数不到一页。`/usr/src/sys/dev/usb/misc/ugold.c` 是一个稍大的USB驱动程序,通过中断传输从TEMPer温度计读取温度数据。它演示了另一种常见的传输类型,并展示了驱动程序如何使用callout来控制读取节奏。`/usr/src/sys/dev/uart/uart_dev_ns8250.c` 是经典的16550 UART驱动程序;世界上所有的PC串行端口都使用它。在本章开始时和结束时各读一次这三个文件。第一次阅读会感觉大部分不透明;第二次会感觉几乎显而易见。这种变化是本章所提供的进步的衡量标准。 -Third, **type every code addition by hand**. The `myfirst_usb.c` file grows through the chapter in roughly a dozen small increments. Each increment corresponds to a paragraph or two of prose. Typing the code by hand is what turns the prose into muscle memory. Pasting the code skips the lesson. If that sounds pedantic, notice that every working USB驱动程序 author has written a USB驱动程序's 附加 function at least a dozen times; typing this one is the first of that dozen. +第三,**手动输入每个代码添加**。`myfirst_usb.c` 文件通过大约十几个小的增量在本章中增长。每个增量对应一两段正文。手动输入代码是将正文转化为肌肉记忆的方式。粘贴代码会跳过这一课。如果这听起来很迂腐,请注意每个能工作的USB驱动程序作者都至少写过十几次USB驱动程序的附加函数;输入这个是那十几次中的第一次。 -Fourth, **read `dmesg` after every `kldload`**. A USB驱动程序 produces a predictable pattern of 附加 messages: the 设备 is detected on a port, the 驱动程序 探测, the match succeeds, the 驱动程序 附加, the `/dev` node appears. If any of those steps is missing, something is wrong, and the sooner you notice the missing step, the sooner you fix it. The smallest discipline this chapter can give you is the habit of running `dmesg | tail -30` immediately after `kldload` and reading every line. If the output is boring, the 驱动程序 probably works. If the output surprises you, investigate before proceeding. +第四,**在每次 `kldload` 后阅读 `dmesg`**。一个USB驱动程序产生一组可预测的附加消息模式:设备在端口上被检测到,驱动程序探测,匹配成功,驱动程序附加,`/dev` 节点出现。如果这些步骤中有任何一步缺失,说明出了问题,你越早注意到缺失的步骤,就能越早修复它。本章能给你的最小纪律是在 `kldload` 之后立即运行 `dmesg | tail -30` 并阅读每一行的习惯。如果输出很无聊,驱动程序可能工作正常。如果输出让你惊讶,在继续之前进行调查。 -Fifth, **after every section, ask yourself what would happen if you pulled the cable**. The question sounds silly; it is central. A well-written transport-specific 驱动程序 is always one that handles being removed while in use. A USB驱动程序 in particular runs in a world where 热拔出 is the normal operating condition. If you find yourself writing a section of code and cannot answer "what if the cable were pulled right here," the section is not yet finished. 第26章 returns to this question often, not as rhetoric but as a discipline. +第五,**在每一节之后,问问自己如果拔掉线缆会发生什么**。这个问题听起来很傻;但它是核心问题。一个写得好的特定传输层驱动程序总是能够处理在使用中被移除的情况。USB驱动程序尤其运行在一个热拔出是正常工作条件的世界中。如果你发现自己在编写一段代码但无法回答"如果此时线缆被拔出会怎样",那么这段代码还没有完成。第26章经常回到这个问题,不是作为修辞,而是作为一项纪律。 -### What to Do When Something Does Not Work +### 当某些东西不工作时该怎么办 -It will not all work the first time. USB驱动程序 have a few common failure modes, and the chapter documents each of them in the troubleshooting section at the end. A short preview of the most common ones: +不会所有东西都在第一次就工作。USB驱动程序有一些常见的故障模式,本章在最后的故障排除部分记录了每一种模式。最常见的一些的简要预览: -- The 驱动程序 compiles but does not 附加 when the 设备 is plugged in. Usually the 匹配表 has the wrong vendor or product identifier. The fix is to verify the identifier with `usbconfig dump_设备_desc`. -- The 驱动程序 附加 but the `/dev` node does not appear. Usually the `usb_fifo_附加` call failed because the name conflicts with an existing 设备. The fix is to change the `basename` or to 分离 the conflicting 驱动程序 first. -- The 驱动程序 附加 but the first transfer never completes. Usually `usbd_transfer_start` was not called, or the transfer was submitted with a zero-length 帧. The fix is to trace through `USB_ST_SETUP` and confirm that `usbd_xfer_set_帧_len` was called before `usbd_transfer_submit`. -- The 驱动程序 附加 but the 内核 panics on unplug. Usually the 分离 path is missing a `usbd_transfer_unsetup` call or a `usb_fifo_分离` call. The fix is to run the 分离 sequence under INVARIANTS and follow the WITNESS output back to the first dropped cleanup. +- 驱动程序编译通过但在设备插入时不附加。通常是匹配表中的供应商标识符或产品标识符错误。修复方法是使用 `usbconfig dump_device_desc` 验证标识符。 +- 驱动程序附加但 `/dev` 节点不出现。通常是 `usb_fifo_attach` 调用因为名称与现有设备冲突而失败。修复方法是更改 `basename` 或先分离冲突的驱动程序。 +- 驱动程序附加但第一次传输从未完成。通常是没有调用 `usbd_transfer_start`,或者传输以零长度帧提交。修复方法是跟踪 `USB_ST_SETUP` 并确认在 `usbd_transfer_submit` 之前调用了 `usbd_xfer_set_frame_len`。 +- 驱动程序附加但在拔出时内核崩溃。通常是分离路径缺少 `usbd_transfer_unsetup` 调用或 `usb_fifo_detach` 调用。修复方法是在INVARIANTS下运行分离序列,并按照WITNESS输出回溯到第一个被遗漏的清理。 -The troubleshooting section at the end of the chapter develops each of these cases in full, with diagnostic commands and expected output. The goal of this chapter is not to have everything work on the first try; the goal is to have a systematic debugging posture that turns every failure into a teachable moment. +本章末尾的故障排除部分详细展开了每一种情况,包括诊断命令和预期输出。本章的目标不是让一切在第一次尝试时就工作;目标是建立一个系统的调试姿态,将每一次失败转化为一次教学时刻。 -### Roadmap Through the Chapter +### 本章路线图 -The sections in order are: +各节顺序如下: -1. **Understanding USB and Serial Device Fundamentals.** The USB mental model at the level needed to write a 驱动程序: host and 设备, hubs and ports, classes, 描述符, transfer types, 热插拔 lifecycle. The serial mental model: UART hardware, RS-232 framing, 波特率, 奇偶校验, 流控制, the tty discipline. The FreeBSD-specific split between `uart(4)` and `ucom(4)`. A first exercise with `usbconfig` and `dmesg` that grounds the vocabulary in a 设备 you can see. +1. **理解USB和串行设备基础。**编写驱动程序所需的USB思维模型:主机与设备、集线器和端口、设备类、描述符、传输类型、热插拔生命周期。串行思维模型:UART硬件、RS-232成帧、波特率、奇偶校验、流控制、tty规程。FreeBSD特有的 `uart(4)` 和 `ucom(4)` 之间的分工。一个使用 `usbconfig` 和 `dmesg` 的初步练习,将词汇建立在你可见的设备之上。 -2. **Writing a USB Device Driver.** The FreeBSD USB subsystem layout. The New总线 shape of a USB驱动程序. `STRUCT_USB_HOST_ID` and the 匹配表. `DRIVER_MODULE` with `uhub` as the parent. `MODULE_DEPEND` on `usb`. `USB_PNP_HOST_INFO` for auto-load. The 探测 method using `usbd_lookup_id_by_uaa`. The 附加 method, the softc layout, the labelled-goto cleanup chain in 附加 and 分离. +2. **编写USB设备驱动程序。**FreeBSD USB子系统布局。USB驱动程序的Newbus形态。`STRUCT_USB_HOST_ID` 和匹配表。以 `uhub` 为父设备的 `DRIVER_MODULE`。对 `usb` 的 `MODULE_DEPEND`。用于自动加载的 `USB_PNP_HOST_INFO`。使用 `usbd_lookup_id_by_uaa` 的探测方法。附加方法、softc布局、附加和分离中的标签化goto清理链。 -3. **Performing USB Data Transfers.** The `struct usb_config` array. `usbd_transfer_setup` and the lifetime of a `struct usb_xfer`. Control, bulk, and 中断传输 shapes. The `usb_回调_t` state machine and `USB_GET_STATE`. Stall handling with `usbd_xfer_set_stall`. Frame-level operations (`usbd_xfer_set_帧_len`, `usbd_copy_in`, `usbd_copy_out`). Creating a `/dev` entry for the USB 设备 through the `usb_fifo` 框架. A worked example that sends bytes down a bulk-out 端点 and reads bytes back from a bulk-in 端点. +3. **执行USB数据传输。**`struct usb_config` 数组。`usbd_transfer_setup` 和 `struct usb_xfer` 的生命周期。控制、批量和中断传输的形态。`usb_callback_t` 状态机和 `USB_GET_STATE`。使用 `usbd_xfer_set_stall` 的停滞处理。帧级操作(`usbd_xfer_set_frame_len`、`usbd_copy_in`、`usbd_copy_out`)。通过 `usb_fifo` 框架为USB设备创建 `/dev` 条目。一个将字节发送到批量输出端点并从批量输入端点读回字节的完整示例。 -4. **Writing a Serial (UART) Driver.** The `uart(4)` subsystem at the level needed to read a real 驱动程序. The `uart_class`/`uart_ops` split. The method table dispatched through kobj. The relationship between `uart_总线_附加` and `uart_tty_附加`. Baud rate, 数据位, 停止位, 奇偶校验, and the `param` method. RTS/CTS hardware 流控制. `struct termios` and how it reaches the 驱动程序. `/dev/ttyu*` versus `/dev/cuau*` in FreeBSD. The `ucom(4)` 框架 for USB-to-serial bridges. A guided reading of the `ns8250` 驱动程序 as a canonical example. +4. **编写串行(UART)驱动程序。**阅读真实驱动程序所需级别的 `uart(4)` 子系统。`uart_class`/`uart_ops` 拆分。通过kobj分派的方法表。`uart_bus_attach` 和 `uart_tty_attach` 之间的关系。波特率、数据位、停止位、奇偶校验和 `param` 方法。RTS/CTS硬件流控制。`struct termios` 以及它如何到达驱动程序。FreeBSD中的 `/dev/ttyu*` 与 `/dev/cuau*`。用于USB转串行桥接器的 `ucom(4)` 框架。以 `ns8250` 驱动程序为经典示例的引导阅读。 -5. **Testing USB和串行驱动程序 Without Real Hardware.** `nmdm(4)` virtual null-modem pairs for serial testing. `cu(1)` and `tip(1)` for terminal access. `stty(1)` and `comcontrol(8)` for configuration. QEMU USB 设备 redirection for host-to-guest pass-through. `usb_template(4)` for FreeBSD-as-gadget testing. Software loopback patterns that exercise 驱动程序 logic without any 设备 at all. A reproducible test harness that runs a regression without human intervention. +5. **在没有真实硬件的情况下测试USB和串行驱动程序。**用于串行测试的 `nmdm(4)` 虚拟空调制解调器对。用于终端访问的 `cu(1)` 和 `tip(1)`。用于配置的 `stty(1)` 和 `comcontrol(8)`。用于主机到客户机直通的QEMU USB设备重定向。用于FreeBSD作为gadget测试的 `usb_template(4)`。在完全没有任何设备的情况下测试驱动程序逻辑的软件环回模式。一个无需人工干预即可运行回归测试的可复现的测试工具。 -After the five sections come a set of hands-on labs, a set of challenge exercises, a troubleshooting reference, a 总结 that closes 第26章's story, a bridge to 第27章, and a glossary. Read linearly on a first pass. +五个小节之后是一组动手实验、一组挑战练习、一个故障排除参考、一个结束第26章故事的总结、一个通往第27章的过渡和一个术语表。第一次阅读时请按顺序线性阅读。 -## 第1节: Understanding USB and Serial Device Fundamentals +## 第1节:理解USB和串行设备基础 -The first section teaches the mental models the rest of the chapter relies on. USB and serial 设备 share a surprising 挂载 of machinery at the `tty`/`cdevsw` layer, and at the same time they differ dramatically at the transport layer. A reader who is clear on both the similarities and the differences will find Sections 2 through 5 straightforward. A reader who is not will find the subsequent code confusingly non-obvious. This section is the single best place to spend an extra thirty minutes if you want the rest of the chapter to feel easier. +第一节教授本章其余部分所依赖的思维模型。USB和串行设备在 `tty`/`cdevsw` 层共享了惊人的大量机制,同时它们在传输层又有显著差异。清楚了解两者相似之处和不同之处的读者会发现第2到第5节很直观。不清楚的读者会发现后续代码令人困惑地不直观。如果你想让本章的其余部分感觉更容易,这个小节是额外花三十分钟的最佳地点。 -The section is organised in three arcs. The first arc establishes what a *transport* is, and why transport-specific 驱动程序 look different from the pseudo-驱动程序 of Parts 2 through 5. The second arc teaches the USB model: host and 设备, hubs and ports, classes, 描述符, 端点, transfer types, and the 热插拔 lifecycle. The third arc teaches the serial model: the UART, RS-232 framing, 波特率, 奇偶校验, 流控制, and the FreeBSD-specific split between `uart(4)` and `ucom(4)`. A first exercise at the end grounds the vocabulary in a 设备 you can see with `usbconfig`. +本节按三个弧线组织。第一个弧线确立了什么是*传输层*,以及为什么特定传输层的驱动程序与第2到第5部分的伪驱动程序看起来不同。第二个弧线教授USB模型:主机与设备、集线器和端口、设备类、描述符、端点、传输类型和热插拔生命周期。第三个弧线教授串行模型:UART、RS-232成帧、波特率、奇偶校验、流控制以及FreeBSD特有的 `uart(4)` 和 `ucom(4)` 之间的分工。最后的一个初步练习将词汇建立在你通过 `usbconfig` 可以看到的设备之上。 -### What a Transport Is, and Why It Matters Here +### 什么是传输层,以及为什么它在这里很重要 -A *transport* is the protocol and the lifecycle by which a 设备 is connected to the rest of the system. Up to this point in the book, the `myfirst` 驱动程序 has had no transport. Its 设备 existed entirely in the New总线 tree, connected to the `nexus` through the `pseudo` parent, and its data flowed into a 缓冲区 in 内核 memory. That makes `myfirst` a *pseudo-设备*: a 设备 whose existence is entirely a software fiction. Pseudo-设备 are essential teaching tools. They let the reader learn New总线, softc management, 字符设备 接口, ioctl handling, locking, and the rest, without also learning the specifics of a 总线. By now, those topics are covered. +*传输层*是设备连接到系统其余部分的协议和生命周期。到目前为止,`myfirst` 驱动程序一直没有传输层。它的设备完全存在于Newbus树中,通过 `pseudo` 父设备连接到 `nexus`,其数据流入内核内存中的缓冲区。这使得 `myfirst` 成为一个*伪设备*:一个完全由软件虚构的设备。伪设备是必不可少的教学工具。它们让读者在不学习总线细节的情况下学习Newbus、softc管理、字符设备接口、ioctl处理、锁定等。到目前为止,这些主题已经涵盖完毕。 -A transport-specific 驱动程序, by contrast, is one that 附加 to a *real* 总线. The 总线 has its own rules. It has its own way of saying "a new 设备 has appeared." It has its own way of delivering data. It has its own way of saying "a 设备 has been removed." A transport-specific 驱动程序 is still a New总线 驱动程序 (that never changes in FreeBSD), but its parent is no longer the abstract `pseudo` 总线. Its parent is `uhub` if it is a USB驱动程序, `pci` if it is a PCI 驱动程序, `acpi` or `fdt` if it is on an embedded platform, and so on. The 驱动程序's 附加 method receives arguments specific to that 总线. Its cleanup responsibilities include 总线-specific resources in addition to the ones it already had. Its lifecycle is the 总线's lifecycle, not the module's lifecycle. +相比之下,特定传输层的驱动程序是附加到*真实*总线的驱动程序。总线有自己的规则。它有自己的方式说"一个新设备出现了"。它有自己的数据传递方式。它有自己的方式说"一个设备已被移除"。特定传输层的驱动程序仍然是一个Newbus驱动程序(这在FreeBSD中永远不会改变),但其父设备不再是抽象的 `pseudo` 总线。如果它是USB驱动程序,其父设备是 `uhub`;如果是PCI驱动程序,则是 `pci`;如果在嵌入式平台上,则是 `acpi` 或 `fdt`,等等。驱动程序的附加方法接收特定于该总线的参数。其清理责任除了已有的之外,还包括总线特定的资源。其生命周期是总线的生命周期,而不是模块的生命周期。 -Three broad categories of work distinguish a transport-specific 驱动程序 from the pseudo-驱动程序 of Parts 2 through 5. They are worth naming explicitly because they recur in every transport chapter in 第6部分. +三大类工作将特定传输层的驱动程序与第2到第5部分的伪驱动程序区分开来。它们值得明确指出,因为它们在第6部分的每个传输层章节中都会出现。 -The first is *matching*. A pseudo-驱动程序 附加 on module load; there is nothing to match because there is no real 设备. A transport-specific 驱动程序 has to declare which 设备 it handles. On USB, this means a 匹配表 of vendor and product identifiers. On PCI, it means a 匹配表 of vendor and 设备 identifiers. On ACPI or FDT, it means a 匹配表 of string identifiers. The 内核's 总线 code enumerates 设备 as they appear and offers each one to every 注册ed 驱动程序 in turn; the 驱动程序's 探测 method decides whether to claim the 设备. Getting the 匹配表 right is the first obstacle every transport-specific 驱动程序 faces. +第一类是*匹配*。伪驱动程序在模块加载时附加;没有什么需要匹配的,因为没有真实设备。特定传输层的驱动程序必须声明它处理哪些设备。在USB上,这意味着一个供应商和产品标识符的匹配表。在PCI上,这意味着一个供应商和设备标识符的匹配表。在ACPI或FDT上,这意味着一个字符串标识符的匹配表。内核的总线代码在设备出现时枚举它们,并依次将每个设备提供给每个已注册的驱动程序;驱动程序的探测方法决定是否认领该设备。正确设置匹配表是每个特定传输层驱动程序面临的第一个障碍。 -The second is *transfer mechanics*. A pseudo-驱动程序's `read` and `write` methods touch a 缓冲区 in RAM. A transport-specific 驱动程序's `read` and `write` methods have to arrange for data to move across the 总线. On USB, this means setting up one or more transfers using `usbd_transfer_setup`, submitting them with `usbd_transfer_submit`, and handling completion in a 回调. On PCI, this means programming a DMA engine. On storage, this means translating 块 requests into 总线 transactions. The transfer mechanism is 总线-specific and is where most of a transport-specific 驱动程序's new code lives. +第二类是*传输机制*。伪驱动程序的 `read` 和 `write` 方法访问RAM中的缓冲区。特定传输层驱动程序的 `read` 和 `write` 方法必须安排数据在总线上移动。在USB上,这意味着使用 `usbd_transfer_setup` 设置一个或多个传输,使用 `usbd_transfer_submit` 提交它们,并在回调中处理完成。在PCI上,这意味着编程DMA引擎。在存储上,这意味着将块请求转换为总线事务。传输机制是总线特定的,是特定传输层驱动程序大部分新代码所在的地方。 -The third is *热插拔 lifecycle*. A pseudo-驱动程序 is loaded when the module is loaded and 分离ed when the module is unloaded. That is a simple lifecycle; `kldload` and `kldunload` are the only events it has to respond to. A transport-specific 驱动程序 has to deal with *热插拔*: the 设备 can appear and disappear independently of the module's lifecycle. A USB 设备 can be unplugged in the middle of a read. A SATA disk can be yanked out while the 文件系统 on it is 挂载ed. An 以太网 cable can be pulled while a TCP connection is open. The 驱动程序's 附加 method runs when a 设备 is physically inserted; its 分离 method runs when a 设备 is physically removed. The 分离 may happen while the 驱动程序 is still in use. Handling this correctly is the third big obstacle every transport-specific 驱动程序 faces. +第三类是*热插拔生命周期*。伪驱动程序在模块加载时加载,在模块卸载时分离。那是一个简单的生命周期;`kldload` 和 `kldunload` 是它需要响应的仅有事件。特定传输层的驱动程序必须处理*热插拔*:设备可以独立于模块的生命周期出现和消失。一个USB设备可以在读取过程中被拔出。一个SATA磁盘可以在其上的文件系统已挂载时被拔出。一个以太网线缆可以在TCP连接打开时被拔出。驱动程序的附加方法在设备被物理插入时运行;其分离方法在设备被物理移除时运行。分离可能在驱动程序仍在使用时发生。正确处理这是每个特定传输层驱动程序面临的第三个大障碍。 -The rest of 第6部分 is about those three categories of work in three different transports. 第26章 teaches USB and serial. 第27章 teaches storage. 第28章 teaches networking. The matching, the transfer mechanics, and the 热插拔 lifecycle look different in each transport, but the three-category structure repeats. That structure is what makes it possible to learn one transport well and then learn the next one quickly. +第6部分的其余内容是关于三种不同传输层中的这三类工作。第26章教授USB和串行。第27章教授存储。第28章教授网络。匹配、传输机制和热插拔生命周期在每种传输层中看起来不同,但三类别结构是重复的。正是这种结构使得可以先学好一种传输层,然后快速学习下一种成为可能。 -A useful shorthand: in Parts 2 through 5, you learned how to *be* a New总线 驱动程序. In 第6部分, you learn how to *附加* to a 总线 that has its own ideas about when and how you exist. +一个有用的简写:在第2到第5部分中,你学习了如何*成为*一个Newbus驱动程序。在第6部分中,你学习如何*附加*到一个对你何时以及如何存在有自己想法的总线。 -### The USB Mental Model +### USB思维模型 -USB, the Universal Serial Bus, is a tree-structured, host-controlled, 热插拔gable serial 总线. Every one of those adjectives matters, and understanding each of them is the foundation of writing a USB驱动程序. +USB,即通用串行总线,是一种树状结构、主机控制、支持热插拔的串行总线。这些形容词中每一个都很重要,理解它们中的每一个是编写USB驱动程序的基础。 -*Tree-structured* means that USB 设备 do not sit on a shared wire like 设备 on an I2C 总线 or an old ISA 总线. Every USB 设备 has exactly one upstream connection, to a parent hub. The root of the tree is the *root hub*, which is exposed by the USB 主机控制器. Downstream of the root hub are other hubs and 设备. A hub has a fixed number of downstream ports; each port can either be empty or connect to exactly one 设备. The tree is rebuilt on boot and updated every time a 设备 is connected or disconnected. On FreeBSD, `usbconfig` shows this tree; on a fresh boot of a typical desktop you will see something like: +*树状结构*意味着USB设备不像I2C总线或旧式ISA总线上的设备那样连接在共享线上。每个USB设备恰好有一个上游连接,连接到父集线器。树的根部是*根集线器*,由USB主机控制器暴露。根集线器的下游是其他集线器和设备。一个集线器有固定数量的下游端口;每个端口可以为空或恰好连接一个设备。这棵树在启动时重建,并在每次设备连接或断开时更新。在FreeBSD上,`usbconfig` 显示这棵树;在典型桌面的全新启动上,你会看到类似以下内容: ```text ugen0.1: at usbus0, cfg=0 md=HOST spd=HIGH @@ -207,37 +207,37 @@ ugen0.2: at usbus0, cfg=0 md=HOST spd=HIGH ugen0.3: at usbus0, cfg=0 md=HOST spd=LOW ``` -The tree structure matters to a 驱动程序 author for two reasons. First, it tells you that when you write a USB驱动程序, your 驱动程序's *parent* in the New总线 tree is `uhub`. Every USB 设备 sits under a hub. When you write `DRIVER_MODULE(myfirst_usb, uhub, ...)`, you are telling the 内核 "my 驱动程序 附加 to children of `uhub`," which is the FreeBSD way of saying "my 驱动程序 附加 to USB 设备." Second, the tree structure means that enumeration is dynamic. The 内核 does not know what 设备 are on the tree until the tree is walked; a 驱动程序 is offered each 设备 as it appears, and has to decide whether to claim it. +树状结构对驱动程序作者来说很重要,有两个原因。第一,它告诉你当你编写USB驱动程序时,你的驱动程序在Newbus树中的*父设备*是 `uhub`。每个USB设备都位于一个集线器之下。当你编写 `DRIVER_MODULE(myfirst_usb, uhub, ...)` 时,你是在告诉内核"我的驱动程序附加到 `uhub` 的子设备",这是FreeBSD表达"我的驱动程序附加到USB设备"的方式。第二,树状结构意味着枚举是动态的。内核在遍历树之前不知道树上有哪些设备;驱动程序在设备出现时被依次提供给每个设备,并必须决定是否认领它。 -*Host-controlled* means that one side of the 总线 is the master, the *host*, and all other sides are slaves, the *设备*. The host initiates every transfer; 设备 respond. A USB keyboard does not push keystrokes to the host whenever a key is pressed; the host polls the keyboard on an *interrupt 端点* many times per second, and the keyboard replies with "no new keys" or "key 'A' has been pressed" in response to each poll. This polling-and-response model has important consequences for a 驱动程序. Your 驱动程序, running on the host, has to initiate every transfer. A 设备 cannot spontaneously send data; it can only respond when the host asks. What looks from user space like "the 驱动程序 received data" is always, underneath, "the 驱动程序 had a pending receive transfer and the 主机控制器 notified us that the transfer completed." +*主机控制*意味着总线的一侧是主设备,即*主机*,所有其他侧是从设备,即*设备*。主机发起每一次传输;设备响应。一个USB键盘不会在按键被按下时向主机推送按键信息;主机每秒在一个*中断端点*上轮询键盘多次,键盘以"没有新按键"或"按键'A'已被按下"来响应每次轮询。这种轮询-响应模型对驱动程序有重要的影响。你的驱动程序运行在主机上,必须发起每一次传输。设备不能自发地发送数据;它只能在主机请求时响应。从用户空间看起来的"驱动程序接收了数据",在底层始终是"驱动程序有一个待处理的接收传输,主机控制器通知我们传输已完成"。 -For most of this chapter's purposes, you are writing *host-mode* 驱动程序: 驱动程序 that run on the host side. A FreeBSD system can also be configured as a USB *设备*, through the `usb_template(4)` subsystem, and present itself as a keyboard or mass storage 设备 or CDC 以太网 接口 to another host. Device-mode 驱动程序 are a specialised topic touched on only briefly in Section 5 for testing purposes. +出于本章大部分内容的目的,你是在编写*主机模式*驱动程序:运行在主机端的驱动程序。FreeBSD系统也可以通过 `usb_template(4)` 子系统配置为USB*设备*,并将自己呈现为键盘、大容量存储设备或CDC以太网接口给另一个主机。设备模式的驱动程序是一个专门的主题,仅在第5节中为测试目的简要涉及。 -*Hot-pluggable* means that 设备 can appear and disappear while the system is running, and the subsystem has to cope. The USB 主机控制器 notices when a 设备 is plugged in, a hub's port status 寄存器 tell it so, enumerates the new 设备 by asking it for its 描述符, assigns it an address on the 总线, and then offers it to any 驱动程序 whose 匹配表 applies. When a 设备 is unplugged, the 主机控制器 notices the port status change and tells the subsystem, which in turn calls the 驱动程序's 分离 method. The 分离 method may run at any time, including while the 驱动程序 is holding a transfer that will now never complete, while user space has the 驱动程序's `/dev` node open, or while the system is under load. Writing a correct 分离 method is the single hardest part of USB驱动程序 development. The chapter returns to this repeatedly. +*热插拔*意味着设备可以在系统运行时出现和消失,子系统必须能够应对。USB主机控制器注意到设备被插入,集线器的端口状态寄存器告知它这一点,然后它通过向新设备请求其描述符来枚举它,在总线上分配一个地址,然后将其提供给任何匹配表适用的驱动程序。当设备被拔出时,主机控制器注意到端口状态变化并告知子系统,子系统依次调用驱动程序的分离方法。分离方法可能在任何时间运行,包括当驱动程序正在持有一个现在永远不会完成的传输时、当用户空间打开了驱动程序的 `/dev` 节点时,或当系统处于负载状态时。编写正确的分离方法是USB驱动程序开发中唯一最困难的部分。本章会反复回到这个话题。 -*Serial* means that USB is a wire-level serial protocol: bytes flow one after another on a differential pair. The speed of the 总线 has evolved over the years: low-speed (1.5 Mbps), full-speed (12 Mbps), high-speed (480 Mbps), SuperSpeed (5 Gbps), and faster variants above that. From a 驱动程序 author's perspective, the speed is mostly transparent: the 主机控制器 and the USB core handle the electrical layer and the 数据包 framing, and your 驱动程序 works at the level of "here is a 缓冲区, please send it" or "here is a 缓冲区, please fill it." The speed determines how fast data can move, but the 驱动程序 code is the same. +*串行*意味着USB是一种线路层的串行协议:字节在差分对上一个接一个地流动。总线的速度多年来不断演进:低速(1.5 Mbps)、全速(12 Mbps)、高速(480 Mbps)、超高速(5 Gbps)以及更快的变体。从驱动程序作者的角度来看,速度大部分是透明的:主机控制器和USB核心处理电气层和数据包成帧,你的驱动程序工作在"这是一个缓冲区,请发送它"或"这是一个缓冲区,请填充它"的层面。速度决定了数据移动的速度,但驱动程序代码是相同的。 -With those four adjectives in place, the rest of the USB model falls into shape. +有了这四个形容词,USB模型的其余部分就形成了。 -#### Device Classes and What They Mean to a Driver +#### 设备类及其对驱动程序的意义 -Every USB 设备 belongs to one or more *classes*, and the class tells the host (and the 驱动程序) what kind of 设备 it is. Classes are numerical, defined by the USB Implementers Forum, and the values appear in 描述符. The ones a FreeBSD 驱动程序 author will see most often include: +每个USB设备属于一个或多个*类*,类告诉主机(和驱动程序)它是什么类型的设备。类是数值的,由USB实现者论坛定义,值出现在描述符中。FreeBSD驱动程序作者最常看到的包括: -- **HID (Human Interface Device)**, class 0x03. Keyboards, mice, joysticks, game controllers, and a long tail of programmable 设备 that pretend to be keyboards or mice. HID 设备 present reports through interrupt 端点; FreeBSD's HID subsystem handles them mostly generically, though a vendor-specific 驱动程序 can override. -- **Mass Storage**, class 0x08. USB flash drives, external disks, card readers. These 附加 through `umass(4)` to the CAM storage 框架. -- **Communications (CDC)**, class 0x02, with subclasses for ACM (modem-like serial), ECM (以太网), NCM (以太网 with multi-数据包 aggregation), and others. CDC ACM 设备 appear through `ucom(4)` as 串行端口s. CDC ECM and NCM 设备 appear through `cdce(4)` as 网络接口. -- **Audio**, class 0x01. Microphones, speakers, audio 接口. FreeBSD's audio stack handles these through `uaudio(4)`. -- **Printer**, class 0x07. USB printers. Handled through `ulpt(4)`. -- **Hub**, class 0x09. USB hubs themselves. Handled by the core `uhub(4)` 驱动程序. -- **Vendor-specific**, class 0xff. Any 设备 whose functionality does not fit a standard class. Almost every interesting hobby USB 设备 (USB-to-serial bridges, thermometers, relay controllers, programmers, loggers) is in this class. +- **HID(人机接口设备)**,类 0x03。键盘、鼠标、游戏杆、游戏控制器以及大量伪装成键盘或鼠标的可编程设备。HID设备通过中断端点呈现报告;FreeBSD的HID子系统以通用方式处理它们,尽管供应商特定的驱动程序可以覆盖。 +- **大容量存储**,类 0x08。USB闪存盘、外部磁盘、读卡器。它们通过 `umass(4)` 附加到CAM存储框架。 +- **通信(CDC)**,类 0x02,包括ACM(类似调制解调器的串行)、ECM(以太网)、NCM(带多数据包聚合的以太网)等子类。CDC ACM设备通过 `ucom(4)` 以串行端口形式出现。CDC ECM和NCM设备通过 `cdce(4)` 以网络接口形式出现。 +- **音频**,类 0x01。麦克风、扬声器、音频接口。FreeBSD的音频栈通过 `uaudio(4)` 处理它们。 +- **打印机**,类 0x07。USB打印机。通过 `ulpt(4)` 处理。 +- **集线器**,类 0x09。USB集线器本身。由核心的 `uhub(4)` 驱动程序处理。 +- **供应商特定**,类 0xff。任何功能不适合标准类的设备。几乎所有有趣的业余USB设备(USB转串行桥接器、温度计、继电器控制器、编程器、记录器)都属于此类。 -When you write a USB驱动程序, you often write for a vendor-specific 设备 (class 0xff) and match on vendor/product identifiers. Occasionally you write for a standard-class 设备 that FreeBSD does not yet handle, or for a standard-class 设备 that has quirks requiring a dedicated 驱动程序. The class is not usually the match criterion; the vendor/product pair is. But the class tells you what 框架, if any, you should integrate with. If the 设备's class is CDC ACM, the right 框架 is `ucom`. If the class is HID, the right 框架 is `hid总线` (new in FreeBSD 14). If the class is 0xff, there is no 框架; you write a bespoke 驱动程序. +当你编写USB驱动程序时,你通常是为供应商特定的设备(类 0xff)编写,并在供应商/产品标识符上进行匹配。偶尔你会为FreeBSD尚未处理的标准类设备编写,或者为有quirk需要专用驱动程序的标准类设备编写。类通常不是匹配条件;供应商/产品对才是。但类告诉你应该与哪个框架集成(如果有的话)。如果设备的类是CDC ACM,正确的框架是 `ucom`。如果类是HID,正确的框架是 `hidbus`(FreeBSD 14新增)。如果类是 0xff,没有框架;你编写一个定制的驱动程序。 -#### Descriptors: The Device's Self-Description +#### 描述符:设备的自我描述 -When the host enumerates a new USB 设备, it asks the 设备 to describe itself. The 设备 responds with a hierarchy of *描述符*. Descriptors are the single most important USB concept to get clear: they are the USB equivalent of the PCI configuration space, but richer and nested. +当主机枚举一个新的USB设备时,它要求设备描述自己。设备以一个*描述符*层次结构来响应。描述符是需要弄清楚的最重要USB概念:它们相当于USB的PCI配置空间,但更丰富且嵌套。 -The hierarchy is: +层次结构如下: ```text Device descriptor @@ -246,224 +246,224 @@ Device descriptor Endpoint descriptor [0..E] ``` -A *设备 描述符* (`struct usb_设备_描述符` in `/usr/src/sys/dev/usb/usb.h`) describes the 设备 as a whole: its vendor identifier (`idVendor`), its product identifier (`idProduct`), its 设备 class, subclass, and protocol, its maximum 数据包 size on 端点 zero, its release number, and the number of configurations it supports. Most 设备 have one configuration, but the USB spec allows more (a camera that can run in high-bandwidth or low-bandwidth modes, for example). +*设备描述符*(`/usr/src/sys/dev/usb/usb.h` 中的 `struct usb_device_descriptor`)描述设备整体:其供应商标识符(`idVendor`)、产品标识符(`idProduct`)、设备类、子类和协议、端点零上的最大数据包大小、其版本号以及它支持的配置数量。大多数设备有一个配置,但USB规范允许更多(例如,一个可以以高带宽或低带宽模式运行的相机)。 -A *configuration 描述符* (`struct usb_config_描述符`) describes one mode of operation: the number of 接口 it contains, whether the 设备 is self-powered or 总线-powered, its maximum power draw. When a 驱动程序 selects a configuration (by calling `usbd_req_set_config`, though in practice the USB core does this for you), the 设备's 端点 are activated. +*配置描述符*(`struct usb_config_descriptor`)描述一种操作模式:它包含的接口数量、设备是自供电还是总线供电、其最大功耗。当驱动程序选择一个配置时(通过调用 `usbd_req_set_config`,尽管实际上USB核心为你做了这件事),设备的端点被激活。 -An *接口 描述符* (`struct usb_接口_描述符`) describes one logical function of the 设备. A composite 设备, such as a USB printer with a built-in scanner, has one 接口 per function. Each 接口 has its own class, subclass, and protocol. A 驱动程序 can match on 接口 class rather than 设备 class; this is common when a 设备's overall class is "Miscellaneous" or "Composite" but one of its 接口 has a specific class. An 接口 can have multiple *alternate settings*, which select different 端点 layouts; audio streaming 接口 use alternate settings to offer different bandwidths. +*接口描述符*(`struct usb_interface_descriptor`)描述设备的一个逻辑功能。一个复合设备,例如带有内置扫描仪的USB打印机,每个功能有一个接口。每个接口有自己的类、子类和协议。驱动程序可以在接口类而不是设备类上进行匹配;当设备的整体类是"Miscellaneous"或"Composite"但其中一个接口有特定类时,这很常见。一个接口可以有多个*备用设置*,用于选择不同的端点布局;音频流接口使用备用设置来提供不同的带宽。 -An *端点 描述符* (`struct usb_端点_描述符`) describes one data channel. Endpoints have: +*端点描述符*(`struct usb_endpoint_descriptor`)描述一个数据通道。端点有: -- An *address*, which is the 端点 number (0 through 15) combined with a direction bit (IN, meaning from 设备 to host, or OUT, meaning from host to 设备). -- A *type*, which is one of control, bulk, interrupt, or isochronous. -- A *maximum 数据包 size*, which is the largest single 数据包 the 端点 can handle. -- An *interval*, which for interrupt and isochronous 端点 tells the host how often to poll. +- 一个*地址*,是端点号(0到15)与方向位(IN,表示从设备到主机,或OUT,表示从主机到设备)的组合。 +- 一个*类型*,是控制、批量、中断或等时之一。 +- 一个*最大数据包大小*,是端点可以处理的最大单个数据包。 +- 一个*间隔*,对于中断和等时端点,告诉主机多久轮询一次。 -Endpoint zero is special: every 设备 has it, it is always a control 端点, and it is always bidirectional (one IN half and one OUT half). The USB core uses 端点 zero for enumeration (asking the 设备 for 描述符, setting its address, selecting its configuration). A 驱动程序 can also use 端点 zero for vendor-specific control requests, though 驱动程序 usually access it through helper functions rather than setting up a transfer directly. +端点零是特殊的:每个设备都有它,它始终是控制端点,并且始终是双向的(一个IN半部和一个OUT半部)。USB核心使用端点零进行枚举(向设备请求描述符、设置其地址、选择其配置)。驱动程序也可以使用端点零进行供应商特定的控制请求,不过驱动程序通常通过辅助函数访问它,而不是直接设置传输。 -The 描述符 hierarchy matters to a 驱动程序 because the 驱动程序's `探测` method has access to the 描述符 through the `struct usb_附加_arg` it receives, and its match logic often reads fields from them. The `struct usbd_lookup_info` inside `struct usb_附加_arg` carries the 设备's identifiers, its class, subclass, and protocol, the current 接口's class, subclass, and protocol, and a few other fields. The 匹配表 filters on some subset of those; the helper macros `USB_VP(v, p)`, `USB_VPI(v, p, info)`, `USB_IFACE_CLASS(c)`, and similar build entries that match different combinations of fields. +描述符层次结构对驱动程序很重要,因为驱动程序的 `probe` 方法可以通过它接收的 `struct usb_attach_arg` 访问描述符,其匹配逻辑通常从中读取字段。`struct usb_attach_arg` 中的 `struct usbd_lookup_info` 携带设备的标识符、其类、子类和协议、当前接口的类、子类和协议以及其他一些字段。匹配表对这些字段的某个子集进行过滤;辅助宏 `USB_VP(v, p)`、`USB_VPI(v, p, info)`、`USB_IFACE_CLASS(c)` 等构建匹配不同字段组合的条目。 -#### The Four Transfer Types +#### 四种传输类型 -USB defines four transfer types, each suited to a different kind of data movement. A 驱动程序 picks one or more types for its 端点, and the choice affects everything about how the 驱动程序 is structured. +USB定义了四种传输类型,每种适用于不同类型的数据移动。驱动程序为其端点选择一种或多种类型,该选择影响驱动程序结构的一切。 -*Control transfers* are for setup, configuration, and command exchange. Every 设备 supports them on 端点 zero. They have a small, structured format: an eight-byte setup 数据包 (the `struct usb_设备_request`) followed by an optional data stage and a status stage. The setup 数据包 specifies what the request is doing: its direction (IN or OUT), its type (standard, class, or vendor), its recipient (设备, 接口, or 端点), and four fields (`bRequest`, `wValue`, `wIndex`, `wLength`) whose meaning depends on the request. Standard requests include `GET_DESCRIPTOR`, `SET_CONFIGURATION`, and so on; class and vendor requests are defined by the class specification or the vendor. Control transfers are reliable: the 总线 protocol guarantees delivery or returns a specific error. They are also relatively slow, because the 总线 allocates only a small share of its bandwidth to them. +*控制传输*用于设置、配置和命令交换。每个设备在端点零上支持它们。它们有一个小型、结构化的格式:一个八字节的设置数据包(`struct usb_device_request`)后跟一个可选的数据阶段和一个状态阶段。设置数据包指定请求正在做什么:其方向(IN或OUT)、其类型(标准、类或供应商)、其接收者(设备、接口或端点)以及四个字段(`bRequest`、`wValue`、`wIndex`、`wLength`),其含义取决于请求。标准请求包括 `GET_DESCRIPTOR`、`SET_CONFIGURATION` 等;类和供应商请求由类规范或供应商定义。控制传输是可靠的:总线协议保证交付或返回特定错误。它们也相对较慢,因为总线只分配很小一部分带宽给它们。 -*Bulk transfers* are for large, reliable, non-time-critical data. A USB flash drive uses 批量传输 for the actual data. A printer uses bulk OUT for the print stream. A USB-to-serial bridge uses bulk IN and bulk OUT for the two directions of the serial stream. Bulk transfers are reliable (errors are retried by the 总线 hardware), but they have no guaranteed timing: they use whatever bandwidth is left after control, interrupt, and isochronous traffic has been scheduled. In practice, on a lightly-loaded 总线, 批量传输 are very fast. On a heavily-loaded 总线, they can stall for milliseconds at a time. Bulk 端点 are the most common 端点 type for 设备-to-host or host-to-设备 streaming of data where latency is not critical. +*批量传输*用于大量、可靠、非时间关键的数据。USB闪存盘使用批量传输来传输实际数据。打印机使用批量OUT来传输打印流。USB转串行桥接器使用批量IN和批量OUT来传输串行流的两个方向。批量传输是可靠的(错误由总线硬件重试),但它们没有保证的时序:它们使用在控制、中断和等时流量被调度后剩余的任何带宽。在实践中,在轻负载的总线上,批量传输非常快。在重负载的总线上,它们可能一次停滞数毫秒。批量端点是在延迟不关键的设备到主机或主机到设备数据流中最常见的端点类型。 -*Interrupt transfers* are for small, time-sensitive data. The name is misleading: there are no hardware interrupts here. The "interrupt" refers to the fact that the 设备 needs to get the host's attention periodically, and the host polls the 端点 at a configurable interval to see whether there is new data. A USB keyboard uses 中断传输 to deliver keystrokes; a USB mouse uses them for movement reports; a thermometer uses them to deliver periodic readings. Interrupt 端点 have an `interval` field that tells the host how often to poll (in milliseconds for low- and full-speed 设备, in micro帧 for high-speed). A 驱动程序 that wants to know about input as it happens sets up an interrupt-IN transfer, submits it, and the USB core arranges the polling. When data arrives, the 驱动程序's 回调 fires. +*中断传输*用于小型、时间敏感的数据。这个名字有误导性:这里没有硬件中断。"中断"指的是设备需要定期引起主机的注意,主机以可配置的间隔轮询端点以查看是否有新数据。USB键盘使用中断传输来传递按键信息;USB鼠标使用它们来传递移动报告;温度计使用它们来传递周期性读数。中断端点有一个 `interval` 字段,告诉主机多久轮询一次(对于低速和全速设备以毫秒为单位,对于高速以微帧为单位)。一个希望在输入发生时就得到通知的驱动程序设置一个中断IN传输,提交它,USB核心安排轮询。当数据到达时,驱动程序的回调被触发。 -*Isochronous transfers* are for streaming data with guaranteed bandwidth but no error recovery. USB audio and USB video use isochronous 端点. The 总线 reserves a fixed share of each 帧 for isochronous traffic, so the bandwidth is predictable, but transfers are not retried on error; if a 数据包 is corrupted, it is lost. This trade-off makes sense for audio and video, where a dropped sample is better than a stall. Isochronous transfers are the most complex to program because they typically operate on many small 帧 per transfer; the `struct usb_xfer` machinery supports up to thousands of 帧 per transfer. 第26章 introduces 等时传输 at the conceptual level and does not develop them further; real isochronous 驱动程序 (audio, video) are beyond the chapter's scope. +*等时传输*用于具有保证带宽但没有错误恢复的流数据。USB音频和USB视频使用等时端点。总线为每个帧保留固定份额给等时流量,因此带宽是可预测的,但传输在错误时不被重试;如果一个数据包损坏,它就丢失了。这种权衡对音频和视频是有意义的,因为丢弃一个样本比一个停滞要好。等时传输编程最复杂,因为它们通常在一次传输中操作许多小帧;`struct usb_xfer` 机制支持每次传输多达数千帧。第26章在概念层面介绍等时传输,不会进一步展开;真正的等时驱动程序(音频、视频)超出了本章的范围。 -A typical vendor-specific USB 设备 that a hobbyist or a 驱动程序-development learner will write code for looks like this: a vendor/product identifier, one vendor-specific 接口, one bulk-IN 端点, one bulk-OUT 端点, and possibly an interrupt-IN 端点 for status events. That is the shape of the worked example in Sections 2 and 3. +一个业余爱好者或驱动程序开发学习者通常会编写的典型供应商特定USB设备看起来像这样:一个供应商/产品标识符、一个供应商特定的接口、一个批量IN端点、一个批量OUT端点,可能还有一个用于状态事件的中断IN端点。这就是第2节和第3节中示例的形态。 -#### The USB Hot-Plug Lifecycle +#### USB热插拔生命周期 -The 热插拔 lifecycle is the sequence of events that happens when a USB 设备 is inserted, in use, and removed. Writing a 驱动程序 that handles this lifecycle correctly is the most important single discipline in USB驱动程序 development. +热插拔生命周期是USB设备被插入、使用和移除时发生的事件序列。编写一个正确处理此生命周期的驱动程序是USB驱动程序开发中最重要的单项技能。 -When a 设备 is inserted, the 主机控制器 notices a port status change. It waits for the 设备 to stabilise, then resets the port and assigns the 设备 a temporary address of zero. It sends `GET_DESCRIPTOR` to 端点 zero on address zero, retrieves the 设备 描述符, and then assigns the 设备 a unique address with `SET_ADDRESS`. All subsequent communication uses the new address. The host sends `GET_DESCRIPTOR` for the full configuration 描述符 (including 接口 and 端点), chooses a configuration, and sends `SET_CONFIGURATION`. At that point the 设备's 端点 are active and the USB subsystem offers the 设备 to every 注册ed 驱动程序 in turn by calling each 驱动程序's `探测` method. The first 驱动程序 to claim the 设备 by returning a non-error code from `探测` wins; the subsystem then calls that 驱动程序's `附加` method. +当设备被插入时,主机控制器注意到端口状态变化。它等待设备稳定,然后重置端口并给设备分配一个临时地址零。它向地址零的端点零发送 `GET_DESCRIPTOR`,获取设备描述符,然后使用 `SET_ADDRESS` 给设备分配一个唯一地址。所有后续通信使用新地址。主机发送 `GET_DESCRIPTOR` 获取完整的配置描述符(包括接口和端点),选择一个配置,并发送 `SET_CONFIGURATION`。此时设备的端点处于活动状态,USB子系统通过调用每个已注册驱动程序的 `probe` 方法依次将设备提供给每个驱动程序。第一个通过从 `probe` 返回非错误代码来认领设备的驱动程序获胜;子系统随后调用该驱动程序的 `attach` 方法。 -During normal operation, the 驱动程序 submits transfers to its 端点, the 主机控制器 schedules them on the 总线, and the 回调 fire on completion. This is the steady state 第26章's code examples operate in. +在正常操作期间,驱动程序向其端点提交传输,主机控制器在总线上调度它们,回调在完成时触发。这就是第26章代码示例运行的稳定状态。 -When the 设备 is removed, the 主机控制器 notices another port status change. It does not wait; the electrical signal is gone immediately. The subsystem cancels any outstanding transfers on the 设备's 端点 (they complete in the 回调 with `USB_ERR_CANCELLED`), and then it calls the 驱动程序's `分离` method. The `分离` method has to release every resource the `附加` method acquired, including any `/dev` nodes it created, any locks, any 缓冲区, and any transfers. It has to do this in the face of the fact that other threads may be in the middle of calling into the 驱动程序 through those resources. A read in progress must be woken up and returned with an error. An ioctl in progress must be allowed to finish or interrupted. A 回调 that has just fired with `USB_ERR_CANCELLED` must not try to re-submit. +当设备被移除时,主机控制器注意到另一个端口状态变化。它不等待;电信号立即消失。子系统取消设备端点上所有未完成的传输(它们在回调中以 `USB_ERR_CANCELLED` 完成),然后调用驱动程序的 `detach` 方法。`detach` 方法必须释放 `attach` 方法获取的每一个资源,包括它创建的任何 `/dev` 节点、任何锁、任何缓冲区和任何传输。它必须在其他线程可能正在通过这些资源调用驱动程序的情况下来完成这些工作。一个正在进行中的读取必须被唤醒并返回错误。一个正在进行中的ioctl必须被允许完成或被中断。一个刚刚以 `USB_ERR_CANCELLED` 触发的回调不能尝试重新提交。 -The 热插拔 lifecycle is why USB驱动程序 cannot be written the way pseudo-驱动程序 are written. In a pseudo-驱动程序, the module lifecycle (`kldload`/`kldunload`) is the only lifecycle; nothing unexpected happens. In a USB驱动程序, the 设备 lifecycle is separate from the module lifecycle and is driven by physical events. A user can unplug the 设备 while a user-space process is 块ed in `read()` on the 驱动程序's `/dev` node. The 驱动程序 must wake that process up and return an error. A well-written USB驱动程序 treats this as the normal case, not the edge case. +热插拔生命周期就是为什么USB驱动程序不能用伪驱动程序的方式编写的原因。在伪驱动程序中,模块生命周期(`kldload`/`kldunload`)是唯一的生命周期;不会发生意外的事情。在USB驱动程序中,设备生命周期与模块生命周期是分开的,由物理事件驱动。用户可以在用户空间进程在驱动程序的 `/dev` 节点上阻塞在 `read()` 中时拔出设备。驱动程序必须唤醒该进程并返回错误。一个编写良好的USB驱动程序将此视为正常情况,而非边界情况。 -Section 2 will walk through the structure of a USB驱动程序 that handles this correctly. For now, keep the lifecycle in mind: 探测, 附加, steady-state transfers, 分离. Every USB驱动程序 has that sequence. +第2节将演示一个正确处理此情况的USB驱动程序的结构。现在,请记住生命周期:探测、附加、稳定状态传输、分离。每个USB驱动程序都有这个序列。 -#### USB Speeds and What They Imply +#### USB速度及其影响 -USB has gone through several speed generations, and each matters to a 驱动程序 writer in different ways. Low-speed (1.5 Mbps) was the original USB 1.0 speed, mostly used by keyboards and mice. Full-speed (12 Mbps) was USB 1.1, used by printers, early cameras, and mass-storage 设备. High-speed (480 Mbps) was USB 2.0, which became the dominant speed for most 设备 in the 2000s. SuperSpeed (5 Gbps) was USB 3.0, which added a separate physical layer for high-throughput applications. SuperSpeed+ (10 Gbps and 20 Gbps) came with USB 3.1 and 3.2. USB 4.0 reuses the Thunderbolt physical layer and supports 40 Gbps. +USB经历了几个速度代际,每一代对驱动程序编写者都有不同的影响。低速(1.5 Mbps)是USB 1.0的原始速度,主要用于键盘和鼠标。全速(12 Mbps)是USB 1.1,用于打印机、早期相机和大容量存储设备。高速(480 Mbps)是USB 2.0,在2000年代成为大多数设备的主流速度。超高速(5 Gbps)是USB 3.0,为高吞吐量应用添加了独立的物理层。超高速+(10 Gbps和20 Gbps)随USB 3.1和3.2出现。USB 4.0复用Thunderbolt物理层,支持40 Gbps。 -For most 驱动程序 writing, only three differences between these speeds matter: +对于大多数驱动程序编写,这些速度之间只有三个差异是重要的: -**Maximum 数据包 size.** Low-speed 端点 have a maximum 数据包 size of 8 bytes. Full-speed goes up to 64 bytes. High-speed bulk 端点 go up to 512 bytes. SuperSpeed bulk 端点 go up to 1024 bytes with burst support. Your 缓冲区 sizes in the transfer configuration should match the 端点's speed; using a 512-byte 缓冲区 on a full-speed bulk 端点 wastes memory because only 64 bytes fit in each 数据包. +**最大数据包大小。**低速端点的最大数据包大小为8字节。全速最高到64字节。高速批量端点最高到512字节。超高速批量端点最高到1024字节并支持突发。你在传输配置中的缓冲区大小应该与端点的速度匹配;在全速批量端点上使用512字节缓冲区是浪费内存,因为每个数据包只能容纳64字节。 -**Isochronous bandwidth.** Isochronous transfers reserve bandwidth at a specific speed. A 设备 that asks for 1 MB/s of isochronous bandwidth can only be supported on a 主机控制器 that can provide it; on slower hosts, the 设备 must negotiate a lower rate or fail. This is why some USB audio 设备 work on one port but not another. +**等时带宽。**等时传输以特定速度保留带宽。一个要求1 MB/s等时带宽的设备只能在能够提供该带宽的主机控制器上支持;在较慢的主机上,设备必须协商较低的速率或失败。这就是为什么一些USB音频设备在一个端口上工作而在另一个上不工作。 -**Endpoint polling interval.** Interrupt 端点 are polled at a specific interval encoded in the 描述符's `bInterval` field. The units are milliseconds at low/full speed and "125 microsecond micro帧" at high/SuperSpeed. The 框架 handles the math; your 驱动程序 just declares the logical polling interval via the 端点 描述符 and the 框架 does the right thing. +**端点轮询间隔。**中断端点以描述符 `bInterval` 字段中编码的特定间隔轮询。单位在低速/全速时为毫秒,在高速/超高速时为"125微秒微帧"。框架处理数学运算;你的驱动程序只需通过端点描述符声明逻辑轮询间隔,框架会做正确的事情。 -For the 驱动程序 we write in this chapter (`myfirst_usb` and the UART bridges like FTDI), speed does not affect the code structure. A bulk-IN channel's 回调 is the same whether it runs at 12 Mbps or 5 Gbps. The differences are in the numbers, not the flow. +对于我们本章编写的驱动程序(`myfirst_usb` 和像FTDI这样的UART桥接器),速度不影响代码结构。一个批量IN通道的回调在12 Mbps或5 Gbps下运行是相同的。差异在于数字,而不在于流程。 -#### Endpoints, FIFOs, and Flow Control +#### 端点、FIFO和流控制 -A USB 端点 is logically an I/O queue at one end of a pipe. On the 设备 side, an 端点 corresponds to a hardware FIFO in the chip. On the host side, the 端点 is a 框架 abstraction. Between them, USB 数据包 flow under the control of the USB protocol itself, which handles retransmission, sequencing, and error detection. +USB端点在逻辑上是管道一端的I/O队列。在设备侧,端点对应芯片中的硬件FIFO。在主机侧,端点是框架抽象。在它们之间,USB数据包在USB协议本身的控制下流动,协议处理重传、排序和错误检测。 -The host cannot be told "the 设备 is full" the way you might expect on a traditional serial link. Instead, when a 设备 cannot accept more data (because its FIFO is full), it returns a NAK handshake. NAK means "try again later." The host will keep retrying, at the protocol level, until either the 设备 accepts the data (returns ACK) or some higher-level timeout fires. This is called NAK-limiting or 总线 throttling, and it happens invisibly to the 驱动程序: the 框架 sees the final ACK and delivers a successful completion. +主机不能像在传统串行链路上预期的那样被告知"设备已满"。相反,当设备无法接受更多数据时(因为其FIFO已满),它返回一个NAK握手。NAK意味着"稍后重试"。主机将在协议层持续重试,直到设备接受数据(返回ACK)或某个更高级别的超时触发。这被称为NAK限制或总线节流,它对驱动程序是不可见的:框架看到最终的ACK并交付一个成功的完成。 -Similarly, when the 设备 has no data to send (for a bulk-IN or interrupt-IN transfer), it returns NAK to the IN token, and the host polls again. From the 驱动程序's perspective, the transfer is simply "pending" until the 设备 has something to say. +类似地,当设备没有数据要发送时(对于批量IN或中断IN传输),它对IN令牌返回NAK,主机再次轮询。从驱动程序的角度来看,传输只是"待处理"的,直到设备有话要说。 -This NAK mechanism is how USB handles 流控制 at the protocol level. Your 驱动程序 does not need to implement its own throttling logic for bulk and interrupt channels; the USB protocol does it. Where 流控制 does come into play is in higher-level protocols, where the 设备 might want to signal a logical end-of-message or a temporary unavailability. Those signals are protocol-specific and not part of USB itself. +这种NAK机制是USB在协议层处理流控制的方式。你的驱动程序不需要为批量和中断通道实现自己的节流逻辑;USB协议会处理它。流控制确实发挥作用的地方是在更高级别的协议中,设备可能想要发出逻辑上的消息结束或临时不可用的信号。这些信号是协议特定的,不属于USB本身。 -#### Descriptors In Depth +#### 深入了解描述符 -USB 描述符 are the self-describing mechanism by which a 设备 tells the host what it is and how to talk to it. We introduced them briefly earlier; here is a more complete picture. +USB描述符是设备向主机描述自己以及如何与其通信的自我描述机制。我们之前简要介绍了它们;这里给出更完整的图景。 -The 设备 描述符 is the root. It contains the 设备's 供应商ID, 产品ID, USB specification version, 设备 class/subclass/protocol (for 设备 that declare themselves at the 设备 level rather than the 接口 level), maximum 数据包 size for 端点 zero, and the number of configurations. +设备描述符是根。它包含设备的供应商标识符、产品标识符、USB规范版本、设备类/子类/协议(对于在设备级别而非接口级别声明自己的设备)、端点零的最大数据包大小以及配置数量。 -Configuration 描述符 describe complete configurations. A configuration is a set of 接口 that work together. Most 设备 have one configuration; some have multiple to support different modes of operation (e.g., a 设备 that can be either a printer or a scanner, selected by configuration). +配置描述符描述完整的配置。配置是一组协同工作的接口。大多数设备有一个配置;有些有多个以支持不同的操作模式(例如,一个可以通过配置选择作为打印机或扫描仪的设备)。 -Interface 描述符 describe functional subsets of the 设备. Each 接口 has a class, subclass, and protocol that tells the host what kind of 驱动程序 to use. A multi-function 设备 has multiple 接口 描述符 in the same configuration. Additionally, an 接口 can have alternate settings: different sets of 端点 selectable on the fly for things like "low bandwidth mode" vs "high bandwidth mode". +接口描述符描述设备的功能子集。每个接口有一个类、子类和协议,告诉主机使用哪种驱动程序。多功能设备在同一个配置中有多个接口描述符。此外,一个接口可以有备用设置:可以选择不同的端点集合,用于"低带宽模式"与"高带宽模式"之类的情况。 -Endpoint 描述符 describe individual 端点 within an 接口. Each has an address (with direction bit), a transfer type, a maximum 数据包 size, and an interval (for interrupt and isochronous 端点). +端点描述符描述接口内的单个端点。每个端点有一个地址(带方向位)、一个传输类型、一个最大数据包大小和一个间隔(用于中断和等时端点)。 -String 描述符 hold human-readable strings: the manufacturer name, the product name, the serial number. These are optional; their presence is indicated by nonzero string indices in the other 描述符. +字符串描述符包含人类可读的字符串:制造商名称、产品名称、序列号。这些是可选的;它们的存在由其他描述符中的非零字符串索引指示。 -Class-specific 描述符 extend the standard 描述符 with class-specific metadata. HID 设备 have a report 描述符 that describes the format of the reports they send. Audio 设备 have 描述符 for audio controls. Mass-storage 设备 have 描述符 for 接口 subclasses. +类特定描述符用类特定的元数据扩展标准描述符。HID设备有一个报告描述符,描述它们发送的报告格式。音频设备有用于音频控制的描述符。大容量存储设备有用于接口子类的描述符。 -The USB 框架 parses all of this at enumeration time and exposes the parsed data to 驱动程序 through the `struct usb_附加_arg`. Your 驱动程序 does not have to read 描述符 itself; it queries the 框架 for the information it needs. When the chapter says "the 接口's `bInterfaceClass`", what is meant is "the `bInterfaceClass` field of the 接口 描述符 the 框架 parsed and cached for us." +USB框架在枚举时解析所有这些内容,并通过 `struct usb_attach_arg` 将解析后的数据暴露给驱动程序。你的驱动程序不必自己读取描述符;它查询框架获取所需的信息。当本章说"接口的 `bInterfaceClass`"时,指的是"框架为我们解析并缓存的接口描述符的 `bInterfaceClass` 字段。" -`usbconfig -d ugenN.M dump_all_config_desc` is how you see the parsed 描述符 from userland. Run that command on a few 设备 you own and note how the 描述符 look. You will see that even simple 设备 like a mouse have a nontrivial 描述符 tree: typically one 设备 描述符, one configuration 描述符, one 接口 描述符 (with class=HID), and one or two 端点 描述符 (for the HID report input and maybe an output). +`usbconfig -d ugenN.M dump_all_config_desc` 是从用户空间查看已解析描述符的方式。在你拥有的几个设备上运行该命令,注意描述符的样子。你会看到即使是像鼠标这样简单的设备也有一个不平凡的描述符树:通常一个设备描述符、一个配置描述符、一个接口描述符(类=HID)和一两个端点描述符(用于HID报告输入,可能还有一个输出)。 -#### Request-Response Over USB +#### USB上的请求-响应 -The USB 控制传输 type supports a request-response pattern between host and 设备. A 控制传输 consists of three phases: a setup stage where the host sends an 8-byte setup 数据包 describing the request, an optional data stage where either the host sends data or the 设备 returns data, and a status stage where the recipient acknowledges the operation. +USB控制传输类型支持主机和设备之间的请求-响应模式。一个控制传输由三个阶段组成:主机发送描述请求的八字节设置数据包的设置阶段、主机发送数据或设备返回数据的可选数据阶段,以及接收者确认操作的状态阶段。 -The setup 数据包 has five fields: +设置数据包有五个字段: -- `bmRequestType`: describes the direction (in or out), the type of request (standard, class, or vendor), and the recipient (设备, 接口, 端点, or other). -- `bRequest`: the request number. Standard requests have well-known numbers (GET_DESCRIPTOR = 6, SET_ADDRESS = 5, and so on). Class and vendor requests have class-specific or vendor-specific meanings. -- `wValue`: a 16-bit parameter, often used to specify a 描述符 index or a value to set. -- `wIndex`: another 16-bit parameter, often used to specify an 接口 or 端点. -- `wLength`: the number of bytes in the data stage (zero if there is no data stage). +- `bmRequestType`:描述方向(输入或输出)、请求类型(标准、类或供应商)和接收者(设备、接口、端点或其他)。 +- `bRequest`:请求编号。标准请求有众所周知的编号(GET_DESCRIPTOR = 6,SET_ADDRESS = 5等)。类和供应商请求有类特定或供应商特定的含义。 +- `wValue`:一个16位参数,通常用于指定描述符索引或要设置的值。 +- `wIndex`:另一个16位参数,通常用于指定接口或端点。 +- `wLength`:数据阶段中的字节数(如果没有数据阶段则为零)。 -Every USB 设备 must support a small set of standard requests: GET_DESCRIPTOR, SET_ADDRESS, SET_CONFIGURATION, and a few others. The 框架 handles all of these at enumeration time. Your 驱动程序 may also issue vendor-specific requests to configure the 设备 in ways the standard does not define. +每个USB设备必须支持一小组标准请求:GET_DESCRIPTOR、SET_ADDRESS、SET_CONFIGURATION和其他几个。框架在枚举时处理所有这些。你的驱动程序也可以发出供应商特定的请求来以标准未定义的方式配置设备。 -For example, the FTDI 驱动程序 issues vendor-specific requests like `FTDI_SIO_SET_BAUD_RATE`, `FTDI_SIO_SET_LINE_CTRL`, and `FTDI_SIO_MODEM_CTRL` to program the chip. These requests are documented in FTDI's application notes; they are not part of USB itself, but they work over the USB control-transfer mechanism. +例如,FTDI驱动程序发出像 `FTDI_SIO_SET_BAUD_RATE`、`FTDI_SIO_SET_LINE_CTRL` 和 `FTDI_SIO_MODEM_CTRL` 这样的供应商特定请求来编程芯片。这些请求记录在FTDI的应用笔记中;它们不是USB本身的一部分,但它们通过USB控制传输机制工作。 -When your 驱动程序 needs to issue a vendor-specific control request, the pattern is the one we showed in 第3节: construct the setup 数据包, copy it into 帧 zero of a 控制传输, copy any data into 帧 one (for data-stage requests), and submit. The 框架 handles the three phases and calls your 回调 when the transfer completes. +当你的驱动程序需要发出供应商特定的控制请求时,模式是我们在第3节中展示的:构造设置数据包,将其复制到控制传输的帧零中,将任何数据复制到帧一中(对于有数据阶段的请求),然后提交。框架处理三个阶段并在传输完成时调用你的回调。 -### The Serial Mental Model +### 串行思维模型 -The serial side of 第26章 is about a much older and much simpler protocol than USB. Serial communication over a UART is one of the oldest ways two computers can talk to each other, and its simplicity is both its strength and its limitation. A reader coming to UART after USB will find the protocol almost trivially small. But the integration with the rest of the operating system, the tty discipline, 波特率 management, 奇偶校验, 流控制, and the two-worlds split between `uart(4)` and `ucom(4)`, is where most of the actual work lives. +第26章的串行部分是关于一个比USB古老得多也简单得多的协议。通过UART进行的串行通信是两台计算机互相通信的最古老方式之一,其简单性既是它的优势也是它的局限。一个在USB之后接触UART的读者会发现这个协议几乎小得不值一提。但与操作系统其余部分的集成、tty规程、波特率管理、奇偶校验、流控制以及 `uart(4)` 和 `ucom(4)` 之间的两个世界分裂,才是大部分实际工作所在。 -#### The UART as a Piece of Hardware +#### UART作为一种硬件 -A UART is a *Universal Asynchronous Receiver/Transmitter*: a chip that converts bytes into a serial bit stream on a wire and back again. The classical UART has two pins for data (TX and RX), two pins for 流控制 (RTS and CTS), four pins for modem status (DTR, DSR, DCD, RI), a ground pin, and occasionally a pin for a second "ring" signal that most modern equipment ignores. On a classic PC, the 串行端口 has a nine-pin or twenty-five-pin D-subminiature connector and operates at RS-232 voltage levels (typically +/- 12 V). Modern embedded UARTs usually operate at 3.3 V or 1.8 V logic levels; a level converter chip sits between the UART and the RS-232 connector if a compatible port is needed. +UART是*通用异步收发器*:一种将字节转换为线缆上的串行比特流并反向转换的芯片。经典UART有两个数据引脚(TX和RX)、两个流控制引脚(RTS和CTS)、四个调制解调器状态引脚(DTR、DSR、DCD、RI)、一个接地引脚,偶尔还有一个大多数现代设备忽略的第二个"振铃"信号引脚。在经典PC上,串行端口有一个九针或二十五针的D型超小型连接器,以RS-232电压电平运行(通常为+/- 12 V)。现代嵌入式UART通常以3.3 V或1.8 V逻辑电平运行;如果需要兼容端口,UART和RS-232连接器之间会有一个电平转换芯片。 -Inside the UART, the core is a shift 注册. When the 驱动程序 writes a byte to the UART's transmit 注册, the UART adds a start bit, shifts the byte out bit by bit at the configured 波特率, adds an optional 奇偶校验 bit, and then adds one or two 停止位. When a receiving UART detects a falling edge (the start bit), it samples the line at the middle of each bit time, assembles the bits into a byte, checks the 奇偶校验, verifies the stop bit, and then stores the byte in its receive 注册. If any of those steps fails (the 奇偶校验 does not match, the stop bit is wrong, the framing is off), the UART notes a framing error, a 奇偶校验 error, or a break condition in its status 注册. +UART内部的核心是一个移位寄存器。当驱动程序向UART的发送寄存器写入一个字节时,UART添加一个起始位,以配置的波特率逐位移出该字节,添加一个可选的奇偶校验位,然后添加一个或两个停止位。当接收UART检测到一个下降沿(起始位)时,它在每个位时间的中间采样线路,将位组装成一个字节,检查奇偶校验,验证停止位,然后将字节存储在其接收寄存器中。如果这些步骤中有任何一步失败(奇偶校验不匹配、停止位错误、成帧错误),UART会在其状态寄存器中记录一个成帧错误、奇偶校验错误或中断条件。 -On most modern UARTs, the single receive and transmit 寄存器 are backed by small first-in-first-out 缓冲区 (FIFOs). The 16550A UART, still the de facto standard, has a 16-byte FIFO on each side. A 驱动程序 that programs the FIFO with an appropriate "trigger level" can let the hardware 缓冲区 incoming bytes and raise an interrupt only when the FIFO passes the trigger level. This is the difference between "one interrupt per byte" (slow) and "one interrupt per trigger level" (fast). The 16550A's FIFO is a big part of why this chip became the universal PC standard. +在大多数现代UART上,单个接收和发送寄存器由小型先进先出缓冲区(FIFO)支持。16550A UART仍然是事实上的标准,每侧有一个16字节的FIFO。一个用适当的"触发级别"编程FIFO的驱动程序可以让硬件缓冲传入的字节,只在FIFO超过触发级别时才引发中断。这就是"每字节一次中断"(慢)和"每个触发级别一次中断"(快)之间的区别。16550A的FIFO是这块芯片成为通用PC标准的重要原因。 -The UART's speed is controlled by a *波特率 divisor*: the UART has an input clock (often 1.8432 MHz on classic PC hardware), and the 波特率 is the clock divided by 16 times the divisor. A divisor of 1 with a 1.8432 MHz clock gives 115200 baud. A divisor of 12 gives 9600 baud. The FreeBSD `ns8250` 驱动程序 computes the divisor from the requested 波特率 and programs it into the UART's divisor-latch 寄存器. Section 4 walks through this code. +UART的速度由一个*波特率除数*控制:UART有一个输入时钟(在经典PC硬件上通常为1.8432 MHz),波特率是时钟除以16倍除数。除数为1、时钟为1.8432 MHz时得到115200波特率。除数为12时得到9600波特率。FreeBSD的 `ns8250` 驱动程序从请求的波特率计算除数并将其编程到UART的除数锁存寄存器中。第4节将详细讲解这段代码。 -RS-232 framing is the full protocol: start bit (one), 数据位 (five, six, seven, or eight), optional 奇偶校验 bit (none, odd, even, mark, or space), stop bit (one or two). A typical modern configuration is "8N1": eight 数据位, no 奇偶校验, one stop bit. An older configuration sometimes seen on industrial equipment is "7E1": seven 数据位, even 奇偶校验, one stop bit. The 驱动程序 programs the UART's line control 注册 to select the framing; `struct termios` carries the configuration from user space. +RS-232成帧是完整的协议:起始位(一个)、数据位(五个、六个、七个或八个)、可选的奇偶校验位(无、奇、偶、标记或空格)、停止位(一个或两个)。典型的现代配置是"8N1":八个数据位、无奇偶校验、一个停止位。在工业设备上有时会看到的较旧配置是"7E1":七个数据位、偶校验、一个停止位。驱动程序编程UART的线路控制寄存器来选择成帧方式;`struct termios` 从用户空间传递配置。 -#### Flow Control +#### 流控制 -The UART can transmit faster than the receiver can read if the receiver's code is slow or is doing other work. *Flow control* is how the receiver tells the transmitter to pause. Two mechanisms exist. +如果接收方代码运行缓慢或正在做其他工作,UART的传输速度可能快于接收方的读取速度。*流控制*是接收方告诉发送方暂停的方式。有两种机制。 -*Hardware 流控制* uses two extra wires: *RTS* (Request To Send) from the receiver, and *CTS* (Clear To Send) from the transmitter's perspective (it is the wire the other side drives). When the receiver's 缓冲区 is filling up, it deasserts RTS. The transmitter, seeing CTS deasserted, stops transmitting. When the 缓冲区 empties, the receiver reasserts RTS, CTS asserts on the other side, and transmission resumes. Hardware 流控制 is reliable and requires no software overhead on either side; it is the default choice when the hardware supports it. +*硬件流控制*使用两根额外的线:来自接收方的*RTS*(请求发送),以及从发送方角度看(即对方驱动的线)的*CTS*(清除发送)。当接收方的缓冲区快满时,它撤销RTS。发送方看到CTS被撤销,停止发送。当缓冲区排空时,接收方重新置位RTS,另一侧的CTS被置位,传输恢复。硬件流控制可靠且不需要任何一侧的软件开销;当硬件支持时,它是默认选择。 -*Software 流控制*, also called XON/XOFF, uses two in-band bytes: XOFF (traditionally ASCII DC3, 0x13) to pause transmission, and XON (ASCII DC1, 0x11) to resume. The receiver sends XOFF when it is almost full and XON when it has room again. This mechanism works over a three-wire connection (TX, RX, ground) with no extra pins, at the cost of reserving two byte values for control use. If you are sending binary data that may contain 0x11 or 0x13, you cannot use software 流控制; hardware 流控制 is the only option. +*软件流控制*,也称为XON/XOFF,使用两个带内字节:XOFF(传统上是ASCII DC3,0x13)来暂停传输,XON(ASCII DC1,0x11)来恢复传输。接收方在几乎满时发送XOFF,在有空间时发送XON。这种机制在三线连接(TX、RX、地线)上工作,不需要额外引脚,代价是保留两个字节值用于控制。如果你发送的二进制数据可能包含0x11或0x13,就不能使用软件流控制;硬件流控制是唯一选择。 -FreeBSD's tty discipline handles software 流控制 entirely in software, at the line-discipline layer, with no involvement from the UART 驱动程序. Hardware 流控制 is partly in the 驱动程序 (the 驱动程序 programs the UART's automatic RTS/CTS feature if the chip supports it) and partly in the tty layer. A 驱动程序 author should know which 流控制 method the tty layer has selected; the CRTSCTS flag in `struct termios` signals hardware 流控制. +FreeBSD的tty规程完全在软件中、在线路规程层处理软件流控制,不涉及UART驱动程序。硬件流控制部分在驱动程序中(如果芯片支持,驱动程序编程UART的自动RTS/CTS功能),部分在tty层。驱动程序作者应该知道tty层选择了哪种流控制方法;`struct termios` 中的CRTSCTS标志表示硬件流控制。 -#### /dev/ttyuN and /dev/cuauN: A FreeBSD-Specific Quirk +#### /dev/ttyuN 和 /dev/cuauN:FreeBSD特有的特性 -The FreeBSD tty layer creates two 设备 nodes per 串行端口. The *callin* node is `/dev/ttyuN` (where N is the port number, 0 for the first port). The *callout* node is `/dev/cuauN`. The distinction is historical, from the days of dial-up modems, and remains useful. +FreeBSD的tty层为每个串行端口创建两个设备节点。*呼入*节点是 `/dev/ttyuN`(其中N是端口号,第一个端口为0)。*呼出*节点是 `/dev/cuauN`。这个区别是历史性的,来自拨号调制解调器时代,但仍然有用。 -A process opening `/dev/ttyuN` is saying "I want to answer an incoming call": the open 块 until the modem raises DCD (Data Carrier Detect). Once DCD is up, the open completes. When DCD drops, the open process receives SIGHUP. The node is for incoming connections. +一个打开 `/dev/ttyuN` 的进程是在说"我想接听一个来电":打开操作会阻塞直到调制解调器升起DCD(数据载波检测)。一旦DCD升起,打开操作完成。当DCD下降时,打开的进程收到SIGHUP。该节点用于传入连接。 -A process opening `/dev/cuauN` is saying "I want to make an outgoing call": the open succeeds immediately, without 块ing on DCD. The process can then dial out or, on non-modem uses, simply talk to the 串行端口. The node is for outgoing connections, and more generally for any use that does not require modem semantics. +一个打开 `/dev/cuauN` 的进程是在说"我想拨打一个外线":打开操作立即成功,不会在DCD上阻塞。进程然后可以拨出,或者在非调制解调器使用中,简单地与串行端口通信。该节点用于外发连接,更一般地用于任何不需要调制解调器语义的使用场景。 -In modern use, when a 串行端口 is connected to something that is not a modem (a microcontroller, a console, a GPS receiver), the right node to open is almost always `/dev/cuau0`. Opening `/dev/ttyu0` on a non-modem port will usually hang, because DCD is never asserted. The distinction is FreeBSD-specific; Linux has no callout nodes and uses `/dev/ttyS0` or `/dev/ttyUSB0` for everything. +在现代使用中,当串行端口连接到非调制解调器的东西(微控制器、控制台、GPS接收器)时,正确的节点几乎总是 `/dev/cuau0`。在非调制解调器端口上打开 `/dev/ttyu0` 通常会挂起,因为DCD永远不会被置位。这个区别是FreeBSD特有的;Linux没有呼出节点,对一切都使用 `/dev/ttyS0` 或 `/dev/ttyUSB0`。 -The chapter's labs will use `/dev/cuau0` and the simulated pair `/dev/nmdm0A`/`/dev/nmdm0B` for serial exercises. The callin nodes are not used. +本章的实验将使用 `/dev/cuau0` 和模拟对 `/dev/nmdm0A`/`/dev/nmdm0B` 进行串行练习。呼入节点不使用。 -#### Two Worlds: `uart(4)` and `ucom(4)` +#### 两个世界:`uart(4)` 和 `ucom(4)` -FreeBSD separates real UART hardware from USB-to-serial bridges into two distinct subsystems. The separation is not visible from user space (a USB serial adapter and a built-in 串行端口 both appear as tty 设备), but it is very visible from inside the 内核, and a 驱动程序 author must not confuse the two. +FreeBSD将真正的UART硬件与USB转串行桥接器分离为两个不同的子系统。这种分离从用户空间不可见(USB串行适配器和内置串行端口都显示为tty设备),但从内核内部非常明显,驱动程序作者绝不能混淆两者。 -`uart(4)` is the subsystem for real UARTs. Its scope includes the built-in 串行端口 on a PC motherboard, PCI serial cards, the PrimeCell `PL011` found on ARM embedded boards, the embedded SoC UARTs on i.MX, Marvell, Qualcomm, Broadcom, and Allwinner platforms, and so on. The `uart` subsystem lives in `/usr/src/sys/dev/uart/`. Its core code is in `uart_core.c` and `uart_tty.c`. Its canonical hardware 驱动程序 is `uart_dev_ns8250.c`. A 驱动程序 that 附加 to a real UART writes a `uart_class` and a small set of `uart_ops`, and the subsystem handles everything else. The `/dev` nodes that `uart(4)` creates are called `ttyu0`, `ttyu1`, and so on (callin) and `cuau0`, `cuau1`, and so on (callout). +`uart(4)` 是用于真正UART的子系统。其范围包括PC主板上的内置串行端口、PCI串行卡、ARM嵌入式板上发现的PrimeCell `PL011`、i.MX、Marvell、Qualcomm、Broadcom和Allwinner平台上的嵌入式SoC UART等。`uart` 子系统位于 `/usr/src/sys/dev/uart/`。其核心代码在 `uart_core.c` 和 `uart_tty.c` 中。其经典硬件驱动程序是 `uart_dev_ns8250.c`。一个附加到真正UART的驱动程序编写一个 `uart_class` 和一小组 `uart_ops`,子系统处理其余一切。`uart(4)` 创建的 `/dev` 节点称为 `ttyu0`、`ttyu1` 等(呼入)和 `cuau0`、`cuau1` 等(呼出)。 -`ucom(4)` is the 框架 for USB-to-serial bridges: FTDI, Prolific, Silicon Labs, WCH, and similar. Its scope is *not* a UART at all; it is a USB 设备 whose 端点 happen to behave like a 串行端口. The `ucom` 框架 lives in `/usr/src/sys/dev/usb/serial/`. Its header is `usb_serial.h`. Its body is `usb_serial.c`. A USB-to-串行驱动程序 writes USB 探测, 附加, and 分离 methods as in any other USB驱动程序, and then 寄存器 a `struct ucom_回调` with the 框架. The 回调 has entries for "open", "close", "set line parameters", "start reading", "stop reading", "start writing", and so on. The 框架 creates the `/dev` node (called `ttyU0`, `ttyU1` for callin, `cuaU0`, `cuaU1` for callout, note the capital U) and runs the tty discipline on top of the 驱动程序's USB transfers. +`ucom(4)` 是用于USB转串行桥接器的框架:FTDI、Prolific、Silicon Labs、WCH等。其范围*不是*UART;它是一个端点碰巧表现得像串行端口的USB设备。`ucom` 框架位于 `/usr/src/sys/dev/usb/serial/`。其头文件是 `usb_serial.h`。其主体是 `usb_serial.c`。一个USB转串行驱动程序像任何其他USB驱动程序一样编写USB探测、附加和分离方法,然后向框架注册一个 `struct ucom_callback`。回调有条目用于"打开"、"关闭"、"设置线路参数"、"开始读取"、"停止读取"、"开始写入"等。框架创建 `/dev` 节点(呼入称为 `ttyU0`、`ttyU1`,呼出称为 `cuaU0`、`cuaU1`,注意大写字母U)并在驱动程序的USB传输之上运行tty规程。 -The two worlds never mix. `uart(4)` is for hardware that is physically a UART. `ucom(4)` is for USB 设备 that behave like a UART. A USB-to-serial adapter is a `ucom` 驱动程序, not a `uart` 驱动程序. A PCI serial card is a `uart` 驱动程序 (specifically, a shim in `uart_总线_pci.c`), not a `ucom` 驱动程序. The user-space 接口 is similar (both produce `cu*` 设备 nodes), but the 内核 code is entirely disjoint. +这两个世界从不混合。`uart(4)` 用于物理上是UART的硬件。`ucom(4)` 用于行为像UART的USB设备。USB转串行适配器是一个 `ucom` 驱动程序,而不是 `uart` 驱动程序。PCI串行卡是一个 `uart` 驱动程序(具体来说是 `uart_bus_pci.c` 中的一个垫片),而不是 `ucom` 驱动程序。用户空间接口是相似的(两者都产生 `cu*` 设备节点),但内核代码完全不相交。 -A historical note that sometimes confuses readers: FreeBSD once had a separate `sio(4)` 驱动程序 for 16550-family UARTs. `sio(4)` was retired years ago and is not present in FreeBSD 14.3. If you see references to `sio` in older documentation, translate them mentally to `uart(4)`. Do not try to find or extend `sio`; it is gone. +一个有时会让读者困惑的历史注记:FreeBSD曾经有一个单独的 `sio(4)` 驱动程序用于16550系列UART。`sio(4)` 已在多年前退役,在FreeBSD 14.3中不存在。如果你在旧文档中看到对 `sio` 的引用,在心中将它们翻译为 `uart(4)`。不要试图找到或扩展 `sio`;它已经不存在了。 -#### What termios Carries, and Where It Goes +#### termios传递什么,以及它去哪里 -`struct termios` is the user-space structure that configures a tty. It has five fields: `c_iflag` (input flags), `c_oflag` (output flags), `c_cflag` (control flags), `c_lflag` (local flags), `c_cc` (control characters), and two speed fields `c_ispeed` and `c_ospeed`. The fields are manipulated with `tcgetattr(3)`, `tcsetattr(3)`, and the shell command `stty(1)`. +`struct termios` 是配置tty的用户空间结构。它有五个字段:`c_iflag`(输入标志)、`c_oflag`(输出标志)、`c_cflag`(控制标志)、`c_lflag`(本地标志)、`c_cc`(控制字符),以及两个速度字段 `c_ispeed` 和 `c_ospeed`。这些字段通过 `tcgetattr(3)`、`tcsetattr(3)` 和shell命令 `stty(1)` 来操作。 -A UART 驱动程序 cares almost exclusively about `c_cflag` and the speed fields. `c_cflag` carries: +UART驱动程序几乎只关心 `c_cflag` 和速度字段。`c_cflag` 携带: -- `CSIZE`: the character size (CS5, CS6, CS7, CS8). -- `CSTOPB`: if set, two 停止位; if clear, one. -- `PARENB`: if set, 奇偶校验 is enabled; the type depends on `PARODD`. -- `PARODD`: if set with `PARENB`, odd 奇偶校验; if clear with `PARENB`, even 奇偶校验. -- `CRTSCTS`: hardware 流控制. -- `CLOCAL`: ignore modem status lines; treat the link as local. -- `CREAD`: enable the receiver. +- `CSIZE`:字符大小(CS5、CS6、CS7、CS8)。 +- `CSTOPB`:如果设置,两个停止位;如果清除,一个。 +- `PARENB`:如果设置,启用奇偶校验;类型取决于 `PARODD`。 +- `PARODD`:如果与 `PARENB` 一起设置,奇校验;如果与 `PARENB` 一起清除,偶校验。 +- `CRTSCTS`:硬件流控制。 +- `CLOCAL`:忽略调制解调器状态线;将链路视为本地。 +- `CREAD`:启用接收器。 -When user space calls `tcsetattr`, the tty layer checks the request, invokes the 驱动程序's `param` method (via the `tsw_param` 回调 in `ttydevsw`), and the 驱动程序 translates the termios fields into hardware 注册 settings. The `uart_tty.c` bridge code walks through this in full and is the best place to see the translation happen. +当用户空间调用 `tcsetattr` 时,tty层检查请求,调用驱动程序的 `param` 方法(通过 `ttydevsw` 中的 `tsw_param` 回调),驱动程序将termios字段翻译为硬件寄存器设置。`uart_tty.c` 桥接代码完整地展示了这个过程,是查看翻译发生的最佳位置。 -`c_iflag`, `c_oflag`, and `c_lflag` are mostly handled by the tty line discipline, not by the 驱动程序. They control things like whether the line discipline maps CR to LF, whether echo is enabled, whether canonical mode is active, and so on. A UART 驱动程序 does not need to know any of that; the tty layer handles it. +`c_iflag`、`c_oflag` 和 `c_lflag` 主要由tty线路规程处理,而不是由驱动程序处理。它们控制诸如线路规程是否将CR映射为LF、是否启用回显、规范模式是否激活等。UART驱动程序不需要知道任何这些;tty层会处理它。 -#### Flow Control at the Multiple Layers of a TTY +#### TTY多层中的流控制 -Flow control sounds like a single concept, but in practice there are several independent layers that can each throttle the data flow. Understanding the layers helps debug situations where data is mysteriously not flowing. +流控制听起来像是一个单一概念,但实际上有几个独立的层,每一层都可以限制数据流。理解这些层有助于调试数据神秘地不流动的情况。 -The lowest layer is electrical. On a real RS-232 line, 流控制 signals (RTS, CTS, DTR, DSR) are physical pins on the connector. The remote side's transmitter only sends data when its CTS pin is asserted. The local side asserts the RTS pin to tell the remote it is ready to receive. For this to work, the cable must pass RTS and CTS through correctly, and both ends must have 流控制 configured consistently. +最底层是电气层。在真正的RS-232线路上,流控制信号(RTS、CTS、DTR、DSR)是连接器上的物理引脚。远端的发送器只在CTS引脚被置位时才发送数据。本端置位RTS引脚告诉远端它准备好接收了。为了使这工作,线缆必须正确地传递RTS和CTS,两端必须一致地配置流控制。 -The next layer is in the UART chip itself. Some 16650 and later UARTs have automatic 流控制: if configured, the chip itself monitors CTS and pauses the transmitter without 驱动程序 involvement. The `CRTSCTS` flag in `c_cflag` enables this. +下一层在UART芯片本身。一些16650和更高版本的UART具有自动流控制:如果配置了,芯片本身监控CTS并在没有驱动程序参与的情况下暂停发送器。`c_cflag` 中的 `CRTSCTS` 标志启用此功能。 -The next layer is in the UART 框架's 环形缓冲区. When the RX ring fills past a high-water mark, the 框架 deasserts RTS (if 流控制 is enabled) to tell the remote side to pause. When it drains below a low-water mark, RTS is reasserted. +下一层在UART框架的环形缓冲区中。当RX环超过高水位标记时,框架撤销RTS(如果启用了流控制)以告诉远端暂停。当它排空到低水位标记以下时,RTS被重新置位。 -The next layer is the tty line discipline, which has its own input and output queues. The line discipline can also generate XON/XOFF bytes (0x11 and 0x13) if `IXON` and `IXOFF` are set in `c_iflag`. These are software 流控制 signals. +下一层是tty线路规程,它有自己的输入和输出队列。如果在 `c_iflag` 中设置了 `IXON` 和 `IXOFF`,线路规程还可以生成XON/XOFF字节(0x11和0x13)。这些是软件流控制信号。 -The highest layer is the userland program's read loop. If the program is slow at consuming data, bytes accumulate at every layer below it. +最高层是用户态程序的读取循环。如果程序消耗数据很慢,字节会在它下面的每一层累积。 -When debugging flow-control issues, check each layer. Use `stty -a -f /dev/cuau0` to see what `c_cflag` and `c_iflag` have active. Use `comcontrol /dev/cuau0` to see the current modem signals. Use a multimeter or oscilloscope on the physical signals if you can. Work down the layers until you find the one that is actually 块ing the flow. +在调试流控制问题时,检查每一层。使用 `stty -a -f /dev/cuau0` 查看 `c_cflag` 和 `c_iflag` 有哪些处于活动状态。使用 `comcontrol /dev/cuau0` 查看当前的调制解调器信号。如果可以的话,在物理信号上使用万用表或示波器。从上到下检查各层,直到找到实际阻塞数据流的那一层。 -#### Why Baud Rate Errors Are Insidious +#### 为什么波特率误差难以察觉 -A common class of serial bug is a baud-rate mismatch that almost works. Suppose one side is running at 115200 and the other at 114400 (which is what you get from a slightly-off crystal). Most bytes will come through, but a few will be corrupted. The exact error rate depends on the bit pattern. Long runs of one polarity drift further than alternating patterns. +一类常见的串行bug是波特率不匹配但几乎能工作的情况。假设一边以115200运行,另一边以114400运行(这是由稍微偏差的晶体产生的)。大多数字节会通过,但少数会损坏。确切的错误率取决于位模式。长连同一极性的位比交替模式的位偏移更大。 -Even worse, the error rate depends on the byte being sent. ASCII printable characters are in the range 0x20 to 0x7e, where the bits are well-distributed. Non-printable characters like 0xff or 0x00 are more likely to suffer bit errors because they present long runs of one polarity. +更糟糕的是,错误率取决于发送的字节。ASCII可打印字符在0x20到0x7e范围内,其中位分布良好。像0xff或0x00这样的不可打印字符更容易出现位错误,因为它们呈现长连同一极性。 -If you find your 串行驱动程序 "mostly works" but drops or corrupts a few bytes out of thousands, suspect a baud-rate mismatch before suspecting a logic bug in your 驱动程序. Compare the actual divisor the chip is using against the expected divisor. If they differ, the 波特率 is not what you asked for. +如果你发现你的串行驱动程序"大部分工作正常"但在数千字节中丢弃或损坏了少数字节,在怀疑驱动程序中的逻辑bug之前,先怀疑波特率不匹配。比较芯片使用的实际除数与预期除数。如果它们不同,波特率就不是你要求的值。 -The 16550 uses a clock source (usually 1.8432 MHz) divided by a 16-bit divisor to produce 16 times the 波特率. For 115200, the divisor is `(1843200 / (115200 * 16)) = 1`. For 9600, it is 12. For arbitrary rates, the divisor may not be an integer, and the closest integer produces a rounded rate. A rate of 115200 requested from a 24 MHz clock would produce a divisor of `(24000000 / (115200 * 16)) = 13.02`, rounding to 13, giving an actual rate of `(24000000 / (13 * 16)) = 115384`, which is 0.16% off. Standard tolerance for serial communication is 2-3%, so 0.16% is fine. +16550使用时钟源(通常为1.8432 MHz)除以16位除数来产生16倍波特率。对于115200,除数为 `(1843200 / (115200 * 16)) = 1`。对于9600,为12。对于任意速率,除数可能不是整数,最接近的整数产生一个舍入的速率。从24 MHz时钟请求115200的速率会产生除数 `(24000000 / (115200 * 16)) = 13.02`,舍入为13,给出实际速率 `(24000000 / (13 * 16)) = 115384`,偏差0.16%。串行通信的标准容差为2-3%,所以0.16%是可以的。 -When you configure a UART for a nonstandard 波特率, check whether the rate can be represented exactly. If not, test with actual data exchange, not just a loopback check. +当你为非标准波特率配置UART时,检查速率是否可以精确表示。如果不能,用实际数据交换测试,而不仅仅是环回检查。 -#### Historical Note on Minor Numbers +#### 关于次设备号的历史注记 -Older FreeBSD versions encoded a lot of information into the minor numbers of serial 设备 files. Different minor numbers for the "callin" side vs the "callout" side, for hardware-flow vs software-flow, and for various lock states. This encoding is largely gone in modern FreeBSD; the distinctions are now handled by separate 设备 nodes with different names (`ttyu` vs `cuau`, with suffixes for lock and init states). If you see odd minor-number manipulation in old code, know that modern code does not need it. +较旧的FreeBSD版本在串行设备文件的次设备号中编码了大量信息。不同的次设备号用于"呼入"侧与"呼出"侧、硬件流控制与软件流控制以及各种锁定状态。这种编码在现代FreeBSD中已基本消失;这些区别现在由具有不同名称的独立设备节点处理(`ttyu` 与 `cuau`,带有锁定和初始化状态的后缀)。如果你在旧代码中看到奇怪次设备号操作,要知道现代代码不需要它。 -#### 总结 Section 1 +#### 第1节总结 -Section 1 has established the two mental models 第26章 depends on. The USB model is a tree-structured, host-controlled, 热插拔gable serial 总线 with four transfer types, a rich 描述符 hierarchy, and a lifecycle in which physical events drive 内核 events. The serial model is a simple shift-注册 hardware protocol with 波特率, 奇偶校验, 停止位, and optional 流控制, integrated into FreeBSD through a subsystem split between `uart(4)` for real UARTs and `ucom(4)` for USB-to-serial bridges, and exposed to user space through the tty discipline and 设备 nodes like `/dev/cuau0`. +第1节建立了第26章所依赖的两个思维模型。USB模型是一个树状结构、主机控制、支持热插拔的串行总线,具有四种传输类型、丰富的描述符层次结构以及物理事件驱动内核事件的生命周期。串行模型是一个简单的移位寄存器硬件协议,具有波特率、奇偶校验、停止位和可选的流控制,通过 `uart(4)`(用于真正UART)和 `ucom(4)`(用于USB转串行桥接器)之间的子系统分裂集成到FreeBSD中,并通过tty规程和像 `/dev/cuau0` 这样的设备节点暴露给用户空间。 -Before moving on, spend a few minutes with `usbconfig` on a real system. The vocabulary you have just learned is easier to keep straight once you have seen a real USB 设备's 描述符 with your own eyes. +在继续之前,花几分钟在一个真实系统上使用 `usbconfig`。你刚刚学到的词汇在你亲眼看到真实USB设备的描述符后更容易理清。 -### Exercise: Use `usbconfig` and `dmesg` to Explore USB Devices on Your System +### 练习:使用 `usbconfig` 和 `dmesg` 探索你系统上的USB设备 -This exercise is a short hands-on checkpoint that grounds Section 1's vocabulary in a 设备 you can see. Perform it on your lab VM (or on any FreeBSD 14.3 system with at least one USB 设备 connected). It takes about fifteen minutes. +本练习是一个简短的动手检查点,将第1节的词汇建立在你可见的设备上。在你的实验VM上(或任何连接了至少一个USB设备的FreeBSD 14.3系统上)执行它。大约需要十五分钟。 -**Step 1. Inventory.** Run `usbconfig` with no arguments: +**步骤1. 清单。** 运行无参数的 `usbconfig`: ```console $ usbconfig @@ -472,9 +472,9 @@ ugen0.2: at usbus0, cfg=0 md=HOST spd=HIGH (500mA) ugen0.3: at usbus0, cfg=0 md=HOST spd=LOW (98mA) ``` -The first line is the root hub. Each other line is a 设备. Read the format: `ugenN.M` where N is the 总线 number and M is the 设备 number; the description in angle brackets is the 设备's string; `cfg` is the active configuration; `md` is the mode (HOST or DEVICE); `spd` is the 总线 speed (LOW, FULL, HIGH, SUPER); the parenthesised current is the maximum 总线-supplied power draw. +第一行是根集线器。其余每行是一个设备。阅读格式:`ugenN.M` 其中N是总线号,M是设备号;尖括号中的描述是设备的字符串;`cfg` 是活动配置;`md` 是模式(HOST或DEVICE);`spd` 是总线速度(LOW、FULL、HIGH、SUPER);括号中的电流是最大总线供电功耗。 -**Step 2. Dump a 设备's 描述符.** Pick one of the non-root-hub 设备 and dump its 设备 描述符: +**步骤2. 转储设备的描述符。** 选择一个非根集线器的设备并转储其设备描述符: ```console $ usbconfig -d ugen0.2 dump_device_desc @@ -497,9 +497,9 @@ ugen0.2: at usbus0, cfg=0 md=HOST spd=HIGH (500mA) bNumConfigurations = 0x0001 ``` -Read each field. Notice that `bDeviceClass` is zero: that is the USB convention for "the class is defined per 接口, not at the 设备 level." For this 设备, the 接口 class will be Mass Storage (0x08). +读取每个字段。注意 `bDeviceClass` 为零:这是USB中"类在每个接口上定义,而不是在设备级别"的约定。对于这个设备,接口类将是Mass Storage(0x08)。 -**Step 3. Dump the active configuration.** Now dump the configuration 描述符, which includes the 接口 and 端点: +**步骤3. 转储活动配置。** 现在转储配置描述符,它包括接口和端点: ```console $ usbconfig -d ugen0.2 dump_curr_config_desc @@ -545,9 +545,9 @@ ugen0.2: at usbus0, cfg=0 md=HOST spd=HIGH (500mA) bInterval = 0x0000 ``` -Every field in Section 1's vocabulary is right there. The 接口 class is 0x08 (Mass Storage). The subclass is 0x06 (SCSI). The protocol is 0x50 (Bulk-only Transport). There are two 端点. Endpoint 0 has address 0x81 (the high bit indicates IN direction, the low five bits are the 端点 number, 1). Endpoint 1 has address 0x02 (the high bit is clear, meaning OUT; the 端点 number is 2). Both 端点 are bulk. Both have a maximum 数据包 size of 0x0200 = 512 bytes. The interval is zero because bulk 端点 do not use it. +第1节词汇中的每个字段都在这里。接口类是0x08(Mass Storage)。子类是0x06(SCSI)。协议是0x50(Bulk-only Transport)。有两个端点。端点0的地址是0x81(高位表示IN方向,低五位是端点号1)。端点1的地址是0x02(高位清除,表示OUT;端点号是2)。两个端点都是批量的。它们都有0x0200 = 512字节的最大数据包大小。间隔为零,因为批量端点不使用它。 -**Step 4. Match this against `dmesg`.** Run `dmesg | grep -A 3 ugen0.2` (or look at the last boot's output for the matching 设备). You should see a line like: +**步骤4. 将此与 `dmesg` 匹配。** 运行 `dmesg | grep -A 3 ugen0.2`(或查看上次启动的输出以找到匹配的设备)。你应该看到类似这样的行: ```text ugen0.2: at usbus0 @@ -555,37 +555,37 @@ umass0 on uhub0 umass0: on usbus0 ``` -This is the same information, formatted by the 内核's own logging. The 驱动程序 that 附加ed is `umass`, which is FreeBSD's USB mass 存储驱动程序, and it 附加ed to the Mass Storage 接口 class. +这是相同的信息,由内核自己的日志格式化。附加的驱动程序是 `umass`,即FreeBSD的USB大容量存储驱动程序,它附加到了Mass Storage接口类。 -**Step 5. Try `usbconfig -d ugen0.3 dump_all_config_desc` on another 设备.** A mouse, a keyboard, or a flash drive will all work. Compare the 端点 types: a mouse has one interrupt-IN 端点; a flash drive has one bulk-IN and one bulk-OUT; a keyboard has one interrupt-IN. The pattern holds. +**步骤5. 在另一个设备上尝试 `usbconfig -d ugen0.3 dump_all_config_desc`。** 鼠标、键盘或闪存盘都可以。比较端点类型:鼠标有一个中断IN端点;闪存盘有一个批量IN和一个批量OUT;键盘有一个中断IN。模式是一致的。 -If you want a small additional exercise, write down the vendor and product identifiers of one of your 设备. In Section 2 you will be asked to put vendor and product identifiers into a 匹配表; using ones you can see now is concrete. +如果你想要一个小的额外练习,写下你其中一个设备的供应商标识符和产品标识符。在第2节中,你将被要求将供应商标识符和产品标识符放入匹配表;使用你现在能看到的标识符更具体。 -### 总结 Section 1 +### 第1节总结 -Section 1 has done four things. It established the mental model of a transport: the protocol plus the lifecycle, plus the three broad categories of work (matching, transfer mechanics, 热插拔 lifecycle) that a transport-specific 驱动程序 has to add to its New总线 foundation. It built the USB model: host and 设备, hubs and ports, classes, 描述符 with their nested structure, the four transfer types, and the 热插拔 lifecycle. It built the serial model: the UART as a shift 注册 with a baud generator, RS-232 framing, 波特率 and 奇偶校验 and 停止位, hardware and software 流控制, the FreeBSD-specific callin and callout node distinction, the two-worlds split between `uart(4)` and `ucom(4)`, and the role of `struct termios`. And it anchored the vocabulary in a concrete exercise that reads 描述符 off a real USB 设备 with `usbconfig`. +第1节完成了四件事。它确立了传输层的思维模型:协议加生命周期,加上特定传输层驱动程序必须在其Newbus基础上增加的三大类工作(匹配、传输机制、热插拔生命周期)。它构建了USB模型:主机和设备、集线器和端口、设备类、具有嵌套结构的描述符、四种传输类型以及热插拔生命周期。它构建了串行模型:UART作为带有波特率发生器的移位寄存器、RS-232成帧、波特率和奇偶校验和停止位、硬件和软件流控制、FreeBSD特有的呼入和呼出节点区别、`uart(4)` 和 `ucom(4)` 之间的两个世界分裂以及 `struct termios` 的作用。它通过一个使用 `usbconfig` 从真实USB设备读取描述符的具体练习锚定了词汇。 -From here, the chapter turns to code. Section 2 builds a USB驱动程序 skeleton: 探测, 附加, 分离, 匹配表, registration macros. Section 3 makes that 驱动程序 do real work by adding transfers. Section 4 turns to the serial side, walks through the `uart(4)` subsystem with a real 驱动程序 as the guide, and explains where `ucom(4)` fits in. Section 5 brings the material back to the lab and teaches how to test USB and 串行驱动程序 without physical hardware. Each section builds on the mental models just established. If a later paragraph refers to a 描述符 or a transfer type and the term does not feel immediate, return to Section 1 for a quick refresher before continuing. +从这里开始,本章转向代码。第2节构建USB驱动程序骨架:探测、附加、分离、匹配表、注册宏。第3节通过添加传输使该驱动程序做真正的工作。第4节转向串行方面,以一个真实驱动程序为引导,遍历 `uart(4)` 子系统,并解释 `ucom(4)` 在哪里融入。第5节将材料带回实验室,教授如何在没有物理硬件的情况下测试USB和串行驱动程序。每一节都建立在刚刚建立的思维模型之上。如果后面的段落提到一个描述符或传输类型而这个词不让你感觉立刻明了,在继续之前返回第1节快速复习。 -## 第2节: Writing a USB Device Driver +## 第2节:编写USB设备驱动程序 -### Moving from Concepts to Code +### 从概念到代码 -Section 1 built a mental picture of USB: a host that talks to 设备 through a tree of hubs, 设备 that describe themselves with nested 描述符, four transfer types that cover every conceivable traffic pattern, and a 热插拔 lifecycle that 驱动程序 must respect because USB 设备 appear and disappear at any moment. Section 2 turns those concepts into a real 驱动程序 skeleton. By the end of this section, you will have a USB驱动程序 that compiles, loads, 附加 to a matching 设备, and 分离 cleanly when the 设备 is unplugged. It will not yet perform data transfers; that is the job of Section 3. But the scaffolding you build here is the same scaffolding every FreeBSD USB驱动程序 uses, from the tiniest notification LED to the most complex mass-storage controller. +第1节构建了USB的思维图景:一个通过集线器树与设备通信的主机、用嵌套描述符描述自身的设备、覆盖所有可能流量模式的四种传输类型,以及驱动程序必须遵守的热插拔生命周期,因为USB设备随时可能出现和消失。第2节将这些概念转化为一个真实的驱动程序骨架。到本节结束时,你将拥有一个可以编译、加载、附加到匹配设备并在设备被拔出时干净分离的USB驱动程序。它还不会执行数据传输;那是第3节的工作。但你在这里构建的脚手架是每个FreeBSD USB驱动程序使用的相同脚手架,从最小的通知LED到最复杂的大容量存储控制器。 -The discipline you learned in 第25章 carries forward unchanged. Every resource must have an owner. Every successful allocation in `附加` must be paired with an explicit release in `分离`. Every failure path must leave the system in a clean state. The labelled-goto cleanup chain, the errno-returning helper functions, the softc-based resource tracking, the rate-limited logging: all of it still applies. What changes is the set of resources you manage. Instead of 总线 resources allocated through New总线 and a 字符设备 created through `make_dev`, you will manage USB transfer objects allocated through the USB stack and, optionally, a `/dev` entry created through the `usb_fifo` 框架. The shape of the code stays the same. Only the specific calls change. +你在第25章中学到的规范保持不变。每个资源都必须有一个所有者。`attach` 中每个成功的分配都必须与 `detach` 中的显式释放配对。每个失败路径都必须让系统保持在干净状态。标签化goto清理链、返回errno的辅助函数、基于softc的资源跟踪、速率受限的日志记录:所有这些仍然适用。变化的是你管理的资源集合。不再是通过对Newbus分配的总线资源和通过 `make_dev` 创建的字符设备,你将管理通过USB栈分配的USB传输对象,以及可选地通过 `usb_fifo` 框架创建的 `/dev` 条目。代码的形态保持不变。只有具体的调用改变了。 -This section moves from the outside in. It begins by explaining where a USB驱动程序 sits inside the FreeBSD USB subsystem, because placing the 驱动程序 in its correct environment is a prerequisite for understanding every call that follows. It then covers the 匹配表, which is how a USB驱动程序 declares which 设备 it wants. It walks through `探测` and `附加`, the two halves of the 驱动程序's entry point into the world. It covers the softc layout, which is where the 驱动程序 keeps its per-设备 state. It presents the cleanup chain, which is how the 驱动程序 unwinds its own work when `分离` is called. And it ends with the registration macros that bind the 驱动程序 to the 内核模块 system. +本节从外向内推进。首先解释USB驱动程序在FreeBSD USB子系统中的位置,因为将驱动程序放置在正确的环境中是理解后续每个调用的前提。然后介绍匹配表,这是USB驱动程序声明它想要哪些设备的方式。接着遍历 `probe` 和 `attach`,即驱动程序进入世界的入口点的两半。介绍softc布局,这是驱动程序保存其每个设备状态的地方。展示清理链,这是驱动程序在调用 `detach` 时如何展开自己的工作。最后以将驱动程序绑定到内核模块系统的注册宏结束。 -Along the way, the chapter uses `uled.c` as a recurring reference. That is a real FreeBSD 驱动程序, about three hundred lines long, located at `/usr/src/sys/dev/usb/misc/uled.c`. It is short enough to read end to end in a single sitting and rich enough to show every piece of machinery a USB驱动程序 needs. If you want to ground every idea in this section against real code, open that file now in another window and keep it open. Every time the chapter references a pattern, you will be able to see the pattern in a working 驱动程序. +在此过程中,本章以 `uled.c` 作为反复引用的参考。那是一个真实的FreeBSD驱动程序,大约三百行代码,位于 `/usr/src/sys/dev/usb/misc/uled.c`。它短到可以在一次阅读中从头到尾读完,又足够丰富以展示USB驱动程序需要的每一个机制。如果你想将本节中的每个概念与真实代码对照,现在就在另一个窗口中打开那个文件并保持打开。每次本章引用一个模式时,你都能在一个工作的驱动程序中看到该模式。 -### Where a USB Driver Sits in the FreeBSD Tree +### USB驱动程序在FreeBSD树中的位置 -FreeBSD's USB subsystem lives under `/usr/src/sys/dev/usb/`. That directory contains everything from the 主机控制器 驱动程序 at the bottom (`controller/ehci.c`, `controller/xhci.c`, and so on) to the class 驱动程序 higher up (`net/if_cdce.c`, `wlan/if_rum.c`, `input/ukbd.c`), to 串行驱动程序 (`serial/uftdi.c`, `serial/uplcom.c`), to generic 框架 code (`usb_设备.c`, `usb_transfer.c`, `usb_request.c`). When a new 驱动程序 is added to the tree, it goes into one of these subdirectories according to its role. A 驱动程序 for a blinking-LED gadget belongs under `misc/`. A 驱动程序 for a network adapter belongs under `net/`. A 驱动程序 for a serial adapter belongs under `serial/`. For your own work, you will not add files to `/usr/src/sys/dev/usb/` directly; you will build out-of-tree modules in your own workshop directory, the same way 第25章 did. The directory layout matters for reading the source, not for writing it. +FreeBSD的USB子系统位于 `/usr/src/sys/dev/usb/` 下。该目录包含从底层的主机控制器驱动程序(`controller/ehci.c`、`controller/xhci.c` 等)到更高层的类驱动程序(`net/if_cdce.c`、`wlan/if_rum.c`、`input/ukbd.c`),到串行驱动程序(`serial/uftdi.c`、`serial/uplcom.c`),到通用框架代码(`usb_device.c`、`usb_transfer.c`、`usb_request.c`)的一切。当一个新的驱动程序被添加到树中时,它根据其角色进入这些子目录之一。一个用于闪烁LED小工具的驱动程序属于 `misc/`。一个用于网络适配器的驱动程序属于 `net/`。一个用于串行适配器的驱动程序属于 `serial/`。对于你自己的工作,你不会直接向 `/usr/src/sys/dev/usb/` 添加文件;你将在自己的工作目录中构建树外模块,就像第25章那样。目录布局对于阅读源代码很重要,但对于编写不重要。 -Every FreeBSD USB驱动程序 sits somewhere in a small vertical stack. At the bottom is the 主机控制器 驱动程序, which actually talks to the silicon. Above that is the USB 框架, which handles 描述符 parsing, 设备 enumeration, transfer scheduling, hub routing, and the generic machinery every 设备 needs. Above the 框架 are the class 驱动程序, which you will write. A class 驱动程序 附加 to a USB 接口, not to the 总线 directly. This is the most important architectural point in the chapter. +每个FreeBSD USB驱动程序位于一个小的垂直栈中的某个位置。底部是主机控制器驱动程序,它实际与硅片通信。其上是USB框架,处理描述符解析、设备枚举、传输调度、集线器路由以及每个设备需要的通用机制。框架之上是类驱动程序,你将编写的就是这些。一个类驱动程序附加到一个USB接口,而不是直接附加到总线。这是本章中最重要的架构要点。 -In the New总线 tree, the 附加ment relationship looks like this: +在Newbus树中,附加关系看起来像这样: ```text nexus0 @@ -597,17 +597,17 @@ nexus0 └─ [class driver] ``` -The 驱动程序 you will write 附加 to `uhub`, not to `us总线`, not to `ehci`, and not to `pci`. The USB 框架 walks the 设备 描述符, creates a child for each 接口, and offers those children to class 驱动程序 through the new总线 探测 mechanism. When your 驱动程序's 探测 routine is called, it is being asked: "here is an 接口; is it yours?" The 匹配表 in your 驱动程序 is how you answer that question. +你将编写的驱动程序附加到 `uhub`,而不是 `usbus`,不是 `ehci`,也不是 `pci`。USB框架遍历设备描述符,为每个接口创建一个子设备,并通过Newbus探测机制将这些子设备提供给类驱动程序。当你的驱动程序的探测例程被调用时,它被问到的是:"这是一个接口;是你的吗?"你驱动程序中的匹配表就是你回答这个问题的方式。 -There is one subtle point to absorb. A USB 设备 can expose multiple 接口 simultaneously. A multi-function peripheral (say, a USB audio 设备 with a headset and a microphone on the same silicon) exposes one 接口 for playback and another for capture. FreeBSD gives each 接口 its own new总线 child, and each child can be claimed by a different 驱动程序. This is why USB驱动程序 附加 at the 接口 level: it lets the 框架 route 接口 independently. Your 驱动程序 should not assume the 设备 has only one 接口. When you write the 匹配表, you write it against a specific 接口, identified by its class, subclass, protocol, or by its vendor/product pair plus an optional 接口 number. +有一个微妙的要点需要理解。一个USB设备可以同时暴露多个接口。一个多功能外设(例如,一个在同一硅片上带有耳机和麦克风的USB音频设备)暴露一个接口用于播放,另一个用于捕获。FreeBSD为每个接口提供自己的Newbus子设备,每个子设备可以被不同的驱动程序认领。这就是为什么USB驱动程序在接口级别附加:它让框架独立地路由接口。你的驱动程序不应该假设设备只有一个接口。当你编写匹配表时,你是针对一个特定的接口编写的,由其类、子类、协议或由其供应商/产品对加可选的接口号来标识。 -### The Match Table: Telling the Kernel Which Devices Are Yours +### 匹配表:告诉内核哪些设备是你的 -A USB驱动程序 advertises which 设备 it will accept through an array of `STRUCT_USB_HOST_ID` entries. This is analogous to the PCI 匹配表 from Chapter 23, but with USB-specific fields. The authoritative definition lives in `/usr/src/sys/dev/usb/usbdi.h`. Each entry specifies one or more of the following: a 供应商ID, a 产品ID, a 设备 class/subclass/protocol triple, an 接口 class/subclass/protocol triple, or a manufacturer-defined bcdDevice range. You can match broadly (any 设备 that advertises 接口 class 0x03, which is HID) or narrowly (the single 设备 with vendor 0x0403 and product 0x6001, which is an FTDI FT232). Most 驱动程序 match narrowly, because most real 设备 have 驱动程序-specific quirks that apply only to particular hardware revisions. +USB驱动程序通过一个 `STRUCT_USB_HOST_ID` 条目数组来宣传它将接受哪些设备。这类似于第23章中的PCI匹配表,但具有USB特定的字段。权威定义位于 `/usr/src/sys/dev/usb/usbdi.h`。每个条目指定以下一项或多项:供应商标识符、产品标识符、设备类/子类/协议三元组、接口类/子类/协议三元组,或制造商定义的bcdDevice范围。你可以广泛匹配(任何宣传接口类0x03的设备,即HID)或狭窄匹配(供应商标识符0x0403和产品标识符0x6001的单一设备,即FTDI FT232)。大多数驱动程序狭窄匹配,因为大多数真实设备有仅适用于特定硬件修订版的驱动程序特定quirk。 -The 框架 provides convenience macros to build match entries without having to initialize each field by hand. The most common are `USB_VPI(vendor, product, info)` for vendor/product pairs with an optional 驱动程序-specific information field, and the more verbose form where you fill in `mfl_`, `pfl_`, `dcl_`, `dcsl_`, `dcpl_`, `icl_`, `icsl_`, `icpl_` flags to indicate which fields are significant. For clarity and maintainability, 驱动程序 written today tend to use the compact macros whenever they are applicable. +框架提供了便利宏来构建匹配条目,而不必手动初始化每个字段。最常见的是 `USB_VPI(vendor, product, info)` 用于供应商/产品对,带有一个可选的驱动程序特定信息字段,以及更详细的形式,你填写 `mfl_`、`pfl_`、`dcl_`、`dcsl_`、`dcpl_`、`icl_`、`icsl_`、`icpl_` 标志来指示哪些字段是重要的。为了清晰和可维护性,今天编写的驱动程序倾向于在适用时使用紧凑宏。 -Here is how `uled.c` declares its 匹配表. The source is in `/usr/src/sys/dev/usb/misc/uled.c`: +以下是 `uled.c` 如何声明其匹配表的。源代码位于 `/usr/src/sys/dev/usb/misc/uled.c`: ```c static const STRUCT_USB_HOST_ID uled_devs[] = { @@ -616,9 +616,9 @@ static const STRUCT_USB_HOST_ID uled_devs[] = { }; ``` -Two entries, each naming a specific vendor/product pair. The third argument to `USB_VPI` is an unsigned integer that the 驱动程序 can use to distinguish variants at 探测 time; `uled` sets it to zero because both 设备 behave the same way. The vendor and product symbolic names resolve to numeric identifiers defined in `/usr/src/sys/dev/usb/usbdevs.h`, which is a large table generated from `/usr/src/sys/dev/usb/usbdevs`. Adding a new match entry for your own development hardware often means adding a line to `usbdevs` and regenerating the header, or bypassing the symbolic names entirely and writing the hexadecimal values directly in the 匹配表. +两个条目,每个指定一个特定的供应商/产品对。`USB_VPI` 的第三个参数是一个无符号整数,驱动程序可以在探测时用来区分变体;`uled` 将其设为零,因为两个设备的行为方式相同。供应商和产品的符号名称解析为在 `/usr/src/sys/dev/usb/usbdevs.h` 中定义的数字标识符,这是一个从 `/usr/src/sys/dev/usb/usbdevs` 生成的大型表格。为你自己的开发硬件添加新的匹配条目通常意味着向 `usbdevs` 添加一行并重新生成头文件,或者完全绕过符号名称直接在匹配表中写入十六进制值。 -For your own out-of-tree 驱动程序, you do not need to touch `usbdevs` at all. You can write: +对于你自己的树外驱动程序,你根本不需要碰 `usbdevs`。你可以写: ```c static const STRUCT_USB_HOST_ID myfirst_usb_devs[] = { @@ -626,19 +626,19 @@ static const STRUCT_USB_HOST_ID myfirst_usb_devs[] = { }; ``` -The numeric form is perfectly acceptable. Use it when you are prototyping against a specific 设备 and do not yet want to propose additions to the upstream `usbdevs` file. +数字形式是完全可接受的。当你正在针对特定设备进行原型设计且还不想向上游 `usbdevs` 文件提议添加时使用它。 -One important detail about 匹配表s: the `STRUCT_USB_HOST_ID` type includes a flag byte that records which fields are meaningful. When you use `USB_VPI`, the macro fills in those flags for you. If you hand-build an entry with literal braces, you must also fill in the flags yourself, because a zero flag byte means "match anything," and you rarely want that. Prefer the macros. +关于匹配表的一个重要细节:`STRUCT_USB_HOST_ID` 类型包含一个标志字节,记录哪些字段是有意义的。当你使用 `USB_VPI` 时,宏会为你填充这些标志。如果你用字面花括号手动构建条目,你也必须自己填充标志,因为零标志字节意味着"匹配任何设备",而你很少想要那样。请使用宏。 -The 匹配表 is plain data. It does not allocate memory, it does not touch hardware, and it does not depend on any per-设备 state. It is loaded into the 内核 along with the module and used by the 框架 every time a new USB 设备 is enumerated. +匹配表是纯数据。它不分配内存,不触碰硬件,也不依赖任何每个设备的状态。它随模块一起加载到内核中,并在每次枚举新的USB设备时被框架使用。 -### The `探测` Method +### `probe` 方法 -The USB 框架 calls a 驱动程序's `探测` method once per 接口 when a matching-like candidate is presented. The goal of `探测` is to answer a single question: "Should this 驱动程序 附加 to this 接口?" The method must not touch hardware. It must not allocate resources. It must not sleep. All it does is look at the USB 附加 argument, compare it against the 匹配表, and return either a 总线-探测 value (indicating a match, with an associated priority) or `ENXIO` (indicating that this 驱动程序 does not want this 接口). +当出现一个类似匹配的候选时,USB框架每个接口调用一次驱动程序的 `probe` 方法。`probe` 的目标是回答一个单一的问题:"这个驱动程序应该附加到这个接口吗?"该方法不能触碰硬件。它不能分配资源。它不能睡眠。它所做的就是查看USB附加参数,将其与匹配表比较,然后返回一个总线探测值(表示匹配,带有相关优先级)或 `ENXIO`(表示这个驱动程序不想要这个接口)。 -The 附加 argument lives in a structure called `struct usb_附加_arg`, defined in `/usr/src/sys/dev/usb/usbdi.h`. It carries the 供应商ID, the 产品ID, the 设备 描述符, the 接口 描述符, and a handful of helper fields. New总线 lets a 驱动程序 retrieve it through `设备_get_ivars(dev)`. For USB驱动程序, the 框架 provides a wrapper called `usbd_lookup_id_by_uaa` that takes a 匹配表 and an 附加 argument and returns zero on a match or a nonzero errno on a miss. This wrapper encapsulates every case the 驱动程序 needs to handle: vendor/product matching, class/subclass/protocol matching, the flag-byte logic, and the 接口-level dispatch. +附加参数存在于一个名为 `struct usb_attach_arg` 的结构中,定义在 `/usr/src/sys/dev/usb/usbdi.h`。它携带供应商标识符、产品标识符、设备描述符、接口描述符和一些辅助字段。Newbus让驱动程序通过 `device_get_ivars(dev)` 获取它。对于USB驱动程序,框架提供了一个名为 `usbd_lookup_id_by_uaa` 的包装器,它接收一个匹配表和一个附加参数,匹配时返回零,不匹配时返回非零errno。这个包装器封装了驱动程序需要处理的每一种情况:供应商/产品匹配、类/子类/协议匹配、标志字节逻辑和接口级分派。 -A complete 探测 method for our running example looks like this: +我们的运行示例的一个完整探测方法看起来像这样: ```c static int @@ -660,23 +660,23 @@ myfirst_usb_probe(device_t dev) } ``` -The three guard clauses at the top of the function are worth explaining in detail, because they reflect standard USB-驱动程序 hygiene. +函数顶部的三个守卫子句值得详细解释,因为它们反映了标准的USB驱动程序卫生习惯。 -The first guard rejects the case where the USB stack is acting as a 设备 rather than a host. FreeBSD's USB stack can operate in USB-on-the-Go 设备 mode, where the machine itself appears as a USB peripheral to some other host. Most 驱动程序 are host-side 驱动程序 and have no meaningful behavior in 设备 mode, so they reject it immediately. +第一个守卫拒绝USB栈作为设备而非主机运行的情况。FreeBSD的USB栈可以在USB-on-the-Go设备模式下运行,其中机器本身作为某个其他主机的USB外设出现。大多数驱动程序是主机端驱动程序,在设备模式下没有有意义的行为,所以它们立即拒绝。 -The second guard rejects configurations other than index zero. USB 设备 can expose multiple configurations, and a 驱动程序 usually targets one specific configuration. Restricting 探测 to configuration index zero keeps the logic simple for the common case. +第二个守卫拒绝索引零以外的配置。USB设备可以暴露多个配置,驱动程序通常针对一个特定配置。将探测限制为配置索引零使常见情况的逻辑保持简单。 -The third guard rejects 接口 other than index zero. If the 设备 has multiple 接口 and you are writing a 驱动程序 for the first one, this clause is what ensures the 框架 does not offer you the other 接口 by mistake. +第三个守卫拒绝索引零以外的接口。如果设备有多个接口而你正在为第一个接口编写驱动程序,这个子句确保框架不会错误地将其他接口提供给你。 -After the guards, the call to `usbd_lookup_id_by_uaa` does the real matching work. If the 设备's vendor, product, class, subclass, or protocol matches any entry in the table, the function returns zero, and the 探测 method returns zero, which the USB 框架 interprets as "this 驱动程序 wants this 设备." Returning `ENXIO` tells the 框架 to try another candidate 驱动程序. If no candidate wants the 设备, it ends up 附加ed to `ugen`, the generic USB驱动程序, which exposes raw 描述符 and transfers through `/dev/ugenN.M` nodes but provides no 设备-specific behavior. +守卫之后,对 `usbd_lookup_id_by_uaa` 的调用做真正的匹配工作。如果设备的供应商、产品、类、子类或协议匹配表中的任何条目,函数返回零,探测方法返回零,USB框架将其解释为"这个驱动程序想要这个设备"。返回 `ENXIO` 告诉框架尝试另一个候选驱动程序。如果没有候选者想要该设备,它最终被附加到 `ugen`,即通用USB驱动程序,它通过 `/dev/ugenN.M` 节点暴露原始描述符和传输,但不提供设备特定的行为。 -A subtle point worth noting: `探测` returns zero for a match rather than a positive 总线-探测 value. Other FreeBSD 总线 框架 use positive values like `BUS_PROBE_DEFAULT` to indicate a priority, but for USB the convention is zero for match and a nonzero errno for non-match. The 框架 handles priority through the dispatch order rather than through 探测 return values. +一个值得注意的微妙点:`probe` 为匹配返回零而不是正的总线探测值。其他FreeBSD总线框架使用像 `BUS_PROBE_DEFAULT` 这样的正值来指示优先级,但对于USB,约定是零表示匹配,非零errno表示不匹配。框架通过分派顺序而不是通过探测返回值来处理优先级。 -### The `附加` Method +### `attach` 方法 -Once `探测` reports a match, the 框架 calls `附加`. This is where the 驱动程序 does real work: allocate its softc, record the parent 设备 pointer, lock the 接口, set up transfer channels (covered in Section 3), create a `/dev` entry if the 驱动程序 is user-facing, and log a short informational message. Every allocation and registration in `附加` has to be paired with a symmetric release in `分离`, and because any step can fail, the function must have a clear cleanup path from every failure point. +一旦 `probe` 报告匹配,框架调用 `attach`。这是驱动程序做真正工作的地方:分配其softc、记录父设备指针、锁定接口、设置传输通道(在第3节中介绍)、如果驱动程序面向用户则创建 `/dev` 条目,并记录一条简短的信息消息。`attach` 中的每个分配和注册都必须与 `detach` 中的对称释放配对,并且因为任何步骤都可能失败,函数必须从每个故障点有清晰的清理路径。 -A minimal 附加 method looks like this: +一个最小的附加方法看起来像这样: ```c static int @@ -721,27 +721,27 @@ fail_mtx: } ``` -Read through this function top to bottom. Each 块 does one thing. +从上到下阅读这个函数。每个代码块做一件事。 -The call to `设备_set_usb_desc` fills in the New总线 设备 description string from the USB 描述符. After this call, `设备_printf` messages will include the manufacturer and product strings read from the 设备 itself, which makes logs much more informative. +对 `device_set_usb_desc` 的调用从USB描述符填充Newbus设备描述字符串。在此调用之后,`device_printf` 消息将包含从设备本身读取的制造商和产品字符串,这使日志更加有用。 -The call to `mtx_init` creates a 互斥锁 that will protect the per-设备 state. Every USB 传输回调 runs under this 互斥锁 (the 框架 takes it for you around the 回调), so everything the 回调 touches must be serialised by it. 第25章 introduced 互斥锁es; the usage here is the same. +对 `mtx_init` 的调用创建一个互斥锁,用于保护每个设备的状态。每个USB传输回调都在这个互斥锁下运行(框架在回调周围为你获取它),所以回调触及的一切都必须由它来序列化。第25章介绍了互斥锁;这里的用法是相同的。 -The two `sc->sc_` assignments cache two pointers that the rest of the 驱动程序 will need. `sc->sc_udev` is the `struct usb_设备 *` that the 驱动程序 uses when issuing USB requests. `sc->sc_iface_index` identifies the 接口 index this 驱动程序 附加ed to, so later transfer-setup calls target the right 接口. +两个 `sc->sc_` 赋值缓存了驱动程序其余部分需要的两个指针。`sc->sc_udev` 是驱动程序在发出USB请求时使用的 `struct usb_device *`。`sc->sc_iface_index` 标识该驱动程序附加到的接口索引,以便后续的传输设置调用目标指向正确的接口。 -The call to `usbd_transfer_setup` is the biggest single operation in `附加`. It allocates and configures all the transfer objects the 驱动程序 will use, based on a configuration array (`myfirst_usb_config`) that Section 3 will examine in detail. If this call fails, the 驱动程序 has not yet allocated anything except the 互斥锁, so the cleanup path goes to `fail_mtx` and destroys the 互斥锁. +对 `usbd_transfer_setup` 的调用是 `attach` 中最大的单项操作。它基于一个配置数组(`myfirst_usb_config`,第3节将详细研究)分配并配置驱动程序将使用的所有传输对象。如果此调用失败,驱动程序除了互斥锁之外还没有分配任何东西,所以清理路径转到 `fail_mtx` 并销毁互斥锁。 -The call to `make_dev` creates the user-visible `/dev` node. The 第25章 pattern applies here: set `si_drv1` on the cdev so that the cdevsw handlers can retrieve the softc through `dev->si_drv1`. If this call fails, the cleanup path goes to `fail_xfer`, which also runs the unsetup for the transfers before destroying the 互斥锁. +对 `make_dev` 的调用创建用户可见的 `/dev` 节点。第25章的模式在这里适用:在cdev上设置 `si_drv1`,以便cdevsw处理程序可以通过 `dev->si_drv1` 获取softc。如果此调用失败,清理路径转到 `fail_xfer`,它在销毁互斥锁之前也运行传输的取消设置。 -The `return (0)` on the happy path is the contract with the 框架: a zero return means the 设备 is 附加ed and the 驱动程序 is ready. +成功路径上的 `return (0)` 是与框架的契约:零返回意味着设备已附加,驱动程序准备就绪。 -The two labels at the bottom implement the labelled-goto cleanup chain from 第25章. Each label corresponds to the state the 驱动程序 has reached at the time the failure happened, and the cleanup fall-through runs exactly the teardown steps needed to undo the work done so far. When you read a FreeBSD 驱动程序 and see this pattern, you are looking at the same discipline you practised in 第25章 applied to a new set of resources. +底部的两个标签实现了第25章的标签化goto清理链。每个标签对应驱动程序在失败发生时达到的状态,清理的穿透运行恰好是撤销到目前为止所做工作所需的拆卸步骤。当你阅读FreeBSD驱动程序并看到这种模式时,你正在看的是你在第25章练习过的相同规范应用于一组新资源。 -One important detail about the USB 框架 that 第25章 did not need to cover: if you look at `uled.c` or any other real USB驱动程序, you will sometimes see `usbd_transfer_setup` accept a pointer to the 接口 index rather than an integer. The 框架 can modify that pointer in the case of virtual or multiplexed 接口; pass it by address, not by value. The skeleton above does this correctly. +关于第25章不需要涵盖的USB框架的一个重要细节:如果你查看 `uled.c` 或任何其他真实的USB驱动程序,你有时会看到 `usbd_transfer_setup` 接受一个指向接口索引的指针而不是整数。框架可以在虚拟或复用接口的情况下修改该指针;按地址传递,而不是按值传递。上面的骨架正确地做到了这一点。 -### The Softc: Per-Device State +### Softc:每个设备的状态 -A USB驱动程序's softc is a plain C structure stored as the New总线 驱动程序 data for each 附加ed 设备. It is allocated automatically by the 框架 based on the size declared in the 驱动程序 描述符, and it is the place where all per-设备 mutable state lives. For our running example, the softc looks like this: +USB驱动程序的softc是一个普通的C结构,存储为每个已附加设备的Newbus驱动程序数据。它由框架根据驱动程序描述符中声明的大小自动分配,是所有每个设备可变状态存放的地方。对于我们的运行示例,softc看起来像这样: ```c struct myfirst_usb_softc { @@ -756,27 +756,27 @@ struct myfirst_usb_softc { }; ``` -Let us walk through each member. +让我们逐一看看每个成员。 -`sc_udev` is the opaque pointer the USB 框架 uses to identify the 设备. Every USB call that acts on the 设备 takes this pointer. +`sc_udev` 是USB框架用来标识设备的不透明指针。每个操作设备的USB调用都接收这个指针。 -`sc_mtx` is the per-设备 互斥锁 that protects the softc itself and any shared state the 驱动程序 cares about. The 互斥锁 must be acquired before touching any field that a 传输回调 might also touch, and the 传输回调 always runs with this 互斥锁 held (the 框架 handles the locking for you when it invokes the 回调). +`sc_mtx` 是保护softc本身以及驱动程序关心的任何共享状态的每个设备互斥锁。在触碰传输回调也可能触碰的任何字段之前必须获取该互斥锁,并且传输回调始终在该互斥锁被持有的情况下运行(框架在调用回调时为你处理锁定)。 -`sc_xfer[]` is an array of transfer objects, one per channel the 驱动程序 uses. Its size is a compile-time constant. Section 3 will discuss how each entry in this array is set up by the configuration array passed to `usbd_transfer_setup`. +`sc_xfer[]` 是传输对象数组,驱动程序使用的每个通道一个。其大小是编译时常量。第3节将讨论这个数组中的每个条目是如何由传递给 `usbd_transfer_setup` 的配置数组设置的。 -`sc_dev` is the 字符设备 entry, if the 驱动程序 exposes a user-facing node. For 驱动程序 that do not expose a `/dev` node (some 驱动程序 only export data through `sysctl` or `devctl` events), this field can be omitted. +`sc_dev` 是字符设备条目,如果驱动程序暴露面向用户的节点的话。对于不暴露 `/dev` 节点的驱动程序(一些驱动程序只通过 `sysctl` 或 `devctl` 事件导出数据),此字段可以省略。 -`sc_iface_index` records which 接口 on the USB 设备 this 驱动程序 附加ed to. It is used by transfer setup and, in multi-接口 驱动程序, as a discriminator in logging. +`sc_iface_index` 记录该驱动程序附加到USB设备上的哪个接口。它用于传输设置,在多接口驱动程序中用作日志中的区分器。 -`sc_flags` is a bit vector for 驱动程序-private state. Two flags are declared here: `MYFIRST_USB_FLAG_OPEN` is set while a userland process holds the 设备 open, and `MYFIRST_USB_FLAG_DETACHING` is set at the start of `分离` so that any concurrent I/O path can see that it must abort quickly. This is an application of a standard pattern: setting a flag under the 互斥锁 at the start of 分离, so anyone else who wakes up sees it and bails out. +`sc_flags` 是一个用于驱动程序私有状态的位向量。这里声明了两个标志:`MYFIRST_USB_FLAG_OPEN` 在用户态进程持有设备打开时设置,`MYFIRST_USB_FLAG_DETACHING` 在 `detach` 开始时设置,以便任何并发的I/O路径都能看到它必须快速中止。这是一个标准模式的应用:在互斥锁下、在分离开始时设置一个标志,以便其他唤醒的人看到它并退出。 -Real 驱动程序 often have many more fields: per-transfer 缓冲区, request queues, 回调-to-回调 state machines, timers, and so on. You add to the softc as the 驱动程序 grows. The guiding principle is that any state that persists between function calls, and is not global to the module, belongs in the softc. +真实的驱动程序通常有更多字段:每个传输的缓冲区、请求队列、回调到回调的状态机、定时器等。你随着驱动程序的增长向softc添加内容。指导原则是,任何在函数调用之间持续存在的、不是模块全局的状态,都属于softc。 -### The `分离` Method +### `detach` 方法 -When a 设备 is unplugged, when the module is unloaded, or when userspace uses `devctl 分离`, the 框架 calls the 驱动程序's `分离` method. The 驱动程序's job is to release every resource it allocated in `附加`, cancel any in-flight work, make sure no 回调 is running, and return zero. If `分离` returns an error, the 框架 treats the 设备 as still 附加ed, which can create problems if the hardware has already physically vanished. Most 驱动程序 return zero unconditionally, or only return an error in very specific "设备 总线y" cases where the 驱动程序 implements its own reference counting for userspace handles. +当设备被拔出、模块被卸载或用户空间使用 `devctl detach` 时,框架调用驱动程序的 `detach` 方法。驱动程序的工作是释放它在 `attach` 中分配的每个资源、取消任何进行中的工作、确保没有回调正在运行,并返回零。如果 `detach` 返回错误,框架将设备视为仍然附加,这在硬件已经物理消失时可能造成问题。大多数驱动程序无条件返回零,或仅在驱动程序为用户空间句柄实现了自己的引用计数的非常特定的"设备忙"情况下返回错误。 -The 分离 method for our running example is the symmetric cleanup of the 附加 method: +我们的运行示例的分离方法是附加方法的对称清理: ```c static int @@ -801,15 +801,15 @@ myfirst_usb_detach(device_t dev) } ``` -The first 块 sets the 分离ing flag under the 互斥锁. If another thread is about to take the 互斥锁 and start a new transfer, it will see the flag and refuse. The `destroy_dev` call removes the `/dev` entry; after it returns, no new open calls can arrive. The `usbd_transfer_unsetup` call cancels any in-flight transfers and waits for their 回调 to complete; after it returns, no 传输回调 can still be running. With no new openers and no running 回调, it is safe to destroy the 互斥锁. +第一个代码块在互斥锁下设置分离标志。如果另一个线程即将获取互斥锁并启动一个新的传输,它会看到标志并拒绝。`destroy_dev` 调用移除 `/dev` 条目;它返回后,不会有新的打开调用到来。`usbd_transfer_unsetup` 调用取消任何进行中的传输并等待它们的回调完成;它返回后,没有传输回调可以仍在运行。没有新的打开者和没有运行的回调,销毁互斥锁就是安全的。 -There is a subtlety here that new 内核 programmers sometimes stumble over: the order matters. Destroying the `/dev` entry before unwinding the transfers ensures that no new user operation can start, but it does not stop the transfers that were already running when 分离 was called. That is `usbd_transfer_unsetup`'s job. Both steps are necessary, and the order (cdev first, then transfers, then 互斥锁) is the right one because each later step depends on no new work arriving during it. +这里有一个新的内核程序员有时会犯的微妙错误:顺序很重要。在展开传输之前销毁 `/dev` 条目确保没有新的用户操作可以启动,但不会停止分离被调用时已经在运行的传输。那是 `usbd_transfer_unsetup` 的工作。两步都是必要的,顺序(先是cdev,然后是传输,最后是互斥锁)是正确的,因为每个后续步骤依赖于在其期间没有新工作到来。 -One further point about 分离 and concurrency. The 框架 guarantees that no 探测, 附加, or 分离 runs concurrently with another 探测, 附加, or 分离 on the same 设备. But 传输回调 run on their own path, and they can be in progress at the exact moment 分离 is called. The combination of the 分离ing flag and `usbd_transfer_unsetup` is what makes this safe. If you add new resources to your 驱动程序, you must add symmetric cleanup that accounts for this concurrency. +关于分离和并发性的另一点。框架保证同一个设备上没有探测、附加或分离与另一个探测、附加或分离并发运行。但传输回调在自己的路径上运行,它们可以在分离被调用的确切时刻正在进行。分离标志和 `usbd_transfer_unsetup` 的组合使这变得安全。如果你向驱动程序添加新资源,你必须添加考虑这种并发性的对称清理。 -### Registration Macros +### 注册宏 -Every FreeBSD 驱动程序 needs to 注册 itself with the 内核 so that the 内核 knows when to call its 探测, 附加, and 分离 routines. USB驱动程序 use a small set of macros that bind everything together into a 内核模块. The macros go at the bottom of the 驱动程序 file and look intimidating at first but are entirely mechanical once you know what each line does. +每个FreeBSD驱动程序都需要向内核注册自己,以便内核知道何时调用其probe、attach和detach例程。USB驱动程序使用一小组宏将所有内容绑定到一个内核模块中。这些宏位于驱动程序文件的底部,初看起来令人生畏,但一旦你知道每一行做什么,它们就完全是机械的了。 ```c static device_method_t myfirst_usb_methods[] = { @@ -831,83 +831,83 @@ MODULE_VERSION(myfirst_usb, 1); USB_PNP_HOST_INFO(myfirst_usb_devs); ``` -Let us read each 块. +让我们阅读每个代码块。 -The `设备_method_t` array lists the methods the 驱动程序 supplies. For a USB驱动程序 that does not implement extra new总线 children, the three entries shown are sufficient: 探测, 附加, 分离. More complex 驱动程序 might add `设备_suspend`, `设备_resume`, or `设备_shutdown`, but for the vast majority of USB驱动程序 the three basic entries are all that is needed. `DEVMETHOD_END` terminates the array; the 框架 requires it. +`device_method_t` 数组列出了驱动程序提供的方法。对于不实现额外Newbus子设备的USB驱动程序,显示的三个条目就足够了:probe、attach、detach。更复杂的驱动程序可能会添加 `device_suspend`、`device_resume` 或 `device_shutdown`,但对于绝大多数USB驱动程序来说,三个基本条目就是所需的全部。`DEVMETHOD_END` 终止数组;框架要求它。 -The `驱动程序_t` structure binds the methods array to a human-readable name and declares the softc size. The name is used in 内核 logs and by `devctl`. The softc size tells New总线 how much memory to allocate per 设备. +`driver_t` 结构将方法数组绑定到人类可读的名称并声明softc大小。名称在内核日志和 `devctl` 中使用。softc大小告诉Newbus每个设备分配多少内存。 -The `DRIVER_MODULE` macro 寄存器 the 驱动程序 with the 内核. The arguments are, in order: the module name, the parent 总线 name (always `uhub` for USB class 驱动程序), the 驱动程序 structure, and two optional hooks for events. The event hooks are rarely needed and are usually `NULL`. +`DRIVER_MODULE` 宏将驱动程序注册到内核。参数依次为:模块名称、父总线名称(对于USB类驱动程序始终是 `uhub`)、驱动程序结构和两个可选的事件钩子。事件钩子很少需要,通常为 `NULL`。 -The `MODULE_DEPEND` macro declares that this module needs `usb` to be loaded first. The three numbers are the minimum, preferred, and maximum compatible versions of the `usb` module. For most 驱动程序, `1, 1, 1` is correct: the USB 框架 has versioned its 接口 at 1 for a long time, and it would be unusual to require anything else. +`MODULE_DEPEND` 宏声明此模块需要先加载 `usb`。三个数字是 `usb` 模块的最小、首选和最大兼容版本。对于大多数驱动程序,`1, 1, 1` 是正确的:USB框架已将其接口版本保持在1很长时间,要求其他值是不寻常的。 -The `MODULE_VERSION` macro declares this module's own version number. Other modules that want to depend on `myfirst_usb` would reference the number you declare here. +`MODULE_VERSION` 宏声明此模块自己的版本号。想要依赖 `myfirst_usb` 的其他模块会引用你在这里声明的数字。 -The `USB_PNP_HOST_INFO` macro is the last piece. It exports the 匹配表 into a format the `devd(8)` daemon can read, so that when a matching USB 设备 is plugged in, userspace can auto-load the module. This macro is a relatively recent addition to FreeBSD; older 驱动程序 may not have it. Including it is strongly recommended for any 驱动程序 that wants to participate in FreeBSD's USB plug-and-play system. +`USB_PNP_HOST_INFO` 宏是最后一块。它将匹配表导出为 `devd(8)` 守护进程可以读取的格式,这样当匹配的USB设备被插入时,用户空间可以自动加载模块。这个宏是FreeBSD的较新添加;较旧的驱动程序可能没有它。强烈建议任何想要参与FreeBSD USB即插即用系统的驱动程序包含它。 -Together, these five declarations turn your 驱动程序 file into a loadable 内核模块. Once the file is compiled with a `Makefile` that uses `bsd.kmod.mk`, running `kldload myfirst_usb.ko` will bind the 驱动程序 to the 内核, and any matching 设备 plugged in afterwards will trigger your 探测 and 附加 routines. +这五个声明一起将你的驱动程序文件转化为可加载的内核模块。一旦文件用使用 `bsd.kmod.mk` 的 `Makefile` 编译,运行 `kldload myfirst_usb.ko` 将把驱动程序绑定到内核,之后插入的任何匹配设备都将触发你的probe和attach例程。 -### The Hot-Plug Lifecycle, Revisited in Code +### 热插拔生命周期,代码中的回顾 -Section 1 introduced the 热插拔 lifecycle at the level of mental model: a 设备 appears, the 框架 enumerates it, your 驱动程序 附加, userland interacts with it, the 设备 disappears, the 框架 calls 分离, your 驱动程序 cleans up. With the code in front of you, that narrative now has a concrete sequence: +第1节在思维模型的层面介绍了热插拔生命周期:设备出现,框架枚举它,你的驱动程序附加,用户态与之交互,设备消失,框架调用detach,你的驱动程序清理。有了面前的代码,那个叙述现在有了具体的序列: -1. The user plugs in a matching 设备. -2. The USB 框架 enumerates the 设备, reads all its 描述符, and decides which 接口 to offer to which 驱动程序. -3. For each 接口 that matches your 驱动程序's 匹配表, the 框架 creates a New总线 child and calls your `探测` method. -4. Your `探测` method returns zero. -5. The 框架 calls your `附加` method. You initialise the softc, set up transfers, create the `/dev` node, and return zero. -6. Userland opens the `/dev` node and begins issuing I/O. The 传输回调 from Section 3 start running. -7. The user unplugs the 设备. -8. The 框架 calls your `分离` method. You set the 分离ing flag, destroy the `/dev` node, call `usbd_transfer_unsetup` to cancel all in-flight transfers and wait for 回调 to finish, destroy the 互斥锁, and return zero. -9. The 框架 deallocates the softc and removes the New总线 child. +1. 用户插入一个匹配的设备。 +2. USB框架枚举设备,读取其所有描述符,并决定将哪个接口提供给哪个驱动程序。 +3. 对于匹配你驱动程序匹配表的每个接口,框架创建一个Newbus子设备并调用你的 `probe` 方法。 +4. 你的 `probe` 方法返回零。 +5. 框架调用你的 `attach` 方法。你初始化softc、设置传输、创建 `/dev` 节点,并返回零。 +6. 用户态打开 `/dev` 节点并开始发出I/O。第3节的传输回调开始运行。 +7. 用户拔出设备。 +8. 框架调用你的 `detach` 方法。你设置分离标志、销毁 `/dev` 节点、调用 `usbd_transfer_unsetup` 取消所有进行中的传输并等待回调完成、销毁互斥锁,并返回零。 +9. 框架释放softc并移除Newbus子设备。 -At every step, the 框架 handles the parts you do not have to write yourself. Your responsibility is narrow: react correctly to 探测, 附加, and 分离, and run 传输回调 that respect the state machine. The machinery around you handles enumeration, 总线 arbitration, transfer scheduling, hub routing, and the dozens of corner cases that USB layer imposes. +在每一步,框架处理你不必自己编写的部分。你的责任是狭窄的:正确响应probe、attach和detach,并运行尊重状态机的传输回调。你周围的机制处理枚举、总线仲裁、传输调度、集线器路由以及USB层强加的几十个边界情况。 -The lifecycle has one more subtle quirk that is worth naming. Between the user unplugging the 设备 and the 框架 calling `分离`, there is a brief window in which any in-flight transfer sees a special error: `USB_ERR_CANCELLED`. The transfer 框架 itself generates this error when it tears down the transfers in response to the disconnect. Section 3 will explain how to handle this error in the 回调 state machine. For now, know that it exists and that it is the 驱动程序's normal signal that the 设备 is going away. +生命周期还有一个值得指出的微妙怪癖。在用户拔出设备和框架调用 `detach` 之间,有一个短暂的窗口,其中任何进行中的传输会看到一个特殊错误:`USB_ERR_CANCELLED`。传输框架本身在响应断开连接时拆除传输时生成此错误。第3节将解释如何在回调状态机中处理此错误。现在,只需知道它存在,并且它是驱动程序收到设备即将消失的正常信号。 -### 总结 Section 2 +### 第2节总结 -Section 2 has given you a complete USB驱动程序 skeleton. The skeleton does not yet move data; that is Section 3's topic. But every other part of the 驱动程序 is in place: the 匹配表, the 探测 method, the 附加 method, the softc, the 分离 method, and the registration macros. You have seen how the USB 框架 routes a newly enumerated 设备 through your 探测 routine, how your 附加 routine takes ownership and sets up state, how the 驱动程序 integrates with New总线 through `设备_get_ivars` and `设备_get_softc`, and how the 分离 routine walks the allocation steps in reverse to leave the system clean. +第2节给了你一个完整的USB驱动程序骨架。该骨架还没有移动数据;那是第3节的主题。但驱动程序的每个其他部分都已就位:匹配表、probe方法、attach方法、softc、detach方法和注册宏。你已经看到USB框架如何通过你的probe例程路由新枚举的设备,你的attach例程如何获取所有权并设置状态,驱动程序如何通过 `device_get_ivars` 和 `device_get_softc` 与Newbus集成,以及detach例程如何反向遍历分配步骤以使系统保持干净。 -Two themes from 第25章 have extended naturally into USB territory. First, the labelled-goto cleanup chain. Every resource you acquire has its own label, and every failure path falls through exactly the right sequence of teardown calls. When you compare `myfirst_usb_附加` above with the 附加 functions in `uled.c`, `ugold.c`, or `uftdi.c`, you will see the same pattern repeated. Second, the discipline of single-source-of-truth state in the softc. Every field has one owner, one lifecycle, and one clear place where it is initialised and destroyed. These habits are what make a 驱动程序 readable, portable, and maintainable. +第25章的两个主题自然地延伸到了USB领域。第一,标签化goto清理链。你获取的每个资源都有自己的标签,每个失败路径穿透恰好正确的拆卸调用序列。当你将上面的 `myfirst_usb_attach` 与 `uled.c`、`ugold.c` 或 `uftdi.c` 中的附加函数比较时,你会看到相同的模式重复。第二,softc中单一事实来源状态的规范。每个字段有一个所有者、一个生命周期和一个清晰的初始化和销毁位置。这些习惯使驱动程序可读、可移植和可维护。 -Section 3 will now give this skeleton a voice. Transfer channels will be declared in a configuration array. The USB 框架 will allocate the underlying 缓冲区 and schedule the transactions. A 回调 will wake up each time a transfer completes or needs more data, and it will use a three-state state machine to decide what to do. The same discipline you just learned will apply, but the new concern is the data pipeline itself: how bytes move between the 驱动程序 and the 设备. +第3节现在将给这个骨架一个声音。传输通道将在配置数组中声明。USB框架将分配底层缓冲区并调度事务。一个回调将在每次传输完成或需要更多数据时被唤醒,它将使用一个三状态状态机来决定做什么。你刚刚学到的相同规范将适用,但新的关注点是数据管道本身:字节如何在驱动程序和设备之间移动。 -### Reading `uled.c` As a Complete Example +### 阅读作为完整示例的 `uled.c` -Before moving into transfers, it is worth pausing to read the canonical small-驱动程序 example end to end. The file `/usr/src/sys/dev/usb/misc/uled.c` is approximately three hundred lines of C that implements a 驱动程序 for the Dream Cheeky and Riso Kagaku USB webmail notifier LEDs: small USB gadgets with three coloured LEDs that a host program can light up. The 驱动程序 is short enough to hold in your head, self-contained, and it exercises every pattern we have discussed. +在进入传输之前,值得停下来阅读一下经典的小驱动程序示例。文件 `/usr/src/sys/dev/usb/misc/uled.c` 大约三百行C代码,实现了Dream Cheeky和Riso Kagaku USB网络邮件通知器LED的驱动程序:带有三个彩色LED的小型USB小工具,主机程序可以点亮它们。这个驱动程序短到可以完全装在脑子里,自包含,并且练习了我们讨论过的每一种模式。 -When you open the file, the first 块 you encounter is the standard set of header includes. A USB驱动程序 pulls in headers from several layers: `sys/param.h`, `sys/systm.h`, `sys/总线.h` for the fundamentals; `sys/module.h` for `MODULE_VERSION` and `MODULE_DEPEND`; the USB headers under `dev/usb/` for the 框架; and `usbdevs.h` for the symbolic vendor and product constants. Note that `usbdevs.h` is not a hand-maintained header: it is build-generated from the text file `/usr/src/sys/dev/usb/usbdevs` when the 内核 or module is compiled, so the constants it exposes reflect whatever entries the in-tree `usbdevs` file currently lists. `uled.c` also pulls in `sys/conf.h` and friends because it creates a 字符设备. +当你打开文件时,你遇到的第一个代码块是标准的头文件包含。一个USB驱动程序从多个层引入头文件:`sys/param.h`、`sys/systm.h`、`sys/bus.h` 用于基础;`sys/module.h` 用于 `MODULE_VERSION` 和 `MODULE_DEPEND`;`dev/usb/` 下的USB头文件用于框架;以及 `usbdevs.h` 用于符号供应商和产品常量。注意 `usbdevs.h` 不是手动维护的头文件:它是在编译内核或模块时从文本文件 `/usr/src/sys/dev/usb/usbdevs` 构建生成的,所以它暴露的常量反映了树内 `usbdevs` 文件当前列出的任何条目。`uled.c` 还引入了 `sys/conf.h` 和相关文件,因为它创建一个字符设备。 -The second 块 is the softc declaration. `uled` keeps its state in a structure that has the 设备 pointer, a 互斥锁, an array of two transfer pointers (one for control, one for data), a 字符设备 pointer, a 回调 state pointer, and a small "color" byte that records the current LED colour. The softc is straightforward: every field is private, every allocation has one place where it is made and one place where it is freed. +第二个代码块是softc声明。`uled` 将其状态保存在一个结构中,包含设备指针、互斥锁、两个传输指针的数组(一个用于控制,一个用于数据)、字符设备指针、回调状态指针和一个记录当前LED颜色的"color"字节。softc很直接:每个字段都是私有的,每个分配有一个创建的地方和一个释放的地方。 -The third 块 is the 匹配表. `uled` supports two vendors (Dream Cheeky and Riso Kagaku) with one 产品ID each. The `USB_VPI` macro fills in the flag byte for a vendor-plus-product match. The table is two entries, flat and simple. +第三个代码块是匹配表。`uled` 支持两个供应商(Dream Cheeky和Riso Kagaku),每个有一个产品标识符。`USB_VPI` 宏为供应商加产品匹配填充标志字节。表是两个条目,扁平且简单。 -The fourth 块 is the transfer configuration array. `uled` declares two channels: a control-out channel used to send SET_REPORT requests to the 设备 (which is how the LED colour is actually programmed), and an interrupt-in channel that reads status 数据包 from the LED. The control channel has `type = UE_CONTROL` and a 缓冲区 size big enough to hold the setup 数据包 plus the payload. The interrupt channel has `type = UE_INTERRUPT`, `direction = UE_DIR_IN`, and a 缓冲区 size that matches the LED's report size. +第四个代码块是传输配置数组。`uled` 声明两个通道:一个用于向设备发送SET_REPORT请求的控制输出通道(这是LED颜色实际被编程的方式),以及一个从LED读取状态数据包的中断输入通道。控制通道有 `type = UE_CONTROL` 和足够容纳设置数据包加有效载荷的缓冲区大小。中断通道有 `type = UE_INTERRUPT`、`direction = UE_DIR_IN` 和与LED报告大小匹配的缓冲区大小。 -The fifth 块 is the 回调 functions. The control 回调 follows the three-state machine you saw in 第3节: in `USB_ST_SETUP`, it constructs a setup 数据包 and an eight-byte HID report payload, submits the transfer, and returns. In `USB_ST_TRANSFERRED`, it wakes any userland writer that was waiting for the colour change to complete. In the default case (errors), it handles cancellation gracefully and retries on other errors. +第五个代码块是回调函数。控制回调遵循你在第3节中看到的三状态机:在 `USB_ST_SETUP` 中,它构造一个设置数据包和一个八字节HID报告有效载荷,提交传输并返回。在 `USB_ST_TRANSFERRED` 中,它唤醒任何等待颜色更改完成的用户态写入者。在默认情况(错误)中,它优雅地处理取消并在其他错误上重试。 -The interrupt 回调 is similar but without the setup-数据包 complication. It reads an eight-byte status report, checks whether it indicates a button press (the Riso Kagaku 设备 have an optional button), and rearms. +中断回调类似但没有设置数据包的复杂性。它读取一个八字节状态报告,检查它是否指示按钮按下(Riso Kagaku设备有一个可选按钮),然后重新武装。 -The sixth 块 is the character-设备 methods. `uled` exposes a `/dev/uled0` entry that accepts `write(2)` calls with a three-byte payload (red, green, blue). The `d_write` handler copies the three bytes into the softc, starts the 控制传输, and returns. When the transfer completes, the colour is actually programmed. The `d_read` handler is not implemented (LEDs do not have meaningful state to read), so reads return zero. +第六个代码块是字符设备方法。`uled` 暴露一个 `/dev/uled0` 条目,接受带有三字节有效载荷(红、绿、蓝)的 `write(2)` 调用。`d_write` 处理程序将三个字节复制到softc中,启动控制传输并返回。当传输完成时,颜色实际被编程。`d_read` 处理程序未实现(LED没有有意义的状态可读),所以读取返回零。 -The seventh 块 is the New总线 methods: 探测, 附加, 分离. The 探测 uses `usbd_lookup_id_by_uaa` exactly as shown in Section 2. The 附加 calls `设备_set_usb_desc`, initialises the 互斥锁, calls `usbd_transfer_setup` with the configuration array, and creates the 字符设备. The 分离 runs these in reverse. +第七个代码块是Newbus方法:probe、attach、detach。探测使用 `usbd_lookup_id_by_uaa`,与第2节中展示的完全相同。附加调用 `device_set_usb_desc`、初始化互斥锁、用配置数组调用 `usbd_transfer_setup` 并创建字符设备。分离反向运行这些步骤。 -The eighth 块 is the registration macros. `DRIVER_MODULE(uled, uhub, ...)`, `MODULE_DEPEND(uled, usb, 1, 1, 1)`, `MODULE_VERSION(uled, 1)`, and `USB_PNP_HOST_INFO(uled_devs)`. Exactly the sequence you learned. +第八个代码块是注册宏。`DRIVER_MODULE(uled, uhub, ...)`、`MODULE_DEPEND(uled, usb, 1, 1, 1)`、`MODULE_VERSION(uled, 1)` 和 `USB_PNP_HOST_INFO(uled_devs)`。正是你学到的序列。 -Reading through `uled.c` with the Section 2 vocabulary in hand, the whole file legibly maps onto the patterns you now understand. Every structural choice the 驱动程序 makes has a name. Every line of code is an instance of a general pattern. This is the kind of clarity that makes FreeBSD 驱动程序 readable. +带着第2节的词汇阅读 `uled.c`,整个文件清晰地映射到你现在理解的模式上。驱动程序做出的每个结构选择都有一个名称。每一行代码都是一个通用模式的实例。这就是使FreeBSD驱动程序可读的那种清晰度。 -Before continuing to Section 3, we recommend you actually open `uled.c` now and read it. Even if some lines are still obscure, the overall structure will match the mental model you have built. The details will make more sense as you progress through the rest of the chapter, and revisiting this file after finishing the chapter is an excellent way to consolidate the material. +在继续第3节之前,我们建议你现在实际打开 `uled.c` 并阅读它。即使有些行仍然不清楚,整体结构会匹配你构建的思维模型。细节会随着你在本章其余部分的推进而更有意义,在完成本章后重新访问这个文件是巩固材料的绝佳方式。 -## 第3节: Performing USB Data Transfers +## 第3节:执行USB数据传输 -### The Transfer Configuration Array +### 传输配置数组 -A USB驱动程序 declares its transfers up front, at compile time, through a small array of `struct usb_config` entries. Each entry describes one transfer channel: its type (control, bulk, interrupt, or isochronous), its direction (in or out), which 端点 it targets, how big its 缓冲区 is, which flags apply, and which 回调 function to invoke when the transfer completes. The 框架 reads this array once, during `附加`, when the 驱动程序 calls `usbd_transfer_setup`. From that point on, each channel behaves like a small state machine that the 驱动程序 drives through its 回调. +USB驱动程序在编译时通过一个小的 `struct usb_config` 条目数组预先声明其传输。每个条目描述一个传输通道:其类型(控制、批量、中断或等时)、其方向(输入或输出)、它目标指向哪个端点、其缓冲区有多大、哪些标志适用以及传输完成时调用哪个回调函数。框架在 `attach` 期间当驱动程序调用 `usbd_transfer_setup` 时读取这个数组一次。从那时起,每个通道像一个小的状态机一样运行,驱动程序通过其回调来驱动它。 -The configuration array is declarative. You are not programming the sequence of hardware operations; you are telling the 框架 what channels your 驱动程序 will use, and the 框架 builds the infrastructure to support them. This is an effective abstraction, and it is one of the reasons USB驱动程序 in FreeBSD are usually much shorter than equivalent 驱动程序 for 总线es like PCI that demand direct 注册 manipulation. +配置数组是声明性的。你不是在编程硬件操作的序列;你是在告诉框架你的驱动程序将使用哪些通道,框架构建支持它们的基础设施。这是一个有效的抽象,也是FreeBSD中的USB驱动程序通常比需要直接寄存器操作的总线(如PCI)的等效驱动程序短得多的原因之一。 -For our running example, we will declare three channels. A bulk-IN channel for reading data from the 设备, a bulk-OUT channel for writing data to the 设备, and an interrupt-IN channel for receiving asynchronous status events. A real 驱动程序 for a serial adapter or an LED notifier might use one or two of these; we use three to show the pattern applied to different transfer types. +对于我们的运行示例,我们将声明三个通道。一个用于从设备读取数据的批量IN通道、一个用于向设备写入数据的批量OUT通道和一个用于接收异步状态事件的中断IN通道。一个用于串行适配器或LED通知器的真实驱动程序可能使用其中一两个;我们使用三个来展示应用于不同传输类型的模式。 ```c enum { @@ -946,34 +946,34 @@ static const struct usb_config myfirst_usb_config[MYFIRST_USB_N_XFER] = { }; ``` -The enumeration at the top gives each channel a name and defines `MYFIRST_USB_N_XFER` as the total count. This is a common idiom; it keeps the channels symbolically accessible and makes it easy to add a new channel later. `MYFIRST_USB_N_XFER` is what you pass to `usbd_transfer_setup`, to `usbd_transfer_unsetup`, and to the softc's `sc_xfer[]` array declaration. +顶部的枚举为每个通道起了一个名字,并将 `MYFIRST_USB_N_XFER` 定义为总数。这是一个常见的习惯用法;它使通道可以通过符号名访问,并方便以后添加新通道。`MYFIRST_USB_N_XFER` 是你传递给 `usbd_transfer_setup`、`usbd_transfer_unsetup` 以及 softc 的 `sc_xfer[]` 数组声明的值。 -The array itself uses designated initialisers, which keeps the assignment of each channel to its enumeration index explicit. Let us walk through the fields. +数组本身使用指定初始化器,使每个通道到其枚举索引的赋值保持明确。让我们逐一分析各个字段。 -`type` is one of `UE_CONTROL`, `UE_BULK`, `UE_INTERRUPT`, or `UE_ISOCHRONOUS`, from `/usr/src/sys/dev/usb/usb.h`. It has to match the 端点's type as declared in the USB 描述符. If you say `UE_BULK` but the 设备 has an interrupt 端点, `usbd_transfer_setup` will fail. +`type` 是 `UE_CONTROL`、`UE_BULK`、`UE_INTERRUPT` 或 `UE_ISOCHRONOUS` 之一,定义在 `/usr/src/sys/dev/usb/usb.h` 中。它必须匹配 USB 描述符中声明的端点类型。如果你指定 `UE_BULK` 但设备有一个中断端点,`usbd_transfer_setup` 将失败。 -`端点` identifies the 端点 number, but in most 驱动程序 the special value `UE_ADDR_ANY` is used, which tells the 框架 to pick any 端点 whose type and direction match. This works because most USB 接口 have only one 端点 of each (type, direction) pair, so "any" is unambiguous. A 设备 with multiple bulk-in 端点 would require explicit 端点 addresses. +`端点` 标识端点号,但在大多数驱动程序中,使用特殊值 `UE_ADDR_ANY`,它告诉框架挑选任何类型和方向匹配的端点。这之所以有效,是因为大多数 USB 接口每种(类型、方向)对只有一个端点,因此"任意"是明确的。具有多个批量输入端点的设备需要显式的端点地址。 -`direction` is `UE_DIR_IN` or `UE_DIR_OUT`. Again, this must match the 描述符. +`direction` 是 `UE_DIR_IN` 或 `UE_DIR_OUT`。同样,这必须匹配描述符。 -`bufsize` is the size of the 缓冲区 the 框架 allocates for this channel. For 批量传输, 512 bytes is a common choice because that is the maximum 数据包 size for high-speed bulk 端点, so a single 512-byte 缓冲区 can hold exactly one 数据包. Larger 缓冲区 are supported, but for most purposes 512 or a small multiple is correct. For interrupt 端点, the 缓冲区 can be smaller because interrupt 数据包 are typically eight, sixteen, or sixty-four bytes. +`bufsize` 是框架为该通道分配的缓冲区大小。对于批量传输,512字节是一个常见选择,因为那是高速批量端点的最大数据包大小,所以一个512字节的缓冲区可以恰好容纳一个数据包。支持更大的缓冲区,但大多数情况下512或其小的倍数是正确的。对于中断端点,缓冲区可以更小,因为中断数据包通常是八、十六或六十四字节。 -`flags` is a bitfield struct (each flag is a one-bit integer). The flags affect how the 框架 handles short transfers, stalls, timeouts, and pipe behaviour. +`flags` 是一个位字段结构(每个标志是一个一位整数)。这些标志影响框架如何处理短传输、停滞、超时和管道行为。 -- `pipe_bof` (pipe 块ed on failure): if the transfer fails, 块 further transfers on the same pipe until the 驱动程序 explicitly restarts it. This is usually set for both read and write 端点. -- `short_xfer_ok`: for incoming transfers, treat a transfer that completed with less data than requested as success rather than error. Setting this is what allows a bulk-IN channel to read responses of variable length from a 设备. -- `force_short_xfer`: for outgoing transfers, finish the transfer with a short 数据包 even when the data is aligned to a full 数据包 boundary. This is used by some protocols to signal the end of a message. -- Several other flags control more advanced behaviour; for most 驱动程序, `pipe_bof` plus `short_xfer_ok` (on reads) plus possibly `force_short_xfer` (on writes, protocol-dependent) is all that is needed. +- `pipe_bof`(管道失败时阻塞):如果传输失败,阻塞同一管道上的后续传输,直到驱动程序显式重启它。这通常在读写端点上都设置。 +- `short_xfer_ok`:对于传入传输,将以少于请求数据量完成的传输视为成功而非错误。设置这个允许批量IN通道从设备读取可变长度的响应。 +- `force_short_xfer`:对于传出传输,即使数据对齐到完整数据包边界,也以短数据包结束传输。一些协议使用它来发出消息结束信号。 +- 其他几个标志控制更高级的行为;对于大多数驱动程序,`pipe_bof` 加上 `short_xfer_ok`(在读通道上)加上可能的 `force_short_xfer`(在写通道上,取决于协议)就是所需的全部。 -`回调` is the function the 框架 calls whenever this channel needs attention. The 回调 is a `usb_回调_t`, which takes a pointer to the `struct usb_xfer` and returns void. All of the channel's state-machine logic lives inside the 回调. +`callback` 是框架在该通道需要注意时调用的函数。回调是一个 `usb_callback_t`,接收一个指向 `struct usb_xfer` 的指针并返回void。通道的所有状态机逻辑都在回调内部。 -`timeout` (in milliseconds) sets an upper bound on how long a transfer can wait before being forcibly completed with an error. Setting a timeout is useful for write channels, because it prevents a hung 设备 from stalling the 驱动程序 indefinitely. For read channels, leaving the timeout at zero (meaning "no timeout") is common, because reads are often expected to 块 waiting for the 设备 to have something to say. +`timeout`(以毫秒为单位)设置传输在被强制以错误完成之前可以等待的上限。设置超时对于写通道很有用,因为它防止挂起的设备无限期地阻塞驱动程序。对于读通道,将超时留为零(意味着"无超时")是常见的,因为读取通常被期望阻塞等待设备有话要说。 -This array, combined with `usbd_transfer_setup`, is all the 驱动程序 needs to declare its data pipeline. The 框架 allocates the underlying DMA 缓冲区, sets up the scheduling, and watches the pipes. The 驱动程序 never has to call into a 注册 or schedule a transaction by hand. It just writes 回调. +这个数组结合 `usbd_transfer_setup`,是驱动程序声明其数据管道所需的全部。框架分配底层DMA缓冲区、设置调度并监视管道。驱动程序永远不必手动调用寄存器或调度事务。它只需要编写回调。 -### Setting Up and Tearing Down Transfers +### 设置和拆卸传输 -In the `附加` method shown in Section 2, the call to `usbd_transfer_setup` creates the channels from the configuration array: +在第2节中展示的 `attach` 方法中,对 `usbd_transfer_setup` 的调用从配置数组创建通道: ```c error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, @@ -981,29 +981,29 @@ error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc, &sc->sc_mtx); ``` -The arguments are, in order: the USB 设备 pointer, a pointer to the 接口 index (the 框架 can update it in certain multi-接口 scenarios), the destination array for the created transfer objects, the configuration array, the number of channels, the softc pointer (which is passed into 回调 via `usbd_xfer_softc`), and the 互斥锁 the 框架 will hold around each 回调. +参数依次为:USB设备指针、指向接口索引的指针(框架可以在某些多接口场景中更新它)、创建的传输对象的目标数组、配置数组、通道数量、softc指针(通过 `usbd_xfer_softc` 传递给回调)和框架将在每个回调周围持有的互斥锁。 -If this call succeeds, `sc->sc_xfer[]` is populated with pointers to `struct usb_xfer` objects. Each object encapsulates a channel's state. From this point, the 驱动程序 can submit a transfer on a channel with `usbd_transfer_submit(sc->sc_xfer[i])`, and the 框架 will, in the fullness of time, call the corresponding 回调. +如果此调用成功,`sc->sc_xfer[]` 被填充为指向 `struct usb_xfer` 对象的指针。每个对象封装了一个通道的状态。从这时起,驱动程序可以通过 `usbd_transfer_submit(sc->sc_xfer[i])` 在通道上提交传输,框架最终会调用相应的回调。 -The symmetric teardown, shown in the `分离` method, is `usbd_transfer_unsetup`: +在 `detach` 方法中展示的对称拆卸是 `usbd_transfer_unsetup`: ```c usbd_transfer_unsetup(sc->sc_xfer, MYFIRST_USB_N_XFER); ``` -This call does three things, in order. It cancels any in-flight transfer on each channel. It waits for the corresponding 回调 to run with `USB_ST_ERROR` or `USB_ST_CANCELLED`, so the 驱动程序 has a chance to clean up any per-transfer state. It frees the 框架's internal state for the channel. After `usbd_transfer_unsetup` returns, the `sc_xfer[]` entries are no longer valid, and the associated 回调 will not be invoked again. +此调用依次做三件事。它取消每个通道上任何进行中的传输。它等待相应的回调以 `USB_ST_ERROR` 或 `USB_ST_CANCELLED` 运行,以便驱动程序有机会清理任何每个传输的状态。它释放框架为通道分配的内部状态。在 `usbd_transfer_unsetup` 返回后,`sc_xfer[]` 条目不再有效,关联的回调也不会再被调用。 -This is the piece of machinery that makes 分离 safe in the presence of ongoing I/O. You do not need to implement your own "wait for outstanding transfers" logic. The 框架 provides it, atomically, through this single call. +这就是使分离在有进行中I/O的情况下变得安全的机制。你不需要实现自己的"等待未完成传输"逻辑。框架通过这单个调用原子地提供了它。 -### The Callback State Machine +### 回调状态机 -Every 传输回调 follows the same three-state state machine. When the 框架 invokes the 回调, you ask `USB_GET_STATE(xfer)` for the current state, and then you handle it. The three possible states are declared in `/usr/src/sys/dev/usb/usbdi.h`: +每个传输回调都遵循相同的三状态状态机。当框架调用回调时,你通过 `USB_GET_STATE(xfer)` 询问当前状态,然后处理它。三个可能的状态在 `/usr/src/sys/dev/usb/usbdi.h` 中声明: -- `USB_ST_SETUP`: the 框架 is ready to submit a new transfer on this channel. You should prepare the transfer (set its length, copy data into its 缓冲区, and so on) and call `usbd_transfer_submit`. If you have no work for this channel right now, simply return; the 框架 will leave the channel idle until something else triggers a submit. -- `USB_ST_TRANSFERRED`: the most recent transfer completed successfully. You should read out the results (copy received data out, decide what to do next) and either return (if the channel should go idle) or fall through to `USB_ST_SETUP` to start another transfer. -- `USB_ST_ERROR`: the most recent transfer failed. You should inspect `usbd_xfer_get_error(xfer)` to see why, handle the error (for most errors, you fall through to `USB_ST_SETUP` to retry after a short delay; for stalls, you issue a clear-stall), and decide whether to continue. +- `USB_ST_SETUP`:框架准备好在此通道上提交新的传输。你应该准备传输(设置其长度、将数据复制到其缓冲区中等)并调用 `usbd_transfer_submit`。如果你现在没有该通道的工作,简单地返回;框架会让通道保持空闲直到其他事情触发提交。 +- `USB_ST_TRANSFERRED`:最近的传输成功完成。你应该读出结果(复制接收的数据、决定下一步做什么)然后要么返回(如果通道应该空闲)要么穿透到 `USB_ST_SETUP` 开始另一次传输。 +- `USB_ST_ERROR`:最近的传输失败。你应该检查 `usbd_xfer_get_error(xfer)` 查看原因,处理错误(对于大多数错误,你穿透到 `USB_ST_SETUP` 在短暂延迟后重试;对于停滞,你发出清除停滞),并决定是否继续。 -The typical shape of a bulk-read 回调 looks like this: +典型的批量读取回调的形状如下: ```c static void @@ -1051,27 +1051,27 @@ tr_setup: } ``` -Let us walk through every piece. +让我们逐一分析每个部分。 -The first line retrieves the softc pointer from the transfer object. This is how the 回调 gets at the per-设备 state. It works because the softc was passed to `usbd_transfer_setup`, which stored it inside the transfer object. +第一行从传输对象获取softc指针。这是回调获取每个设备状态的方式。它之所以有效是因为softc被传递给了 `usbd_transfer_setup`,后者将其存储在传输对象内部。 -The call to `usbd_xfer_status` fills in `actlen`, the number of bytes actually transferred on 帧 zero. For a read, this is how much data arrived. For a write, it is how much data was sent. The other three parameters (which this example does not use) give the total transfer length, the timeout, and a status flags pointer; most 回调 only need `actlen`. +对 `usbd_xfer_status` 的调用填充 `actlen`,即帧零上实际传输的字节数。对于读取,这是到达了多少数据。对于写入,这是发送了多少数据。其他三个参数(本例不使用)提供总传输长度、超时和状态标志指针;大多数回调只需要 `actlen`。 -The switch on `USB_GET_STATE(xfer)` is the state machine. In `USB_ST_TRANSFERRED`, the 回调 copies the received data out of the USB 帧 into the 驱动程序's own 缓冲区. The helper function `myfirst_usb_deliver_received` (which you would write) could push the data onto a queue, wake a sleeping read() on the `/dev` node, or feed a higher-level protocol parser. +对 `USB_GET_STATE(xfer)` 的switch是状态机。在 `USB_ST_TRANSFERRED` 中,回调将接收到的数据从USB帧复制到驱动程序自己的缓冲区。辅助函数 `myfirst_usb_deliver_received`(你需要编写的)可以将数据推送到队列、唤醒 `/dev` 节点上睡眠的read()或馈送给更高级别的协议解析器。 -The `FALLTHROUGH` after processing the transferred data takes the 回调 into the `USB_ST_SETUP` branch. This is the idiomatic pattern for channels that run continuously: every time a read finishes, immediately start another read. If the 驱动程序 wanted to stop reading after one transfer (say, a one-shot control request), it would `return;` at the end of `USB_ST_TRANSFERRED` instead of falling through. +处理传输数据后的 `FALLTHROUGH` 将回调带入 `USB_ST_SETUP` 分支。这是连续运行通道的惯用模式:每次读取完成后,立即开始另一次读取。如果驱动程序想在一次传输后停止读取(比如一次性控制请求),它会在 `USB_ST_TRANSFERRED` 末尾 `return;` 而不是穿透。 -In `USB_ST_SETUP`, `usbd_xfer_set_帧_len` sets the length of 帧 zero to the maximum the channel can handle, and `usbd_transfer_submit` hands the transfer to the 框架. The 框架 will start the actual hardware operation and, when complete, call the 回调 again with either `USB_ST_TRANSFERRED` or `USB_ST_ERROR`. +在 `USB_ST_SETUP` 中,`usbd_xfer_set_frame_len` 将帧零的长度设置为通道能处理的最大值,`usbd_transfer_submit` 将传输交给框架。框架将启动实际的硬件操作,完成时以 `USB_ST_TRANSFERRED` 或 `USB_ST_ERROR` 再次调用回调。 -The `default` case is where error handling happens. Two errors get special treatment. `USB_ERR_CANCELLED` is the signal that the transfer is being torn down, typically because the 设备 was unplugged or `usbd_transfer_unsetup` was called. The 回调 must not resubmit the transfer in this case; if it did, it could race with the teardown and potentially touch memory that is about to be freed. Breaking out of the switch without calling `usbd_transfer_submit` is the correct behaviour. +`default` 情况是错误处理发生的地方。两个错误得到特殊处理。`USB_ERR_CANCELLED` 是传输正在被拆除的信号,通常是因为设备被拔出或调用了 `usbd_transfer_unsetup`。在这种情况下回调不能重新提交传输;如果它这样做,可能与拆除竞争并可能触碰即将被释放的内存。不调用 `usbd_transfer_submit` 直接跳出switch是正确的行为。 -`USB_ERR_STALLED` is the signal that the 端点 returned a STALL handshake, meaning the 设备 is refusing to accept more data until the host clears the stall. The call to `usbd_xfer_set_stall` schedules a clear-stall operation on the control 端点. After the clear-stall completes, the 框架 will call the 回调 again with `USB_ST_SETUP`, at which point the 驱动程序 can reissue the transfer. This logic is built into the 框架 so that every 驱动程序 gets the same correct behaviour with minimal code. +`USB_ERR_STALLED` 是端点返回STALL握手的信号,意味着设备拒绝接受更多数据直到主机清除停滞。对 `usbd_xfer_set_stall` 的调用在控制端点上调度一个清除停滞操作。清除停滞完成后,框架将以 `USB_ST_SETUP` 再次调用回调,此时驱动程序可以重新发出传输。这个逻辑内置于框架中,使每个驱动程序以最少的代码获得相同的正确行为。 -For any other error, the 回调 falls through to `tr_setup` and attempts to resubmit the transfer. This is a simple retry policy. A more sophisticated 驱动程序 might count consecutive errors and give up after a threshold, or it might escalate by calling `usbd_transfer_unsetup` on itself. For many 驱动程序, the default retry loop is sufficient. +对于任何其他错误,回调穿透到 `tr_setup` 并尝试重新提交传输。这是一个简单的重试策略。更复杂的驱动程序可能会计算连续错误并在达到阈值后放弃,或者可能通过调用 `usbd_transfer_unsetup` 来升级。对于许多驱动程序,默认的重试循环就足够了。 -### The Write Callback +### 写回调 -The write 回调 has the same shape but its `USB_ST_SETUP` branch is more interesting, because it has to decide whether there is any data to write: +写回调有相同的形状,但其 `USB_ST_SETUP` 分支更有趣,因为它必须决定是否有数据要写: ```c static void @@ -1112,17 +1112,17 @@ tr_setup: } ``` -The main change is the logic at `tr_setup`. For a read, the 驱动程序 always wants another read armed, so the 回调 just sets the 帧 length and submits. For a write, the 驱动程序 only submits if there is something to send. The helper `myfirst_usb_dequeue_write` returns the number of bytes pulled from an internal transmit queue; if zero, the 回调 breaks out of the switch without submitting anything, which leaves the channel idle. When userspace later writes more data into the 设备, the 驱动程序 code that handles the `write()` system call queues the bytes and explicitly calls `usbd_transfer_start(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR])`. That call fires an `USB_ST_SETUP` invocation of the 回调, which now finds data in the queue and submits it. +主要的变化是 `tr_setup` 处的逻辑。对于读取,驱动程序总是想要另一个读取被武装起来,所以回调只设置帧长度并提交。对于写入,驱动程序只在有东西要发送时才提交。辅助函数 `myfirst_usb_dequeue_write` 返回从内部传输队列拉取的字节数;如果为零,回调不提交任何东西就跳出switch,这使通道保持空闲。当用户空间后来向设备写入更多数据时,处理 `write()` 系统调用的驱动程序代码将字节排队并显式调用 `usbd_transfer_start(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR])`。该调用触发回调的 `USB_ST_SETUP` 调用,此时它在队列中找到数据并提交它。 -This interaction between the userspace I/O path and the transfer state machine is the heart of an interactive USB驱动程序. Reads are self-driving: once armed, they rearm themselves on every completion. Writes are demand-driven: they submit only when data is available and go idle otherwise. Both patterns run inside the same three-state machine; the difference is only in what happens at `USB_ST_SETUP`. +用户空间I/O路径和传输状态机之间的这种交互是交互式USB驱动程序的核心。读取是自驱动的:一旦武装起来,它们在每次完成时重新武装自己。写入是需求驱动的:它们只在数据可用时提交,否则进入空闲。两种模式都在同一个三状态机内运行;区别只在于 `USB_ST_SETUP` 时发生什么。 -### Control Transfers +### 控制传输 -Control transfers do not typically run on continuously-armed channels; they are usually issued one-shot, either synchronously from a system-call handler or as a one-shot 回调 triggered by some 驱动程序 event. The `struct usb_config` for a control channel has `type = UE_CONTROL` and otherwise looks similar to the bulk and interrupt configurations. The 缓冲区 size must be at least eight bytes to hold the setup 数据包, and the 回调 deals with two 帧: 帧 zero is the setup 数据包, and 帧 one is the optional data phase. +控制传输通常不在连续武装的通道上运行;它们通常以一次性方式发出,要么从系统调用处理程序同步发出,要么作为由某个驱动程序事件触发的一次性回调。控制通道的 `struct usb_config` 有 `type = UE_CONTROL`,其他方面看起来与批量和中断配置相似。缓冲区大小必须至少八字节以容纳设置数据包,回调处理两个帧:帧零是设置数据包,帧一是可选的数据阶段。 -The typical one-shot use is to issue a vendor-specific request at 驱动程序-load time. The FTDI 串行驱动程序, for example, uses 控制传输 to set the 波特率 and line parameters every time the user configures the 串行端口. Because the control 回调 is scheduled by the 框架 just like any other 传输回调, the code pattern is identical. What differs is the construction of the setup 数据包 in the `USB_ST_SETUP` branch. +典型的一次性用途是在驱动程序加载时发出供应商特定的请求。例如,FTDI串行驱动程序使用控制传输来设置波特率和线路参数,每次用户配置串行端口时都会使用。由于控制回调像任何其他传输回调一样由框架调度,代码模式是相同的。不同之处在于 `USB_ST_SETUP` 分支中设置数据包的构造。 -For a control-read transfer, the code looks something like this: +对于控制读取传输,代码看起来像这样: ```c case USB_ST_SETUP: { @@ -1144,9 +1144,9 @@ case USB_ST_SETUP: { } ``` -The `USETW` macro stores a sixteen-bit value in the request structure in the little-endian byte order USB requires. The `usbd_copy_in` helper copies from a 内核 缓冲区 into a USB 帧. The `usbd_xfer_set_帧_len` and `usbd_xfer_set_帧` calls tell the 框架 how many 帧 the transfer spans and how long each is. For a control-read, 帧 zero is the setup 数据包 (eight bytes) and 帧 one is the data phase; the 框架 transparently handles the status phase at the end. +`USETW` 宏以USB要求的小端字节顺序将一个16位值存储在请求结构中。`usbd_copy_in` 辅助函数从内核缓冲区复制到USB帧。`usbd_xfer_set_frame_len` 和 `usbd_xfer_set_frames` 调用告诉框架传输跨越多少帧以及每帧多长。对于控制读取,帧零是设置数据包(八字节),帧一是数据阶段;框架透明地处理末尾的状态阶段。 -In the `USB_ST_TRANSFERRED` branch, the 驱动程序 reads the response out of 帧 one: +在 `USB_ST_TRANSFERRED` 分支中,驱动程序从帧一读取响应: ```c case USB_ST_TRANSFERRED: @@ -1156,13 +1156,13 @@ case USB_ST_TRANSFERRED: break; ``` -Control transfers are the right tool for configuration operations where latency and bandwidth do not matter but correctness and sequencing do. They are the wrong tool for streaming data; use bulk or 中断传输 for that. +控制传输是配置操作的正确工具,其中延迟和带宽不重要但正确性和排序重要。它们是流数据的错误工具;请使用批量或中断传输。 -### Interrupt Transfers +### 中断传输 -Interrupt transfers are conceptually the simplest of the four types. An interrupt-IN channel runs a continuous state machine that polls a single 端点 at regular intervals. Each time a 数据包 arrives from the 设备, the 回调 wakes up with `USB_ST_TRANSFERRED`. The 驱动程序 reads the 数据包, processes it (often by delivering it to userland), and falls through to rearm. +中断传输在概念上是四种类型中最简单的。一个中断IN通道运行一个连续的状态机,定期轮询单个端点。每次设备的数据包到达时,回调以 `USB_ST_TRANSFERRED` 被唤醒。驱动程序读取数据包、处理它(通常通过传递给用户态),然后穿透以重新武装。 -The 回调 for our interrupt channel is nearly identical to the bulk-read 回调: +我们的中断通道的回调几乎与批量读取回调相同: ```c static void @@ -1195,70 +1195,70 @@ tr_setup: } ``` -The only meaningful difference from the bulk-read 回调 is that the 缓冲区 is smaller (interrupt 端点 数据包 are typically eight to sixty-four bytes) and the semantics of the data are usually "status update" rather than "stream payload." A USB HID 设备, for example, sends a sixty-four-byte report every few milliseconds describing key presses and mouse motions; an interrupt-IN channel polled continuously in this pattern is how the 内核 receives those reports. +与批量读取回调唯一有意义的区别是缓冲区更小(中断端点数据包通常为八到六十四字节),数据的语义通常是"状态更新"而不是"流有效载荷"。例如,一个USB HID设备每隔几毫秒发送一个六十四字节的报告,描述按键和鼠标移动;以此模式连续轮询的中断IN通道是内核接收这些报告的方式。 -Interrupt-OUT channels work the same way but in reverse: the 回调 has to decide whether to send something at each `USB_ST_SETUP`, analogous to the bulk-write pattern. +中断OUT通道以相同的方式工作但方向相反:回调必须在每个 `USB_ST_SETUP` 时决定是否发送什么东西,类似于批量写入模式。 -### Frame-Level Operations: What the Framework Gives You +### 帧级操作:框架为你提供什么 -USB transfers are composed of 帧. A 批量传输 with a large 缓冲区 might be broken into multiple 数据包 by the hardware; the 框架 hides that detail and presents the transfer as a single operation. A 控制传输, on the other hand, has an explicit 帧 structure (setup, data, status). An 等时传输 has one 帧 per scheduled 数据包. The 框架 exposes this structure through a small number of helper functions: +USB传输由帧组成。一个具有大缓冲区的批量传输可能被硬件分成多个数据包;框架隐藏了该细节并将传输呈现为单个操作。另一方面,控制传输有显式的帧结构(设置、数据、状态)。等时传输每个调度的数据包有一个帧。框架通过少量辅助函数暴露此结构: -- `usbd_xfer_max_len(xfer)` returns the largest total length the channel can transfer in a single submit. -- `usbd_xfer_set_帧_len(xfer, 帧, len)` sets the length of a specific 帧. -- `usbd_xfer_set_帧(xfer, n)` sets the total number of 帧 in the transfer. -- `usbd_xfer_get_帧(xfer, 帧)` returns a page-cache pointer for a specific 帧, which is what you pass to `usbd_copy_in` and `usbd_copy_out`. -- `usbd_xfer_帧_len(xfer, 帧)` returns how many bytes were actually transferred in a given 帧 (for completions). -- `usbd_xfer_max_帧len(xfer)` returns the maximum per-帧 length for the channel. +- `usbd_xfer_max_len(xfer)` 返回通道在单次提交中可以传输的最大总长度。 +- `usbd_xfer_set_frame_len(xfer, frame, len)` 设置特定帧的长度。 +- `usbd_xfer_set_frames(xfer, n)` 设置传输中的总帧数。 +- `usbd_xfer_get_frame(xfer, frame)` 返回特定帧的页面缓存指针,这是你传递给 `usbd_copy_in` 和 `usbd_copy_out` 的。 +- `usbd_xfer_frame_len(xfer, frame)` 返回给定帧中实际传输了多少字节(用于完成)。 +- `usbd_xfer_max_frame_len(xfer)` 返回通道的最大每帧长度。 -For bulk and 中断传输, the vast majority of 驱动程序 only touch 帧 zero. For 控制传输, they touch 帧 zero and one. For 等时传输 (which we will not cover in this chapter), they loop over many 帧. The point is that the 框架 gives you complete control over the per-帧 data layout while hiding the hardware details that would otherwise make transfer scheduling a nightmare. +对于批量和中断传输,绝大多数驱动程序只触碰帧零。对于控制传输,它们触碰帧零和帧一。对于等时传输(本章不会涉及),它们循环遍历多帧。关键点是框架给你对每帧数据布局的完全控制,同时隐藏了否则会使传输调度成为噩梦的硬件细节。 -### The `usbd_copy_in` and `usbd_copy_out` Helpers +### `usbd_copy_in` 和 `usbd_copy_out` 辅助函数 -USB 缓冲区 are not plain C 缓冲区. They are allocated by the 框架 in a way that is addressable by the 主机控制器 hardware, which means they often live in DMA-accessible memory pages with platform-specific alignment requirements. The 框架 wraps these 缓冲区 in an opaque `struct usb_page_cache` object, and the 驱动程序 accesses them through two helpers: +USB缓冲区不是普通的C缓冲区。它们由框架以一种可被主机控制器硬件寻址的方式分配,这意味着它们通常位于具有平台特定对齐要求的DMA可访问内存页面中。框架将这些缓冲区包装在一个不透明的 `struct usb_page_cache` 对象中,驱动程序通过两个辅助函数访问它们: -- `usbd_copy_in(pc, offset, src, len)` copies `len` bytes from the plain C 缓冲区 `src` into the 框架-managed 缓冲区 at `offset`. -- `usbd_copy_out(pc, offset, dst, len)` copies `len` bytes out of the 框架-managed 缓冲区 at `offset` into the plain C 缓冲区 `dst`. +- `usbd_copy_in(pc, offset, src, len)` 将 `len` 字节从普通C缓冲区 `src` 复制到偏移 `offset` 处的框架管理缓冲区。 +- `usbd_copy_out(pc, offset, dst, len)` 将 `len` 字节从偏移 `offset` 处的框架管理缓冲区复制到普通C缓冲区 `dst`。 -You never dereference a `struct usb_page_cache *` directly. You never assume it points to a contiguous memory region. You always go through the helpers. This keeps the 驱动程序 portable across platforms with different DMA constraints, and it is the standard convention throughout `/usr/src/sys/dev/usb/`. +你永远不要直接解引用 `struct usb_page_cache *`。你永远不要假设它指向连续的内存区域。你总是通过辅助函数。这使驱动程序在不同DMA约束的平台间可移植,这是 `/usr/src/sys/dev/usb/` 中的标准约定。 -If your 驱动程序 needs to fill a USB 缓冲区 with data from a mbuf chain or from a userland pointer, there are dedicated helpers for that too: `usbd_copy_in_mbuf`, `usbd_copy_from_mbuf`, and the `uiomove` interaction is handled through `usbd_m_copy_in` and related routines. Search the USB 框架 source for the right helper; there is almost certainly one that matches your need. +如果你的驱动程序需要用来自mbuf链或用户态指针的数据填充USB缓冲区,也有专门的辅助函数:`usbd_copy_in_mbuf`、`usbd_copy_from_mbuf`,`uiomove` 交互通过 `usbd_m_copy_in` 和相关例程处理。在USB框架源代码中搜索合适的辅助函数;几乎肯定有一个匹配你的需求。 -### Starting, Stopping, and Querying Transfers +### 启动、停止和查询传输 -Beyond the three 回调, the 驱动程序 interacts with transfer channels through a small number of control functions. The important ones are: +除了三个回调之外,驱动程序通过少量控制函数与传输通道交互。重要的有: -- `usbd_transfer_start(xfer)`: ask the 框架 to schedule a 回调 invocation in the `USB_ST_SETUP` state, even if the channel has been idle. Used when new data becomes available for a write channel. -- `usbd_transfer_stop(xfer)`: stop the channel. Any in-flight transfer is cancelled and the 回调 is invoked with `USB_ST_ERROR` (with `USB_ERR_CANCELLED`). No new 回调 happen until the 驱动程序 calls `usbd_transfer_start` again. -- `usbd_transfer_pending(xfer)`: returns true if a transfer is currently outstanding. Useful for deciding whether to submit a new one or defer. -- `usbd_transfer_drain(xfer)`: 块 until any outstanding transfer completes and the channel is idle. Used in teardown paths that need to wait for in-flight I/O before continuing. +- `usbd_transfer_start(xfer)`:要求框架在 `USB_ST_SETUP` 状态调度回调调用,即使通道一直空闲。当新数据可供写通道使用时使用。 +- `usbd_transfer_stop(xfer)`:停止通道。任何进行中的传输被取消,回调以 `USB_ST_ERROR`(带 `USB_ERR_CANCELLED`)被调用。在驱动程序再次调用 `usbd_transfer_start` 之前不会有新的回调。 +- `usbd_transfer_pending(xfer)`:如果传输当前未完成则返回true。用于决定是提交新的还是推迟。 +- `usbd_transfer_drain(xfer)`:阻塞直到任何未完成的传输完成且通道空闲。用于在继续之前需要等待进行中I/O的拆卸路径。 -These functions are safe to call while holding the 驱动程序's 互斥锁, and in fact most of them require it. The 框架 documentation and the existing 驱动程序 code show the expected usage patterns; when in doubt, grep for the function name in `/usr/src/sys/dev/usb/` and read how existing 驱动程序 use it. +这些函数在持有驱动程序互斥锁时调用是安全的,事实上大多数都要求它。框架文档和现有的驱动程序代码展示了预期的使用模式;有疑问时,在 `/usr/src/sys/dev/usb/` 中grep函数名并阅读现有驱动程序如何使用它。 -### A Worked Example: Echo-Loop over USB +### 完整示例:USB上的回环 -To make the transfer mechanics concrete, consider a small end-to-end scenario. The 驱动程序 exposes a `/dev/myfirst_usb0` entry that accepts writes and returns reads. A user process writes a string to the 设备; the 驱动程序 sends those bytes to the USB 设备 through the bulk-OUT channel. The 设备 bounces the bytes back through its bulk-IN 端点; the 驱动程序 receives them and hands them to any process currently 块ed in a `read()` on the `/dev` node. This is a useful exercise because it exercises both directions of the bulk pipeline and because it has a simple, observable success criterion: the string that goes in is the string that comes out. +为了使传输机制具体化,考虑一个小的端到端场景。驱动程序暴露一个接受写入和返回读取的 `/dev/myfirst_usb0` 条目。用户进程向设备写入一个字符串;驱动程序通过批量OUT通道将这些字节发送到USB设备。设备通过其批量IN端点将字节弹回;驱动程序接收它们并将它们传递给当前在 `/dev` 节点上阻塞在 `read()` 中的任何进程。这是一个有用的练习,因为它锻炼了批量管道的两个方向,并且它有一个简单、可观察的成功标准:进去的字符串就是出来的字符串。 -The 驱动程序 needs a small transmit queue and a small receive queue, both protected by the softc 互斥锁. When userspace writes, the `d_write` handler acquires the 互斥锁, copies the bytes into the transmit queue, and calls `usbd_transfer_start(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR])`. When userspace reads, the `d_read` handler acquires the 互斥锁, checks the receive queue; if empty, it sleeps on a channel related to the queue. The write 回调, running under the 互斥锁, dequeues bytes and submits the transfer. The read 回调, also under the 互斥锁, enqueues received bytes and wakes any 块ed reader. +驱动程序需要一个小型传输队列和一个小型接收队列,两者都由softc互斥锁保护。当用户空间写入时,`d_write` 处理程序获取互斥锁、将字节复制到传输队列,并调用 `usbd_transfer_start(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR])`。当用户空间读取时,`d_read` 处理程序获取互斥锁、检查接收队列;如果为空,它在与队列相关的通道上睡眠。写回调在互斥锁下运行,从队列中取出字节并提交传输。读回调也在互斥锁下运行,将接收到的字节入队并唤醒任何阻塞的读取者。 -The complete flow from userspace `write("hi")` to userspace `read()` seeing "hi" involves three threads of execution interleaved through the state machines: +从用户空间 `write("hi")` 到用户空间 `read()` 看到 "hi" 的完整流程涉及三个通过状态机交织的执行线程: -1. User thread runs `write()`. Driver enqueues "hi" on the TX queue. Driver calls `usbd_transfer_start`. User thread returns. -2. Framework schedules the TX 回调 with `USB_ST_SETUP`. Callback dequeues "hi", copies it into 帧 zero, sets 帧 length to 2, submits. Callback returns. -3. Hardware performs the bulk-OUT transaction. Device echoes "hi" on bulk-IN. -4. Framework schedules the RX 回调 with `USB_ST_TRANSFERRED` (because an earlier `USB_ST_SETUP` had armed a read). Callback reads "hi" from 帧 zero into the RX queue, wakes any 块ed reader, falls through to re-arm the read, submits. Callback returns. -5. User thread, if it was 块ed in `read()`, wakes up. The `d_read` handler copies "hi" out of the RX queue into userspace. User thread returns. +1. 用户线程运行 `write()`。驱动程序将 "hi" 入队到TX队列。驱动程序调用 `usbd_transfer_start`。用户线程返回。 +2. 框架以 `USB_ST_SETUP` 调度TX回调。回调从队列取出 "hi"、将其复制到帧零、设置帧长度为2、提交。回调返回。 +3. 硬件执行批量OUT事务。设备在批量IN上回显 "hi"。 +4. 框架以 `USB_ST_TRANSFERRED` 调度RX回调(因为之前的 `USB_ST_SETUP` 已经武装了一个读取)。回调从帧零读取 "hi" 到RX队列、唤醒任何阻塞的读取者、穿透以重新武装读取、提交。回调返回。 +5. 用户线程,如果它在 `read()` 中阻塞,被唤醒。`d_read` 处理程序将 "hi" 从RX队列复制到用户空间。用户线程返回。 -At each step, the 互斥锁 is held exactly where it needs to be, the state machine moves cleanly between `USB_ST_SETUP` and `USB_ST_TRANSFERRED`, and the 驱动程序 does not have to think about 数据包 boundaries, DMA mappings, or hardware scheduling. The 框架 handles all of that. +在每一步,互斥锁恰好被持有在它需要的地方,状态机在 `USB_ST_SETUP` 和 `USB_ST_TRANSFERRED` 之间干净地移动,驱动程序不必考虑数据包边界、DMA映射或硬件调度。框架处理了所有这些。 -### Putting the Whole Echo-Loop Driver Together +### 将整个回环驱动程序组合起来 -To make the echo-loop description concrete, let us walk through a complete skeleton for `myfirst_usb`. What follows is not a copy of the real 驱动程序 files in `examples/`; it is a narrative presentation of how the pieces fit. The full code is in the examples directory. +为了使回环描述具体化,让我们遍历 `myfirst_usb` 的完整骨架。以下不是 `examples/` 中真实驱动程序文件的副本;它是各部分如何组合的叙述性呈现。完整代码在示例目录中。 -The 驱动程序 has one C source file, `myfirst_usb.c`, and a small header `myfirst_usb.h`. The header declares the softc structure, the constants for the transfer enumeration, and the prototypes for internal helper functions. The source file contains the 匹配表, the transfer configuration array, the 回调 functions, the character-设备 methods, the New总线 探测/附加/分离, and the registration macros. +驱动程序有一个C源文件 `myfirst_usb.c` 和一个小头文件 `myfirst_usb.h`。头文件声明softc结构、传输枚举的常量和内部辅助函数的原型。源文件包含匹配表、传输配置数组、回调函数、字符设备方法、Newbus probe/attach/detach和注册宏。 -The softc is as we described earlier: a USB 设备 pointer, a 互斥锁, the transfer array, a 字符设备 pointer, an 接口 index, a flags byte, and two internal 环形缓冲区 for RX and TX queued data. Each 环形缓冲区 is a fixed-size array (say, 4096 bytes) plus head and tail indices, protected by the 互斥锁. +softc如我们之前描述的:一个USB设备指针、一个互斥锁、传输数组、字符设备指针、接口索引、标志字节和两个用于RX和TX排队数据的内部环形缓冲区。每个环形缓冲区是一个固定大小的数组(比如4096字节)加上头和尾索引,由互斥锁保护。 -The 匹配表 contains one entry: +匹配表包含一个条目: ```c static const STRUCT_USB_HOST_ID myfirst_usb_devs[] = { @@ -1266,11 +1266,11 @@ static const STRUCT_USB_HOST_ID myfirst_usb_devs[] = { }; ``` -The 0x16c0/0x05dc VID/PID pair is the Van Oosting Technologies Incorporated / OBDEV generic test VID/PID, which is free to use for prototyping. +0x16c0/0x05dc VID/PID对是Van Oosting Technologies Incorporated / OBDEV通用测试VID/PID,可以免费用于原型设计。 -The transfer configuration array is the three-channel array from Section 3. The 回调 are the bulk-read, bulk-write, and interrupt-read patterns we walked through. +传输配置数组是第3节中的三通道数组。回调是我们遍历过的批量读取、批量写入和中断读取模式。 -The bulk-read 回调's `USB_ST_TRANSFERRED` branch calls a helper: +批量读取回调的 `USB_ST_TRANSFERRED` 分支调用一个辅助函数: ```c static void @@ -1300,9 +1300,9 @@ myfirst_usb_rx_enqueue(struct myfirst_usb_softc *sc, } ``` -This is a ring-缓冲区 enqueue with wrap-around handling. The `usbd_copy_out` helper is used to move bytes from the USB 帧 into the 环形缓冲区. If the 环形缓冲区 is full, bytes are dropped. A real 驱动程序 would likely either apply USB-level 流控制 (stop arming new reads) or grow the 缓冲区; for the lab, dropping is acceptable. +这是一个带有环绕处理的环形缓冲区入队操作。`usbd_copy_out` 辅助函数用于将字节从 USB 帧移动到环形缓冲区。如果环形缓冲区已满,则丢弃字节。真正的驱动程序可能会应用 USB 级别的流控制(停止武装新读取)或增大缓冲区;对于实验而言,丢弃是可以接受的。 -The bulk-write 回调's helper to dequeue data is the mirror image: +批量写回调的出队辅助函数是它的镜像: ```c static unsigned int @@ -1331,7 +1331,7 @@ myfirst_usb_tx_dequeue(struct myfirst_usb_softc *sc, } ``` -The character-设备 methods are straightforward. Open checks that the 设备 is not already open, sets the open flag, and arms the read channel: +字符设备方法很直接。Open 检查设备是否未打开,设置打开标志,并武装读通道: ```c static int @@ -1355,7 +1355,7 @@ myfirst_usb_open(struct cdev *dev, int flags, int devtype, struct thread *td) } ``` -Close clears the open flag and stops the read channel: +Close 清除打开标志并停止读通道: ```c static int @@ -1374,7 +1374,7 @@ myfirst_usb_close(struct cdev *dev, int flags, int devtype, struct thread *td) } ``` -Read 块 until data is available, then copies bytes from the 环形缓冲区 to userspace: +Read 阻塞直到数据可用,然后将字节从环形缓冲区复制到用户空间: ```c static int @@ -1419,9 +1419,9 @@ myfirst_usb_read(struct cdev *dev, struct uio *uio, int flags) } ``` -Notice the pattern: the 互斥锁 is held while manipulating the 环形缓冲区, but it is released around the `uiomove` call, because `uiomove` can sleep (to fault in user pages) and sleeping while holding a 互斥锁 is forbidden. The 互斥锁 is reacquired after `uiomove` returns. +注意这个模式:操作环形缓冲区时持有互斥锁,但在 `uiomove` 调用周围释放它,因为 `uiomove` 可能睡眠(用于缺页处理),而持有互斥锁时睡眠是被禁止的。`uiomove` 返回后重新获取互斥锁。 -Write is the mirror: copy bytes from user to TX 缓冲区, then kick the write channel: +Write 是镜像操作:将字节从用户空间复制到 TX 缓冲区,然后激活写通道: ```c static int @@ -1467,95 +1467,95 @@ myfirst_usb_write(struct cdev *dev, struct uio *uio, int flags) } ``` -Two things are worth noticing in write. First, when the TX 缓冲区 is full, the write handler sleeps on `sc_tx_count`; the write 回调's `USB_ST_TRANSFERRED` branch calls `wakeup(&sc_tx_count)` after draining some bytes, which wakes the sleeping writer. Second, the write handler calls `usbd_transfer_start` on every chunk it enqueues. This is safe (starting an already-running channel is a no-op) and it ensures the write 回调 is nudged even if the channel had gone idle. +Write 中有两点值得注意。第一,当 TX 缓冲区满时,写处理程序在 `sc_tx_count` 上睡眠;写回调的 `USB_ST_TRANSFERRED` 分支在排空一些字节后调用 `wakeup(&sc_tx_count)`,唤醒睡眠的写入者。第二,写处理程序在入队的每个块上都调用 `usbd_transfer_start`。这是安全的(启动已在运行的通道是无操作),并且确保即使通道已空闲,写回调也会被触发。 -With these four cdev methods and the three 传输回调, you have a complete minimum-viable USB echo 驱动程序. The full source is approximately three hundred lines: short enough to fit on a single screen, concrete enough to exercise the real API. +有了这四个 cdev 方法和三个传输回调,你就有了一个完整的最小可用 USB echo 驱动程序。完整源码大约三百行:短到可以放在一个屏幕上,具体到可以练习真实的 API。 -### Choosing Between `usb_fifo` and a Custom `cdevsw` +### 在 `usb_fifo` 和自定义 `cdevsw` 之间选择 -When a USB驱动程序 needs to expose a `/dev` entry to userland, FreeBSD offers two approaches. The first is the `usb_fifo` 框架, a generic byte-stream abstraction that gives you `/dev/ugenN.M.epM` style nodes with read, write, poll, and a small ioctl 接口. You declare a `struct usb_fifo_methods` with open, close, start-read, start-write, stop-read, and stop-write 回调, and the 框架 handles the cdev plumbing and the queueing. This is the path of least resistance; `uhid(4)` and `ucom(4)` both use it. +当 USB 驱动程序需要向用户空间暴露 `/dev` 条目时,FreeBSD 提供了两种方式。第一种是 `usb_fifo` 框架,一个通用的字节流抽象,提供 `/dev/ugenN.M.epM` 风格的节点,支持 read、write、poll 和小型 ioctl 接口。你声明一个 `struct usb_fifo_methods`,包含 open、close、start-read、start-write、stop-read 和 stop-write 回调,框架处理 cdev 管道和队列。这是阻力最小的路径;`uhid(4)` 和 `ucom(4)` 都使用它。 -The second approach is a custom `cdevsw`, the same pattern you practised in Chapter 24. This gives you total control over the user 接口 at the cost of writing more code. It is appropriate when the 驱动程序 needs a very specific ioctl surface, when the read/write semantics do not fit a byte stream (for example, a message-oriented protocol), or when the 驱动程序 already fits poorly into the `usb_fifo` model. +第二种方式是自定义 `cdevsw`,与你在第24章练习的模式相同。这让你完全控制用户接口,代价是编写更多代码。当驱动程序需要非常特定的 ioctl 接口、当读/写语义不适合字节流(例如面向消息的协议)时,或者当驱动程序已经不太适合 `usb_fifo` 模型时,这是合适的选择。 -For the running example we have built, a custom `cdevsw` is the right choice because we wrote the 附加 method that calls `make_dev` and the 分离 method that calls `destroy_dev`, which is exactly what a custom `cdevsw` requires. For a 驱动程序 that exposes a byte stream (a serial adapter, say), `usb_fifo` is simpler. When you write your next USB驱动程序, look at both options and pick the one whose 接口 matches your problem. +对于我们构建的示例,自定义 `cdevsw` 是正确的选择,因为我们编写了调用 `make_dev` 的附加方法和调用 `destroy_dev` 的分离方法,这正是自定义 `cdevsw` 所需要的。对于暴露字节流的驱动程序(例如串行适配器),`usb_fifo` 更简单。当你编写下一个 USB 驱动程序时,查看两个选项,选择其接口匹配你问题的那一个。 -### Error Handling and Retry Policy +### 错误处理和重试策略 -The retry loop that our bulk-read 回调 uses, "on any error, rearm and try again," is a reasonable default for ro总线t 驱动程序. But it is not the only policy, and sometimes it is the wrong one. +我们的批量读回调使用的重试循环,"在任何错误上重新武装并重试",对于健壮的驱动程序来说是一个合理的默认值。但这不是唯一的策略,有时它是错误的。 -For a 设备 that might genuinely go away mid-transfer (a USB adapter whose physical connection has been removed before the 框架 has had a chance to notice), rearming indefinitely is a waste; the transfers will keep failing until 分离 is called. Adding a small retry counter and giving up after, say, five consecutive errors, keeps the log from filling with noise. +对于可能在传输中途真正消失的设备(在框架有机会注意到之前物理连接已被移除的 USB 适配器),无限期重新武装是浪费的;传输将持续失败直到调用分离。添加一个小的重试计数器,在连续五次错误后放弃,可以防止日志被噪音填满。 -For a 设备 that implements a strict request-response protocol, an error might invalidate the entire session. In that case, the 回调 should not rearm; instead, it should mark the 驱动程序 as "in error" and let the user close and reopen the 设备 to reset. +对于实现严格请求-响应协议的设备,一个错误可能使整个会话失效。在这种情况下,回调不应重新武装;而应将驱动程序标记为"出错",让用户关闭并重新打开设备以重置。 -For a 设备 that supports stall-and-clear as a normal flow-control mechanism, the `usbd_xfer_set_stall` path is in the happy path, not the error path. Some class protocols use stalls to signal "I am not ready right now"; the 框架's automatic clear-stall machinery handles this transparently. +对于支持停滞和清除作为正常流控制机制的设备,`usbd_xfer_set_stall` 路径在正常路径中,而不是错误路径中。一些类协议使用停滞来发出"我现在没准备好"的信号;框架的自动清除停滞机制透明地处理这一点。 -Your choice of retry policy should match the real behaviour of the 设备 you are writing for. When in doubt, start with the simple "rearm on error" default, observe what happens when you plug and unplug the 设备 repeatedly, and refine from there. +你选择的重试策略应与你要编写的设备的实际行为匹配。如有疑问,从简单的"出错时重新武装"默认值开始,观察反复插拔设备时会发生什么,然后据此改进。 -### Timeouts and Their Consequences +### 超时及其后果 -A timeout on a USB transfer is not just a safety net against hardware stalls; it is an explicit statement about how long the 驱动程序 is willing to wait for an operation to complete before treating it as a failure. Choosing a timeout is a design decision that interacts with many other parts of the 驱动程序, and getting it right requires thinking through several scenarios. +USB 传输上的超时不仅是针对硬件停滞的安全网;它是关于驱动程序愿意等待操作完成多长时间后再将其视为失败的明确声明。选择超时是一个设计决策,与驱动程序的许多其他部分交互,正确把握需要思考几个场景。 -The configuration field `timeout` in `struct usb_config` is measured in milliseconds. A value of zero means "no timeout"; the transfer will wait indefinitely. A positive value means "if the transfer has not completed after this many milliseconds, cancel it and deliver a timeout error to the 回调." +`struct usb_config` 中的 `timeout` 配置字段以毫秒为单位。零值表示"无超时";传输将无限期等待。正值表示"如果传输在这许多毫秒后仍未完成,取消它并向回调传递超时错误。" -For a read channel on a bulk 端点, the usual choice is zero. Reads on bulk channels are waiting for the 设备 to have something to say, and if the 设备 is silent for minutes, that is not necessarily an error. A timeout would force the 驱动程序 to rearm the read every few seconds, which wastes time and produces noise in the log. +对于批量端点上的读通道,通常选择是零。批量通道上的读取在等待设备有话要说,如果设备沉默几分钟,那不一定是错误。超时会强制驱动程序每几秒重新武装读取,这浪费时间并在日志中产生噪音。 -For a write channel, the usual choice is a modest positive value like 5000 (five seconds). If the 设备 fails to drain its FIFO in that time, something is wrong; rather than 块 an indefinite-length write, the 驱动程序 returns an error to userland, which can retry if it wishes. +对于写通道,通常选择是适度的正值,如 5000(五秒)。如果设备在那段时间内未能排空其 FIFO,说明出了问题;驱动程序不是阻塞一个无限长的写入,而是向用户空间返回错误,用户空间可以在需要时重试。 -For an interrupt-IN channel polling for status updates, the usual choice is either zero (like a bulk read) or a timeout that matches the expected polling interval from the 端点 描述符's `bInterval` field. Matching `bInterval` gives the 驱动程序 an explicit "I should have heard from the 设备 by now" signal. +对于轮询状态更新的中断输入通道,通常选择是零(像批量读取一样)或与端点描述符的 `bInterval` 字段中的预期轮询间隔匹配的超时。匹配 `bInterval` 给驱动程序一个明确的"我现在应该已经收到设备的消息了"信号。 -For a 控制传输, timeouts matter most, because 控制传输 are how the 驱动程序 configures the 设备, and a 设备 that does not respond to configuration is wedged. A timeout of 500 to 2000 milliseconds is common. If the 设备 does not respond to a configuration request in a few seconds, the 驱动程序 should assume something is wrong. +对于控制传输,超时最重要,因为控制传输是驱动程序配置设备的方式,而不响应配置的设备是卡住的。500 到 2000 毫秒的超时很常见。如果设备在几秒内不响应配置请求,驱动程序应假定出了问题。 -What happens when a timeout fires? The 框架 calls the 回调 with `USB_ERR_TIMEOUT` as the error. The 回调 typically treats this as a transient failure and rearms (for repeating channels) or returns an error to the caller (for one-shot operations). A repeating read channel that keeps timing out is probably talking to a 设备 that is not responding; after a few consecutive timeouts, it may be worth escalating by calling `usbd_transfer_unsetup` or by logging a more visible warning. +超时触发时会发生什么?框架以 `USB_ERR_TIMEOUT` 作为错误调用回调。回调通常将此视为瞬时失败并重新武装(对于重复通道)或向调用者返回错误(对于一次性操作)。持续超时的重复读通道可能正在与不响应的设备通信;在连续几次超时后,可能值得通过调用 `usbd_transfer_unsetup` 或记录更明显的警告来升级。 -One subtle interaction is worth mentioning: if the transfer has a timeout and the 驱动程序 also sets `pipe_bof` (pipe 块ed on failure), a timeout will 块 the pipe until the 驱动程序 explicitly clears the 块. This is usually what you want, because the pipe may be in an inconsistent state, and clearing the 块 (by submitting a fresh setup, or by calling `usbd_transfer_start`) is a good point to log what happened and decide what to do next. +有一个微妙的交互值得一提:如果传输有超时且驱动程序还设置了 `pipe_bof`(管道失败时阻塞),超时将阻塞管道,直到驱动程序显式清除阻塞。这通常是你想要的,因为管道可能处于不一致状态,而清除阻塞(通过提交新的设置,或调用 `usbd_transfer_start`)是记录发生了什么并决定下一步行动的好时机。 -### What Goes Wrong When Transfer Setup Fails +### 传输设置失败时会出现什么问题 -The `usbd_transfer_setup` call can fail for several reasons. Understanding each is useful both for debugging your own 驱动程序 and for reading the FreeBSD source when you encounter failures. +`usbd_transfer_setup` 调用可能因几个原因失败。理解每一个原因对于调试你自己的驱动程序以及在你遇到失败时阅读 FreeBSD 源代码都很有用。 -**Endpoint mismatch.** If the configuration array asks for an 端点 with a specific type/direction pair that does not exist on the 接口, the call fails with `USB_ERR_NO_PIPE`. This usually means the 匹配表 matched a 设备 that has a different 描述符 layout than the 驱动程序 expected; it is a bug in the 驱动程序. +**端点不匹配。** 如果配置数组请求一个在接口上不存在的具有特定类型/方向对的端点,调用将以 `USB_ERR_NO_PIPE` 失败。这通常意味着匹配表匹配了一个具有不同描述符布局的设备,与驱动程序预期不符;这是驱动程序中的一个错误。 -**Unsupported transfer type.** If the configuration specifies `UE_ISOCHRONOUS` on a 主机控制器 that does not support 等时传输, or if the bandwidth reservation cannot be satisfied, the call fails. Isochronous is the most complex transfer type and the most likely to have platform-specific limitations. +**不支持的传输类型。** 如果配置在不支持等时传输的主机控制器上指定了 `UE_ISOCHRONOUS`,或者带宽预留无法满足,调用将失败。等时传输是最复杂的传输类型,也是最有可能具有平台特定限制的。 -**Out of memory.** The 框架 allocates DMA-capable 缓冲区 for the channels. If memory is low, the allocation fails. This is rare on modern systems but can happen on embedded platforms with tight memory budgets. +**内存不足。** 框架为通道分配支持 DMA 的缓冲区。如果内存不足,分配将失败。这在现代系统上很少见,但在内存预算紧张的嵌入式平台上可能发生。 -**Missing or invalid attributes.** If the configuration has a 缓冲区 size of zero, or a negative 帧 count, or an invalid flag combination, the call fails. Check the configuration against the declarations in `/usr/src/sys/dev/usb/usbdi.h`. +**缺少或无效的属性。** 如果配置的缓冲区大小为零、帧计数为负数或标志组合无效,调用将失败。对照 `/usr/src/sys/dev/usb/usbdi.h` 中的声明检查配置。 -**Power management states.** If the 设备 has been suspended or is in a low-power state, some transfer setup requests will fail. This is mainly relevant for 驱动程序 that handle USB selective suspend. +**电源管理状态。** 如果设备已挂起或处于低功耗状态,一些传输设置请求将失败。这主要与处理 USB 选择性挂起的驱动程序相关。 -When `usbd_transfer_setup` fails, the error code is an `usb_error_t` value, not a standard errno. The definitions are in `/usr/src/sys/dev/usb/usbdi.h`. The function `usbd_errstr` converts an error code to a printable string; use it in your `设备_printf` to make diagnostic messages informative. +当 `usbd_transfer_setup` 失败时,错误码是 `usb_error_t` 值,而不是标准的 errno。定义在 `/usr/src/sys/dev/usb/usbdi.h` 中。函数 `usbd_errstr` 将错误码转换为可打印字符串;在你的 `device_printf` 中使用它来使诊断消息信息丰富。 -### A Detail About `pipe_bof` +### 关于 `pipe_bof` 的细节 -We mentioned `pipe_bof` (pipe 块ed on failure) as a flag in the transfer configuration, but the motivation for it deserves a closer look. USB 端点 are conceptually single-threaded from the 设备's perspective. When the host submits a bulk-OUT 数据包, the 设备 must process that 数据包 before accepting another. If the 数据包 fails, the 设备 may be in an indeterminate state, and the next 数据包 should not be sent until the 驱动程序 has had a chance to resynchronise. +我们在传输配置中提到 `pipe_bof`(管道失败时阻塞)作为一个标志,但它的动机值得更仔细地审视。从设备的角度来看,USB 端点在概念上是单线程的。当主机提交一个批量输出数据包时,设备必须先处理该数据包才能接受另一个。如果数据包失败,设备可能处于不确定状态,在驱动程序有机会重新同步之前不应该发送下一个数据包。 -`pipe_bof` tells the 框架 to pause the pipe when a transfer fails. The next `usbd_transfer_submit` will not actually start a hardware operation; instead, the 框架 waits until the 驱动程序 explicitly calls `usbd_transfer_start` on the channel, which acts as a "resume" signal. This lets the 驱动程序 do a clear-stall or otherwise resynchronise before the next transfer begins. +`pipe_bof` 告诉框架在传输失败时暂停管道。下一次 `usbd_transfer_submit` 实际上不会启动硬件操作;相反,框架会等待,直到驱动程序显式调用通道上的 `usbd_transfer_start`,这充当一个"恢复"信号。这让驱动程序在下一次传输开始之前执行清除停滞或其他重新同步操作。 -Without `pipe_bof`, the 框架 would immediately submit the next transfer after a failure, which might run into the same failure before the 驱动程序 has had a chance to react. +没有 `pipe_bof`,框架会在失败后立即提交下一次传输,这可能在驱动程序有机会反应之前就遇到相同的失败。 -Setting `pipe_bof = 1` is the safe default for most 驱动程序. Clearing it is appropriate for 驱动程序 that want to keep a pipeline full even through occasional errors (for example, audio 驱动程序 where a brief glitch is preferable to a synchronous resynchronisation). +将 `pipe_bof = 1` 设置为大多数驱动程序的安全默认值。清除它适用于希望在即使偶有错误的情况下也保持管道满载的驱动程序(例如,短暂故障优于同步重新同步的音频驱动程序)。 -### `short_xfer_ok` and Data-Length Semantics +### `short_xfer_ok` 和数据长度语义 -The `short_xfer_ok` flag is another configuration option whose meaning is worth spelling out. USB 批量传输 do not have an inherent end-of-message marker. If the host has a 缓冲区 of 512 bytes and the 设备 only has 100 bytes to send, what should happen? There are two possible answers. +`short_xfer_ok` 标志是另一个值得详细说明的配置选项。USB 批量传输没有固有的消息结束标记。如果主机有一个 512 字节的缓冲区而设备只有 100 字节要发送,应该发生什么?有两种可能的答案。 -With `short_xfer_ok` clear (the default), a transfer that completes with less data than requested is treated as an error. The 框架 delivers `USB_ERR_SHORT_XFER` to the 回调, and the 驱动程序 must decide whether to retry, ignore, or escalate. +当 `short_xfer_ok` 清除时(默认),以少于请求数据量完成的传输被视为错误。框架向回调传递 `USB_ERR_SHORT_XFER`,驱动程序必须决定是重试、忽略还是升级。 -With `short_xfer_ok` set, a short transfer is treated as success. The 回调 gets `USB_ST_TRANSFERRED` with `actlen` set to the actual number of bytes received. This is almost always what you want for bulk-IN on message-oriented protocols, where the 设备 decides how much data to send. +当 `short_xfer_ok` 设置时,短传输被视为成功。回调获得 `USB_ST_TRANSFERRED`,`actlen` 设置为实际接收到的字节数。对于面向消息的协议上的批量输入,这几乎总是你想要的,因为设备决定发送多少数据。 -There is a corresponding flag for outgoing transfers: `force_short_xfer`. If set, a transfer whose data happens to be an exact multiple of the 端点's maximum 数据包 size will be padded with a zero-length 数据包 at the end to signal "end of message." USB treats a zero-length 数据包 as a valid transaction, and many protocols use it as an explicit boundary marker. The FTDI 驱动程序 sets this flag on its write channel, for example, because the FTDI protocol expects a trailing short 数据包. +对于传出传输有一个对应的标志:`force_short_xfer`。如果设置,数据恰好是端点最大数据包大小整数倍的传输将在末尾填充一个零长度数据包,以表示"消息结束"。USB 将零长度数据包视为有效事务,许多协议将其用作显式边界标记。例如,FTDI 驱动程序在其写通道上设置了这个标志,因为 FTDI 协议期望一个尾随短数据包。 -Knowing which flag is appropriate requires knowing the protocol the 设备 implements. When you write a 驱动程序 for a 设备 documented with a public protocol specification, check the specification for how it handles boundaries. When you write a 驱动程序 for a poorly-documented 设备, set `short_xfer_ok` on reads (you can always count the bytes), and test both settings of `force_short_xfer` on writes to see which the 设备 accepts. +知道哪个标志合适需要了解设备实现的协议。当你为有公开协议规范的设备编写驱动程序时,检查规范关于如何处理边界的说明。当你为文档不完善的设备编写驱动程序时,在读取上设置 `short_xfer_ok`(你总是可以计数字节),并在写入上测试 `force_short_xfer` 的两种设置,看设备接受哪种。 -### Locking Rules Around Transfers +### 关于传输的锁定规则 -The USB 框架 imposes two locking rules that are essential to get right. +USB 框架强制两个必须正确掌握的锁定规则。 -First, the 互斥锁 you pass to `usbd_transfer_setup` is held by the 框架 around every invocation of the 回调. You do not need to acquire it inside the 回调; it is already held. You also must not release it inside the 回调; doing so breaks the 框架's assumption and can cause random failures. +第一,你传递给 `usbd_transfer_setup` 的互斥锁在每次调用回调时由框架持有。你不需要在回调内部获取它;它已经被持有。你也不得在回调内部释放它;这样做会破坏框架的假设,并可能导致随机故障。 -Second, every call from 驱动程序 code (not from the 回调) to one of `usbd_transfer_start`, `usbd_transfer_stop`, `usbd_transfer_submit`, `usbd_transfer_drain`, and `usbd_transfer_pending` must be made with the 互斥锁 held. This is because these functions read and write fields inside the transfer object that the 回调 also touches, and the 互斥锁 is what serialises access. +第二,从驱动程序代码(不是从回调)到 `usbd_transfer_start`、`usbd_transfer_stop`、`usbd_transfer_submit`、`usbd_transfer_drain` 和 `usbd_transfer_pending` 的每次调用都必须在持有互斥锁的情况下进行。这是因为这些函数读取和写入传输对象内部回调也触及的字段,而互斥锁正是序列化访问的手段。 -Practically, this means most 驱动程序 code that interacts with transfers looks like: +实际上,这意味着大多数与传输交互的驱动程序代码看起来像这样: ```c mtx_lock(&sc->sc_mtx); @@ -1563,7 +1563,7 @@ usbd_transfer_start(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR]); mtx_unlock(&sc->sc_mtx); ``` -or in longer critical sections: +或者在更长的临界区中: ```c mtx_lock(&sc->sc_mtx); @@ -1575,49 +1575,49 @@ if (!usbd_transfer_pending(sc->sc_xfer[MYFIRST_USB_BULK_DT_WR])) mtx_unlock(&sc->sc_mtx); ``` -Drivers that violate these rules occasionally appear to work but fail intermittently on load, under heavy I/O, or during 分离. Getting the locking right from the start saves many hours of debugging later. +违反这些规则的驱动程序偶尔看起来工作正常,但在负载、高 I/O 或分离期间间歇性失败。从一开始就正确掌握锁定可以节省以后许多小时的调试时间。 -### 总结 Section 3 +### 第3节总结 -Section 3 has shown how data flows through a USB驱动程序. A configuration array declares the channels, `usbd_transfer_setup` allocates them, the 回调 drive them through the three-state machine, and `usbd_transfer_unsetup` tears them down. The 框架 abstracts away the hardware details: DMA 缓冲区, 帧 scheduling, 端点 arbitration, stall handling. The 驱动程序's job is to write 回调 that handle completion and to arrange the flow of data through the 回调. +第3节展示了数据如何在 USB 驱动程序中流动。配置数组声明通道,`usbd_transfer_setup` 分配它们,回调通过三状态机驱动它们,`usbd_transfer_unsetup` 拆除它们。框架抽象掉了硬件细节:DMA 缓冲区、帧调度、端点仲裁、停滞处理。驱动程序的工作是编写处理完成的回调,并安排数据通过回调流动。 -Three themes are worth carrying forward. First, the three-state state machine (`USB_ST_SETUP`, `USB_ST_TRANSFERRED`, `USB_ST_ERROR`) is the same in every channel, regardless of transfer type. Learning to read a USB 回调 means learning to parse this state machine; once you know it, every 回调 in every USB驱动程序 in the tree is legible. Second, the `struct usb_page_cache` abstraction is the only safe way to move data into and out of USB 缓冲区. Never bypass `usbd_copy_in` and `usbd_copy_out`. Third, the locking discipline around `usbd_transfer_start`, `_stop`, and `_submit` is not optional; every call from 驱动程序 code must be made under the 互斥锁. +有三个主题值得铭记。第一,三状态状态机(`USB_ST_SETUP`、`USB_ST_TRANSFERRED`、`USB_ST_ERROR`)在每个通道中都是相同的,无论传输类型如何。学会阅读 USB 回调就是学会解析这个状态机;一旦你掌握了它,树中每个 USB 驱动程序的每个回调都是可读的。第二,`struct usb_page_cache` 抽象是在 USB 缓冲区内外移动数据的唯一安全方式。永远不要绕过 `usbd_copy_in` 和 `usbd_copy_out`。第三,围绕 `usbd_transfer_start`、`_stop` 和 `_submit` 的锁定纪律是不可选的;从驱动程序代码发出的每次调用都必须在持有互斥锁的情况下进行。 -With Sections 1 through 3 in hand, you have a complete mental model of USB驱动程序 writing: the concepts, the skeleton, and the data pipeline. Section 4 now shifts to the serial side of 第6部分. The UART subsystem is older, simpler in some ways, more constrained in others, and its idioms are different from USB's. But many of the same habits carry over: match against what you support, 附加 in phases that can be cleanly reversed, drive the hardware through a state machine, and respect the locking. +掌握了第1到第3节,你就拥有了 USB 驱动程序编写的完整思维模型:概念、骨架和数据管道。第4节现在转向第6部分的串行侧。UART 子系统更旧,在某些方面更简单,在其他方面更受限,其惯用语与 USB 不同。但许多相同的习惯延续下来:匹配你支持的内容、可以干净地逆向的阶段化附加、通过状态机驱动硬件、以及尊重锁定纪律。 -> **Take a breath.** We have now worked through the USB half of the chapter: the host and 设备 roles, the 描述符 tree, the four transfer types, the 探测/附加/分离 skeleton, and the three-state `USB_ST_SETUP`/`USB_ST_TRANSFERRED`/`USB_ST_ERROR` 回调 machine that every USB驱动程序 runs. The rest of the chapter turns to the serial side: the `uart(4)` 框架 with its `ns8250` reference 驱动程序, integration with the TTY layer and `termios`, the `ucom(4)` bridge used by USB-to-serial adapters, and the tools and labs that let you test both kinds of 驱动程序 without real hardware. If you want to close the book and come back, this is a natural pause. +> **休息一下。**我们现在已经完成了本章的USB部分:主机和设备角色、描述符树、四种传输类型、probe/attach/detach骨架以及每个USB驱动程序运行的三状态 `USB_ST_SETUP`/`USB_ST_TRANSFERRED`/`USB_ST_ERROR` 回调机。本章的其余部分转向串行方面:带有其 `ns8250` 参考驱动程序的 `uart(4)` 框架、与TTY层和 `termios` 的集成、USB转串行适配器使用的 `ucom(4)` 桥接,以及让你在没有真实硬件的情况下测试两种驱动程序的工具和实验。如果你想合上书稍后再来,这是一个自然的暂停点。 -## 第4节: Writing a Serial UART Driver +## 第4节:编写串行(UART)驱动程序 -### From USB to UART: A Shift of Landscape +### 从USB到UART:场景的转换 -Sections 2 and 3 gave you a complete USB驱动程序. The 框架 there was modern in every sense: 热插拔, DMA-aware, message-oriented, richly abstracted. Section 4 now turns to `uart(4)`, FreeBSD's 框架 for driving Universal Asynchronous Receiver/Transmitters. The landscape is different. Many UART chips are older than USB itself, and the 框架's design reflects that. There is no 热插拔 (a 串行端口 is usually soldered to the board). There is no DMA for most parts (the chip has a small FIFO you poll or an interrupt you handle). There is no 描述符 hierarchy (the chip does not advertise its capabilities; you know what you built against). And there is no notion of transfer channels; there is just the port, into which bytes go and out of which bytes come. +第2节和第3节给了你一个完整的USB驱动程序。那里的框架在每个意义上都是现代的:热插拔、DMA感知、面向消息、丰富抽象。第4节现在转向 `uart(4)`,FreeBSD用于驱动通用异步收发器的框架。场景是不同的。许多UART芯片比USB本身还要老,框架的设计反映了这一点。没有热插拔(串行端口通常焊接在板上)。大多数部分没有DMA(芯片有一个你轮询的小型FIFO或一个你处理的中断)。没有描述符层次结构(芯片不广告其能力;你知道你针对什么构建的)。没有传输通道的概念;只有端口,字节进去,字节出来。 -What the 框架 does provide is a disciplined split of responsibilities between three layers. At the bottom sits your 驱动程序, which knows how the chip's 寄存器 work, how its interrupts fire, how its FIFOs behave, and what platform-specific resources (IRQ line, I/O port range, clock source) it needs. In the middle sits the `uart(4)` 框架 itself, which handles registration, baud-rate configuration calculations, 缓冲区ing, TTY integration, and the scheduling of read and write work. At the top sits the TTY layer, which presents the port to userland as `/dev/ttyuN` and `/dev/cuauN` and handles terminal semantics: line editing, signal generation, control characters, and the vast vocabulary of `termios` knobs that `stty(1)` exposes. +框架确实提供的是三层之间职责的有纪律的分工。底部是你的驱动程序,它知道芯片的寄存器如何工作、其中断如何触发、其FIFO如何行为以及它需要什么平台特定的资源(IRQ线、I/O端口范围、时钟源)。中间是 `uart(4)` 框架本身,处理注册、波特率配置计算、缓冲、TTY集成以及读写工作的调度。顶部是TTY层,它将端口呈现给用户态为 `/dev/ttyuN` 和 `/dev/cuauN` 并处理终端语义:行编辑、信号生成、控制字符以及 `stty(1)` 暴露的庞大 `termios` 旋钮词汇。 -You do not write the TTY layer. You do not write most of the `uart(4)` 框架. Your job, when you write a UART 驱动程序, is to implement a small set of hardware-specific methods that the 框架 calls when it needs to do something at the 注册 level. The 框架 then wires those methods into the rest of the 内核's serial machinery for free. +你不编写TTY层。你不编写 `uart(4)` 框架的大部分。当你编写UART驱动程序时,你的工作是实现一小组硬件特定的方法,框架在需要在寄存器级别做某事时调用这些方法。框架然后将这些方法免费连接到内核其余的串行机制中。 -This section walks through that wiring. It covers the layout of the `uart(4)` 框架, the structures and methods you have to fill in, the canonical `ns8250` 驱动程序 as a concrete reference, and the integration with the TTY layer. It ends with the related `ucom(4)` 框架, which is how USB-to-serial bridges expose themselves to userland using the same TTY 接口 as a real UART. +本节遍历这种连接。它涵盖 `uart(4)` 框架的布局、你必须填充的结构和方法、作为具体参考的经典 `ns8250` 驱动程序以及与TTY层的集成。最后以相关的 `ucom(4)` 框架结束,这是USB转串行桥接器使用与真正UART相同的TTY接口向用户态暴露自己的方式。 -### Where the `uart(4)` Framework Lives +### `uart(4)` 框架位于哪里 -The 框架 itself lives in `/usr/src/sys/dev/uart/`. If you list that directory, you see a handful of 框架 files and a family of hardware-specific 驱动程序. +框架本身位于 `/usr/src/sys/dev/uart/`。如果你列出该目录,你会看到少量框架文件和一系列硬件特定的驱动程序。 -The 框架 files are: +框架文件有: -- `/usr/src/sys/dev/uart/uart.h`: the top-level header that defines the 框架's public API. -- `/usr/src/sys/dev/uart/uart_总线.h`: the structures for new总线 integration and the per-port softc. -- `/usr/src/sys/dev/uart/uart_core.c`: the 附加ment logic, the interrupt dispatcher, the polling loop, the link between `uart(4)` and `tty(4)`. -- `/usr/src/sys/dev/uart/uart_tty.c`: the `ttydevsw` implementation that maps `uart(4)` operations onto `tty(4)` operations. -- `/usr/src/sys/dev/uart/uart_cpu.h`, `uart_dev_*.c`: platform glue and console registration. +- `/usr/src/sys/dev/uart/uart.h`:定义框架公共API的顶级头文件。 +- `/usr/src/sys/dev/uart/uart_bus.h`:用于Newbus集成和每个端口softc的结构。 +- `/usr/src/sys/dev/uart/uart_core.c`:附加逻辑、中断分派器、轮询循环、`uart(4)` 和 `tty(4)` 之间的链接。 +- `/usr/src/sys/dev/uart/uart_tty.c`:将 `uart(4)` 操作映射到 `tty(4)` 操作的 `ttydevsw` 实现。 +- `/usr/src/sys/dev/uart/uart_cpu.h`、`uart_dev_*.c`:平台粘合和控制台注册。 -The hardware-specific 驱动程序 are files of the form `uart_dev_NAME.c` and occasionally `uart_dev_NAME.h`. The most important of these is `uart_dev_ns8250.c`, which implements the ns8250 family (including the 16450, 16550, 16550A, 16650, 16750, and many compatibles). Because the 16550A is effectively the standard UART for PC-style 串行端口s, this one 驱动程序 handles the majority of actual serial hardware in the world. When you want to learn how a real FreeBSD UART 驱动程序 looks, this is the file to open. +硬件特定的驱动程序是 `uart_dev_NAME.c` 形式的文件,偶尔有 `uart_dev_NAME.h`。其中最重要的是 `uart_dev_ns8250.c`,它实现了ns8250系列(包括16450、16550、16550A、16650、16750和许多兼容芯片)。因为16550A实际上是PC风格串行端口的标准UART,这一个驱动程序处理了世界上大多数实际的串行硬件。当你想学习真正的FreeBSD UART驱动程序是什么样子时,这就是要打开的文件。 -Other 驱动程序 in the directory handle chips that are not 16550-compatible: the Intel MID variant, the PL011 ARM UART used on Raspberry Pi and other ARM boards, the NXP i.MX UART, the Sun Microsystems Z8530, and so on. Each one follows the same pattern: fill in a `struct uart_class` and a `struct uart_ops`, 注册 with the 框架, and implement the hardware access methods. +目录中的其他驱动程序处理不兼容16550的芯片:Intel MID变体、Raspberry Pi和其他ARM板上使用的PL011 ARM UART、NXP i.MX UART、Sun Microsystems Z8530等。每一个都遵循相同的模式:填充一个 `struct uart_class` 和一个 `struct uart_ops`,向框架注册,并实现硬件访问方法。 -### The `uart_class` Structure +### `uart_class` 结构 -Every UART 驱动程序 begins by declaring a `struct uart_class`, which is the hardware 描述符 that the 框架 uses to identify the chip family. The definition lives in `/usr/src/sys/dev/uart/uart_总线.h`. The structure looks like this (paraphrased; the real declaration has a few more fields): +每个UART驱动程序首先声明一个 `struct uart_class`,这是框架用来标识芯片系列的硬件描述符。定义位于 `/usr/src/sys/dev/uart/uart_bus.h`。结构看起来像这样(简化版;真实声明有更多字段): ```c struct uart_class { @@ -1629,17 +1629,17 @@ struct uart_class { }; ``` -The `KOBJ_CLASS_FIELDS` macro pulls in the kobj machinery that Chapter 23 introduced (in the context of New总线). A `uart_class` is, at the 内核's abstract-object level, a kobj class whose instances are `uart_softc`. This is how the 框架 can call into 驱动程序-specific methods without needing an `if` ladder: the method dispatch is done by kobj lookup. +`KOBJ_CLASS_FIELDS` 宏引入了第23章在Newbus上下文中介绍的kobj机制。`uart_class` 在内核的抽象对象层面是一个kobj类,其实例是 `uart_softc`。这就是框架如何能够调用驱动程序特定的方法而无需if阶梯:方法分派通过kobj查找完成。 -`uc_ops` is a pointer to the operations structure (coming next), which lists the chip-specific methods. +`uc_ops` 是指向操作结构(接下来介绍)的指针,它列出了芯片特定的方法。 -`uc_range` is how many bytes of 注册 address space the chip uses. For an ns16550-compatible UART, this is 8. +`uc_range` 是芯片使用的寄存器地址空间的字节数。对于ns16550兼容的UART,这是8。 -`uc_rclk` is the reference clock frequency in hertz. The 框架 uses this to compute baud-rate divisors. For a PC-style UART, the reference clock is usually 1,843,200 hertz (a specific multiple of the standard 波特率s). +`uc_rclk` 是以赫兹为单位的参考时钟频率。框架用它来计算波特率除数。对于PC风格的UART,参考时钟通常是1,843,200赫兹(标准波特率的特定倍数)。 -`uc_rshift` is the 注册 address shift. On some 总线es, UART 寄存器 are spaced at intervals other than one byte (for example, every four bytes on some memory-mapped designs). A shift of zero means tight packing; a shift of two means each logical 注册 occupies four bytes of address space. +`uc_rshift` 是寄存器地址移位。在某些总线上,UART寄存器以一字节以外的间隔排列(例如,在某些内存映射设计上每四字节一个)。移位为零意味着紧密排列;移位为二意味着每个逻辑寄存器占用四字节的地址空间。 -For our running example, the class declaration looks like this: +对于我们的运行示例,类声明看起来像这样: ```c static struct uart_class myfirst_uart_class = { @@ -1653,11 +1653,11 @@ static struct uart_class myfirst_uart_class = { }; ``` -The first three positional arguments are the `KOBJ_CLASS_FIELDS` entries: a name, a method table, and a per-instance size. The named fields are the UART-specific ones. For a 驱动程序 targeting 16550-compatible chips, these values are the conventional defaults. +前三个位置参数是 `KOBJ_CLASS_FIELDS` 条目:名称、方法表和每个实例的大小。命名字段是UART特定的。对于针对16550兼容芯片的驱动程序,这些值是传统的默认值。 -### The `uart_ops` Structure +### `uart_ops` 结构 -The `struct uart_ops` is where the real hardware-specific code lives. It is a table of function pointers that the 框架 calls at specific moments. The definition lives in `/usr/src/sys/dev/uart/uart_cpu.h`: +`struct uart_ops` 是真正的硬件特定代码所在的地方。它是一个函数指针表,框架在特定时刻调用。定义位于 `/usr/src/sys/dev/uart/uart_cpu.h`: ```c struct uart_ops { @@ -1670,29 +1670,29 @@ struct uart_ops { }; ``` -Each operation takes a `struct uart_bas *` as its first argument. The "bas" stands for "总线 address space"; it is the 框架's abstraction for access to the chip's 寄存器. A 驱动程序 does not know or care whether the chip is in I/O space or in memory-mapped space; it just calls `uart_getreg(bas, offset)` and `uart_setreg(bas, offset, value)` (declared in `/usr/src/sys/dev/uart/uart.h`), and the 框架 routes the access correctly. +每个操作以 `struct uart_bas *` 作为第一个参数。"bas"代表"总线地址空间";它是框架对芯片寄存器访问的抽象。驱动程序不知道也不关心芯片是在I/O空间还是在内存映射空间;它只调用 `uart_getreg(bas, offset)` 和 `uart_setreg(bas, offset, value)`(在 `/usr/src/sys/dev/uart/uart.h` 中声明),框架正确路由访问。 -Let us go through the six operations in turn. +让我们逐一看看这六个操作。 -`探测` is called when the 框架 needs to know whether a chip of this class is present at a given address. The 驱动程序 typically pokes a 注册, reads it back, and returns zero if the readback matches (suggesting the chip is really there) or a nonzero errno otherwise. For an ns16550, the 探测 writes a test pattern to the scratch 注册 and reads it back. +`probe` 在框架需要知道给定地址处是否存在该类的芯片时被调用。驱动程序通常写入一个寄存器、读回它,如果读回匹配则返回零(表明芯片确实在那里),否则返回非零errno。对于ns16550,探测向暂存寄存器写入测试模式并读回。 -`init` is called to initialise the chip to a known state. The arguments after the bas are `baudrate`, `databits`, `stopbits`, and `奇偶校验`. The 驱动程序 computes the divisor, writes the divisor-latch-access bit, writes the divisor, clears the divisor-latch, sets the line control 注册 for the requested data/stop/奇偶校验 configuration, enables the FIFOs, and enables the chip's interrupts. The exact 注册 sequence for a 16550 is several dozen lines of code and is documented in the chip's data sheet. +`init` 被调用以将芯片初始化为已知状态。bas之后的参数是 `baudrate`、`databits`、`stopbits` 和 `parity`。驱动程序计算除数、写入除数锁存访问位、写入除数、清除除数锁存、为请求的数据/停止/奇偶校验配置设置线路控制寄存器、启用FIFO并启用芯片的中断。16550的确切寄存器序列有几十行代码,记录在芯片的数据手册中。 -`term` is called to shut down the chip. It typically disables interrupts, flushes the FIFOs, and leaves the chip in a safe state. +`term` 被调用以关闭芯片。它通常禁用中断、刷新FIFO并将芯片留在安全状态。 -`putc` sends a single character. This is used by the low-level console path and by polling-based diagnostic output. The 驱动程序 总线y-waits on the transmitter-holding-注册-empty flag, then writes the byte to the transmit 注册. +`putc` 发送单个字符。这用于低级控制台路径和基于轮询的诊断输出。驱动程序忙等待发送保持寄存器空闲标志,然后将字节写入发送寄存器。 -`rxready` returns nonzero if at least one byte is available to read. The 驱动程序 reads the line status 注册 and checks the data-ready bit. +`rxready` 如果至少有一个字节可读则返回非零。驱动程序读取线路状态寄存器并检查数据就绪位。 -`getc` reads a single character. Used by the low-level console for input. The 驱动程序 总线y-waits on the data-ready flag (or the caller ensures `rxready` just returned true), then reads the receive 注册. +`getc` 读取单个字符。由低级控制台用于输入。驱动程序忙等待数据就绪标志(或调用者确保 `rxready` 刚返回true),然后读取接收寄存器。 -These six methods are the entire hardware-specific surface for a UART 驱动程序 at the low level. Everything else (interrupt handling, 缓冲区ing, TTY integration, 热插拔 of PCIe UARTs, console selection) is provided by the 框架. A new UART 驱动程序 is, in effect, a six-function implementation plus a handful of declarations. +这六个方法是UART驱动程序在低级别的整个硬件特定接口。其他一切(中断处理、缓冲、TTY集成、PCIe UART的热插拔、控制台选择)都由框架提供。一个新的UART驱动程序实际上就是一个六函数实现加上少量声明。 -### A Closer Look at `ns8250` +### 近距离查看 `ns8250` -The ns8250 驱动程序 at `/usr/src/sys/dev/uart/uart_dev_ns8250.c` is the best place to see these methods concretely. It is a mature, production-grade 驱动程序 that handles every variant of the 8250/16450/16550/16550A family. The 注册 definitions it uses (from `/usr/src/sys/dev/ic/ns16550.h`) are the same ones every UART-related header in the PC world uses. When you read this 驱动程序, you are reading, in effect, the reference implementation of a 16550 驱动程序 for FreeBSD. +位于 `/usr/src/sys/dev/uart/uart_dev_ns8250.c` 的ns8250驱动程序是具体看到这些方法的最佳位置。它是一个成熟的、生产级的驱动程序,处理8250/16450/16550/16550A系列的每个变体。它使用的寄存器定义(来自 `/usr/src/sys/dev/ic/ns16550.h`)与PC世界中每个UART相关头文件使用的相同。当你阅读这个驱动程序时,你实际上在阅读FreeBSD的16550驱动程序的参考实现。 -The put-character implementation is instructive for its simplicity: +发送字符的实现因其简单性而富有教学意义: ```c static void @@ -1711,13 +1711,13 @@ ns8250_putc(struct uart_bas *bas, int c) } ``` -The loop polls the line status 注册 (LSR) for the transmitter-holding-注册-empty (THRE) flag. When it is set, the transmit holding 注册 is ready to accept a byte. The 驱动程序 writes the byte to the data 注册 (REG_DATA) and then polls again for the transmitter-empty (TEMT) flag to ensure the byte has been shifted out before returning. +循环轮询线路状态寄存器(LSR)的发送保持寄存器空闲(THRE)标志。当它被设置时,发送保持寄存器准备好接受一个字节。驱动程序将字节写入数据寄存器(REG_DATA),然后再次轮询发送器空闲(TEMT)标志以确保字节在返回之前已被移出。 -The `uart_barrier` call is a memory barrier that ensures the write to the data 注册 is visible to the hardware before subsequent reads. On platforms with weak memory ordering, missing this barrier would cause intermittent data loss. +`uart_barrier` 调用是一个内存屏障,确保对数据寄存器的写入在后续读取之前对硬件可见。在弱内存排序的平台上,缺少此屏障会导致间歇性数据丢失。 -The `DELAY(4)` yields four microseconds per iteration, and the `limit` counter is 250,000. Together, they give a one-second timeout before the loop gives up. For a real UART, 250,000 iterations is a cap that should never be reached in normal operation; it is a safety net for the pathological case where the chip is in an unexpected state. +`DELAY(4)` 每次迭代产生四微秒的延迟,`limit` 计数器为250,000。它们一起在循环放弃之前给出一个一秒的超时。对于真正的UART,250,000次迭代是一个正常操作中永远不应该达到的上限;它是芯片处于意外状态时的安全网。 -The 探测 is equally direct: +探测同样直接: ```c static int @@ -1733,135 +1733,136 @@ ns8250_probe(struct uart_bas *bas) } ``` -Bits 4 and 5 of the Interrupt Identification Register (IIR) are defined as always-zero for every variant of the 16550 family. If those bits read as one, this is not a real 16550 注册, and the 探测 rejects the address. +中断标识寄存器(IIR)的第4位和第5位在16550系列的所有变体中均被定义为始终为零。如果这些位读取为1,说明这不是一个真正的16550寄存器,探测函数将拒绝该地址。 -You could read the whole 驱动程序 in an afternoon. What you would come away with is a clear mental model: the methods are narrow, the 框架 is large, and the real engineering is in handling the quirks of specific chip revisions (a FIFO bug in the 16550 predecessor, an erratum in some PC chipsets, a signal-detect issue on certain Oxford 设备). A new UART 驱动程序 for a well-behaved chip is genuinely a small file. +你可以在一个下午读完整个驱动程序。你会获得一个清晰的心智模型:方法是精简的,框架是庞大的,真正的工程在于处理特定芯片版本的怪癖(16550前身的FIFO缺陷、某些PC芯片组的勘误、特定Oxford设备的信号检测问题)。为一个行为良好的芯片编写新的UART驱动程序确实只需要一个小文件。 -### The `uart_softc` and How the Framework Uses It +### `uart_softc` 以及框架如何使用它 -Each instance of a UART 驱动程序 has a `struct uart_softc`, defined in `/usr/src/sys/dev/uart/uart_总线.h`. The 框架 allocates one per 附加ed port. Its important fields include a pointer to the `uart_bas` that describes the port's 注册 layout, the I/O resources (the IRQ, the memory range or I/O port range), the TTY 设备 附加ed to this port, the current line parameters, and two byte 缓冲区 (RX and TX) that the 框架 uses internally. The 驱动程序 does not usually allocate its own softc; it uses the 框架's `uart_softc`, with the hardware-specific extensions added through kobj class inheritance. +每个UART驱动程序实例都有一个 `struct uart_softc`,定义在 `/usr/src/sys/dev/uart/uart_bus.h` 中。框架为每个已附加的端口分配一个实例。其重要字段包括一个指向 `uart_bas` 的指针(描述端口的寄存器布局)、I/O资源(IRQ、内存范围或I/O端口范围)、附加到此端口的TTY设备、当前线路参数,以及框架内部使用的两个字节缓冲区(RX和TX)。驱动程序通常不分配自己的softc;它使用框架的 `uart_softc`,通过kobj类继承添加硬件特定的扩展。 -When the 框架 receives an interrupt from a UART, it calls a 框架-internal function that reads the interrupt-identification 注册, decides what kind of work the chip has requested (transmit-ready, receive-data-available, line-status, modem-status), and dispatches to the appropriate handler. The handlers pull data out of the chip's RX FIFO into the 框架's RX 环形缓冲区, or push data from the 框架's TX 环形缓冲区 into the chip's TX FIFO, or update state variables in response to modem-signal changes. The 中断处理程序 returns, and the TTY layer consumes the 环形缓冲区 at its own pace through the 框架's put-character and get-character paths. +当框架收到来自UART的中断时,它会调用一个框架内部函数,该函数读取中断标识寄存器,判断芯片请求了哪种类型的工作(发送就绪、接收数据可用、线路状态、调制解调器状态),并分发到相应的处理程序。处理程序将数据从芯片的RX FIFO拉入框架内部的RX环形缓冲区,或者将数据从框架的TX环形缓冲区推入芯片的TX FIFO,或者更新状态变量以响应调制解调器信号变化。中断处理程序返回后,TTY层通过框架的put-character和get-character路径按自己的节奏消费环形缓冲区中的数据。 -This is why the 驱动程序's `uart_ops` table is so small. The high-volume work (moving bytes between the chip and the 环形缓冲区) is handled by shared 框架 code that reads the chip's 寄存器 through `uart_getreg` and `uart_setreg`. The 驱动程序 only needs to expose the low-level primitives; the composition is done for it. +这就是为什么驱动程序的 `uart_ops` 表如此之小。大量的工作(在芯片和环形缓冲区之间移动字节)由共享的框架代码处理,该代码通过 `uart_getreg` 和 `uart_setreg` 读写芯片的寄存器。驱动程序只需要暴露底层原语;组合工作已经为它完成了。 -### Integration with the TTY Layer +### 与TTY层集成 -Above the `uart(4)` 框架 sits the TTY layer, defined in `/usr/src/sys/kern/tty.c` and friends. A UART port in FreeBSD appears to userland as two `/dev` nodes: +在 `uart(4)` 框架之上是TTY层,定义在 `/usr/src/sys/kern/tty.c` 及相关文件中。FreeBSD中的UART端口对用户态表现为两个 `/dev` 节点: -- `/dev/ttyuN`: the callin node. Opening it 块 until a carrier detect signal is asserted (which models an incoming call on a modem). It is used for 设备 that answer, not initiate, connections. -- `/dev/cuauN`: the callout node. Opening it does not wait for carrier detect. It is used for 设备 that initiate connections, or for developers who want to talk to a 串行端口 without pretending it is a modem. +- `/dev/ttyuN`:呼入节点。打开它会阻塞,直到载波检测信号被置位(这模拟了调制解调器上的来电)。它用于应答而非发起连接的设备。 +- `/dev/cuauN`:呼出节点。打开它不会等待载波检测。它用于发起连接的设备,或者开发者想要与串行端口通信而不需要假装它是调制解调器的情况。 -The distinction is historical, dating from the era when 串行端口s were genuinely connected to analog modems with separate "someone is calling" and "I am initiating a call" semantics. FreeBSD preserves the distinction because some embedded and industrial workflows still rely on it, and because the implementation cost is minimal once the TTY layer's "two sides of the same port" pattern is in place. +这种区别是历史性的,可以追溯到串行端口真正连接到模拟调制解调器的时代,那时有独立的"有人来电"和"我正在拨号"语义。FreeBSD保留了这种区别,因为一些嵌入式和工业工作流仍然依赖它,而且一旦TTY层的"同一端口两侧"模式就位,实现成本是微乎其微的。 -The TTY layer calls into the `uart(4)` 框架 through a `ttydevsw` structure whose methods map neatly onto UART operations. The important entries include: +TTY层通过 `ttydevsw` 结构体调用 `uart(4)` 框架,其方法与UART操作直接对应。重要的条目包括: -- `tsw_open`: called when userland opens the port. The 框架 enables interrupts, powers on the chip, and applies the default `termios`. -- `tsw_close`: called when the last userland reference is released. The 框架 drains the TX 缓冲区, disables interrupts (unless the port is also a console), and puts the chip in an idle state. -- `tsw_ioctl`: called for ioctls the TTY layer does not handle itself. Most UART-specific ioctls are handled by the 框架. -- `tsw_param`: called when `termios` changes. The 框架 reprograms the chip's 波特率, 数据位, 停止位, 奇偶校验, and 流控制. -- `tsw_outwakeup`: called when there is new data to transmit. The 框架 enables the transmit-ready interrupt if it was disabled; on the next IRQ, the 框架 pushes bytes from the 环形缓冲区 into the chip. +- `tsw_open`:当用户态打开端口时调用。框架启用中断、给芯片上电并应用默认的 `termios`。 +- `tsw_close`:当最后一个用户态引用被释放时调用。框架排空TX缓冲区、禁用中断(除非端口同时也是控制台)并将芯片置于空闲状态。 +- `tsw_ioctl`:用于TTY层自身不处理的ioctl调用。大多数UART特定的ioctl由框架处理。 +- `tsw_param`:当 `termios` 改变时调用。框架重新编程芯片的波特率、数据位、停止位、奇偶校验和流控制。 +- `tsw_outwakeup`:当有新数据需要发送时调用。框架启用发送就绪中断(如果之前被禁用);在下一次IRQ时,框架将字节从环形缓冲区推入芯片。 -You do not usually have to write any of these. The 框架 in `uart_tty.c` implements them once for every UART 驱动程序. Your 驱动程序's only contribution is the six methods in `uart_ops`. +你通常不需要编写这些方法中的任何一个。`uart_tty.c` 中的框架为每个UART驱动程序实现了一次。你的驱动程序唯一的贡献是 `uart_ops` 中的六个方法。 -### The `termios` Interface in Practice +### 实践中的 `termios` 接口 -When a user runs `stty 115200` on a 串行端口, the following chain of calls happens: +当用户在串行端口上运行 `stty 115200` 时,会发生以下调用链: -1. `stty(1)` opens the port and issues a `TIOCSETA` ioctl carrying the new `struct termios`. -2. The 内核 TTY layer receives the ioctl and updates its internal copy of the port's termios. -3. The TTY layer calls `tsw_param` on the port's `ttydevsw`, passing the new termios. -4. The `uart(4)` 框架's `uart_param` implementation looks at the termios fields (`c_ispeed`, `c_ospeed`, `c_cflag` with its `CSIZE`, `CSTOPB`, `PARENB`, `PARODD`, `CRTSCTS` sub-bits) and calls the 驱动程序's `init` method with the corresponding raw values. -5. The 驱动程序's `init` method computes the divisor, writes the line-control 注册, reconfigures the FIFO, and returns. +1. `stty(1)` 打开端口并发出一个携带新 `struct termios` 的 `TIOCSETA` ioctl。 +2. 内核TTY层接收该ioctl并更新其内部端口termios副本。 +3. TTY层在端口的 `ttydevsw` 上调用 `tsw_param`,传递新的termios。 +4. `uart(4)` 框架的 `uart_param` 实现查看termios字段(`c_ispeed`、`c_ospeed`、`c_cflag` 及其 `CSIZE`、`CSTOPB`、`PARENB`、`PARODD`、`CRTSCTS` 子位),并使用对应的原始值调用驱动程序的 `init` 方法。 +5. 驱动程序的 `init` 方法计算分频器、写入线路控制寄存器、重新配置FIFO并返回。 -None of this requires the 驱动程序 to know about termios. The translation from termios bits to raw integers is done by the 框架. The 驱动程序 sees only the raw values: baudrate in bits per second, databits (usually 5 through 8), stopbits (1 or 2), and a 奇偶校验 code. +这一切都不需要驱动程序了解termios。从termios位到原始整数的转换由框架完成。驱动程序只看到原始值:以比特/秒为单位的波特率、数据位(通常5到8)、停止位(1或2)以及奇偶校验代码。 -This separation is what lets FreeBSD run the same `uart(4)` 框架 on top of radically different chips. A 16550 驱动程序 and a PL011 驱动程序 both implement the same six `uart_ops` methods. The termios-to-raw translation happens once, in 框架 code, for every chip family. +这种分离使得FreeBSD能够在截然不同的芯片上运行相同的 `uart(4)` 框架。16550驱动程序和PL011驱动程序都实现了相同的六个 `uart_ops` 方法。termios到原始值的转换在每个芯片系列中只发生一次,在框架代码中完成。 -### Flow Control at the Register Level +### 寄存器级别的流控制 -Hardware 流控制 is typically driven by two signals on the UART: CTS (clear to send) and RTS (request to send). When CTS is asserted by the remote side, it is telling the local transmitter "I am ready for more data." When the local side asserts RTS, it is telling the remote transmitter the same thing. When either signal is not asserted, the corresponding transmitter pauses. +硬件流控制通常由UART上的两个信号驱动:CTS(清除发送)和RTS(请求发送)。当远端置位CTS时,它告诉本地发送方"我准备好接收更多数据了"。当本地端置位RTS时,它告诉远端发送方同样的事情。当任一信号未被置位时,相应的发送方暂停。 -In a 16550, RTS is driven by a bit in the modem control 注册 (MCR), and CTS is read from a bit in the modem status 注册 (MSR). The 框架 exposes 流控制 through termios (`CRTSCTS` flag), through ioctls (`TIOCMGET`, `TIOCMSET`, `TIOCMBIS`, `TIOCMBIC`), and through automatic responses to FIFO fill levels. +在16550中,RTS由调制解调器控制寄存器(MCR)中的一个位驱动,CTS从调制解调器状态寄存器(MSR)中的一个位读取。框架通过termios(`CRTSCTS` 标志)、通过ioctl(`TIOCMGET`、`TIOCMSET`、`TIOCMBIS`、`TIOCMBIC`)以及通过对FIFO填充级别的自动响应来暴露流控制。 -When the receive FIFO fills past a threshold, the 驱动程序 deasserts RTS to ask the remote side to stop transmitting. When the FIFO drains below a different threshold, the 驱动程序 reasserts RTS. When the modem-status-interrupt fires because CTS changed, the 中断处理程序 enables or disables the transmit path accordingly. All of this is 框架 logic; the 驱动程序 only exposes the 注册-level primitives. +当接收FIFO填充超过阈值时,驱动程序撤销RTS以请求远端停止发送。当FIFO排空到另一个阈值以下时,驱动程序重新置位RTS。当因CTS变化而触发调制解调器状态中断时,中断处理程序相应地启用或禁用发送路径。所有这些都是框架逻辑;驱动程序只需要暴露寄存器级别的原语。 -Software 流控制 (XON/XOFF) is handled entirely in the TTY layer, by inserting and interpreting the XON (0x11) and XOFF (0x13) bytes in the data stream. The UART 驱动程序 has no role in it. +软件流控制(XON/XOFF)完全由TTY层处理,通过在数据流中插入和解释XON(0x11)和XOFF(0x13)字节来实现。UART驱动程序在其中不承担任何角色。 -### The Interrupt Handler Path in Detail +### 中断处理程序路径详解 -Beyond the six `uart_ops` methods, a real UART 驱动程序 usually implements an 中断处理程序. The 框架 provides a generic one in `uart_core.c` that works for the vast majority of chips, but the 驱动程序 can supply its own for chips with unusual behaviour. To understand what the 框架's generic handler does, and when you might want to override it, it helps to trace the handler's path. +除了六个 `uart_ops` 方法之外,实际的UART驱动程序通常还实现一个中断处理程序。框架在 `uart_core.c` 中提供了一个通用中断处理程序,适用于绝大多数芯片,但驱动程序可以为具有异常行为的芯片提供自己的处理程序。要理解框架的通用处理程序做了什么,以及何时需要覆盖它,跟踪处理程序的路径会很有帮助。 -When the hardware interrupt fires, the 框架's ISR reads the interrupt identification 注册 (IIR) through `uart_getreg`. The IIR encodes which of four conditions triggered the interrupt: line-status (a framing error or overrun occurred), received-data-available (at least one byte is in the receive FIFO), transmitter-holding-注册-empty (the TX FIFO wants more data), or modem-status (a modem signal changed state). +当硬件中断触发时,框架的ISR通过 `uart_getreg` 读取中断标识寄存器(IIR)。IIR编码了四种触发中断的条件之一:线路状态(发生了帧错误或溢出)、接收数据可用(接收FIFO中至少有一个字节)、发送保持寄存器空闲(TX FIFO需要更多数据)或调制解调器状态(调制解调器信号状态改变)。 -For line-status interrupts, the 框架 logs a warning (or increments a counter) and continues. +对于线路状态中断,框架记录警告(或递增计数器)并继续。 -For received-data-available, the 框架 reads bytes out of the chip's RX FIFO one at a time, pushing each into the 驱动程序's internal RX 环形缓冲区. The loop continues until the receive-data-available flag clears. Once the 环形缓冲区 has bytes, the 框架 signals the TTY layer's input path, which will pull bytes out as the consumer is ready. +对于接收数据可用中断,框架逐字节从芯片的RX FIFO中读出数据,将每个字节推入框架内部的RX环形缓冲区。循环持续到接收数据可用标志清除为止。一旦环形缓冲区有数据,框架向TTY层的输入路径发出信号,TTY层将在消费者就绪时拉取字节。 -For transmitter-holding-注册-empty, the 框架 pulls bytes out of its internal TX 环形缓冲区 and pushes them into the chip's TX FIFO one at a time. The loop continues until the TX FIFO is full or the 环形缓冲区 is empty. Once the 环形缓冲区 is empty, the 框架 disables the transmit interrupt so the chip does not keep firing; the next `tsw_outwakeup` call (from the TTY layer, when there is new data) will reenable it. +对于发送保持寄存器空闲中断,框架从其内部TX环形缓冲区拉取字节并逐个推入芯片的TX FIFO。循环持续到TX FIFO满或环形缓冲区空为止。一旦环形缓冲区为空,框架禁用发送中断,以免芯片持续触发;下一次 `tsw_outwakeup` 调用(来自TTY层,当有新数据时)将重新启用它。 -For modem-status changes, the 框架 updates its internal modem-signal state and signals the TTY layer if the change is significant (for example, CTS deassertion when hardware 流控制 is enabled). +对于调制解调器状态变化,框架更新其内部调制解调器信号状态,并在变化显著时(例如,启用硬件流控制时CTS被撤销)向TTY层发出信号。 -This is all done in interrupt context with the 驱动程序's 互斥锁 held. The 互斥锁 is a spin 互斥锁 (`MTX_SPIN`) for UART 驱动程序, because taking a sleepable 互斥锁 in an 中断处理程序 is forbidden. The 框架's helpers know this and use appropriate primitives. +所有这些都在中断上下文中完成,并持有驱动程序的互斥锁。对于UART驱动程序,互斥锁是自旋互斥锁(`MTX_SPIN`),因为在中断处理程序中获取可睡眠的互斥锁是被禁止的。框架的辅助函数知道这一点,并使用适当的原语。 -When might a 驱动程序 want to override the generic handler? Three situations come to mind. +驱动程序何时需要覆盖通用处理程序?有三种情况值得考虑。 -First, if the chip has unusual FIFO semantics. Some chips do not clear their interrupt identification 寄存器 in the obvious way; you have to drain the FIFO completely, or you have to read a specific 注册 to acknowledge. If your chip's data sheet describes such a quirk, you override the handler with chip-specific logic. +第一种,芯片具有异常的FIFO语义。某些芯片不以常规方式清除其中断标识寄存器;你必须完全排空FIFO,或者必须读取特定寄存器来确认。如果你的芯片数据手册描述了这样的怪癖,你需要用芯片特定的逻辑覆盖处理程序。 -Second, if the chip has DMA support you want to use. The 框架's generic handler is PIO (programmed I/O): one byte per 注册 access. A chip with a DMA engine could move many bytes per interrupt, significantly reducing CPU overhead at high 波特率s. Implementing DMA requires chip-specific code. +第二种,你想使用芯片的DMA支持。框架的通用处理程序是PIO(编程I/O)方式:每次寄存器访问处理一个字节。带有DMA引擎的芯片可以在每次中断中移动多个字节,在高波特率下显著降低CPU开销。实现DMA需要芯片特定的代码。 -Third, if the chip has hardware timestamping or other advanced features. Some embedded UARTs can timestamp individual received bytes with microsecond precision, which is invaluable for industrial protocols. The 框架 does not know about this, so the 驱动程序 must implement it. +第三种,芯片具有硬件时间戳或其他高级功能。某些嵌入式UART可以以微秒精度为每个接收到的字节打时间戳,这对工业协议来说极其宝贵。框架不知道这些功能,因此驱动程序必须自行实现。 -For typical hardware, the generic handler is correct and performant. Do not override it without a specific reason. +对于典型的硬件,通用处理程序是正确且高效的。没有特定的理由不要覆盖它。 -### The TX and RX Ring Buffers +### TX 和 RX 环形缓冲区 -The `uart(4)` 框架 keeps two 环形缓冲区 inside each port's softc. These are separate from any 缓冲区ing on the chip itself: even if the chip has a 64-byte FIFO, the 框架 has its own 环形缓冲区 of some configurable size (typically 4 KB for each direction) that sit between the chip and the TTY layer. +`uart(4)` 框架在每个端口的softc中维护两个环形缓冲区。它们与芯片本身的缓冲是分开的:即使芯片有64字节的FIFO,框架也有自己的可配置大小的环形缓冲区(通常每个方向4 KB),位于芯片和TTY层之间。 -The purpose of these 环形缓冲区 is to absorb bursts. Suppose the consumer of data is slow (a 总线y userland process), and the producer (the remote serial 设备) is pushing data at 115200 baud. Without a 环形缓冲区, the chip's 64-byte FIFO would fill up in about 6 milliseconds, and bytes would be lost. With a 4 KB 环形缓冲区, the 缓冲区 can absorb a 350-millisecond burst at 115200 baud, which is enough for userland to catch up in almost every realistic scenario. +这些环形缓冲区的目的是吸收突发数据。假设数据消费者很慢(一个繁忙的用户态进程),而生产者(远端串行设备)以115200波特率推送数据。没有环形缓冲区的话,芯片的64字节FIFO将在约6毫秒内填满,字节将会丢失。有了4 KB的环形缓冲区,缓冲区可以在115200波特率下吸收350毫秒的突发数据,这在几乎所有的实际场景中都足以让用户态跟上。 -The sizes of these 环形缓冲区 are not generally configurable per-驱动程序; they are baked into the 框架. The 环形缓冲区 implementation is in `uart_core.c` and uses the same kind of head/tail pointer arithmetic as the 环形缓冲区 in our USB echo 驱动程序. +这些环形缓冲区的大小通常不能按驱动程序配置;它们是固定在框架中的。环形缓冲区的实现在 `uart_core.c` 中,使用与我们USB echo驱动程序中环形缓冲区相同的头/尾指针算术。 -When the TTY layer asks for bytes (through `ttydisc_rint`), the 框架 moves bytes out of the RX ring into the TTY layer's own input queue, which has its own 缓冲区ing and line-discipline processing (canonical mode, echo, signal generation, and so on). When userland writes bytes, they arrive at the 框架's `tsw_outwakeup` path and are moved into the TX ring; the 框架's transmit-empty 中断处理程序 pushes them from the ring into the chip. +当TTY层请求字节时(通过 `ttydisc_rint`),框架将字节从RX环形缓冲区移到TTY层自己的输入队列中,该队列有自己的缓冲和线路规程处理(规范模式、回显、信号生成等)。当用户态写入字节时,它们到达框架的 `tsw_outwakeup` 路径并被移入TX环形缓冲区;框架的发送空中断处理程序将它们从环形缓冲区推入芯片。 -This arrangement has a nice property: the 驱动程序, the 框架, and the TTY layer are all loosely coupled. The 驱动程序 only knows about the chip. The 框架 only knows about 寄存器 and 环形缓冲区. The TTY layer only knows about 缓冲区ing and line discipline. Each layer can be tested and reasoned about independently. +这种安排有一个很好的特性:驱动程序、框架和TTY层都是松耦合的。驱动程序只了解芯片。框架只了解寄存器和环形缓冲区。TTY层只了解缓冲和线路规程。每一层都可以独立测试和推理。 -### Debugging Serial Drivers +### 串行驱动程序的调试 -When a 串行驱动程序 does not work, the symptoms can be confusing. Bytes go in, bytes come out, but the two do not match. The clock ticks, but the characters look like gibberish. The port opens, but writes return zero bytes. This section lists the diagnostic techniques that help. +当串行驱动程序不工作时,症状可能令人困惑。字节进去了,字节出来了,但两者不匹配。时钟在走,但字符看起来像乱码。端口打开了,但写入返回零字节。本节列出了有助于诊断的技术。 -**Log aggressively at 附加.** Use `设备_printf(dev, "附加ed at %x, IRQ %d\n", ...)` to verify the address and IRQ your 驱动程序 ended up with. If the address is wrong, no I/O will work; if the IRQ is wrong, no interrupts will fire. Attach messages are the first line of defence. +**在附加时积极记录日志。** 使用 `device_printf(dev, "attached at %x, IRQ %d\n", ...)` 来验证驱动程序最终获得的地址和IRQ。如果地址错误,所有I/O都不会工作;如果IRQ错误,所有中断都不会触发。附加消息是第一道防线。 -**Use `sysctl dev.uart.0.*` to inspect port state.** The `uart(4)` 框架 exports many per-port knobs and statistics through sysctl. Reading them shows the current 波特率, the number of bytes transmitted, the number of overruns, the modem signal state, and more. If `tx` is incrementing but `rx` is not, the transmitter works but the receiver does not; if both are zero, nothing is happening at all. +**使用 `sysctl dev.uart.0.*` 检查端口状态。** `uart(4)` 框架通过sysctl导出许多每端口的参数和统计信息。读取它们可以看到当前的波特率、已传输的字节数、溢出次数、调制解调器信号状态等。如果 `tx` 在递增但 `rx` 没有,说明发送器工作但接收器不工作;如果两者都为零,说明什么都没有发生。 -**Probe the hardware with `kgdb`.** If you have a 内核 crash dump or the ability to 附加 a 内核 debugger, you can inspect the `uart_softc` directly and read its 注册 values. This is invaluable when the chip is in a confused state that the software abstraction hides. +**使用 `kgdb` 探测硬件。** 如果你有内核崩溃转储或能够附加内核调试器,你可以直接检查 `uart_softc` 并读取其寄存器值。当芯片处于软件抽象所隐藏的混乱状态时,这极其宝贵。 -**Compare against a working 驱动程序.** If your modification broke something, bisect the change against the upstream `ns8250.c`. The difference will be small, and once you identify it, the fix is usually clear. +**与工作的驱动程序进行比较。** 如果你的修改破坏了什么,将变更与上游的 `ns8250.c` 进行二分法比较。差异通常很小,一旦识别出来,修复通常是显而易见的。 -**Use `dd` for small, repeatable tests.** Instead of `cu` for debugging, use `dd if=/dev/zero of=/dev/cuau0 bs=1 count=100` to write exactly 100 bytes. Then `dd if=/dev/cuau0 of=output.bin bs=1 count=100` to read exactly 100 bytes (with a suitable timeout or a second open). This isolates timing and character-encoding issues that interactive `cu` might mask. +**使用 `dd` 进行小型、可重复的测试。** 不要用 `cu` 来调试,而是用 `dd if=/dev/zero of=/dev/cuau0 bs=1 count=100` 来精确写入100个字节。然后用 `dd if=/dev/cuau0 of=output.bin bs=1 count=100` 来精确读取100个字节(需要有合适的超时或第二次打开)。这可以隔离交互式 `cu` 可能掩盖的时序和字符编码问题。 -**Check the hardware 流控制 pins.** Many flow-control bugs are hardware, not software. Use a break-out board, a multimeter, or an oscilloscope to verify that DTR, RTS, CTS, and DSR are at the voltages you expect. If one is stuck floating, the chip's behaviour is undefined. +**检查硬件流控制引脚。** 许多流控制错误是硬件问题而非软件问题。使用分线板、万用表或示波器来验证DTR、RTS、CTS和DSR是否处于你期望的电压。如果其中一个引脚悬空,芯片的行为是未定义的。 -**Compare behaviour under `nmdm(4)`.** If your userland tool works with `nmdm(4)` but not with your 驱动程序, the bug is in the 驱动程序. If it fails with both, the bug is in the tool. +**在 `nmdm(4)` 下比较行为。** 如果你的用户态工具在 `nmdm(4)` 下工作正常但在你的驱动程序下不行,那么错误在驱动程序中。如果两者都失败,错误在工具中。 -These techniques apply equally to `uart(4)` 驱动程序 and `ucom(4)` 驱动程序. The difference is that `uart(4)` problems often come down to 注册 manipulation (did you set the divisor correctly?), while `ucom(4)` problems often come down to USB transfers (did the 控制传输 to set the 波特率 actually succeed?). The debugging tools (USB: `usbconfig`, transfer statistics; UART: `sysctl`, chip 寄存器) are different, but the investigative mindset is the same. +这些技术同样适用于 `uart(4)` 驱动程序和 `ucom(4)` 驱动程序。区别在于 `uart(4)` 问题通常归结为寄存器操作(分频器设置正确吗?),而 `ucom(4)` 问题通常归结为USB传输(设置波特率的控制传输真的成功了吗?)。调试工具不同(USB:`usbconfig`、传输统计;UART:`sysctl`、芯片寄存器),但调查思路是相同的。 -### Writing a UART Driver Yourself -Putting the pieces together, a minimal UART 驱动程序 for an imaginary 注册-compatible chip would be organised like this: +### 自己编写UART驱动程序 -1. Define 注册 offsets and bit positions in a local header. -2. Implement the six `uart_ops` methods: `探测`, `init`, `term`, `putc`, `rxready`, `getc`. -3. Declare a `struct uart_ops` initialised with those six methods. -4. Declare a `struct uart_class` initialised with the ops and the hardware parameters (range, reference clock, 注册 shift). -5. Implement the 中断处理程序 if the chip needs more than the 框架's default dispatch. -6. Register the 驱动程序 with New总线 using the standard macros. +将各个部分组合起来,一个用于假想的寄存器兼容芯片的最小UART驱动程序的组织方式如下: -Most new UART 驱动程序 in the tree are small. Oxford single-port PCIe UARTs, for example, are a few hundred lines because they are fundamentally 16550-compatible and only need a thin layer of PCI-specific 附加 code. Complex ones like the Z8530 are larger because the chip has a more complicated programming model; the 驱动程序 size tracks the chip's complexity, not the 框架's. +1. 在本地头文件中定义寄存器偏移量和位位置。 +2. 实现六个 `uart_ops` 方法:`probe`、`init`、`term`、`putc`、`rxready`、`getc`。 +3. 声明一个用这六个方法初始化的 `struct uart_ops`。 +4. 声明一个用操作集和硬件参数(范围、参考时钟、寄存器移位)初始化的 `struct uart_class`。 +5. 如果芯片需要超出框架默认分发的功能,则实现中断处理程序。 +6. 使用标准宏将驱动程序注册到Newbus。 -### Looking at `myfirst_uart.c` in Skeleton Form +内核树中大多数新的UART驱动程序都很小。例如,Oxford单端口PCIe UART只有几百行代码,因为它们基本上是16550兼容的,只需要一层薄薄的PCI特定附加代码。复杂的芯片如Z8530则更大,因为芯片有更复杂的编程模型;驱动程序的大小跟踪的是芯片的复杂度,而非框架的复杂度。 -For our running example, the skeleton of a minimal UART 驱动程序 looks like this: +### 查看 `myfirst_uart.c` 的骨架形式 + +对于我们的运行示例,一个最小UART驱动程序的骨架如下: ```c #include @@ -1913,17 +1914,17 @@ struct uart_class myfirst_uart_class = { }; ``` -The inclusion of `uart_if.h` is notable: that header is generated at build time by the kobj machinery from the 接口 definition in `/usr/src/sys/dev/uart/uart_if.m`. It declares the method prototypes that the 框架 expects 驱动程序 to implement. When you write a new 驱动程序, you depend on this header. +包含 `uart_if.h` 值得注意:该头文件在构建时由kobj机制从 `/usr/src/sys/dev/uart/uart_if.m` 中的接口定义生成。它声明了框架期望驱动程序实现的方法原型。当你编写新驱动程序时,你需要依赖这个头文件。 -The six methods themselves are straightforward once you have the chip's programming manual open. `init` computes the divisor from `uc_rclk` and the 波特率, writes the line control 注册 for the databits/stopbits/奇偶校验 combination, enables FIFOs, and sets the interrupt enable 注册 to the desired mask. `term` inverts `init`. `putc`, `getc`, and `rxready` each do a single-注册 access plus a spin on the status 注册. +打开芯片的编程手册后,这六个方法本身很简单。`init` 从 `uc_rclk` 和波特率计算分频器,为数据位/停止位/奇偶校验组合写入线路控制寄存器,启用FIFO,并将中断使能寄存器设置为所需的掩码。`term` 是 `init` 的逆操作。`putc`、`getc` 和 `rxready` 各自进行一次单寄存器访问加上对状态寄存器的轮询。 -A complete implementation of all six methods for a 16550-compatible chip is about three hundred lines. For a chip with quirks, it might grow to five hundred or more. The `ns8250` 驱动程序 is longer than most because it handles errata and variant detection for dozens of real chips, but the core logic of its six methods is still the standard pattern. +16550兼容芯片的所有六个方法的完整实现大约三百行。对于有怪癖的芯片,可能会增长到五百行或更多。`ns8250` 驱动程序比大多数都长,因为它处理数十种实际芯片的勘误和变体检测,但其六个方法的核心逻辑仍然是标准模式。 -### The `ucom(4)` Framework: USB-to-Serial Bridges +### `ucom(4)` 框架:USB转串口桥接 -Not every 串行端口 is a real UART on the system 总线. Many are USB adapters: a PL2303, a CP2102, an FTDI FT232, a CH340G. These chips expose a 串行端口 over USB, and FreeBSD's approach to supporting them is a small 框架 called `ucom(4)`. It lives in `/usr/src/sys/dev/usb/serial/`, alongside the 驱动程序 for each chip family. +并非每个串行端口都是系统总线上的真正UART。许多是USB适配器:PL2303、CP2102、FTDI FT232、CH340G。这些芯片通过USB暴露一个串行端口,FreeBSD支持它们的方法是一个叫做 `ucom(4)` 的小型框架。它位于 `/usr/src/sys/dev/usb/serial/`,与每个芯片系列的驱动程序并排。 -`ucom(4)` is distinct from `uart(4)`. It does not use `uart_ops`, it does not use `uart_bas`, and it does not use the 环形缓冲区 inside `uart_core.c`. What it does is provide a TTY abstraction on top of USB transfers. A `ucom(4)` client declares itself through a `struct ucom_回调`: +`ucom(4)` 与 `uart(4)` 不同。它不使用 `uart_ops`,不使用 `uart_bas`,也不使用 `uart_core.c` 中的环形缓冲区。它所做的是在USB传输之上提供TTY抽象。`ucom(4)` 客户端通过 `struct ucom_callback` 声明自己: ```c struct ucom_callback { @@ -1950,209 +1951,209 @@ struct ucom_callback { }; ``` -The methods divide into three groups. Configuration methods (names prefixed with `ucom_cfg_`) are called to change the state of the underlying chip: set DTR, set RTS, change the 波特率, and so on. These methods run in the 框架's configuration thread, which is designed for making synchronous USB control requests. Flow methods (`ucom_start_read`, `ucom_start_write`, `ucom_stop_read`, `ucom_stop_write`) are called to enable or disable the data path on the underlying USB channels. The pre-methods (`ucom_pre_open`, `ucom_pre_param`) run on the caller's context before the 框架 schedules a configuration task, which is where a 驱动程序 validates userland-supplied arguments and returns an errno if they are unacceptable. The `ucom_ioctl` method translates chip-specific userland ioctls that the 框架 does not handle into USB requests. +这些方法分为三组。配置方法(名称以 `ucom_cfg_` 为前缀)用于改变底层芯片的状态:设置DTR、设置RTS、更改波特率等。这些方法在框架的配置线程中运行,该线程专为发起同步USB控制请求而设计。流方法(`ucom_start_read`、`ucom_start_write`、`ucom_stop_read`、`ucom_stop_write`)用于启用或禁用底层USB通道上的数据路径。前置方法(`ucom_pre_open`、`ucom_pre_param`)在框架调度配置任务之前在调用者的上下文中运行,这是驱动程序验证用户态提供的参数并在不可接受时返回errno的地方。`ucom_ioctl` 方法将框架不处理的芯片特定用户态ioctl转换为USB请求。 -A USB-to-串行驱动程序's job is to implement these 回调 in terms of USB transfers. When `ucom_cfg_param` is called with a new 波特率, the 驱动程序 issues a vendor-specific 控制传输 that programs the chip's baud-rate 注册. When `ucom_start_read` is called, the 驱动程序 starts a bulk-IN channel that delivers incoming bytes. When `ucom_start_write` is called, the 驱动程序 starts a bulk-OUT channel that flushes outgoing bytes. +USB转串行驱动程序的任务是以USB传输的方式实现这些回调。当 `ucom_cfg_param` 被调用并传入新的波特率时,驱动程序发出一个厂商特定的控制传输来编程芯片的波特率寄存器。当 `ucom_start_read` 被调用时,驱动程序启动一个批量输入通道来传送传入的字节。当 `ucom_start_write` 被调用时,驱动程序启动一个批量输出通道来冲刷传出的字节。 -The FTDI 驱动程序 at `/usr/src/sys/dev/usb/serial/uftdi.c` is the concrete reference. Its `ucom_cfg_param` implementation translates the termios fields into the FTDI's proprietary baud-rate divisor format (which is weird, because FTDI chips use a sub-integer divisor scheme that is almost but not quite standard 16550) and issues a 控制传输 to `bRequest = FTDI_SIO_SET_BAUD_RATE`. Its `ucom_start_read` starts the bulk-IN channel that reads from the FTDI's RX FIFO. Its `ucom_start_write` starts the bulk-OUT channel that writes to the FTDI's TX FIFO. +位于 `/usr/src/sys/dev/usb/serial/uftdi.c` 的FTDI驱动程序是具体的参考。其 `ucom_cfg_param` 实现将termios字段转换为FTDI专有的波特率分频器格式(这很奇怪,因为FTDI芯片使用一种几乎是但不完全是标准16550的子整数分频方案),并向 `bRequest = FTDI_SIO_SET_BAUD_RATE` 发出控制传输。其 `ucom_start_read` 启动从FTDI的RX FIFO读取的批量输入通道。其 `ucom_start_write` 启动向FTDI的TX FIFO写入的批量输出通道。 -From userland's perspective, a `ucom(4)` 设备 looks identical to a `uart(4)` 设备. Both appear as `/dev/ttyuN` and `/dev/cuauN`. Both respond to `stty`, `cu`, `tip`, `minicom`, and every other serial tool. Both support the same termios flags. The distinction only matters to a 驱动程序 writer. +从用户态的角度看,`ucom(4)` 设备与 `uart(4)` 设备看起来完全相同。两者都显示为 `/dev/ttyuN` 和 `/dev/cuauN`。两者都响应 `stty`、`cu`、`tip`、`minicom` 以及所有其他串行工具。两者都支持相同的termios标志。这种区别只对驱动程序编写者有意义。 -### Reading `uftdi.c` As a Complete Example +### 阅读 `uftdi.c` 作为完整示例 -FTDI chips (FT232R, FT232H, FT2232H, and many others) are the most widely deployed USB-to-serial chips in the embedded world. If you ever work with microcontrollers, evaluation boards, 3D printers, or industrial sensors, you will encounter FTDI hardware. FreeBSD has supported FTDI since 4.x, and the current 驱动程序 lives in `/usr/src/sys/dev/usb/serial/uftdi.c`. At roughly three thousand lines, it is not short, but most of that length is devoted to the large 匹配表 (FTDI products are legion) and to chip-variant quirks (every few years FTDI adds a new FIFO size, a new baud-rate divisor scheme, or a new 注册). The pedagogically interesting core is a few hundred lines, and reading it is a direct reward for the conceptual work of Section 4. +FTDI芯片(FT232R、FT232H、FT2232H 以及许多其他型号)是嵌入式世界中部署最广泛的USB转串口芯片。如果你曾经使用过微控制器、评估板、3D打印机或工业传感器,你一定会遇到FTDI硬件。FreeBSD从4.x版本开始支持FTDI,当前驱动程序位于 `/usr/src/sys/dev/usb/serial/uftdi.c`。大约三千行代码,不算短,但大部分篇幅用于大型匹配表(FTDI产品众多)和芯片变体的怪癖处理(每隔几年FTDI就会增加新的FIFO大小、新的波特率分频方案或新的寄存器)。教学上有趣的核心只有几百行,阅读它是第4节概念工作的直接回报。 -When you open the file, the first thing to notice is the enormous 匹配表. FTDI assigns OEM-specific USB IDs to their customers, so the 匹配表 includes not just FTDI's own VID/PID pairs but also hundreds of VIDs and PIDs from companies that embed FTDI chips in their products. Sparkfun, Pololu, Olimex, Adafruit, various industrial vendors: every one has at least one entry in the uftdi 匹配表. The `STRUCT_USB_HOST_ID` array is a few hundred entries long, grouped with comments indicating which product family each cluster belongs to. +打开文件时,首先注意到的是巨大的匹配表。FTDI为其客户分配OEM特定的USB ID,因此匹配表不仅包括FTDI自己的VID/PID对,还包括在其产品中嵌入FTDI芯片的公司的数百个VID和PID。Sparkfun、Pololu、Olimex、Adafruit以及各种工业厂商:每家在uftdi匹配表中都至少有一个条目。`STRUCT_USB_HOST_ID` 数组有几百个条目长,按注释分组,标明每个集群属于哪个产品系列。 -The softc comes next. An FTDI softc includes the USB 设备 pointer, a 互斥锁, the transfer array for the bulk-IN and bulk-OUT channels (FTDI 设备 use bulk for data, not interrupt), a `struct ucom_super_softc` for the `ucom(4)` layer, a `struct ucom_softc` for the per-port state, and FTDI-specific fields: the current baud-rate divisor, the current line control 注册 contents, the current modem control 注册 contents, and a few flags for the variant family (FT232, FT2232, FT232H, and so on). Each variant requires slightly different code for some operations, so the 驱动程序 keeps a variant identifier in the softc and branches on it in the operations that differ. +接下来是softc。FTDI softc包括USB设备指针、一个互斥锁、批量输入和批量输出通道的传输数组(FTDI设备使用批量传输而非中断传输传输数据)、用于 `ucom(4)` 层的 `struct ucom_super_softc`、用于每端口状态的 `struct ucom_softc`,以及FTDI特定的字段:当前波特率分频器、当前线路控制寄存器内容、当前调制解调器控制寄存器内容,以及变体系列(FT232、FT2232、FT232H等)的几个标志。每个变体在某些操作上需要略有不同的代码,因此驱动程序在softc中保持一个变体标识符,并在不同的操作中进行分支。 -The transfer configuration array is where the FTDI 驱动程序's interaction with the USB 框架 is declared. It declares two channels: `UFTDI_BULK_DT_RD` for incoming data and `UFTDI_BULK_DT_WR` for outgoing. Each is a `UE_BULK` transfer with a moderate 缓冲区 size (the FTDI default is 64 bytes for low-speed and 512 bytes for full-speed, and the 驱动程序 picks the right size at 附加 based on the chip variant). The 回调 are `uftdi_read_回调` and `uftdi_write_回调`, and they follow the three-state pattern exactly as described in Section 3. +传输配置数组声明了FTDI驱动程序与USB框架的交互。它声明了两个通道:用于传入数据的 `UFTDI_BULK_DT_RD` 和用于传出数据的 `UFTDI_BULK_DT_WR`。每个都是 `UE_BULK` 传输,具有适度的缓冲区大小(FTDI默认低速为64字节,全速为512字节,驱动程序在附加时根据芯片变体选择正确的大小)。回调是 `uftdi_read_callback` 和 `uftdi_write_callback`,它们完全遵循第3节中描述的三状态模式。 -The `ucom_回调` structure is the next important 块. It wires the FTDI 驱动程序 into the `ucom(4)` 框架. The methods it provides include `uftdi_cfg_param` (called when the 波特率 or byte format changes), `uftdi_cfg_set_dtr` (called to assert or deassert DTR), `uftdi_cfg_set_rts` (same for RTS), `uftdi_cfg_open` and `uftdi_cfg_close` (called when a userland process opens or closes the 设备), and `uftdi_start_read`, `uftdi_start_write`, `uftdi_stop_read`, `uftdi_stop_write` (called to enable or disable the data channels). Each configuration method translates a high-level operation into a USB 控制传输 to the FTDI chip. +`ucom_callback` 结构是下一个重要的块。它将FTDI驱动程序接入 `ucom(4)` 框架。它提供的方法包括 `uftdi_cfg_param`(在波特率或字节格式更改时调用)、`uftdi_cfg_set_dtr`(在置位或撤销DTR时调用)、`uftdi_cfg_set_rts`(对RTS相同)、`uftdi_cfg_open` 和 `uftdi_cfg_close`(在用户态进程打开或关闭设备时调用),以及 `uftdi_start_read`、`uftdi_start_write`、`uftdi_stop_read`、`uftdi_stop_write`(在启用或禁用数据通道时调用)。每个配置方法将高级操作转换为对FTDI芯片的USB控制传输。 -The baud-rate programming is one of the most instructive parts of the 驱动程序, because FTDI chips use a peculiar divisor scheme. Rather than the clean integer divisors a 16550 UART uses, FTDI supports a fractional divisor where the numerator is an integer and the denominator is computed from two bits that select one-eighth, one-quarter, three-eighths, one-half, or five-eighths. The function `uftdi_encode_baudrate` takes a requested 波特率 and the chip's reference clock and computes the closest valid divisor. It handles the edge cases (very low 波特率s, very high 波特率s on newer chips, standard rates like 115200 which are exactly representable, nonstandard rates like 31250 used by MIDI). The resulting sixteen-bit value is passed to `uftdi_set_baudrate`, which issues a 控制传输 to the FTDI's baud-rate 注册. +波特率编程是驱动程序中最有教学意义的部分之一,因为FTDI芯片使用一种特殊的分频方案。与16550 UART使用的简洁整数分频器不同,FTDI支持分数分频器,其中分子是整数,分母由两个选择八分之一、四分之一、八分之三、二分之一或八分之五的位计算得出。函数 `uftdi_encode_baudrate` 接受请求的波特率和芯片的参考时钟,计算最接近的有效分频器。它处理边缘情况(极低波特率、较新芯片上的极高波特率、可精确表示的标准速率如115200、MIDI使用的非标准速率如31250)。得到的十六位值传递给 `uftdi_set_baudrate`,后者向FTDI的波特率寄存器发出控制传输。 -The line control 注册 (数据位, 停止位, 奇偶校验) is programmed through a similar sequence: the termios structure arrives at `uftdi_cfg_param`, the 驱动程序 extracts the relevant bits, encodes them into the FTDI's line-control format, and issues a 控制传输. +线路控制寄存器(数据位、停止位、奇偶校验)通过类似的序列编程:termios结构到达 `uftdi_cfg_param`,驱动程序提取相关位,将它们编码为FTDI的线路控制格式,并发出控制传输。 -The modem control signals (DTR, RTS) are programmed through `uftdi_cfg_set_dtr` and `uftdi_cfg_set_rts`. These are the simplest transfers: a control-out with no payload, which the chip interprets as "set DTR to X" or "set RTS to Y." +调制解调器控制信号(DTR、RTS)通过 `uftdi_cfg_set_dtr` 和 `uftdi_cfg_set_rts` 编程。这些是最简单的传输:一个没有有效载荷的控制输出,芯片将其解释为"设置DTR为X"或"设置RTS为Y"。 -The data path is in the two 回调. `uftdi_read_回调` handles the bulk-IN channel. On `USB_ST_TRANSFERRED`, it extracts the received bytes from the USB 帧 (ignoring the first two bytes, which are FTDI status bytes) and feeds them into the `ucom(4)` layer for delivery to userland. On `USB_ST_SETUP`, it rearms the read for another 缓冲区. `uftdi_write_回调` handles the bulk-OUT channel. On `USB_ST_SETUP`, it asks the `ucom(4)` layer for more data, copies it into a USB 帧, and submits the transfer. On `USB_ST_TRANSFERRED`, it rearms to check for more data. +数据路径在两个回调中。`uftdi_read_callback` 处理批量输入通道。在 `USB_ST_TRANSFERRED` 时,它从USB帧中提取接收到的字节(忽略前两个字节,它们是FTDI状态字节),并将它们送入 `ucom(4)` 层以传递给用户态。在 `USB_ST_SETUP` 时,它重新准备读取另一个缓冲区。`uftdi_write_callback` 处理批量输出通道。在 `USB_ST_SETUP` 时,它向 `ucom(4)` 层请求更多数据,将其复制到USB帧中并提交传输。在 `USB_ST_TRANSFERRED` 时,它重新准备以检查是否有更多数据。 -Reading through `uftdi.c` with Section 4 vocabulary in hand, you can see how the entire `ucom(4)` 框架 pattern is instantiated for a specific chip. The FTDI-specific logic (baud-rate encoding, line-control encoding, modem-control setting) is isolated into helper functions. The 框架 integration is handled by the `ucom_回调` structure. The data flow is handled by the two 批量传输. If you were writing a 驱动程序 for a different USB-to-serial chip, you would copy this structure and change the chip-specific parts. +带着第4节的词汇阅读 `uftdi.c`,你可以看到整个 `ucom(4)` 框架模式是如何为特定芯片实例化的。FTDI特定的逻辑(波特率编码、线路控制编码、调制解调器控制设置)被隔离到辅助函数中。框架集成由 `ucom_callback` 结构处理。数据流由两个批量传输处理。如果你要为不同的USB转串口芯片编写驱动程序,你会复制这个结构并更改芯片特定的部分。 -The existence of this 驱动程序 explains something that might otherwise be puzzling. Why did FreeBSD add `ucom(4)` as a separate 框架 rather than as part of `uart(4)`? Because the entire data-path machinery of a `uart(4)` 驱动程序 (中断处理程序s, 环形缓冲区, 注册 accesses) has no analogue in a USB-to-serial world. The FTDI chip's "FIFO" is an on-chip 缓冲区 that the 驱动程序 cannot directly access; it can only send bulk 数据包 to the chip and receive them back. The `uart(4)` machinery would be unused overhead. By having `ucom(4)` as a separate 框架 with its own data-path abstractions, FreeBSD can make a USB-to-串行驱动程序 like `uftdi` weigh just a few hundred lines of core logic rather than wrap an unnecessary layer of 16550 emulation. +这个驱动程序的存在解释了一个可能令人困惑的问题。为什么FreeBSD将 `ucom(4)` 作为一个单独的框架添加,而不是作为 `uart(4)` 的一部分?因为 `uart(4)` 驱动程序的整个数据路径机制(中断处理程序、环形缓冲区、寄存器访问)在USB转串行世界中没有对应物。FTDI芯片的"FIFO"是一个驱动程序无法直接访问的片上缓冲区;它只能向芯片发送批量数据包并接收返回的数据包。`uart(4)` 的机制将是未使用的开销。通过将 `ucom(4)` 作为具有自己数据路径抽象的独立框架,FreeBSD可以使像 `uftdi` 这样的USB转串行驱动程序只有几百行核心逻辑,而不是包裹一层不必要的16550模拟。 -When you finish reading `uftdi.c`, open `uplcom.c` (the Prolific PL2303 驱动程序) and `uslcom.c` (the Silicon Labs CP210x 驱动程序) in sequence. They follow the same structure with different chip-specific details. After reading all three, you will have a working understanding of how a USB-to-串行驱动程序 is organised in FreeBSD, and you will be ready to write one for any chip you encounter. +读完 `uftdi.c` 后,依次打开 `uplcom.c`(Prolific PL2303驱动程序)和 `uslcom.c`(Silicon Labs CP210x驱动程序)。它们遵循相同的结构,但具有不同的芯片特定细节。读完这三个之后,你将对USB转串行驱动程序在FreeBSD中如何组织有一个实用的理解,并准备好为任何你遇到的芯片编写驱动程序。 -### Choosing Between `uart(4)` and `ucom(4)` +### 在 `uart(4)` 和 `ucom(4)` 之间选择 -The choice is mechanical. If the chip sits on the system 总线 (PCI, ISA, a platform I/O port, a memory-mapped SoC peripheral), you write a `uart(4)` 驱动程序. If the chip sits on USB and exposes a serial 接口, you write a `ucom(4)` 驱动程序. +选择是机械性的。如果芯片位于系统总线(PCI、ISA、平台I/O端口、内存映射的SoC外设)上,你编写 `uart(4)` 驱动程序。如果芯片位于USB上并暴露一个串行接口,你编写 `ucom(4)` 驱动程序。 -The two 框架 do not mix. You cannot take a `uart(4)` 驱动程序 and plug it into USB, and you cannot take a `ucom(4)` 驱动程序 and 附加 it to PCIe. They are independent implementations of the same user-visible abstraction (a TTY port), but with very different internals. +这两个框架不能混合使用。你不能拿一个 `uart(4)` 驱动程序插入USB,也不能拿一个 `ucom(4)` 驱动程序附加到PCIe。它们是同一用户可见抽象(TTY端口)的独立实现,但内部结构截然不同。 -Beginners sometimes ask why the two 框架 exist at all, instead of a unified serial 框架 with a pluggable transport layer. The answer is historical: `uart(4)` was rewritten in its modern form in the early 2000s to replace the older `sio(4)` 驱动程序, and at that time USB serial support was a set of ad-hoc 驱动程序. When USB serial support was unified, the natural approach was to add a thin TTY-integration layer (`ucom(4)`) rather than retrofit `uart(4)`. The two are now independent because decoupling them has been stable and useful. A unification effort would be a significant project with modest payoff. +初学者有时会问为什么存在两个框架,而不是一个带有可插拔传输层的统一串行框架。答案是历史性的:`uart(4)` 在2000年代初以其现代形式重写以替代更老的 `sio(4)` 驱动程序,那时USB串行支持是一组临时的驱动程序。当USB串行支持被统一时,自然的方法是添加一个薄的TTY集成层(`ucom(4)`)而不是改造 `uart(4)`。两者现在是独立的,因为解耦它们一直是稳定且有用的。统一工作将是一个回报有限的大型项目。 -For your purposes as a beginning 驱动程序 writer, the rule is simple. If you are writing a 驱动程序 for a chip that lives on your motherboard's 串行端口s or on a PCIe card, use `uart(4)`. If you are writing a 驱动程序 for a USB dongle that pretends to be a 串行端口, use `ucom(4)`. The reference 驱动程序 for each case (`ns8250` for `uart(4)`, `uftdi` for `ucom(4)`) are the right places to learn the details. +作为初学驱动程序编写者,规则很简单。如果你要为位于主板串行端口或PCIe卡上的芯片编写驱动程序,使用 `uart(4)`。如果你要为假装是串行端口的USB适配器编写驱动程序,使用 `ucom(4)`。每种情况的参考驱动程序(`uart(4)` 的 `ns8250`,`ucom(4)` 的 `uftdi`)是学习细节的正确起点。 -### Differences Between Chip Variants +### 芯片变体之间的差异 -Working with real UART hardware quickly teaches you that "16550-compatible" is a spectrum, not a fixed specification. Here are the variants you are most likely to encounter and the differences that matter. +使用真正的UART硬件很快就会教你,"16550兼容"是一个谱系,而非固定的规格说明。以下是你最可能遇到的变体以及它们之间重要的差异。 -**8250.** The original, from the late 1970s. Has no FIFO; every received byte must be collected by the CPU before the next arrives. Software for 16550A will usually work, with reduced performance. +**8250。** 1970年代末的原始版本。没有FIFO;每个接收到的字节必须在下一个到达之前被CPU收集。为16550A编写的软件通常可以工作,但性能降低。 -**16450.** Like 8250 but with some 注册 improvements and slightly more reliable behaviour. Still no FIFO. +**16450。** 类似8250,但有一些寄存器改进和更可靠的行为。仍然没有FIFO。 -**16550.** Introduced a 16-byte FIFO, but the original 16550 had buggy FIFO behaviour. Software should detect this and refuse to use the FIFO in the bad case. +**16550。** 引入了16字节FIFO,但原始16550有缺陷性的FIFO行为。软件应该检测到这一点并拒绝在有缺陷的情况下使用FIFO。 -**16550A.** Fixed the FIFO bugs. This is the canonical "16550" that every PC 串行驱动程序 targets. Reliable, widely compatible. +**16550A.** 修复了FIFO缺陷。这是每个PC串行驱动程序所针对的规范"16550"。可靠,广泛兼容。 -**16550AF.** Further revisions for clocking and margin. For software purposes, identical to 16550A. +**16550AF。** 时钟和裕量的进一步修订。从软件角度看,与16550A相同。 -**16650.** Extended the FIFO to 32 bytes and added automatic hardware 流控制. Mostly 16550A-compatible. +**16650。** 将FIFO扩展到32字节并添加了自动硬件流控制。大部分兼容16550A。 -**16750.** Extended the FIFO to 64 bytes. Some chips with this label also have additional autobaud and high-speed modes. Software must decide whether to enable the extended FIFO. +**16750。** 将FIFO扩展到64字节。一些标有此型号的芯片还具有额外的自动波特率检测和高速模式。软件必须决定是否启用扩展FIFO。 -**16950 (Oxford Semiconductor).** A 128-byte FIFO, additional flow-control features, and support for unusual 波特率s through a modified divisor scheme. Often seen on high-performance PCIe serial cards. +**16950(Oxford Semiconductor)。** 128字节FIFO、额外的流控制功能,以及通过修改的分频方案支持非标准波特率。常见于高性能PCIe串行卡。 -**UART-compatible SoC controllers.** Many embedded processors have built-in UARTs that are 注册-compatible with 16550 but with quirks: some have different clock rates, some have different 注册 offsets, some have DMA support, some have different interrupt semantics. The `ns8250` 驱动程序 in FreeBSD 探测 for these variants during 附加 and adjusts its behaviour accordingly. +**UART兼容的SoC控制器。** 许多嵌入式处理器具有与16550寄存器兼容但带有怪癖的内置UART:一些有不同的时钟频率,一些有不同的寄存器偏移,一些有DMA支持,一些有不同的中断语义。FreeBSD中的 `ns8250` 驱动程序在附加期间探测这些变体并相应地调整其行为。 -The `ns8250` 驱动程序's 探测 logic reads several 寄存器 to determine which variant is present. It checks the IIR bits we saw earlier, reads the FIFO control 注册 to see what FIFO size is reported, checks for 16650/16750/16950 identification markers, and records the result in a variant field in the softc. The body of the 驱动程序 then branches on this field at a few places where the variants differ. +`ns8250` 驱动程序的探测逻辑读取多个寄存器来确定存在哪个变体。它检查我们之前看到的IIR位,读取FIFO控制寄存器查看报告的FIFO大小,检查16650/16750/16950标识标记,并将结果记录在softc的变体字段中。驱动程序的主体然后在该字段上进行分支,在变体不同的几个地方进行处理。 -When you write a 驱动程序 for a new UART, decide upfront whether you want to target a single variant or a family. Targeting a single variant is simpler but limits the hardware you can support. Targeting a family requires variant detection logic like `ns8250`'s. +当你为新的UART编写驱动程序时,预先决定你是要针对单个变体还是一个系列。针对单个变体更简单,但限制了你能够支持的硬件。针对一个系列需要像 `ns8250` 那样的变体检测逻辑。 -### The Console Path +### 控制台路径 -FreeBSD can use a 串行端口 as the console. This is especially useful for embedded systems that do not have a display, for servers that do not have a keyboard and monitor, and for 内核 debugging (so that `printf` output goes somewhere visible even when the display 驱动程序 is broken). +FreeBSD可以使用串行端口作为控制台。这对于没有显示器的嵌入式系统、没有键盘和显示器的服务器以及内核调试特别有用(这样即使显示驱动程序坏了,`printf` 输出也能去到一个可见的地方)。 -The console path is tightly integrated with `uart(4)`. A UART that is designated as the console is 探测d early in boot, before most of the 内核 is initialised. The console's putc and getc methods are used to emit boot messages and to read boot-time keyboard input. Only after the full 内核 is up does the UART get 附加ed to the TTY layer in the normal way. +控制台路径与 `uart(4)` 紧密集成。被指定为控制台的UART在启动早期、内核大部分初始化之前就被探测。控制台的putc和getc方法用于发出启动消息和读取启动时的键盘输入。只有在整个内核启动完成后,UART才以正常方式附加到TTY层。 -Two mechanisms select which port is the console. The boot loader can set a variable (typically `console=comconsole`) in the environment, which the 内核 reads at startup. Alternatively, the 内核 can be configured at build time with a specific port as the console (via `options UART_EARLY_CONSOLE` in a 内核 configuration file). +有两种机制选择哪个端口作为控制台。引导加载程序可以在环境中设置一个变量(通常是 `console=comconsole`),内核在启动时读取它。或者,可以在构建时通过内核配置文件中的 `options UART_EARLY_CONSOLE` 将特定端口配置为控制台。 -When a port is the console, it stays active across 驱动程序 unload and 分离. You cannot unload `uart` or disable the console port without losing console output. This constraint is enforced in the `uart(4)` 框架 and is usually invisible to 驱动程序 writers (you do not need to special-case the console port), but it is worth knowing about in case you see console-related oddities during testing. +当一个端口是控制台时,它在驱动程序卸载和分离过程中保持活动。你不能在不丢失控制台输出的情况下卸载 `uart` 或禁用控制台端口。这个约束在 `uart(4)` 框架中强制执行,通常对驱动程序编写者不可见(你不需要特殊处理控制台端口),但值得了解,以防在测试期间看到与控制台相关的异常。 -### Comparing UART Drivers Across Architectures +### 跨架构比较UART驱动程序 -One of FreeBSD's strengths is that the same `uart(4)` 框架 works across multiple architectures. An `x86_64` laptop with a 16550 on a PCIe card, an `aarch64` Raspberry Pi with a PL011 on-chip UART, and a `riscv64` development board with a SiFive-specific UART all expose the same TTY 接口 to userland. Only the 驱动程序 differs. +FreeBSD的一个优势是相同的 `uart(4)` 框架可以在多种架构上工作。一台带有PCIe卡上16550的 `x86_64` 笔记本电脑、一台带有PL011片上UART的 `aarch64` 树莓派,以及一块带有SiFive特定UART的 `riscv64` 开发板,都向用户态暴露相同的TTY接口。不同的只是驱动程序。 -Here is a quick survey of the UART 驱动程序 in FreeBSD 14.3: +以下是FreeBSD 14.3中UART驱动程序的快速概览: -- `uart_dev_ns8250.c`: the 16550 family for x86 and many other platforms. -- `uart_dev_pl011.c`: the ARM PrimeCell PL011 UART, used on Raspberry Pi and many ARM SoCs. -- `uart_dev_imx.c`: the NXP i.MX UART, used on i.MX-based ARM boards. -- `uart_dev_z8530.c`: the Zilog Z8530, historically used on SPARC workstations. -- `uart_dev_ti8250.c`: a TI variant of the 16550 with additional features. -- `uart_dev_pl011.c` (sbsa variant): the SBSA-standardised ARM UART for server-class ARM hardware. -- `uart_dev_snps.c`: the Synopsys DesignWare UART, used on many RISC-V boards. +- `uart_dev_ns8250.c`:x86和许多其他平台的16550系列。 +- `uart_dev_pl011.c`:ARM PrimeCell PL011 UART,用于树莓派和许多ARM SoC。 +- `uart_dev_imx.c`:NXP i.MX UART,用于基于i.MX的ARM板。 +- `uart_dev_z8530.c`:Zilog Z8530,历史上用于SPARC工作站。 +- `uart_dev_ti8250.c`:带有额外功能的16550 TI变体。 +- `uart_dev_pl011.c`(sbsa变体):用于服务器级ARM硬件的SBSA标准化ARM UART。 +- `uart_dev_snps.c`:Synopsys DesignWare UART,用于许多RISC-V板。 -Open any two of these and compare their `uart_ops` implementations side by side. The structure is identical: six methods, each pointing at a function that reads or writes chip-specific 寄存器. The chip-specific details differ, but the 框架's API is the same. +打开其中任意两个,并排比较它们的 `uart_ops` 实现。结构是相同的:六个方法,每个指向一个读写芯片特定寄存器的函数。芯片特定的细节不同,但框架的API是相同的。 -This is the payoff of the layered design. A new UART 驱动程序 is a contained project: a few hundred lines of code, reusing all the 缓冲区ing and TTY integration from the 框架. If FreeBSD had to reimplement 缓冲区ing for every UART, the system would be much larger and much harder to verify. +这就是分层设计的回报。新的UART驱动程序是一个有限范围的项目:几百行代码,重用框架的所有缓冲和TTY集成。如果FreeBSD必须为每个UART重新实现缓冲,系统会大得多,也难验证得多。 -### What About the USB CDC ACM Standard? +### 那么USB CDC ACM标准呢? -USB has a standard class for serial 设备, called CDC ACM (Communication Device Class, Abstract Control Model). Chips that implement CDC ACM advertise themselves with a specific class/subclass/protocol triple at the 接口 level, and they can be driven by a single generic 驱动程序 rather than a vendor-specific one. FreeBSD's generic CDC ACM 驱动程序 is `u3g.c` in `/usr/src/sys/dev/usb/serial/`, and it is also built on top of `ucom(4)`. +USB有一个用于串行设备的标准类别,称为CDC ACM(通信设备类,抽象控制模型)。实现CDC ACM的芯片在接口级别以特定的类/子类/协议三元组来宣告自己,它们可以由一个通用驱动程序驱动,而不需要厂商特定的驱动程序。FreeBSD的通用CDC ACM驱动程序是 `/usr/src/sys/dev/usb/serial/` 中的 `u3g.c`,它也是建立在 `ucom(4)` 之上的。 -Many modern USB serial chips implement CDC ACM, so the generic 驱动程序 just works for them without a vendor-specific file. Others (like FTDI) use proprietary protocols that require a vendor-specific 驱动程序. The class/subclass/protocol triple in the 接口 描述符 is what tells you which case you are in; `usbconfig -d ugenN.M dump_all_config_desc` will show it. +许多现代USB串行芯片实现了CDC ACM,因此通用驱动程序无需厂商特定的文件即可工作。其他芯片(如FTDI)使用专有协议,需要厂商特定的驱动程序。接口描述符中的类/子类/协议三元组告诉你属于哪种情况;`usbconfig -d ugenN.M dump_all_config_desc` 会显示它。 -When you are shopping for a USB serial adapter for development work, prefer chips that implement CDC ACM. They are cheaper, more portable, and do not require proprietary 驱动程序. FTDI chips are historically dominant in embedded development because of their reliability, and FreeBSD supports them well, but a modern CP2102 or CH340G running in CDC ACM mode is equally usable. +当你为开发工作选购USB串行适配器时,优先选择实现CDC ACM的芯片。它们更便宜、更便携,不需要专有驱动程序。FTDI芯片因其可靠性在嵌入式开发中历史上占主导地位,FreeBSD对它们的支持也很好,但现代的CP2102或CH340G在CDC ACM模式下运行同样可用。 -### 总结 Section 4 +### 第4节总结 -Section 4 has given you a complete picture of how 串行驱动程序 work in FreeBSD. You have seen the layering: `uart(4)` at the 框架 level, `ttydevsw` at the TTY integration level, `uart_ops` at the hardware level. You have seen the distinction between `uart(4)` for 总线-附加ed UARTs and `ucom(4)` for USB-to-serial bridges, and the practical rule for deciding which to use. You have seen, at a high level, the six hardware methods a UART 驱动程序 implements, the configuration 回调 a USB-to-串行驱动程序 implements, and how the TTY layer sits on top of both with one uniform 接口 to userland. +第4节为你提供了串行驱动程序在FreeBSD中如何工作的完整图景。你看到了分层:框架层的 `uart(4)`、TTY集成层的 `ttydevsw`、硬件层的 `uart_ops`。你看到了总线附加UART使用 `uart(4)` 与USB转串口桥接使用 `ucom(4)` 的区别,以及决定使用哪个的实用规则。你从高层次看到了UART驱动程序实现的六个硬件方法、USB转串行驱动程序实现的配置回调,以及TTY层如何以统一的接口位于两者之上。 -The level of depth in this section is necessarily lighter than the USB-side sections, because 串行驱动程序 in FreeBSD are more specialised than USB驱动程序 and you are more likely to read an existing one (or modify one) than to write a brand-new one from scratch. If you do find yourself writing a new UART 驱动程序 for a custom board, the path is clear: open `ns8250` in one window, open your chip's data sheet in another, and write the six methods one by one. +本节的深度必然比USB侧的章节浅一些,因为FreeBSD中的串行驱动程序比USB驱动程序更专业化,你更有可能阅读或修改现有的驱动程序,而不是从头开始编写一个全新的。如果你确实要为定制板编写新的UART驱动程序,路径很清楚:在一个窗口打开 `ns8250`,在另一个窗口打开你芯片的数据手册,逐一编写六个方法。 -Two key takeaways 帧 Section 5. First, testing 串行驱动程序 does not require real hardware. FreeBSD ships a `nmdm(4)` null-modem 驱动程序 that creates pairs of virtual TTYs you can wire together, letting you exercise termios changes, 流控制, and data flow without plugging in anything. Second, testing USB驱动程序 without hardware is harder but not impossible: you can use QEMU with USB redirection to test against real 设备 through a VM, or you can use FreeBSD's USB gadget mode to make one machine present itself as a USB 设备 to another. Section 5 covers both. The goal is to enable a development loop that does not depend on cable-handling and on plugging things in and out. +通向第5节的两个关键要点。首先,测试串行驱动程序不需要真正的硬件。FreeBSD附带一个 `nmdm(4)` 空调制解调器驱动程序,可以创建成对的虚拟TTY供你连接在一起,让你无需插入任何东西就能测试termios更改、流控制和数据流。其次,在没有硬件的情况下测试USB驱动程序更难但并非不可能:你可以使用带有USB重定向的QEMU通过虚拟机测试真实设备,或者你可以使用FreeBSD的USB gadget模式让一台机器作为USB设备呈现给另一台机器。第5节涵盖这两者。目标是实现一个不依赖于处理线缆和插拔的开发循环。 -## 第5节: Testing USB和串行驱动程序 Without Real Hardware +## 第5节:不使用真实硬件测试USB和串行驱动程序 -### Why This Section Exists +### 为什么有这一节 -A beginning 驱动程序 writer often gets stuck at the same obstacle. They write a 驱动程序, compile it, want to try it, and discover they do not have the hardware, the hardware is behaving badly, the hardware is on the wrong machine, or the iteration loop of "change code, plug it in, see what happens, unplug it, change code again" is painfully slow and unreliable. Section 5 addresses this directly. FreeBSD provides several mechanisms that let you exercise 驱动程序 code paths without physical hardware, and knowing these mechanisms will save you hours of frustration. +初学驱动程序编写者经常卡在同一个障碍上。他们编写了驱动程序、编译了它、想要尝试,然后发现他们没有硬件、硬件行为异常、硬件在错误的机器上,或者 "change code, plug it in, see what happens, unplug it, change code again" 的迭代循环缓慢且不可靠。第5节直接解决了这个问题。FreeBSD提供了几种机制让你无需物理硬件就能测试驱动程序代码路径,了解这些机制将为你节省数小时的挫败感。 -The goal is not to pretend hardware is present when it is not. The goal is to give you tools that cover the parts of 驱动程序 development where hardware is incidental, so that when you do plug in real hardware, you already know your code path logic is correct and you are only validating the physical interaction. Debugging a 注册-level quirk is faster when you know that your locking, your state machines, and your user 接口 are already sound. +目标不是在硬件不存在时假装它存在。目标是为你提供工具来覆盖驱动程序开发中硬件是附带的部分,这样当你确实插入真实硬件时,你已经知道你的代码路径逻辑是正确的,只需要验证物理交互。当你知道你的锁定、状态机和用户接口已经正确时,调试寄存器级别的怪癖会更快。 -This section covers four such mechanisms: the `nmdm(4)` null-modem 驱动程序 for serial testing, basic userland tools for exercising TTYs (`cu`, `tip`, `stty`, `comcontrol`), QEMU with USB redirection for USB驱动程序 testing, and FreeBSD's USB gadget mode for presenting one machine as a USB 设备 to another. It ends with a short discussion of techniques that do not require any special tooling: unit tests at the functional layer, logging discipline, and assertion-driven development. +本节涵盖四种这样的机制:用于串行测试的 `nmdm(4)` 空调制解调器驱动程序、用于操作TTY的基本用户态工具(`cu`、`tip`、`stty`、`comcontrol`)、用于USB驱动程序测试的带USB重定向的QEMU,以及FreeBSD的USB gadget模式(让一台机器作为USB设备呈现给另一台机器)。最后简要讨论不需要任何特殊工具的技术:功能层的单元测试、日志规范和断言驱动开发。 -### The `nmdm(4)` Null-Modem Driver +### `nmdm(4)` 空调制解调器驱动程序 -`nmdm(4)` is a 内核模块 that creates pairs of linked virtual TTYs. When you write to one side, it comes out the other side, exactly as if you had connected two real 串行端口s with a null-modem cable. The 驱动程序 is in `/usr/src/sys/dev/nmdm/nmdm.c`, and it is loaded with: +`nmdm(4)` 是一个内核模块,创建成对的链接虚拟TTY。当你写入一侧时,它会从另一侧出来,就像你用空调制解调器电缆连接了两个真正的串行端口一样。驱动程序位于 `/usr/src/sys/dev/nmdm/nmdm.c`,使用以下命令加载: ```console # kldload nmdm ``` -Once loaded, you can instantiate pairs on demand simply by opening them. Run: +加载后,你可以通过简单地打开它们来按需创建对。运行: ```console # cu -l /dev/nmdm0A ``` -This opens the `A` side of pair `0`. On another terminal, run: +这打开了第0对的 `A` 侧。在另一个终端上运行: ```console # cu -l /dev/nmdm0B ``` -Whatever you type into one `cu` session will appear in the other. You have now created a pair of virtual TTYs, with no hardware involved. You can change 波特率s with `stty` and the change will be noticed on both sides. You can assert DTR and CTS through ioctls and see the effect on the other side. +你在任一 `cu` 会话中输入的内容都会出现在另一个会话中。你现在创建了一对虚拟TTY,无需任何硬件。你可以使用 `stty` 更改波特率,更改将在两侧都生效。你可以通过ioctl置位DTR和CTS并在另一侧看到效果。 -The utility of `nmdm(4)` for 驱动程序 development is twofold. First, if you are writing a TTY-layer user (say, a 驱动程序 that spawns a shell on a virtual TTY, or a userland program that implements a protocol over a TTY), you can test it end-to-end against `nmdm(4)` without any hardware. Second, if you are writing a `ucom(4)` or `uart(4)` 驱动程序, you can compare its behaviour to `nmdm(4)`'s behaviour by running the same userland test against both. If your 驱动程序 misbehaves where `nmdm(4)` does not, the bug is in your 驱动程序; if both misbehave, the bug is probably in your userland test. +`nmdm(4)` 对驱动程序开发的用处有两个方面。首先,如果你正在编写一个TTY层用户(例如,一个在虚拟TTY上生成shell的驱动程序,或一个在TTY上实现协议的用户态程序),你可以端到端地针对 `nmdm(4)` 进行测试,无需任何硬件。其次,如果你正在编写 `ucom(4)` 或 `uart(4)` 驱动程序,你可以通过在两者上运行相同的用户态测试来比较其行为与 `nmdm(4)` 的行为。如果你的驱动程序在 `nmdm(4)` 正常的地方行为异常,错误在你的驱动程序中;如果两者都异常,错误可能在你的用户态测试中。 -A small caveat: `nmdm(4)` does not simulate 波特率 delays. Whatever you write comes out the other side at memory speed. This is usually what you want (you do not want to wait through a real 9600-baud transmission for a hundred-kilobyte test payload), but it does mean that timing-sensitive protocols cannot be tested with `nmdm(4)` alone. +一个小注意事项:`nmdm(4)` 不模拟波特率延迟。你写入的任何内容都以内存速度从另一侧出来。这通常是你想要的(你不想等待真正的9600波特率传输来完成一百千字节的测试有效载荷),但这确实意味着时序敏感的协议不能仅用 `nmdm(4)` 测试。 -### The `cu(1)`, `tip(1)`, and `stty(1)` Toolbox +### `cu(1)`、`tip(1)` 和 `stty(1)` 工具箱 -Whether you are using `nmdm(4)`, a real UART, or a USB-to-serial dongle, the userland tools you use to interact with a TTY are the same. The most important three are `cu(1)`, `tip(1)`, and `stty(1)`. +无论你使用 `nmdm(4)`、真正的UART还是USB转串口适配器,与TTY交互的用户态工具都是相同的。最重要的三个是 `cu(1)`、`tip(1)` 和 `stty(1)`。 -`cu` is the classic "call up" program. It opens a TTY, puts the terminal into raw mode, and lets you type bytes to the port and see bytes coming back. To open a port at a specific 波特率: +`cu` 是经典的 "call up" 程序。它打开一个TTY,将终端置于原始模式,让你向端口输入字节并看到返回的字节。要以特定波特率打开端口: ```console # cu -l /dev/cuau0 -s 115200 ``` -The `-l` argument specifies the 设备, and `-s` specifies the 波特率. `cu` supports a handful of escape sequences (all starting with `~`) for exiting, sending files, and similar operations; `~.` is the standard "exit" escape and `~?` lists the others. +`-l` 参数指定设备,`-s` 指定波特率。`cu` 支持一些转义序列(都以 `~` 开头)用于退出、发送文件和类似操作;`~.` 是标准的 "exit" 转义序列,`~?` 列出其他转义序列。 -`tip` is a related tool with similar semantics but a different configuration mechanism. `tip` reads `/etc/remote` for named connection entries and can take a name argument rather than a 设备 path. For most purposes, `cu` and `tip` are interchangeable; `cu` is more convenient for one-off use. +`tip` 是一个相关工具,具有类似的语义但不同的配置机制。`tip` 读取 `/etc/remote` 获取命名的连接条目,可以接受名称参数而非设备路径。在大多数情况下,`cu` 和 `tip` 可以互换使用;`cu` 更便于一次性使用。 -`stty` prints or changes the termios parameters of a TTY. Run `stty -a -f /dev/ttyu0` to see every termios flag on the port. Run `stty 115200 -f /dev/ttyu0` to set the 波特率. Run `stty cs8 -parenb -cstopb -f /dev/ttyu0` to set eight 数据位, no 奇偶校验, one stop bit (the most common configuration in modern embedded work). The manual page is extensive, and the flags map almost directly onto the bits of `c_cflag`, `c_iflag`, `c_lflag`, and `c_oflag` in the `termios` struct. +`stty` 打印或更改TTY的termios参数。运行 `stty -a -f /dev/ttyu0` 查看端口上的每个termios标志。运行 `stty 115200 -f /dev/ttyu0` 设置波特率。运行 `stty cs8 -parenb -cstopb -f /dev/ttyu0` 设置八个数据位、无奇偶校验、一个停止位(现代嵌入式工作中最常见的配置)。手册页很详细,这些标志几乎直接映射到 `termios` 结构中 `c_cflag`、`c_iflag`、`c_lflag` 和 `c_oflag` 的位。 -Using these three tools together gives you a flexible way to poke at your 驱动程序 from userland. You can change settings with `stty`, open the port with `cu`, send and receive bytes, close the port, check the state with `stty` again, and repeat. If your 驱动程序's `tsw_param` implementation has a bug, `stty` will expose it: the settings you set will not read back correctly, or the port will behave differently than requested. +将这三个工具一起使用为你提供了一种灵活的方式来从用户态测试你的驱动程序。你可以用 `stty` 更改设置、用 `cu` 打开端口、发送和接收字节、关闭端口、再用 `stty` 检查状态,然后重复。如果你的驱动程序的 `tsw_param` 实现有错误,`stty` 会暴露它:你设置的设置将不能正确读回,或者端口的行为与请求的不同。 -### The `comcontrol(8)` Utility +### `comcontrol(8)` 工具 -`comcontrol` is a specialised utility for 串行端口s. It sets port-specific parameters that are not exposed through termios. The two most important are the `drainwait` and the specific-RS-485 options. For beginner 驱动程序 testing, the more common use is inspecting port state: `comcontrol /dev/ttyu0` shows the current modem signals (DTR, RTS, CTS, DSR, CD, RI) and the current `drainwait`. You can also set the signals: +`comcontrol` 是一个专门用于串行端口的工具。它设置不通过termios暴露的端口特定参数。两个最重要的是 `drainwait` 和特定的RS-485选项。对于初学者的驱动程序测试,更常见的用途是检查端口状态:`comcontrol /dev/ttyu0` 显示当前的调制解调器信号(DTR、RTS、CTS、DSR、CD、RI)和当前的 `drainwait`。你也可以设置信号: ```console # comcontrol /dev/ttyu0 dtr rts ``` -sets DTR and RTS. This is useful for testing flow-control handling without writing a custom program. +设置DTR和RTS。这对于在不编写自定义程序的情况下测试流控制处理很有用。 -### The `usbconfig(8)` Utility +### `usbconfig(8)` 工具 -On the USB side, `usbconfig(8)` is the Swiss Army knife. You used it at the end of Section 1 to inspect a 设备's 描述符. Several other subcommands are useful during 驱动程序 development: +在USB方面,`usbconfig(8)` 是瑞士军刀。你在第1节末尾使用它检查设备的描述符。在驱动程序开发期间还有几个有用的子命令: -- `usbconfig list`: list all 附加ed USB 设备. -- `usbconfig -d ugenN.M dump_all_config_desc`: print every 描述符 for a 设备. -- `usbconfig -d ugenN.M dump_设备_quirks`: print any quirks applied by the USB 框架. -- `usbconfig -d ugenN.M dump_stats`: print per-transfer statistics. -- `usbconfig -d ugenN.M suspend`: put the 设备 into the USB suspend state. -- `usbconfig -d ugenN.M resume`: wake it up. -- `usbconfig -d ugenN.M reset`: physically reset the 设备. +- `usbconfig list`:列出所有已附加的USB设备。 +- `usbconfig -d ugenN.M dump_all_config_desc`:打印设备的每个描述符。 +- `usbconfig -d ugenN.M dump_device_quirks`:打印USB框架应用的任何怪癖。 +- `usbconfig -d ugenN.M dump_stats`:打印每传输统计。 +- `usbconfig -d ugenN.M suspend`:将设备置于USB挂起状态。 +- `usbconfig -d ugenN.M resume`:唤醒它。 +- `usbconfig -d ugenN.M reset`:物理重置设备。 -The `reset` command is particularly useful during development. A 驱动程序 under test can easily leave a 设备 in a confused state; `usbconfig reset` puts the 设备 back to the just-plugged-in condition without requiring a physical unplug. +`reset` 命令在开发期间特别有用。测试中的驱动程序很容易让设备处于混乱状态;`usbconfig reset` 将设备恢复到刚插入的状态,而不需要物理拔出。 -### Testing USB Drivers with QEMU +### 使用QEMU测试USB驱动程序 -QEMU, the generic CPU emulator, has strong USB support. You can run a FreeBSD guest inside QEMU and redirect real host USB 设备 into the guest. This is the single most useful technique for USB驱动程序 development, because it lets you test against real hardware while retaining all the iteration speed of working inside a VM. +QEMU是通用CPU模拟器,具有强大的USB支持。你可以在QEMU内运行FreeBSD客户机,并将真实的主机USB设备重定向到客户机中。这是USB驱动程序开发中最有用的技术,因为它让你在保持虚拟机内工作迭代速度的同时测试真实硬件。 -On a FreeBSD host, install QEMU from ports: +在FreeBSD主机上,从ports安装QEMU: ```console # pkg install qemu ``` -Install a FreeBSD guest image into a disk file (the mechanics are covered in Chapter 4 and Appendix A). When you boot the guest, add USB redirection options: +将FreeBSD客户机镜像安装到磁盘文件中(具体步骤在第4章和附录A中介绍)。启动客户机时,添加USB重定向选项: ```console qemu-system-x86_64 \ @@ -2162,56 +2163,56 @@ qemu-system-x86_64 \ -device usb-host,bus=xhci.0,vendorid=0x0403,productid=0x6001 ``` -The `-设备 nec-usb-xhci` line adds a USB 3.0 controller to the guest. The `-设备 usb-host` line 附加 a specific USB 设备 from the host (identified by vendor and product) to that controller. When the guest boots, the 设备 appears on the guest's USB 总线 and can be enumerated by the guest's 内核. +`-device nec-usb-xhci` 行向客户机添加了一个USB 3.0控制器。`-device usb-host` 行将主机中的一个特定USB设备(由供应商和产品标识符标识)附加到该控制器。当客户机启动时,该设备出现在客户机的USB总线上,并可由客户机的内核枚举。 -This setup gives you the full iteration loop inside the VM. You can load your 驱动程序, unload it, reload a rebuilt version, all without physically handling any cables. You can use serial console or networking to interact with the VM. You can snapshot the VM state before a risky test and revert if the test panics. +这个设置为你提供了虚拟机内的完整迭代循环。你可以加载驱动程序、卸载它、重新加载重建的版本,所有这些都不需要物理处理任何线缆。你可以使用串行控制台或网络与虚拟机交互。你可以在有风险的测试之前快照虚拟机状态,如果测试崩溃则恢复。 -The main limitation is USB isochronous support, which is less stable across emulators. For bulk, interrupt, and 控制传输 (the three types most 驱动程序 use), QEMU USB redirection is reliable enough to be your primary development environment. +主要限制是USB等时传输支持,在不同模拟器之间稳定性较差。对于批量、中断和控制传输(大多数驱动程序使用的三种类型),QEMU USB重定向足够可靠,可以作为你的主要开发环境。 -### FreeBSD USB Gadget Mode +### FreeBSD USB Gadget模式 -If QEMU is not available and you have two FreeBSD machines, there is another option: `usb_template(4)` and the dual-role USB support on some hardware let you make one machine present itself as a USB 设备 to another. The host machine sees a normal USB peripheral; the gadget machine is actually running the 设备 side of the USB protocol. +如果QEMU不可用且你有两台FreeBSD机器,还有另一个选择:`usb_template(4)` 和某些硬件上的双角色USB支持可以让你让一台机器作为USB设备呈现给另一台机器。主机看到的是一个普通的USB外设;gadget机器实际上在运行USB协议的设备端。 -This is an advanced topic and the hardware support is variable. On x86 platforms with USB-on-the-Go-capable chipsets, on some ARM boards, and on specific embedded configurations, the setup works. On most desktop hardware, it does not. The gory details are in `/usr/src/sys/dev/usb/template/` and in the `usb_template(4)` manual page. +这是一个高级主题,硬件支持情况各异。在具有USB-on-the-Go功能芯片组的x86平台、某些ARM板和特定嵌入式配置上,设置有效。在大多数桌面硬件上,它不起作用。详细信息在 `/usr/src/sys/dev/usb/template/` 和 `usb_template(4)` 手册页中。 -If you have the hardware to use this technique, it is the closest thing to a full end-to-end USB驱动程序 test without physical peripherals. If you do not, do not pursue it for a learning project; use QEMU instead. +如果你有硬件可以使用这种技术,这是在没有物理外设的情况下最接近完整端到端USB驱动程序测试的方法。如果没有,不要在学习项目中使用它;改用QEMU。 -### Techniques That Do Not Require Special Tooling +### 不需要特殊工具的技术 -Beyond the 框架 above, there are several techniques that rely only on good 驱动程序 design. +除了上述框架之外,还有几种仅依赖于良好驱动程序设计的技术。 -First, design your 驱动程序 so that the hardware-independent parts can be unit-tested in userland. If your 驱动程序 has a protocol parser, a state machine, or a checksum calculator, factor those into functions that take plain C 缓冲区 and return plain C results. You can then compile those functions into a userland test program and run them against known inputs. This catches many bugs before they reach the 内核. +第一,设计你的驱动程序使硬件无关的部分可以在用户态进行单元测试。如果你的驱动程序有协议解析器、状态机或校验和计算器,将它们提取为接受普通C缓冲区并返回普通C结果的函数。然后你可以将这些函数编译到用户态测试程序中,用已知输入运行它们。这可以在bug到达内核之前捕获许多错误。 -Second, log aggressively during development and quietly in production. The `DLOG_RL` macro from 第25章 is your friend: it lets you emit frequent diagnostic messages during development, with a sysctl to suppress them in production. Rate-limiting prevents log storms if something goes wrong. +第二,在开发期间积极记录日志,在生产环境中保持安静。第25章的 `DLOG_RL` 宏是你的朋友:它让你在开发期间频繁发出诊断消息,在生产环境中通过sysctl抑制它们。速率限制可以在出问题时防止日志风暴。 -Third, use assertions for invariants. `KASSERT(cond, ("message", args...))` will panic the 内核 if `cond` is false, but only in `INVARIANTS` 内核s. You can run your 驱动程序 in an `INVARIANTS` 内核 during development and in a production 内核 later, without changing the code. The Chapter 20 discussion of `INVARIANTS` is the reference. +第三,为不变量使用断言。`KASSERT(cond, ("message", args...))` 会在 `cond` 为假时导致内核崩溃,但仅在 `INVARIANTS` 内核中。你可以在开发期间在 `INVARIANTS` 内核中运行驱动程序,之后在生产内核中运行,无需更改代码。第20章对 `INVARIANTS` 的讨论是参考。 -Fourth, be rigorous about concurrency testing. Use `INVARIANTS` plus `WITNESS` (which tracks lock ordering) during development. If your 驱动程序 has a locking bug that almost always works but occasionally deadlocks, `WITNESS` will catch it on the first occurrence. +第四,对并发测试要严格。在开发期间使用 `INVARIANTS` 加上 `WITNESS`(跟踪锁顺序)。如果你的驱动程序有一个几乎总是有效但偶尔会死锁的锁错误,`WITNESS` 会在第一次发生时捕获它。 -Fifth, write a simple userland client for your 驱动程序 and use it as part of your development loop. Even a ten-line program that opens the 设备, writes a known string, reads a known response, and checks the result is enormously useful. You can run it in a loop during stress testing, you can run it with `ktrace -f cmd` to get a trace of system calls, and you can run it under a debugger if something surprises you. +第五,为你的驱动程序编写一个简单的用户态客户端,并将其作为开发循环的一部分。即使是一个十行的程序,打开设备、写入已知字符串、读取已知响应并检查结果,也非常有用。你可以在压力测试期间循环运行它,你可以用 `ktrace -f cmd` 获取系统调用追踪,如果有什么出乎意料的情况,你可以在调试器下运行它。 -### A Walkthrough of QEMU USB Redirection +### QEMU USB重定向演练 -QEMU's USB support is the single most useful tool for USB驱动程序 development, so a more detailed walkthrough is in order. Suppose you want to develop a 驱动程序 for a specific FT232 adapter. Your host is a FreeBSD 14.3 machine, and you want to run your 驱动程序 on a guest FreeBSD 14.3 VM inside QEMU. +QEMU的USB支持是USB驱动程序开发中最有用的工具,因此值得进行更详细的演练。假设你要为特定的FT232适配器开发驱动程序。你的主机是FreeBSD 14.3机器,你想在QEMU内的FreeBSD 14.3虚拟机上运行你的驱动程序。 -First, install QEMU and create a guest disk image: +首先,安装QEMU并创建客户机磁盘镜像: ```console # pkg install qemu # truncate -s 16G guest.img ``` -Install FreeBSD into the image. The exact procedure is covered in Appendix A, but the short version is: boot a FreeBSD installer ISO as the CD-ROM, install onto the disk image, reboot. +在镜像中安装FreeBSD。具体步骤在附录A中介绍,简短版本是:将FreeBSD安装ISO作为CD-ROM启动,安装到磁盘镜像,重启。 -Once the guest is installed, locate the host USB 设备 you want to redirect. Plug in the FT232 and note the vendor and 产品IDs from `usbconfig list`: +客户机安装完成后,找到你想要重定向的主机USB设备。插入FT232并从 `usbconfig list` 记录厂商和产品ID: ```text ugen0.3: at usbus0 ``` -`usbconfig -d ugen0.3 dump_设备_desc` will show `idVendor = 0x0403` and `idProduct = 0x6001`. +`usbconfig -d ugen0.3 dump_device_desc` 将显示 `idVendor = 0x0403` 和 `idProduct = 0x6001`。 -Now start QEMU with USB redirection: +现在启动带有USB重定向的QEMU: ```console qemu-system-x86_64 \ @@ -2224,9 +2225,9 @@ qemu-system-x86_64 \ -net user -net nic ``` -The `-设备 nec-usb-xhci` line adds a USB 3.0 controller to the VM. The `-设备 usb-host` line redirects the matching host 设备 into the VM. When the VM boots, the FT232 will appear as if it were plugged directly into the VM's USB port. +`-device nec-usb-xhci` 行向虚拟机添加了一个USB 3.0控制器。`-device usb-host` 行将匹配的主机设备重定向到虚拟机中。当虚拟机启动时,FT232就像直接插入虚拟机的USB端口一样出现。 -Inside the VM, run `dmesg` and look for the USB 附加: +在虚拟机内运行 `dmesg` 查找USB附加信息: ```text uhub0: 4 ports with 4 removable, self powered @@ -2234,27 +2235,27 @@ uftdi0 on usbus0 uftdi0: on usbus0 ``` -Your 驱动程序 (whether `uftdi` or your own work-in-progress) will see a real FT232 with real 描述符, real transfer behaviour, and real quirks. You can unload and reload your 驱动程序 inside the VM without disconnecting anything; you can run 内核 with `INVARIANTS` and `WITNESS` without worrying about host-side impact; you can snapshot the VM and revert if a test goes badly. +你的驱动程序(无论是 `uftdi` 还是你正在开发中的驱动程序)将看到一个真正的FT232,具有真实的描述符、真实的传输行为和真实的怪癖。你可以在虚拟机内卸载和重新加载驱动程序而不断开任何东西;你可以在带有 `INVARIANTS` 和 `WITNESS` 的内核中运行而不用担心对主机的影响;你可以在测试出错时快照虚拟机并恢复。 -A few subtleties to be aware of with USB redirection: +USB重定向需要注意的几个细节: -- Only one consumer can claim a USB 设备 at a time. If you redirect a 设备 into a VM, the host loses access to it until the VM releases it. This matters if you are redirecting something like a USB keyboard or mouse; choose a spare 设备 for development. +- 一次只有一个消费者可以声明一个USB设备。如果你将设备重定向到虚拟机,主机将失去对它的访问,直到虚拟机释放它。如果你重定向的是USB键盘或鼠标之类的东西,这很重要;选择一个备用设备用于开发。 -- USB 等时传输 have some quirks in QEMU. They work, but timing can be slightly off. For most 驱动程序 development, you will be working with bulk, interrupt, and 控制传输, so this is rarely a concern. +- USB等时传输在QEMU中有一些怪癖。它们可以工作,但时序可能略有偏差。对于大多数驱动程序开发,你将使用批量、中断和控制传输,因此这很少是问题。 -- Some 主机控制器s (particularly xHCI) can reset under heavy I/O. If your 驱动程序 behaves strangely under stress testing, try with a different `-设备` type (uhci, ehci, xhci) to see whether the issue is in your 驱动程序 or in the emulated controller. +- 一些主机控制器(特别是xHCI)在繁重I/O下可能会重置。如果你的驱动程序在压力测试下行为异常,尝试使用不同的 `-设备` 类型(uhci、ehci、xhci)来看看问题是在你的驱动程序还是在模拟控制器中。 -- USB 3.0 SuperSpeed transfers are more reliable with `-设备 nec-usb-xhci`. Older `-usb` flag-based controllers are limited to USB 2.0. +- 使用 `-device nec-usb-xhci` 时,USB 3.0 SuperSpeed 传输更可靠。较旧的基于 `-usb` 标志的控制器仅限于 USB 2.0。 -When the VM is running, the iteration cycle becomes: edit code on the host, copy to the VM (or 挂载 a shared directory), build inside the VM, load, test, reload, repeat. A Makefile with a `test:` target that does all of this can cut iteration time to tens of seconds. +当虚拟机运行时,迭代循环变为:在主机上编辑代码,复制到虚拟机(或挂载共享目录),在虚拟机内构建、加载、测试、重新加载,重复。一个带有 `test:` 目标的Makefile可以将迭代时间缩短到几十秒。 -### Using `devd(8)` During Development +### 在开发期间使用 `devd(8)` -`devd(8)` is FreeBSD's 设备-event daemon. It reacts to 内核 notifications about 设备 附加 and 分离 and can run configured commands in response. During 驱动程序 development, `devd` is useful in two ways. +`devd(8)` 是FreeBSD的设备事件守护进程。它对内核关于设备附加和分离的通知做出反应,可以运行配置的命令来响应。在驱动程序开发期间,`devd` 在两方面很有用。 -First, it can auto-load your module when a matching 设备 is plugged in. If your module is in `/boot/modules/` and your `USB_PNP_HOST_INFO` is set, `devd` will run `kldload` automatically when it sees a 设备 that would match. +第一,它可以在匹配的设备插入时自动加载你的模块。如果你的模块在 `/boot/modules/` 中并且设置了 `USB_PNP_HOST_INFO`,`devd` 会在看到匹配的设备时自动运行 `kldload`。 -Second, it can run diagnostic commands on 附加. A `/etc/devd.conf` entry like: +第二,它可以在附加时运行诊断命令。一个 `/etc/devd.conf` 条目如: ```text attach 100 { @@ -2263,9 +2264,9 @@ attach 100 { }; ``` -will write a log line every time a `myfirst_usb` 设备 附加. For more elaborate diagnostics, you can invoke your own shell script that dumps state, starts userland consumers, or sends notifications. +将在每次 `myfirst_usb` 设备附加时写入一行日志。对于更详细的诊断,你可以调用自己的shell脚本来转储状态、启动用户态消费者或发送通知。 -During development, a useful pattern is to have `devd` open a `cu` session to a newly 附加ed `ucom` 设备, so you can exercise the 驱动程序 the moment it 附加: +在开发期间,一个有用的模式是让 `devd` 在新附加的 `ucom` 设备上打开一个 `cu` 会话,这样你可以在驱动程序附加的瞬间就测试它: ```text attach 100 { @@ -2274,11 +2275,11 @@ attach 100 { }; ``` -This runs the test in a 分离ed `screen` session, which you can later 附加 to with `screen -r usb-serial`. +这在一个分离的 `screen` 会话中运行测试,你之后可以用 `screen -r usb-serial` 附加到它。 -### Writing a Simple Userland Test Harness +### 编写简单的用户态测试工具 -Most 驱动程序 bugs are exposed by actually running the 驱动程序 against userland. Even a short test program catches more bugs than reading the 驱动程序's code carefully. For our echo 驱动程序, a minimal test program looks like: +大多数驱动程序错误是通过实际运行驱动程序与用户态交互来暴露的。即使是一个简短的测试程序也能比仔细阅读驱动程序代码捕获更多的错误。对于我们的echo驱动程序,一个最小的测试程序如下: ```c #include @@ -2321,20 +2322,20 @@ main(int argc, char **argv) } ``` -Compile with `cc -o lab03-test lab03-test.c`. Run with `./lab03-test`. The expected output is "got 5 bytes: hello". +用 `cc -o lab03-test lab03-test.c` 编译。用 `./lab03-test` 运行。预期输出是"got 5 bytes: hello"。 -Extensions to this test harness that catch more bugs: +这个测试工具的扩展可以捕获更多错误: -- Loop the open/write/read/close cycle a thousand times. Memory leaks and resource leaks show up after a few hundred iterations. -- Fork multiple processes and have them all read/write concurrently. Race conditions manifest as random data corruption or deadlocks. -- Intentionally kill the test process mid-transfer. Driver-side state machines sometimes get confused when a userland consumer disappears unexpectedly. -- Send random-length writes (1 byte, 10 bytes, 100 bytes, 1 KB, 10 KB). Edge cases around short and long transfers are where many subtle bugs live. +- 将open/write/read/close循环运行一千次。内存泄漏和资源泄漏在几百次迭代后就会显现。 +- 派生多个进程让它们同时读写。竞态条件表现为随机数据损坏或死锁。 +- 故意在传输过程中杀死测试进程。当用户态消费者意外消失时,驱动程序侧的状态机有时会混乱。 +- 发送随机长度的写入(1字节、10字节、100字节、1 KB、10 KB)。短传输和长传输的边缘情况是许多微妙错误藏身的地方。 -Build these extensions incrementally. Each one will probably reveal a bug the previous version did not; each bug you fix will make your 驱动程序 more ro总线t. +逐步构建这些扩展。每个扩展可能会揭示前一个版本没有发现的错误;你修复的每个错误都会让你的驱动程序更健壮。 -### Logging Patterns for Development +### 开发期间的日志模式 -During development, you want verbose logging. In production, you want silence. The pattern from 第25章 (`DLOG_RL` with a sysctl to control verbosity) carries over unchanged to USB and UART 驱动程序. Define a rate-limited logging macro that compiles to a no-op in production builds, and sprinkle it through every branch that might be interesting during debugging: +在开发期间,你需要详细的日志。在生产环境中,你需要安静。第25章的模式(`DLOG_RL` 加上sysctl来控制详细程度)原样适用于USB和UART驱动程序。定义一个在生产构建中编译为空操作的速率限制日志宏,并将它散布在调试期间可能感兴趣的每个分支中: ```c #ifdef MYFIRST_USB_DEBUG @@ -2348,7 +2349,7 @@ During development, you want verbose logging. In production, you want silence. T #endif ``` -Then in the 回调: +然后在回调中: ```c case USB_ST_TRANSFERRED: @@ -2356,7 +2357,7 @@ case USB_ST_TRANSFERRED: ... ``` -Control `myfirst_usb_debug` through a sysctl: +通过sysctl控制 `myfirst_usb_debug`: ```c static int myfirst_usb_debug = 0; @@ -2364,287 +2365,287 @@ SYSCTL_INT(_hw_myfirst_usb, OID_AUTO, debug, CTLFLAG_RWTUN, &myfirst_usb_debug, 0, "Enable debug logging"); ``` -Now you can turn logging on and off at runtime with `sysctl hw.myfirst_usb.debug=1`. During development, turn it on. During stress tests, turn it off (logging rate-limiting helps, but zero logging is even cheaper). During post-mortem analysis of a bug, turn it on and reproduce. +现在你可以用 `sysctl hw.myfirst_usb.debug=1` 在运行时打开和关闭日志。在开发期间打开它。在压力测试期间关闭它(日志速率限制有帮助,但零日志更廉价)。在bug的事后分析期间,打开它并重现问题。 -### A Test-Driven Workflow for 第26章 +### 第26章的测试驱动工作流 -For the hands-on labs coming in the next section, a good workflow looks like this: +对于下一节中的动手实验,一个好的工作流如下: -1. Write the 驱动程序 code. -2. Compile it. Fix build errors. -3. Load it in a test VM. Observe `dmesg` for 附加 failures. -4. Run a small userland client that exercises the 驱动程序's I/O paths. -5. Unload. Make a change. Go back to step 2. -6. Once the 驱动程序 behaves well in the VM, test it on real hardware as a sanity check. +1. 编写驱动程序代码。 +2. 编译它。修复构建错误。 +3. 在测试虚拟机中加载它。观察 `dmesg` 查找附加失败。 +4. 运行一个小型用户态客户端来测试驱动程序的I/O路径。 +5. 卸载。做修改。回到第2步。 +6. 一旦驱动程序在虚拟机中表现良好,在真实硬件上测试作为完整性检查。 -Most of the time spent on this loop is in steps 1 through 4. Real hardware testing in step 6 is a validation step, not an iteration step. If you try to iterate on real hardware, you will waste time on plug-unplug cycles and on recovering from accidental misconfigurations; the VM saves you this. +在这个循环中花费的大部分时间在第1到第4步。第6步的真实硬件测试是验证步骤,不是迭代步骤。如果你试图在真实硬件上迭代,你会浪费时间在插拔循环和从意外错误配置中恢复上;虚拟机为你节省了这些。 -A fresh install of FreeBSD in a small VM, configured to boot quickly and to have your 驱动程序's build directory 挂载ed as a shared 文件系统, is a highly productive development environment. Spending half a day to set one up pays back many times over in the days that follow. +在一个小型虚拟机中全新安装FreeBSD,配置为快速启动并将驱动程序的构建目录挂载为共享文件系统,是一个高效的开发环境。花半天时间设置一个在之后的日子里会获得多次回报。 -### 总结 Section 5 +### 第5节总结 -Section 5 has given you the tools to develop USB and 串行驱动程序 without being tied to specific physical hardware. `nmdm(4)` covers the serial-port side for any test that does not need a real modem. QEMU USB redirection covers the USB side for nearly any 驱动程序 you might write. The `cu`, `tip`, `stty`, `comcontrol`, and `usbconfig` utilities give you the userland tools to exercise 驱动程序 code paths by hand. And the general techniques, from factoring hardware-independent code into userland-testable functions to using `INVARIANTS` and `WITNESS` for 内核-time correctness checking, work regardless of what transport you are writing for. +第5节为你提供了开发USB和串行驱动程序而不依赖特定物理硬件的工具。`nmdm(4)` 覆盖了任何不需要真正调制解调器的测试的串行端口侧。QEMU USB重定向覆盖了你可能编写的几乎所有驱动程序的USB侧。`cu`、`tip`、`stty`、`comcontrol` 和 `usbconfig` 工具为你提供了手动测试驱动程序代码路径的用户态工具。通用技术,从将硬件无关代码提取为用户态可测试的函数到使用 `INVARIANTS` 和 `WITNESS` 进行内核时的正确性检查,无论你编写什么传输层都有效。 -Having reached the end of Section 5, you have everything you need to start writing real USB and 串行驱动程序 for FreeBSD 14.3. The conceptual models, the code skeletons, the transfer mechanics, the TTY integration, and the testing environment are all in place. What remains is practice, which is the purpose of the next section. +到达第5节末尾时,你已经具备了开始为FreeBSD 14.3编写真正的USB和串行驱动程序所需的一切。概念模型、代码骨架、传输机制、TTY集成和测试环境都已就绪。剩下的就是练习,这是下一节的目的。 -## Common Patterns Across Transport Drivers +## 跨传输驱动程序的通用模式 -Now that we have walked through USB and serial in detail, it is worth stepping back and noting the patterns that recur. These patterns appear in 网络驱动程序 (第28章), 块 驱动程序 (第27章), and most other transport-specific 驱动程序 in FreeBSD. Recognising them saves time when you read a new 驱动程序. +现在我们已经详细介绍了USB和串行,值得退后一步,注意那些反复出现的模式。这些模式出现在网络驱动程序(第28章)、块驱动程序(第27章)以及FreeBSD中大多数其他传输特定的驱动程序中。识别它们可以在你阅读新驱动程序时节省时间。 -### Pattern 1: Match Table, Probe, Attach, Detach +### 模式1:匹配表、探测、附加、分离 -Every transport 驱动程序 begins with a 匹配表 describing which 设备 it supports. Every transport 驱动程序 has a 探测 method that tests a candidate against the 匹配表 and returns zero or `ENXIO`. Every transport 驱动程序 has an 附加 method that takes ownership of a matched 设备 and allocates all per-设备 state. Every transport 驱动程序 has a 分离 method that releases everything the 附加 method allocated, in reverse order. +每个传输驱动程序都以一个描述其支持哪些设备的匹配表开始。每个传输驱动程序都有一个探测方法,根据匹配表测试候选设备并返回零或 `ENXIO`。每个传输驱动程序都有一个附加方法,接管匹配设备的所有权并分配所有每设备状态。每个传输驱动程序都有一个分离方法,以相反的顺序释放附加方法分配的所有内容。 -The specifics vary. USB 匹配表s use `STRUCT_USB_HOST_ID`. PCI 匹配表s use `pcidev(9)` entries. ISA 匹配表s use resource descriptions. The content differs, but the structure is identical. +具体细节因传输方式而异。USB匹配表使用 `STRUCT_USB_HOST_ID`。PCI匹配表使用 `pcidev(9)` 条目。ISA匹配表使用资源描述。内容不同,但结构相同。 -When you read a new 驱动程序, the first thing to find is the 匹配表. It tells you what hardware the 驱动程序 supports. The second thing to find is the 附加 method. It tells you what resources the 驱动程序 owns. The third thing to find is the 分离 method. It tells you the shape of the 驱动程序's resource hierarchy. +当你阅读一个新驱动程序时,首先要找的是匹配表。它告诉你驱动程序支持什么硬件。第二要找的是附加方法。它告诉你驱动程序拥有什么资源。第三要找的是分离方法。它告诉你驱动程序资源层次结构的形状。 -### Pattern 2: Softc As The Single Source of Per-Device State +### 模式2:Softc作为每设备状态的唯一来源 -Every transport 驱动程序 has a per-设备 softc. Every piece of mutable state lives in the softc. No global variables are used to hold per-设备 state (global configuration like module flags is fine). This pattern keeps multi-设备驱动程序 correct without surprise. +每个传输驱动程序都有一个每设备的softc。每个可变状态都存在于softc中。不使用全局变量来保存每设备状态(像模块标志这样的全局配置是可以的)。这种模式使多设备驱动程序保持正确而不会出现意外。 -The softc's size is declared in the 驱动程序 structure. The 框架 allocates and frees the softc automatically. The 驱动程序 accesses it through `设备_get_softc(dev)` inside New总线 methods and through whatever 框架 helper (like `usbd_xfer_softc`) is appropriate in 回调. +softc的大小在驱动程序结构中声明。框架自动分配和释放softc。驱动程序在Newbus方法内通过 `device_get_softc(dev)` 访问它,在回调中通过适当的框架辅助函数(如 `usbd_xfer_softc`)访问。 -Adding a new feature to a 驱动程序 often means adding a new field to the softc, a new initialisation step in 附加, a new cleanup step in 分离, and whatever code uses the field in between. When you structure changes this way, you rarely forget to clean things up, because the shape of the change makes the cleanup step obvious. +为驱动程序添加新功能通常意味着在softc中添加新字段、在附加中添加新的初始化步骤、在分离中添加新的清理步骤,以及使用该字段的代码。当你以这种方式组织更改时,你很少会忘记清理,因为更改的形状使清理步骤变得显而易见。 -### Pattern 3: Labelled-Goto Cleanup Chain +### 模式3:标签化Goto清理链 -When an 附加 method has to allocate several resources, each allocation has a failure path that unwinds all previous allocations. The labelled-goto chain from 第25章 implements this uniformly. Every resource has a label corresponding to "the state where this resource has been successfully allocated." A failure at any point jumps to the label for the state just before, which cleans up in reverse order. +当附加方法需要分配多个资源时,每个分配都有一个失败路径来展开所有先前的分配。第25章的标签化goto链统一实现了这一点。每个资源都有一个对应于"该资源已成功分配的状态"。任何点的失败都会跳转到恰好前一个状态的标签,该标签以相反顺序进行清理。 -This pattern is not aesthetically pleasing to some programmers (C's `goto` has a bad reputation), but it is pragmatically the cleanest way to handle an arbitrary number of cleanup steps in C. Alternatives like wrapping each resource in a separate function with its own cleanup are often more verbose. Alternatives like setting a flag per resource and testing it in a common cleanup routine add error-prone state management. +这种模式对一些程序员来说在美学上不太令人愉悦(C语言的 `goto` 有不好的名声),但实际上这是在C语言中处理任意数量清理步骤的最干净的方法。像将每个资源包装在带有自己清理的单独函数中的替代方案通常更冗长。像为每个资源设置标志并在公共清理例程中测试它的替代方案增加了容易出错的状态管理。 -Whatever you think of `goto`, FreeBSD 驱动程序 use the labelled-goto pattern, and new 驱动程序 are expected to follow the convention. +无论你对 `goto` 有什么看法,FreeBSD驱动程序使用标签化goto模式,新驱动程序应遵循这一约定。 -### Pattern 4: Frameworks Hide Transport Details +### 模式4:框架隐藏传输细节 -Each transport has a 框架 that hides transport-specific details behind a uniform API. The USB 框架 hides DMA 缓冲区 management behind `usb_page_cache` and `usbd_copy_in/out`. The UART 框架 hides interrupt dispatching behind `uart_ops`. The network 框架 (第28章) will hide 数据包 缓冲区 management behind mbufs and `ifnet(9)`. +每种传输都有一个框架,在统一的API后面隐藏传输特定的细节。USB框架在 `usb_page_cache` 和 `usbd_copy_in/out` 后面隐藏DMA缓冲区管理。UART框架在 `uart_ops` 后面隐藏中断分发。网络框架(第28章)将在mbufs和 `ifnet(9)` 后面隐藏数据包缓冲区管理。 -The value of these 框架 is that 驱动程序 become smaller and more portable. A 200-line UART 驱动程序 that supports dozens of chip variants would be impossible without the 框架. A 500-line USB驱动程序 that supports a complex protocol like USB audio would likewise be out of reach. +这些框架的价值在于驱动程序变得更小、更可移植。一个支持数十种芯片变体的200行UART驱动程序如果没有框架是不可能的。一个支持像USB音频这样的复杂协议的500行USB驱动程序同样不可能实现。 -When you read a new 驱动程序, the parts you find most dense are usually the chip-specific logic. The parts that seem almost absent (the transfer scheduling, the 缓冲区 management, the TTY integration) are where the 框架 is doing its work. +当你阅读新驱动程序时,你发现最密集的部分通常是芯片特定的逻辑。那些似乎几乎不存在的部分(传输调度、缓冲区管理、TTY集成)是框架在发挥作用的地方。 -### Pattern 5: Callbacks with State Machines +### 模式5:带状态机的回调 -The USB 回调's three-state machine (`USB_ST_SETUP`, `USB_ST_TRANSFERRED`, `USB_ST_ERROR`) is the canonical example, but similar patterns appear in other transport 驱动程序. A 网络驱动程序's transmit completion 回调 has a similar structure. A 块 驱动程序's request completion 回调 is similar. The 框架 calls the 驱动程序 back at well-defined moments, and the 驱动程序 uses a state machine to decide what to do. +USB回调的三状态机(`USB_ST_SETUP`、`USB_ST_TRANSFERRED`、`USB_ST_ERROR`)是典型的例子,但类似的模式出现在其他传输驱动程序中。网络驱动程序的传输完成回调有类似的结构。块驱动程序的请求完成回调也类似。框架在明确定义的时刻回调驱动程序,驱动程序使用状态机来决定做什么。 -Learning to read these state machines is learning a universal 驱动程序-reading skill. The specific states differ from 框架 to 框架, but the pattern is recognisable. +学会阅读这些状态机就是学习一种通用的驱动程序阅读技能。具体的状态因框架而异,但模式是可识别的。 -### Pattern 6: Mutexes and Wakeups +### 模式6:互斥锁和唤醒 -Every 驱动程序 protects its softc with a 互斥锁. Userland-facing code (read, write, ioctl) takes the 互斥锁 while manipulating softc fields. Callback code runs with the 互斥锁 held (the 框架 acquires it before calling). Userland code releases the 互斥锁 before sleeping and reacquires it after waking. Wakeup calls from 回调 release any sleeper waiting on the relevant channel. +每个驱动程序用互斥锁保护其softc。面向用户态的代码(read、write、ioctl)在操作softc字段时获取互斥锁。回调代码在持有互斥锁的情况下运行(框架在调用之前获取它)。用户态代码在睡眠之前释放互斥锁并在醒来后重新获取。来自回调的唤醒调用释放任何在相关通道上等待的睡眠者。 -The specifics vary by transport, but the pattern is universal. Modern FreeBSD 驱动程序 are uniformly multithreaded and multi-CPU safe, which requires disciplined locking. +具体细节因传输方式而异,但模式是通用的。现代FreeBSD驱动程序统一是多线程和多CPU安全的,这需要规范的锁定。 -### Pattern 7: Errno-Returning Helpers +### 模式7:返回errno的辅助函数 -第25章 introduced the errno-returning helper function pattern: every internal function returns an integer errno (zero for success, nonzero for failure). Callers check the return value and propagate failure up through the stack. The 附加 method accumulates successful helpers in the labelled-goto chain; each helper's failure triggers the cleanup corresponding to its position. +第25章介绍了返回errno的辅助函数模式:每个内部函数返回一个整数errno(零表示成功,非零表示失败)。调用者检查返回值并通过栈向上传播失败。附加方法在标签化goto链中累积成功的辅助函数;每个辅助函数的失败触发对应其位置的清理。 -This pattern requires discipline. Every helper must be consistent; no helper can return a "success value" that varies in meaning, and no helper can use global state to communicate failure. When followed rigorously, the pattern produces 驱动程序 where the control flow is legible and the error paths are easy to audit. +这种模式需要纪律。每个辅助函数必须一致;没有辅助函数可以返回一个 "success value" 含义不同的值,也没有辅助函数可以使用全局状态来传达失败。严格遵循时,这种模式产生的驱动程序中控制流是清晰的,错误路径易于审计。 -### Pattern 8: Version Declarations and Module Dependencies +### 模式8:版本声明和模块依赖 -Every 驱动程序 module declares its own version with `MODULE_VERSION`. Every 驱动程序 module declares its dependencies with `MODULE_DEPEND`. Dependencies are versioned ranges (minimum, preferred, maximum), which allows parallel development of 框架 and 驱动程序 to proceed without lockstep releases. +每个驱动程序模块用 `MODULE_VERSION` 声明自己的版本。每个驱动程序模块用 `MODULE_DEPEND` 声明其依赖。依赖是版本化的范围(最小值、首选值、最大值),这允许框架和驱动的并行开发而无需同步发布。 -When a new major version of a 框架 is released with breaking API changes, the version range in `MODULE_DEPEND` is how a 驱动程序 expresses "I work with 框架 v1 or v2, but not v3." The 内核模块 loader refuses to load a 驱动程序 whose dependencies cannot be satisfied, which prevents many classes of silent breakage. +当框架的新主版本发布并带有破坏性API更改时,`MODULE_DEPEND` 中的版本范围是驱动程序表达"我适用于框架v1或v2,但不适用于v3"的方式。 内核模块加载器拒绝加载依赖无法满足的驱动程序,这防止了许多类的静默破坏。 -### Pattern 9: Cross-Framework Layering +### 模式9:跨框架分层 -Some 驱动程序 sit on top of multiple 框架. A USB-to-以太网 驱动程序 sits on top of `usbdi(9)` (for USB transfers) and `ifnet(9)` (for 网络接口 semantics). A USB-to-串行驱动程序 sits on top of `usbdi(9)` and `ucom(4)`. A USB mass-存储驱动程序 sits on top of `usbdi(9)` and CAM. +一些驱动程序位于多个框架之上。USB转以太网驱动程序位于 `usbdi(9)`(用于USB传输)和 `ifnet(9)`(用于网络接口语义)之上。USB转串行驱动程序位于 `usbdi(9)` 和 `ucom(4)` 之上。USB大容量存储驱动程序位于 `usbdi(9)` 和CAM之上。 -When you write a cross-框架 驱动程序, the structure is: you write 回调 for each 框架, and you orchestrate the interaction between them in your 驱动程序's helper code. The 框架 on top of which you sit defines how userland sees your 驱动程序. The 框架 below handles the transport. +当你编写跨框架驱动程序时,结构是:你为每个框架编写回调,并在驱动程序的辅助代码中协调它们之间的交互。你位于其上的框架定义了用户态如何看待你的驱动程序。下面的框架处理传输。 -Reading `uftdi.c` showed you this pattern: the 驱动程序 is a USB驱动程序 (it uses `usbdi(9)`) and a 串行驱动程序 (it uses `ucom(4)`), and the orchestration between the two is the heart of the file. +阅读 `uftdi.c` 向你展示了这种模式:驱动程序既是USB驱动程序(使用 `usbdi(9)`),也是串行驱动程序(使用 `ucom(4)`),两者之间的协调是文件的核心。 -### Pattern 10: Early Attach Deferral +### 模式10:早期附加延迟 -Some 驱动程序 cannot finish their 附加 work synchronously. For example, a 驱动程序 might need to read a configuration EEPROM that takes a few hundred milliseconds, or it might need to wait for a PHY to autonegotiate a link. These 驱动程序 use a deferred-附加 pattern: the New总线 附加 method queues a taskqueue task that does the slow work, then returns quickly. +一些驱动程序无法同步完成其附加工作。例如,驱动程序可能需要读取需要几百毫秒的配置EEPROM,或者可能需要等待PHY自动协商链路。这些驱动程序使用延迟附加模式:Newbus附加方法将一个taskqueue任务排队来执行慢速工作,然后快速返回。 -This pattern keeps the system boot fast (no single 驱动程序 holds up boot by taking a long time in 附加) and lets 驱动程序 do their work asynchronously. The caller must be aware that 附加 "finishing" does not mean the 设备 is fully usable; a separate "ready" state has to be polled or signalled. +这种模式保持系统启动快速(没有单个驱动程序通过在附加中花费很长时间来阻碍启动)并让驱动程序异步执行其工作。调用者必须意识到附加"完成"并不意味着设备完全可用;有一个单独的"就绪"状态需要轮询或信号通知。 -For USB and UART 驱动程序, 附加 is usually fast enough that deferral is not needed. For more complex 驱动程序 (network cards in particular), deferral is common. 第28章 will show an example. +对于USB和UART驱动程序,附加通常足够快,不需要延迟。对于更复杂的驱动程序(特别是网卡),延迟很常见。第28章将展示一个例子。 -### Pattern 11: Separate Data Path and Control Path +### 模式11:分离数据路径和控制路径 -In every transport 驱动程序, two conceptual paths exist: the control path (configuration, state changes, error recovery) and the data path (the actual bytes moving through the 设备). Most 驱动程序 structure these as separate code paths, sometimes with separate locking. +在每个传输驱动程序中,存在两个概念路径:控制路径(配置、状态更改、错误恢复)和数据路径(通过设备移动的实际字节)。大多数驱动程序将它们构建为单独的代码路径,有时使用单独的锁定。 -The control path is low-bandwidth and infrequent. It can afford heavy locking and synchronous calls. The data path is high-bandwidth and continuous. It must be optimised for throughput: minimal locking, no synchronous calls, efficient 缓冲区 management. +控制路径是低带宽和不频繁的。它可以承受重度锁定和同步调用。数据路径是高带宽和连续的。它必须为吞吐量进行优化:最少的锁定、无同步调用、高效的缓冲区管理。 -The USB 框架 keeps them naturally separate: configuration through `usbd_transfer_setup` and 控制传输; data through bulk and 中断传输. The UART 框架 likewise: configuration through `tsw_param`; data through the 中断处理程序 and 环形缓冲区. Network 驱动程序 have the most pronounced separation: configuration through ioctls; data through the TX and RX queues. +USB框架自然地将它们分开:通过 `usbd_transfer_setup` 和控制传输进行配置;通过批量传输和中断传输传输数据。UART框架同样:通过 `tsw_param` 进行配置;通过中断处理程序和环形缓冲区传输数据。网络驱动程序的分离最为明显:通过ioctl进行配置;通过TX和RX队列传输数据。 -Reading a new 驱动程序, knowing this separation exists helps you parse what each code 块 is doing. A function with extensive locking and error handling is probably control path. A function with short, tight code and careful 缓冲区 management is probably data path. +阅读新驱动程序时,知道这种分离的存在有助于你解析每个代码块在做什么。一个具有大量锁定和错误处理的函数可能是控制路径。一个具有简短、紧凑代码和仔细缓冲区管理的函数可能是数据路径。 -### Pattern 12: Reference Drivers +### 模式12:参考驱动程序 -Every transport in FreeBSD has one or two "canonical" reference 驱动程序 that illustrate the patterns correctly and thoroughly. For USB, `uled.c` and `uftdi.c` are the references. For UART, `uart_dev_ns8250.c` is the reference. For networking, `em` (Intel 以太网) and `rl` (Realtek) are the references. For 块设备, `da` (direct-access storage) is the reference. +FreeBSD中的每种传输都有一个或两个"规范"参考驱动程序——正确且详尽地展示模式的参考驱动程序。对于USB,`uled.c` 和 `uftdi.c` 是参考。对于UART,`uart_dev_ns8250.c` 是参考。对于网络,`em`(Intel以太网)和 `rl`(Realtek)是参考。对于块设备,`da`(直接访问存储)是参考。 -When you need to understand how to write a new 驱动程序 in an existing transport, the reference 驱动程序 is the right place to start. Do not try to understand the 框架 from its code alone; that is too abstract. Start from a working 驱动程序 and let it ground your understanding. +当你需要理解如何在现有传输中编写新驱动程序时,参考驱动程序是正确的起点。不要试图仅从框架的代码来理解它;那太抽象了。从一个工作的驱动程序开始,让它为你的理解奠定基础。 ## 动手实验 -These labs give you a chance to turn the reading into muscle memory. Each lab is designed to fit in a single sitting, ideally under an hour. They assume a FreeBSD 14.3 lab environment (either on physical hardware or inside a virtual machine), root access, and a working build environment as described in Chapter 3. The companion files for every lab in this chapter are available under `examples/part-06/ch26-usb-serial/` in the book's repository. +这些实验给你机会将阅读转化为肌肉记忆。每个实验设计为一次完成,理想情况下不超过一小时。它们假设一个FreeBSD 14.3实验环境(物理硬件或虚拟机内)、root访问权限和第3章中描述的工作构建环境。本章每个实验的配套文件可在书籍仓库的 `examples/part-06/ch26-usb-serial/` 下找到。 -The labs build on each other but do not strictly depend on each other. You can skip a lab and come back to it later without losing continuity. The first three labs focus on USB; the last three focus on serial. Each lab has the same structure: a short summary, the steps, expected output, and a "what to watch for" note that highlights the learning goal. +实验相互衔接但不严格相互依赖。你可以跳过一个实验稍后再回来而不失去连续性。前三个实验关注USB;后三个关注串行。每个实验有相同的结构:简短摘要、步骤、预期输出,以及一个"注意事项"注释来突出学习目标。 -### Lab 1: Exploring a USB Device with `usbconfig` +### 实验1:使用 `usbconfig` 探索USB设备 -This lab exercises the 描述符 vocabulary from Section 1 by inspecting real USB 设备 on your machine. It does not involve writing any code. +本实验通过检查你机器上的真实USB设备来练习第1节的描述符词汇。不涉及编写任何代码。 -**Goal.** Read the 描述符 of three different USB 设备 and identify their 接口 class, the number of 端点, and the 端点 types. +**目标。** 读取三个不同USB设备的描述符,识别它们的接口类、端点数量和端点类型。 -**Requirements.** A FreeBSD system with at least three USB 设备 plugged in. If you only have one machine and few USB ports, a USB hub with a few small peripherals (mouse, keyboard, flash drive) is ideal. +**要求。** 一台至少插入三个USB设备的FreeBSD系统。如果你只有一台机器且USB端口少,一个带有几个小外设(鼠标、键盘、闪存驱动器)的USB集线器是理想的。 -**Steps.** +**步骤。** -1. Run `usbconfig list` as root. Record the `ugenN.M` identifiers of three 设备. +1. 以root身份运行 `usbconfig list`。记录三个设备的 `ugenN.M` 标识符。 -2. For each 设备, run: +2. 对于每个设备,运行: ``` # usbconfig -d ugenN.M dump_all_config_desc ``` - Read through the output. Identify the `bInterfaceClass`, `bInterfaceSubClass`, and `bInterfaceProtocol` for each 接口. For each 端点 in each 接口, record the `bEndpointAddress` (including direction bit), the `bmAttributes` (including transfer type), and the `wMaxPacketSize`. + 阅读输出。识别每个接口的 `bInterfaceClass`、`bInterfaceSubClass` 和 `bInterfaceProtocol`。对于每个接口中的每个端点,记录 `bEndpointAddress`(包括方向位)、`bmAttributes`(包括传输类型)和 `wMaxPacketSize`。 -3. Build a small table. For each 设备, write down: 供应商ID, 产品ID, 接口 class (with name from the USB class list), number of 端点, and the transfer type of each 端点. +3. 制作一个小表。对于每个设备,写下:供应商ID、产品ID、接口类(使用USB类列表中的名称)、端点数量以及每个端点的传输类型。 -4. Match your table against `dmesg`. Confirm that the 驱动程序 that claimed each 设备 makes sense given the 接口 class you recorded. +4. 将你的表与 `dmesg` 对比。确认声明每个设备的驱动程序在给定你记录的接口类的情况下是合理的。 -5. Optional: repeat the exercise for a 设备 you have not seen before (someone else's keyboard, a USB audio 接口, a game controller). The more variety you see, the faster 描述符 reading becomes. +5. 可选:对你之前没见过的设备(别人的键盘、USB音频接口、游戏控制器)重复这个练习。你看到的种类越多,描述符阅读就越快。 -**Expected output.** A filled-in table with at least three rows. The exercise is successful if you can answer, for any 设备 in the table: "What class of 驱动程序 would handle this?" +**预期输出。** 一个至少三行的填好的表。如果你能回答表中任何设备的以下问题,则练习成功:"什么样的驱动程序会处理这个设备?" -**What to watch for.** Pay attention to 设备 that expose multiple 接口. A webcam, for example, often has an audio 接口 (for the microphone) in addition to its video 接口. A multi-function printer might expose a printer 接口, a scanner 接口, and a mass-storage 接口. Noticing these is what trains your eye for the multi-接口 logic in the `探测` method. +**注意事项。** 注意暴露多个接口的设备。例如,网络摄像头通常除了视频接口外还有音频接口(用于麦克风)。多功能打印机可能暴露打印机接口、扫描仪接口和大容量存储接口。注意到这些有助于训练你发现探测方法中多接口逻辑的眼光。 -### Lab 2: Building and Loading the USB Driver Skeleton +### 实验2:构建和加载USB驱动程序骨架 -This lab walks through building the skeleton 驱动程序 from Section 2, loading it, and observing its behaviour when a matching 设备 is plugged in. +本实验演示构建第2节的骨架驱动程序、加载它,并观察匹配设备插入时的行为。 -**Goal.** Compile and load `myfirst_usb.ko`, and observe its 附加 and 分离 messages. +**目标。** 编译并加载 `myfirst_usb.ko`,观察其附加和分离消息。 -**Requirements.** The build environment from Chapter 3. The files under `examples/part-06/ch26-usb-serial/lab02-usb-skeleton/`. A USB 设备 whose vendor/product you can match. For development, a VOTI/OBDEV test VID/PID (0x16c0/0x05dc) is free to use; otherwise, pick a cheap prototyping 设备 (like an FT232 breakout board) and adjust the 匹配表 to match its IDs. +**要求。** 第3章的构建环境。`examples/part-06/ch26-usb-serial/lab02-usb-skeleton/` 下的文件。一个你可以匹配其vendor/product的USB设备。用于开发时,VOTI/OBDEV测试VID/PID(0x16c0/0x05dc)可免费使用;否则,选择一个廉价的原型设备(如FT232分线板)并调整匹配表以匹配其ID。 -**Steps.** +**步骤。** -1. Enter the lab directory: +1. 进入实验目录: ``` # cd examples/part-06/ch26-usb-serial/lab02-usb-skeleton ``` -2. Read `myfirst_usb.c` and `myfirst_usb.h`. Identify the 匹配表, the 探测 method, the 附加 method, the softc, and the 分离 method. For each, trace how it relates to the Section 2 walkthrough. +2. 阅读 `myfirst_usb.c` 和 `myfirst_usb.h`。识别匹配表、探测方法、附加方法、softc和分离方法。对于每个,追踪它如何与第2节的演练相关。 -3. Build the module: +3. 构建模块: ``` # make ``` - You should see `myfirst_usb.ko` created in the build directory. + 你应该看到 `myfirst_usb.ko` 在构建目录中创建。 -4. Load the module: +4. 加载模块: ``` # kldload ./myfirst_usb.ko ``` - Run `kldstat | grep myfirst_usb` to confirm the module is loaded. + 运行 `kldstat | grep myfirst_usb` 确认模块已加载。 -5. Plug in a matching 设备. Observe `dmesg`. You should see a line like: +5. 插入匹配的设备。观察 `dmesg`。你应该看到类似这样的行: ``` myfirst_usb0: on uhub0 myfirst_usb0: attached ``` - If the 设备 does not match, nothing will happen. In that case, open `usbdevs` on the target machine, find the vendor/product of a 设备 you do have, and edit the 匹配表 accordingly. Rebuild, reload, and try again. + 如果设备不匹配,什么都不会发生。在这种情况下,在目标机器上打开 `usbdevs`,找到你确实有的设备的vendor/product,并相应地编辑匹配表。重建、重新加载并重试。 -6. Unplug the 设备. Observe `dmesg`. You should see the 内核 remove the 设备. Your `分离` does not log anything explicitly in this minimal skeleton, but you can add a `设备_printf(dev, "分离ed\n")` if you want confirmation. +6. 拔出设备。观察 `dmesg`。你应该看到内核移除设备。在这个最小骨架中,你的分离方法不会显式记录任何内容,但如果你想要确认,可以添加 `device_printf(dev, "分离ed\n")`。 -7. Unload the module: +7. 卸载模块: ``` # kldunload myfirst_usb ``` -**Expected output.** Attach messages in `dmesg` when the 设备 is plugged in. Clean unload with no panics when the module is removed. +**预期输出。** 设备插入时 `dmesg` 中出现附加消息。模块移除时干净卸载,没有崩溃。 -**What to watch for.** If `kldload` fails with an error about symbol lookups, you probably forgot a `MODULE_DEPEND` line or misspelled a symbol name. If `附加` is never called but the 设备 is definitely present, the 匹配表 is wrong: check the vendor and 产品IDs in `usbconfig list` and verify they match what you wrote in `myfirst_usb_devs`. If `附加` is called but fails, check `设备_printf` output for the failure reason. +**注意事项。** 如果 `kldload` 因符号查找错误而失败,你可能忘记了一个 `MODULE_DEPEND` 行或拼错了符号名称。如果附加从未被调用但设备确实存在,匹配表是错误的:检查 `usbconfig list` 中的vendor和产品ID,验证它们是否与你在 `myfirst_usb_devs` 中写的一致。如果附加被调用但失败了,检查 `device_printf` 输出了解失败原因。 -### Lab 3: A Bulk Loopback Test +### 实验3:批量环回测试 -This lab adds the transfer mechanics from Section 3 to the skeleton from Lab 2 and sends a few bytes through a USB 设备 that implements a loopback protocol. It is the first lab that actually moves data. +本实验将第3节的传输机制添加到实验2的骨架中,通过实现环回协议的USB设备发送几个字节。这是第一个真正传输数据的实验。 -**Goal.** Add a bulk-OUT and bulk-IN channel to the 驱动程序, write a small userland client that sends a string and reads it back, and observe the roundtrip. +**目标。** 向驱动程序添加批量输出和批量输入通道,编写一个小型用户态客户端发送字符串并读回,观察往返过程。 -**Requirements.** A USB 设备 that implements bulk loopback. The simplest such 设备 for development is a USB gadget controller running a loopback program (possible on some ARM boards and on some development kits). If you do not have one, you can substitute a simpler exercise: 附加 the 驱动程序 to a USB flash drive, open one of its `ugen` 端点, and simply armed-submit-complete a single read transfer. The loop will fail (because flash drives do not echo data), but the mechanics of setup and submission will run correctly. +**要求。** 一个实现批量环回的USB设备。最简单的这种开发设备是运行环回程序的USB gadget控制器(在某些ARM板和某些开发板上可能)。如果没有,你可以替代为一个更简单的练习:将驱动程序附加到USB闪存驱动器,打开其 `ugen` 端点之一,简单地执行一次读取传输的 armed-submit-complete。环回将失败(因为闪存驱动器不会回显数据),但设置和提交的机制将正确运行。 -**Steps.** +**步骤。** -1. Copy `lab02-usb-skeleton` to `lab03-bulk-loopback` as a working copy. +1. 将 `lab02-usb-skeleton` 复制到 `lab03-bulk-loopback` 作为工作副本。 -2. Add the bulk channels to the 驱动程序. Paste the config array from Section 3, the 回调 functions, and the userland interaction. Make sure the `/dev` entry your 驱动程序 creates supports `read(2)` and `write(2)`, which are what the lab test program uses. +2. 将批量通道添加到驱动程序。粘贴第3节的配置数组、回调函数和用户态交互。确保你的驱动程序创建的 `/dev` 条目支持 `read(2)` 和 `write(2)`,这是实验测试程序使用的。 -3. Rebuild and reload the module. +3. 重新构建并重新加载模块。 -4. Run the userland client: +4. 运行用户态客户端: ``` # ./lab03-test ``` - which you will find alongside the 驱动程序 in the lab directory. The program opens `/dev/myfirst_usb0`, writes "hello", reads up to 16 bytes, and prints them. If loopback works, the output is "hello". + 你会在实验目录中的驱动程序旁边找到它。程序打开 `/dev/myfirst_usb0`,写入"hello",读取最多16个字节并打印它们。如果环回工作,输出是"hello"。 -5. Observe `dmesg` for any stall warnings or error messages. +5. 观察 `dmesg` 查找任何停顿警告或错误消息。 -**Expected output.** "hello" echoed back. If the remote 设备 does not implement loopback, the read will return after the channel's timeout with no data, which is also a valid test outcome for the purposes of exercising the state machine. +**预期输出。** "hello"被回显。如果远端设备不实现环回,读取将在通道超时后返回无数据,这也是用于测试状态机的有效测试结果。 -**What to watch for.** The most common mistake in this lab is mismatched 端点 directions. Remember: `UE_DIR_IN` means "the host reads from the 设备" and `UE_DIR_OUT` means "the host writes to the 设备". If you swap them, the transfers will fail with stalls. Watch also for missing locking around the userland read/write handlers; if you manipulate the transmit queue without the softc 互斥锁 held, you can race with the write 回调 and see bytes disappear. +**注意事项。** 本实验最常见的错误是端点方向不匹配。记住:`UE_DIR_IN` 表示"主机从设备读取",`UE_DIR_OUT` 表示"主机向设备写入"。如果你交换了它们,传输将以停顿失败。还要注意用户态读/写处理程序周围缺少锁定;如果你在没有持有softc互斥锁的情况下操作传输队列,你可能会与写回调竞争并看到字节消失。 -### Lab 4: A Simulated Serial Driver with `nmdm(4)` +### 实验4:使用 `nmdm(4)` 的模拟串行驱动程序 -This lab is not about writing a 驱动程序; it is about learning the userland half of serial testing. The results will inform how you approach Lab 5 and how you debug any TTY-layer work in the future. +本实验不是关于编写驱动程序;而是关于学习串行测试的用户态部分。结果将影响你如何进行实验5以及未来如何调试任何TTY层工作。 -**Goal.** Create a pair of `nmdm(4)` virtual ports, observe how data flows, and exercise `stty` and `comcontrol` to see how termios and modem signals work. +**目标。** 创建一对 `nmdm(4)` 虚拟端口,观察数据如何流动,使用 `stty` 和 `comcontrol` 查看termios和调制解调器信号如何工作。 -**Requirements.** A FreeBSD system. No special hardware. +**要求。** 一台FreeBSD系统。无需特殊硬件。 -**Steps.** +**步骤。** -1. Load the `nmdm` module: +1. 加载 `nmdm` 模块: ``` # kldload nmdm ``` -2. In terminal A, open the `A` side: +2. 在终端A中,打开 `A` 侧: ``` # cu -l /dev/nmdm0A -s 9600 ``` -3. In terminal B, open the `B` side: +3. 在终端B中,打开 `B` 侧: ``` # cu -l /dev/nmdm0B -s 9600 ``` -4. Type in terminal A. Observe that the characters appear in terminal B. Type in terminal B; they appear in terminal A. +4. 在终端A中输入。观察字符出现在终端B中。在终端B中输入;它们出现在终端A中。 -5. Exit `cu` in both terminals (type `~.`). In a third terminal, run: +5. 在两个终端中退出 `cu`(输入 `~.`)。在第三个终端中运行: ``` # stty -a -f /dev/nmdm0A ``` - Read through the output. Notice `9600` for the 波特率, `cs8 -parenb -cstopb` for the byte format, and various flags for line discipline. + 阅读输出。注意波特率为 `9600`,字节格式为 `cs8 -parenb -cstopb`,以及各种线路规程标志。 -6. Change the 波特率 on one side: +6. 更改一侧的波特率: ``` # stty 115200 -f /dev/nmdm0A ``` - Then open the ports again with `cu -s 115200`. The 波特率 change is visible, even though `nmdm(4)` does not actually wait for serialised bits. + 然后用 `cu -s 115200` 再次打开端口。波特率更改是可见的,尽管 `nmdm(4)` 实际上并不等待串行化位。 7. Run: @@ -2652,118 +2653,118 @@ This lab is not about writing a 驱动程序; it is about learning the userland # comcontrol /dev/ttyu0A ``` - ...or rather, the equivalent for the `nmdm` 字符设备. The `nmdm` pairs do not always have `comcontrol`-visible modem signals, depending on the FreeBSD version; if your version does not, skip this step. + ...或者更准确地说,`nmdm` 字符设备的等价物。`nmdm` 对并不总是有 `comcontrol` 可见的调制解调器信号,取决于FreeBSD版本;如果你的版本没有,跳过这一步。 -**Expected output.** Text appears on the opposite side. `stty` shows termios flags. You now have a reproducible way to test TTY-layer behaviour on your machine. +**预期输出。** 文本出现在对面。`stty` 显示termios标志。你现在有了一种可复现的方式来在你的机器上测试TTY层行为。 -**What to watch for.** The pair identifiers (`0`, `1`, `2`...) are implicit and allocated on first open. If you cannot open `/dev/nmdm5A` because nothing has opened `/dev/nmdm4A` yet, this is expected: pairs are created lazily in increasing order. Also note that `cu` uses a lock file in `/var/spool/lock/`; if you kill `cu` abruptly, the lock file may persist and prevent reopens. Delete it manually if you get a "port in use" error. +**注意事项。** 对标识符(`0`、`1`、`2`...)是隐式的并在首次打开时分配。如果你无法打开 `/dev/nmdm5A` 是因为还没有任何东西打开过 `/dev/nmdm4A`,这是预期的:对是按递增顺序延迟创建的。还要注意 `cu` 使用 `/var/spool/lock/` 中的锁文件;如果你突然杀死 `cu`,锁文件可能持续存在并阻止重新打开。如果你得到"port in use"错误,手动删除它。 -### Lab 5: Talking to a Real USB-to-Serial Adapter +### 实验5:与真正的USB转串口适配器通信 -This lab brings real hardware into the loop. You will use a USB-to-serial adapter (an FT232, a CP2102, a CH340G, or anything else FreeBSD supports) and a terminal program to exercise the full path from `ucom(4)` through the TTY layer to userland. +本实验将真正的硬件引入循环。你将使用USB转串口适配器(FT232、CP2102、CH340G或FreeBSD支持的任何其他设备)和终端程序来测试从 `ucom(4)` 到TTY层再到用户态的完整路径。 -**Goal.** Plug in a USB-to-serial adapter, verify it 附加, and use `cu` to send data to it (perhaps by looping the TX and RX pins together with a jumper). +**目标。** 插入USB转串口适配器,验证它已附加,并使用 `cu` 向其发送数据(也许通过跳线将TX和RX引脚连接在一起)。 -**Requirements.** A USB-to-serial adapter. A jumper wire (if you want to do a hardware loopback) or a second serial 设备 to talk to (a development board, an embedded computer, or an old serial modem). +**要求。** 一个USB转串口适配器。一根跳线(如果你想进行硬件环回)或一个可以通信的第二串行设备(开发板、嵌入式计算机或旧串行调制解调器)。 -**Steps.** +**步骤。** -1. Plug in the adapter. Run `dmesg | tail` and confirm it 附加. You should see lines like: +1. 插入适配器。运行 `dmesg | tail` 确认它已附加。你应该看到类似这样的行: ``` uftdi0 on uhub0 uftdi0: on usbus0 ``` - and a `ucomN: <...>` line just after that. + 以及紧随其后的 `ucomN: <...>` 行。 -2. Run `ls -l /dev/cuaU*`. The adapter's port is usually `/dev/cuaU0` for the first adapter, `/dev/cuaU1` for the second, and so on. (Note the capital-U suffix, which distinguishes USB-provided ports from the real UART ports at `/dev/cuau0`.) +2. 运行 `ls -l /dev/cuaU*`。适配器的端口通常是 `/dev/cuaU0` 用于第一个适配器,`/dev/cuaU1` 用于第二个,以此类推。(注意大写U后缀,它区分USB提供的端口和 `/dev/cuau0` 处的真正UART端口。) -3. Put a jumper wire between the TX and RX pins of the adapter. This creates a hardware loopback: whatever the adapter transmits comes back on its own RX line. +3. 在适配器的TX和RX引脚之间放置一根跳线。这创建了一个硬件环回:适配器发送的任何内容都会在其自己的RX线上返回。 -4. In one terminal, set the 波特率: +4. 在一个终端中,设置波特率: ``` # stty 9600 -f /dev/cuaU0 ``` -5. Open the port with `cu`: +5. 用 `cu` 打开端口: ``` # cu -l /dev/cuaU0 -s 9600 ``` - Type characters. Every character you type should appear twice: once as local echo (if your terminal is echoing), and once as the character coming back through the loopback. Disable the local echo in `cu` if it is confusing; the `stty -echo` will help. + 输入字符。你输入的每个字符应该出现两次:一次作为本地回显(如果你的终端在回显),一次作为通过环回返回的字符。如果令人困惑,在 `cu` 中禁用本地回显;`stty -echo` 会有帮助。 -6. Remove the jumper. Type characters. Now they will not come back, because there is nothing connected to RX. +6. 移除跳线。输入字符。现在它们不会回来了,因为RX上没有连接任何东西。 -7. Exit `cu` with `~.`. Unplug the adapter. Run `dmesg | tail` and verify clean 分离. +7. 用 `~.` 退出 `cu`。拔出适配器。运行 `dmesg | tail` 验证干净的分离。 -**Expected output.** Characters are echoed back when the jumper is in place and lost when it is not. The `dmesg` shows clean 附加 and 分离. +**预期输出。** 跳线在位时字符被回显,不在位时丢失。`dmesg` 显示干净的附加和分离。 -**What to watch for.** If the adapter 附加 but no `cuaU` 设备 appears, the underlying `ucom(4)` instance may have 附加ed but failed to create its TTY. Check `dmesg` for errors. If characters come out garbled, the 波特率 is probably wrong: make sure every stage of the path (your terminal, `cu`, `stty`, the adapter, and the far end) is set to the same rate. On older hardware, some USB-to-serial adapters do not reset their internal configuration when you open them; you may need to explicitly set the 波特率 with `stty` before `cu` will work correctly. +**注意事项。** 如果适配器已附加但没有 `cuaU` 设备出现,底层 `ucom(4)` 实例可能已附加但未能创建其TTY。检查 `dmesg` 查找错误。如果字符出来是乱码,波特率可能错误:确保路径的每个阶段(你的终端、`cu`、`stty`、适配器和远端)都设置为相同的速率。在较旧的硬件上,一些USB转串口适配器在你打开它们时不会重置其内部配置;在 `cu` 正确工作之前,你可能需要用 `stty` 显式设置波特率。 -### Lab 6: Observing Hot-Plug Lifecycle +### 实验6:观察热插拔生命周期 -This lab does not require writing any new 驱动程序 code. It exercises the 热插拔 lifecycle we described conceptually in Section 1 and in code in Section 2, using the existing `uhid` or `ukbd` 驱动程序 as the test subject. +本实验不需要编写任何新的驱动程序代码。它使用现有的 `uhid` 或 `ukbd` 驱动程序作为测试对象,练习我们在第1节概念上和第2节代码中描述的热插拔生命周期。 -**Goal.** Plug in and unplug a USB 设备 repeatedly while monitoring 内核 logs, observing the full 附加/分离 sequence. +**目标。** 在监视内核日志的同时反复插入和拔出USB设备,观察完整的附加/分离序列。 -**Requirements.** A USB 设备 you can plug and unplug without disrupting your work session. A USB flash drive or a USB mouse are both safe; a USB keyboard is not (because 分离ing a keyboard in the middle of a session can strand your shell). +**要求。** 一个你可以插拔而不中断工作会话的USB设备。USB闪存驱动器或USB鼠标都是安全的;USB键盘不安全(因为在会话中间分离键盘可能使你的shell搁浅)。 -**Steps.** +**步骤。** -1. Open a terminal window and run: +1. 打开一个终端窗口并运行: ``` # tail -f /var/log/messages ``` - or, if your system does not log 内核 messages to that file: + 或者,如果你的系统不将内核消息记录到该文件: ``` # dmesg -w ``` - (The `-w` flag is a FreeBSD 14 addition that streams new 内核 messages as they arrive.) + (`-w` 标志是FreeBSD 14的新增功能,流式传输新到达的内核消息。) -2. Plug in your USB 设备. Observe the messages. You should see: - - A message from the USB controller about the new 设备 appearing. - - A message from `uhub` about the port powering up. - - A message from the class 驱动程序 that matched the 设备 (e.g., `ums0` for a mouse, `umass0` for a flash drive). - - Possibly a message from the higher-level subsystem (e.g., `da0` for a mass-storage 设备). +2. 插入你的USB设备。观察消息。你应该看到: + - 来自USB控制器关于新设备出现的消息。 + - 来自 `uhub` 关于端口上电的消息。 + - 来自匹配设备的类驱动程序的消息(例如,鼠标的 `ums0`,闪存驱动器的 `umass0`)。 + - 可能还有来自更高级子系统的消息(例如,大容量存储设备的 `da0`)。 -3. Unplug the 设备. Observe the messages. You should see: - - A message from `uhub` about the port powering down. - - A 分离 message from the class 驱动程序. +3. 拔出设备。观察消息。你应该看到: + - 来自 `uhub` 关于端口下电的消息。 + - 来自类驱动程序的分离消息。 -4. Repeat several times. Watch that every 附加 is matched by a 分离. Watch that no message is missed. Watch the timing; the 附加 sequence can take tens or hundreds of milliseconds because enumeration involves several 控制传输. +4. 重复几次。注意每个附加都有匹配的分离。注意没有消息被遗漏。注意时间;附加序列可能需要几十或几百毫秒,因为枚举涉及多个控制传输。 -5. Write a tiny shell loop that records the 附加 and 分离 times: +5. 写一个小的shell循环记录附加和分离时间: ``` # dmesg -w | awk '/ums|umass/ { print systime(), $0 }' ``` - (Adjust the regex for the 设备 type you are using.) This gives you a machine-readable log of 附加 and 分离 timestamps. + (根据你使用的设备类型调整正则表达式。)这给你一个可机器读取的附加和分离时间戳日志。 -**Expected output.** Clean 附加 and 分离 every time, with no dangling state. +**预期输出。** 每次都有干净的附加和分离,没有悬空状态。 -**What to watch for.** Occasionally you will see a 设备 附加 and then immediately 分离 within a few hundred milliseconds. This usually indicates the 设备 is failing enumeration: either a bad cable, insufficient power, or a buggy 设备 firmware. If it happens consistently with one 设备, try a different USB port or a powered hub. Also watch for cases where the 内核 reports a stall during enumeration; these are rarely harmful but indicate that the enumeration needed multiple tries. +**注意事项。** 偶尔你会看到一个设备附加然后在几百毫秒内立即分离。这通常表示设备枚举失败:要么是坏电缆、供电不足,要么是有缺陷的设备固件。如果某个设备持续出现这种情况,尝试不同的USB端口或带电源的集线器。还要注意内核在枚举期间报告停顿的情况;这些通常无害,但表示枚举需要多次尝试。 -### Lab 7: Building a ucom(4) Skeleton from Scratch +### 实验7:从零构建ucom(4)骨架 -This lab is an extended one that combines the USB and serial material from the chapter. You will build a minimal `ucom(4)` 驱动程序 skeleton that presents itself as a 串行端口 but is backed by a simple USB 设备. +本实验是一个扩展实验,结合了本章的USB和串行材料。你将构建一个最小的 `ucom(4)` 驱动程序骨架,它将自己呈现为一个串行端口,但由简单的USB设备支持。 -**Goal.** Build a `ucom(4)` 驱动程序 skeleton that 附加 to a specific USB 设备, 寄存器 with the `ucom(4)` 框架, and provides empty implementations of the key 回调. The 驱动程序 will not actually talk to the hardware, but it will exercise the full `ucom(4)` registration path. +**目标。** 构建一个 `ucom(4)` 驱动程序骨架,附加到特定的USB设备,向 `ucom(4)` 框架注册,并提供关键回调的空实现。驱动程序不会真正与硬件通信,但它将测试完整的 `ucom(4)` 注册路径。 -**Requirements.** The materials from Lab 2 (the USB驱动程序 skeleton). A USB 设备 you can match against (for testing, you can use the same VOTI/OBDEV VID/PID as in Lab 2, or any spare USB 设备 whose IDs you can read). +**要求。** 实验2的材料(USB驱动程序骨架)。一个你可以匹配的USB设备(用于测试,你可以使用与实验2相同的VOTI/OBDEV VID/PID,或任何你可以读取ID的备用USB设备)。 -**Steps.** +**步骤。** -1. Start from Lab 2 as a template. Copy the directory to `lab07-ucom-skeleton`. +1. 以实验2为模板开始。将目录复制到 `lab07-ucom-skeleton`。 -2. Modify the softc to include a `struct ucom_super_softc` and a `struct ucom_softc`: +2. 修改softc以包含 `struct ucom_super_softc` 和 `struct ucom_softc`: ```c struct lab07_softc { @@ -2777,7 +2778,7 @@ This lab is an extended one that combines the USB and serial material from the c }; ``` -3. Add a `struct ucom_回调` with stub implementations: +3. 添加带有存根实现的 `struct ucom_callback`: ```c static void lab07_cfg_open(struct ucom_softc *); @@ -2809,11 +2810,11 @@ This lab is an extended one that combines the USB and serial material from the c }; ``` - `ucom_pre_param` runs on the caller's context before the configuration task is scheduled; use it to reject unsupported termios values by returning a nonzero errno. `ucom_cfg_param` runs in the 框架's task context and is where you would issue the actual USB 控制传输 to reprogram the chip. + `ucom_pre_param` 在配置任务调度之前在调用者的上下文中运行;用它通过返回非零errno来拒绝不支持的termios值。`ucom_cfg_param` 在框架的任务上下文中运行,是你发出实际USB控制传输来重新编程芯片的地方。 -4. Implement each 回调 as a no-op for now. Add `设备_printf(sc->sc_super_ucom.sc_dev, "%s\n", __func__)` to each so that you can see which 回调 are being invoked. +4. 现在将每个回调实现为空操作。向每个回调添加 `device_printf(sc->sc_super_ucom.sc_dev, "%s\n", __func__)`,这样你可以看到哪些回调正在被调用。 -5. In the 附加 method, after `usbd_transfer_setup`, call: +5. 在附加方法中,在 `usbd_transfer_setup` 之后调用: ```c error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, @@ -2823,186 +2824,186 @@ This lab is an extended one that combines the USB and serial material from the c } ``` -6. In the 分离 method, call `ucom_分离(&sc->sc_super_ucom, &sc->sc_ucom)` before `usbd_transfer_unsetup`. +6. 在分离方法中,在 `usbd_transfer_unsetup` 之前调用 `ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom)`。 -7. Add `MODULE_DEPEND(lab07, ucom, 1, 1, 1);` after the existing MODULE_DEPEND. +7. 在现有的MODULE_DEPEND之后添加 `MODULE_DEPEND(lab07, ucom, 1, 1, 1);`。 -8. Build, load, plug in the 设备, and observe. In `dmesg`, you should see the 驱动程序 附加, and you should see a `cuaU0` 设备 appear in `/dev/`. +8. 构建、加载、插入设备并观察。在 `dmesg` 中,你应该看到驱动程序附加,你应该看到 `cuaU0` 设备出现在 `/dev/` 中。 -9. Run `cu -l /dev/cuaU0 -s 9600`. The `cu` command will open the 设备, which triggers several of the ucom 回调. Watch `dmesg` to see which ones fire. Close `cu` with `~.` and observe more 回调. +9. 运行 `cu -l /dev/cuaU0 -s 9600`。`cu` 命令将打开设备,这会触发几个ucom回调。观察 `dmesg` 看哪些被触发了。用 `~.` 关闭 `cu` 并观察更多回调。 -10. Run `stty -a -f /dev/cuaU0`. Observe that the port has default termios settings. Run `stty 115200 -f /dev/cuaU0` and observe that `lab07_cfg_param` is called. +10. 运行 `stty -a -f /dev/cuaU0`。观察端口具有默认的termios设置。运行 `stty 115200 -f /dev/cuaU0` 并观察 `lab07_cfg_param` 被调用。 -11. Unplug the 设备. Observe clean 分离. +11. 拔出设备。观察干净的分离。 -**Expected output.** The 驱动程序 附加 as a `ucom` 设备, creates `/dev/cuaU0`, and responds to configuration ioctls (even though the underlying USB 设备 does not actually do anything). Every 回调 invocation is visible in `dmesg`. +**预期输出。** 驱动程序作为 `ucom` 设备附加,创建 `/dev/cuaU0`,并响应配置ioctl(即使底层USB设备实际上什么也没做)。每次回调调用在 `dmesg` 中可见。 -**What to watch for.** If the 驱动程序 附加 but `/dev/cuaU0` does not appear, check that `ucom_附加` succeeded. The return value is an errno; a nonzero value means failure. If it failed with `ENOMEM`, you are running out of memory for the TTY allocation. If it failed with `EINVAL`, one of the 回调 fields is probably null (look at `/usr/src/sys/dev/usb/serial/usb_serial.c` to see which fields are strictly required). +**注意事项。** 如果驱动程序已附加但 `/dev/cuaU0` 没有出现,检查 `ucom_attach` 是否成功。返回值是errno;非零值表示失败。如果以 `ENOMEM` 失败,你的TTY分配内存不足。如果以 `EINVAL` 失败,可能是某个回调字段为null(查看 `/usr/src/sys/dev/usb/serial/usb_serial.c` 看哪些字段是严格必需的)。 -This lab is a building 块. A real `ucom` 驱动程序 (like `uftdi`) would fill in the 回调 with actual USB transfers to the chip. Starting from an empty skeleton and adding one 回调 at a time is a good way to build a new 驱动程序. +这个实验是一个构建块。一个真正的 `ucom` 驱动程序(如 `uftdi`)会用实际的USB传输来填充回调。从空骨架开始,一次添加一个回调是构建新驱动程序的好方法。 -### Lab 8: Troubleshooting a Hung TTY Session +### 实验8:排查挂起的TTY会话 -This lab is a diagnostic exercise. Given a malfunctioning serial setup, you will use the tools from Section 5 to find the problem. +本实验是一个诊断练习。给定一个功能异常的串行设置,你将使用第5节的工具来找到问题。 -**Goal.** Find why a `cu` session does not echo characters back after connecting to an `nmdm(4)` pair that has an unconfigured 波特率 on one side. +**目标。** 找出为什么 `cu` 会话在连接到一侧波特率未配置的 `nmdm(4)` 对后不回显字符。 -**Steps.** +**步骤。** -1. Load `nmdm`: +1. 加载 `nmdm`: ``` # kldload nmdm ``` -2. Set different 波特率s on the two sides. This is contrived but mimics a real configuration bug: +2. 在两侧设置不同的波特率。这是人为的但模拟了真实的配置错误: ``` # stty 9600 -f /dev/nmdm0A # stty 115200 -f /dev/nmdm0B ``` -3. Open both sides with `cu`, each with the mismatched rate: +3. 用 `cu` 打开两侧,各自使用不匹配的速率: ``` (terminal 1) # cu -l /dev/nmdm0A -s 9600 (terminal 2) # cu -l /dev/nmdm0B -s 115200 ``` -4. Type in terminal 1. You will likely see characters appear in terminal 2, but possibly garbled. Or characters may not appear at all if the `nmdm(4)` 驱动程序 enforces rate matching strictly. +4. 在终端1中输入。你可能会看到字符出现在终端2中,但可能是乱码。或者如果 `nmdm(4)` 驱动程序严格强制速率匹配,字符可能根本不出现。 -5. Exit both `cu` sessions. +5. 退出两个 `cu` 会话。 -6. Run `stty -a -f /dev/nmdm0A` and `stty -a -f /dev/nmdm0B`. Find the discrepancy. +6. 运行 `stty -a -f /dev/nmdm0A` 和 `stty -a -f /dev/nmdm0B`。找出差异。 -7. Fix: set both sides to the same rate. Reopen `cu` and verify that the issue is resolved. +7. 修复:将两侧设置为相同的速率。重新打开 `cu` 并验证问题已解决。 -**What to watch for.** This lab teaches the diagnostic habit of checking both ends of a link. A mismatch at any one end produces problems; finding it requires looking at both. The diagnostic tools (`stty`, `comcontrol`) work from the command line and produce human-readable output. Making use of them is a simple first check before diving into deeper debugging. +**注意事项。** 本实验教授检查链路两端的诊断习惯。任一端的不匹配都会产生问题;找到它需要查看两端。诊断工具(`stty`、`comcontrol`)从命令行工作并产生人类可读的输出。在进行更深入的调试之前,使用它们是一个简单的首要检查。 -### Lab 9: Monitoring USB Transfer Statistics +### 实验9:监控USB传输统计 -This lab explores the per-channel statistics the USB 框架 maintains, which can help identify performance issues or hidden errors. +本实验探索USB框架维护的每通道统计信息,可以帮助识别性能问题或隐藏的错误。 -**Goal.** Use `usbconfig dump_stats` to observe the transfer counts on a 总线y USB 设备 and identify whether the 设备 is performing as expected. +**目标。** 使用 `usbconfig dump_stats` 观察繁忙USB设备上的传输计数,识别设备是否按预期执行。 -**Steps.** +**步骤。** -1. Plug in a USB 设备 that you can exercise meaningfully. A USB flash drive is a good choice because you can trigger 批量传输 by copying files. +1. 插入一个你可以有意义地测试的USB设备。USB闪存驱动器是一个好选择,因为你可以通过复制文件来触发批量传输。 -2. Identify the 设备: +2. 识别设备: ``` # usbconfig list ``` - Note the `ugenN.M` identifier. + 记录 `ugenN.M` 标识符。 -3. Dump the baseline statistics: +3. 转储基线统计: ``` # usbconfig -d ugenN.M dump_stats ``` - Record the output. + 记录输出。 -4. Perform significant I/O to the 设备. For a flash drive, copy a large file: +4. 对设备执行大量I/O。对于闪存驱动器,复制一个大文件: ``` # cp /usr/src/sys/dev/usb/usb_transfer.c /mnt/usb_mount/ ``` -5. Dump the statistics again. Compare. +5. 再次转储统计。比较。 -6. Note which counters changed. `xfer_completed` should have increased significantly. `xfer_err` should still be small. +6. 注意哪些计数器改变了。`xfer_completed` 应该显著增加。`xfer_err` 应该仍然很小。 -7. Try to deliberately cause errors. Unplug the 设备 mid-transfer. Then plug it back in. Dump the stats on the new `ugenN.M` (a new one is allocated on replug). +7. 尝试故意导致错误。在传输过程中拔出设备。然后再插回。转储新 `ugenN.M` 的统计(重新插入时分配新的)。 -**What to watch for.** The statistics reveal invisible behaviours. A 设备 that is mostly working but occasionally stalling will show `stall_count` nonzero. A 设备 that is dropping transfers will show `xfer_err` climbing. In normal operation, a healthy 设备 shows steady `xfer_completed` growth and zero errors. +**注意事项。** 统计揭示了不可见的行为。一个大部分时间正常工作但偶尔停顿的设备将显示 `stall_count` 非零。一个正在丢失传输的设备将显示 `xfer_err` 在攀升。在正常操作中,一个健康的设备显示稳定的 `xfer_completed` 增长和零错误。 -If you are developing a 驱动程序 and the statistics show unexpected errors, that is a clue that something is wrong. The statistics are maintained by the USB 框架, not the 驱动程序, so they reflect reality regardless of whether the 驱动程序 notices. +如果你正在开发驱动程序并且统计显示意外的错误,这是一个线索,说明有问题。统计由USB框架维护,而不是驱动程序,所以无论驱动程序是否注意到,它们都反映了实际情况。 ## 挑战练习 -Challenge exercises stretch your understanding. They are not strictly necessary for progressing to 第27章, but each one will deepen your grasp of USB and 串行驱动程序 work. Take your time. Read relevant FreeBSD source. Write small programs. Expect some challenges to take several hours. +挑战练习扩展你的理解。它们对于进入第27章不是严格必需的,但每一个都会加深你对USB和串行驱动程序工作的掌握。慢慢来。阅读相关的FreeBSD源代码。编写小程序。预期一些挑战需要几个小时。 -### Challenge 1: Add a Third USB Endpoint Type +### 挑战1:添加第三种USB端点类型 -The skeleton in Section 2 supports 批量传输. Extend it to also handle an interrupt 端点. Add a new channel to the `struct usb_config` array with `.type = UE_INTERRUPT`, `.direction = UE_DIR_IN`, and a small 缓冲区 (say, sixteen bytes). Implement the 回调 as a continuous poll, reading a small status 数据包 from the 设备 on every interrupt-IN completion. +第2节的骨架支持批量传输。扩展它以同时处理中断端点。向 `struct usb_config` 数组添加一个新通道,使用 `.type = UE_INTERRUPT`、`.direction = UE_DIR_IN` 和一个小缓冲区(比如十六个字节)。将回调实现为连续轮询,在每次中断输入完成时从设备读取一个小的状态数据包。 -Test the change by comparing the behaviour of the three channels. Bulk channels should be quiet most of the time and only submit transfers when the 驱动程序 has work to do. The interrupt channel should run continuously, quietly consuming interrupt-IN 数据包 whenever the 设备 sends them. +通过比较三个通道的行为来测试更改。批量通道大部分时间应该是安静的,只在驱动程序有工作时提交传输。中断通道应该连续运行,安静地消费设备发送的中断输入数据包。 -A stretch goal: make the interrupt 回调 deliver received bytes to the same `/dev` node as the bulk channel. When userspace reads the node, it gets a merged view of bulk-in and interrupt-in data. This is a useful pattern for 设备 that have both streaming data and asynchronous status events. +一个进阶目标:让中断回调将接收到的字节传递到与批量通道相同的 `/dev` 节点。当用户态读取该节点时,它获得批量输入和中断输入数据的合并视图。这对于既有流式数据又有异步状态事件的设备是一个有用的模式。 -### Challenge 2: Write a Minimal USB Gadget Driver +### 挑战2:编写一个最小的USB Gadget驱动程序 -The running example is a host-side 驱动程序: the FreeBSD machine is the USB host, and the 设备 is the peripheral. Turn the example around by writing a USB gadget 驱动程序 that makes the FreeBSD machine present itself as a simple 设备 to another host. +运行示例是一个主机端驱动程序:FreeBSD机器是USB主机,设备是外设。通过编写一个USB gadget驱动程序来反转示例,使FreeBSD机器将自己作为一个简单设备呈现给另一个主机。 -This requires USB-on-the-Go hardware, so the challenge is only feasible on specific boards (some ARM development boards support it). The relevant source is in `/usr/src/sys/dev/usb/template/`. Start from `usb_template_cdce.c`, which implements the CDC 以太网 class, and modify it to implement a simpler vendor-specific class with one bulk-OUT 端点 that just swallows whatever the host sends. +这需要USB-on-the-Go硬件,因此此挑战仅在特定板子上可行(一些ARM开发板支持它)。相关源代码在 `/usr/src/sys/dev/usb/template/` 中。从 `usb_template_cdce.c` 开始,它实现了CDC以太网类,修改它以实现一个更简单的厂商特定类,带有一个只吞掉主机发送内容的批量输出端点。 -This challenge teaches you how the USB 框架 looks from the other side. Many of the concepts are mirror-imaged: what was a transfer from the host's perspective is a transfer from the 设备's perspective, but the direction of the bulk arrow is reversed. +此挑战教你USB框架从另一侧看起来如何。许多概念是镜像的:从主机角度看是传输的东西从设备角度也是传输,但批量箭头的方向相反。 -### Challenge 3: A Custom `termios` Flag Handler +### 挑战3:自定义 `termios` 标志处理程序 -The `termios` structure has many flags, and the `uart(4)` 框架 handles most of them automatically. Write a small modification to a UART 驱动程序 (or to a copy of `uart_dev_ns8250.c` in a private build) that makes the 驱动程序 log a `设备_printf` message every time a specific termios flag changes value. +`termios` 结构有很多标志,`uart(4)` 框架自动处理其中大多数。对UART驱动程序(或私有构建中的 `uart_dev_ns8250.c` 副本)做一个小的修改,使驱动程序在特定termios标志改变值时记录一条 `device_printf` 消息。 -Pick, say, `CRTSCTS` (hardware 流控制) as the flag to track. Add a log message in the 驱动程序's `param` path that prints "CRTSCTS=on" or "CRTSCTS=off" whenever the flag's new value differs from its old value. +选择,比如 `CRTSCTS`(硬件流控制)作为要跟踪的标志。在驱动程序的 `param` 路径中添加一条日志消息,打印 "CRTSCTS=on" 或 "CRTSCTS=off" 每当标志的新值与旧值不同时。 -Test the modification by running: +通过运行以下命令测试修改: ```console # stty crtscts -f /dev/cuau0 # stty -crtscts -f /dev/cuau0 ``` -Verify that the log messages appear in `dmesg` and that they correspond correctly to the `stty` changes. +验证日志消息出现在 `dmesg` 中并且正确对应 `stty` 的更改。 -This challenge is about understanding exactly where in the call chain the termios change arrives at the 驱动程序. The answer (in `param`) is documented in the source, but seeing it with your own eyes is different from reading about it. +此挑战是关于准确理解termios更改在调用链中的何处到达驱动程序。答案(在 `param` 中)在源代码中有文档说明,但亲眼看到与阅读不同。 -### Challenge 4: Parsing a Small USB Protocol +### 挑战4:解析一个小型USB协议 -Pick a USB protocol you are curious about. HID is a good candidate because it is widely documented. CDC ACM is another good choice because it is simple. Pick one, read the specification on usb.org (the public parts), and write a small protocol parser in C that takes a 缓冲区 of bytes and prints what they mean. +选择一个你感兴趣的USB协议。HID是一个好选择,因为它有广泛的文档。CDC ACM是另一个好选择,因为它很简单。选择一个,阅读usb.org上的规范(公开部分),写一个小的C协议解析器,接受一个字节缓冲区并打印它们的含义。 -For HID, the parser would consume reports: input reports, output reports, feature reports. It would look up the 设备's report 描述符 to learn the layout. It would print, for each report, the usage (mouse motion, button press, keyboard scan code) and the value. +对于HID,解析器将消费报告:输入报告、输出报告、特性报告。它将查找设备的报告描述符以了解布局。它将为每个报告打印用途(鼠标移动、按钮按下、键盘扫描码)和值。 -For CDC ACM, the parser would consume the AT command set: a small set of commands that terminal programs use to configure modems. It would recognise the commands and report which ones the 驱动程序 would handle and which would be passed through to the 设备. +对于CDC ACM,解析器将消费AT命令集:终端程序用来配置调制解调器的一小组命令。它将识别命令并报告哪些将由驱动程序处理,哪些将传递给设备。 -This is not a 驱动程序-writing challenge per se; it is a protocol-understanding challenge. Device 驱动程序 implement protocols, and being comfortable with protocol specifications is a core skill. +这不是一个驱动程序编写挑战本身;它是一个协议理解挑战。设备驱动程序实现协议,熟悉协议规范是一项核心技能。 -### Challenge 5: Ro总线tness Under Load +### 挑战5:负载下的健壮性 -Take the echo-loop 驱动程序 from Lab 3 (or a similar 驱动程序 you have written) and stress-test it. Write a userland program that runs two threads: one constantly writes random bytes to the 设备, one constantly reads and verifies. +使用实验3的echo-loop驱动程序(或你编写的类似驱动程序)进行压力测试。编写一个运行两个线程的用户态程序:一个不断向设备写入随机字节,一个不断读取并验证。 -Run the program for an hour. Then run it for a day. Then unplug and replug the 设备 during the run and see whether the program recovers cleanly. +运行程序一小时。然后运行一天。然后在运行过程中拔出并重新插入设备,看程序是否能干净地恢复。 -You will probably find bugs. Common ones include: write 回调 locking issues under concurrent access, races between close() and in-flight transfers, memory leaks from 缓冲区 that are allocated but never freed on specific error paths, and state machine bugs when a stall arrives at an unexpected moment. +你可能会发现错误。常见的包括:并发访问下的写回调锁定问题、close()和传输中传输之间的竞态、在特定错误路径上分配但从未释放的缓冲区导致的内存泄漏,以及停顿在意料之外时刻到达时的状态机错误。 -Each bug you find will teach you something about where the 驱动程序's contract with its callers is subtle. Fix the bugs. Log what you learned. This is exactly the kind of work that separates a good 驱动程序 from a merely working one. +你发现的每个错误都会教你一些关于驱动程序与调用者之间的约定在哪里微妙的东西。修复错误。记录你学到了什么。这正是一个好的驱动程序与一个仅仅能工作的驱动程序之间的区别。 -### Challenge 6: Implement Suspend/Resume Properly +### 挑战6:正确实现挂起/恢复 -Most USB驱动程序 do not implement suspend and resume handlers. The 框架 has defaults that work for the common case, but a 驱动程序 that holds long-term state (a queue of pending commands, a streaming context, a negotiated session) may need to save and restore that state around suspend cycles. +大多数USB驱动程序不实现挂起和恢复处理程序。框架有适用于常见情况的默认值,但持有长期状态(待处理命令队列、流式上下文、已协商会话)的驱动程序可能需要在挂起周期周围保存和恢复该状态。 -Extend the echo-loop 驱动程序 with `设备_suspend` and `设备_resume` methods. In suspend, flush any pending transfers and save a small 挂载 of state. In resume, restore the state and resubmit any pending work. +用 `device_suspend` 和 `device_resume` 方法扩展echo-loop驱动程序。在挂起时,冲刷所有待处理的传输并保存少量状态。在恢复时,恢复状态并重新提交任何待处理的工作。 -Test by running the system through a suspend cycle (on a laptop that supports it) while the 驱动程序 is running. Verify that after resume, the 驱动程序 continues working correctly and no state was lost. +通过在驱动程序运行时让系统经过一个挂起周期来测试(在支持它的笔记本电脑上)。验证恢复后驱动程序继续正确工作且没有状态丢失。 -This challenge teaches the subtleties of suspend/resume, including that hardware may be in a different state after resume than it was before suspend, and that all in-flight state must be reconstructed or abandoned. +此挑战教授挂起/恢复的微妙之处,包括硬件在恢复后可能处于与挂起前不同的状态,以及所有传输中的状态必须被重建或放弃。 -### Challenge 7: Adding `poll(2)` Support +### 挑战7:添加 `poll(2)` 支持 -Most 驱动程序 shown in this chapter support `read(2)` and `write(2)` but not `poll(2)` or `select(2)`. These system calls let userland programs wait for I/O readiness on multiple 描述符 at once, which is essential for servers and interactive programs. +本章展示的大多数驱动程序支持 `read(2)` 和 `write(2)` 但不支持 `poll(2)` 或 `select(2)`。这些系统调用让用户态程序可以一次在多个描述符上等待I/O就绪,这对于服务器和交互式程序是必不可少的。 -Add a `d_poll` method to the echo 驱动程序's `cdevsw`. The method should return a bitmask indicating which I/O events are currently possible: POLLIN if there is data to read, POLLOUT if there is space to write. +向echo驱动程序的 `cdevsw` 添加 `d_poll` 方法。该方法应返回一个位掩码指示当前可能的I/O事件:如果有数据可读则为POLLIN,如果有空间可写则为POLLOUT。 -The hardest part of adding poll support is the wakeup logic. When a 传输回调 adds data to the RX queue, it must call `selwakeup` on the selinfo structure the poll mechanism uses. Similarly, when the write 回调 drains bytes from the TX queue and makes space, it must call `selwakeup` on the write selinfo. +添加poll支持最难的部分是唤醒逻辑。当传输回调将数据添加到RX队列时,它必须在poll机制使用的selinfo结构上调用 `selwakeup`。类似地,当写回调从TX队列排空字节并腾出空间时,它必须在写selinfo上调用 `selwakeup`。 -This challenge will require reading `/usr/src/sys/kern/sys_generic.c` and `/usr/src/sys/sys/selinfo.h` to understand the selinfo mechanism. +此挑战需要阅读 `/usr/src/sys/kern/sys_generic.c` 和 `/usr/src/sys/sys/selinfo.h` 来理解selinfo机制。 -### Challenge 8: Writing a Character-Counter ioctl +### 挑战8:编写字符计数ioctl -Add an ioctl to the echo 驱动程序 that returns the current TX and RX byte counters. The ioctl 接口 requires you to: +向echo驱动程序添加一个ioctl,返回当前的TX和RX字节计数器。ioctl接口要求你: -1. Define a magic number and struct for the ioctl in a header: +1. 在头文件中为ioctl定义一个魔术数字和结构: ```c struct myfirst_usb_stats { uint64_t tx_bytes; @@ -3011,373 +3012,372 @@ Add an ioctl to the echo 驱动程序 that returns the current TX and RX byte co #define MYFIRST_USB_GET_STATS _IOR('U', 1, struct myfirst_usb_stats) ``` -2. Implement a `d_ioctl` method that responds to `MYFIRST_USB_GET_STATS` by copying the counters out to userland. +2. 实现一个 `d_ioctl` 方法,通过将计数器复制到用户态来响应 `MYFIRST_USB_GET_STATS`。 -3. Maintain the counters in the softc, incrementing them in the 传输回调. +3. 在softc中维护计数器,在传输回调中递增它们。 -4. Write a userland program that issues the ioctl and prints the results. +4. 编写一个用户态程序发出ioctl并打印结果。 -This challenge teaches the ioctl 接口, which is the standard way 驱动程序 expose non-streaming operations to userland. It also introduces you to the `_IOR`, `_IOW`, and `_IOWR` macros from ``. +此挑战教授ioctl接口,这是驱动程序向用户态暴露非流式操作的标准方式。它还向你介绍了 `` 中的 `_IOR`、`_IOW` 和 `_IOWR` 宏。 ## 故障排除指南 -Despite your best efforts, problems will occur. This section documents the most common classes of problem you will hit while working on USB and 串行驱动程序, with concrete steps to diagnose each. +尽管你尽了最大努力,问题仍会发生。本节记录了你在USB和串行驱动程序工作中会遇到的最常见问题类别,以及诊断每个问题的具体步骤。 -### The Module Will Not Load +### 模块无法加载 -Symptom: `kldload myfirst_usb.ko` returns an error, typically with a message about unresolved symbols. +症状:`kldload myfirst_usb.ko` 返回错误,通常带有关于未解析符号的消息。 -Causes and fixes: -- Missing `MODULE_DEPEND` entry. Add `MODULE_DEPEND(myfirst_usb, usb, 1, 1, 1);` to the 驱动程序. -- Missing `MODULE_DEPEND` on a second module, such as `ucom`. If your 驱动程序 uses `ucom_附加`, add a dependency on `ucom`. -- Compiled against a 内核 that does not match the running 内核. Rebuild the module against the currently-running sources. -- Kernel symbol table out of date. After 内核 upgrade, run `kldxref /boot/内核` to refresh. +原因和修复: +- 缺少 `MODULE_DEPEND` 条目。向驱动程序添加 `MODULE_DEPEND(myfirst_usb, usb, 1, 1, 1);`。 +- 缺少对第二个模块(如 `ucom`)的 `MODULE_DEPEND`。如果你的驱动程序使用 `ucom_attach`,添加对 `ucom` 的依赖。 +- 针对不匹配运行内核的内核编译。使用当前运行的源代码重新构建模块。 +- 内核符号表过期。内核升级后,运行 `kldxref /boot/kernel` 刷新。 -If the error message mentions a specific symbol you did not write (like `ttycreate` or `cdevsw_open`), look up the missing symbol in the source tree to find out which subsystem it lives in, and add a `MODULE_DEPEND` on that module. +如果错误消息提到一个你没有编写的特定符号(如 `ttycreate` 或 `cdevsw_open`),在源代码树中查找缺失的符号以找出它属于哪个子系统,并添加对该模块的 `MODULE_DEPEND`。 -### The Driver Loads but Never Attaches +### 驱动程序加载但从不附加 -Symptom: `kldstat` shows the 驱动程序 loaded, but `dmesg` shows no 附加 message when the 设备 is plugged in. +症状:`kldstat` 显示驱动程序已加载,但设备插入时 `dmesg` 没有显示附加消息。 -Causes and fixes: -- Match table does not match the 设备. Compare the vendor and 产品IDs from `usbconfig list` against your `STRUCT_USB_HOST_ID` entries. -- Interface number mismatch. If the 设备 has multiple 接口 and your 探测 guards against `bIfaceIndex != 0`, try a different 接口. -- Probe returns `ENXIO` for some other reason. Add `设备_printf(dev, "探测 with class=%x subclass=%x\n", uaa->info.bInterfaceClass, uaa->info.bInterfaceSubClass);` at the top of `探测` temporarily to see what the 框架 is offering. -- Another 驱动程序 is claiming the 设备 first. Check `dmesg` for other 驱动程序 附加ments; you may need to explicitly unload the competing 驱动程序 with `kldunload` before yours can bind. Alternatively, give your 驱动程序 a higher priority through 总线-探测 return values (applies to PCI-like 总线es, not USB). +原因和修复: +- 匹配表不匹配设备。将 `usbconfig list` 中的vendor和产品ID与你的 `STRUCT_USB_HOST_ID` 条目进行比较。 +- 接口号不匹配。如果设备有多个接口且你的探测防范 `bIfaceIndex != 0`,尝试不同的接口。 +- 探测因其他原因返回 `ENXIO`。在 `probe` 顶部临时添加 `device_printf(dev, "probe with class=%x subclass=%x\n", uaa->info.bInterfaceClass, uaa->info.bInterfaceSubClass);` 来查看框架提供了什么。 +- 另一个驱动程序先声明了设备。检查 `dmesg` 中其他驱动程序的附加;你可能需要用 `kldunload` 显式卸载竞争的驱动程序,你的才能绑定。或者,通过总线探测返回值给你的驱动程序更高的优先级(适用于类似PCI的总线,不适用于USB)。 -### The Driver Attaches but `/dev` Node Does Not Appear +### 驱动程序附加但 `/dev` 节点不出现 -Symptom: 附加 message in `dmesg`, but `ls /dev/` shows no corresponding entry. +症状:`dmesg` 中有附加消息,但 `ls /dev/` 没有显示相应的条目。 -Causes and fixes: -- `make_dev` call failed. Check the return value; if null, handle the error and log it. -- Wrong cdevsw. Make sure `myfirst_usb_cdevsw` is declared correctly with `d_version = D_VERSION` and valid `d_name`, `d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl` where relevant. -- `si_drv1` not set. Although not strictly required for the node to appear, many bugs manifest as "the node appears but ioctls see a NULL softc" because `si_drv1` was not initialised. -- Permissions issue. The default 0644 permissions may restrict access; try 0666 temporarily during development. +原因和修复: +- `make_dev` 调用失败。检查返回值;如果为null,处理错误并记录。 +- 错误的cdevsw。确保 `myfirst_usb_cdevsw` 正确声明了 `d_version = D_VERSION` 和有效的 `d_name`、`d_open`、`d_close`、`d_read`、`d_write`、`d_ioctl`。 +- `si_drv1` 未设置。虽然严格来说不是节点出现所必需的,但许多错误表现为 "the node appears but ioctls see a NULL softc" 因为 `si_drv1` 未初始化。 +- 权限问题。默认的0644权限可能限制访问;在开发期间尝试0666。 -### The Driver Panics on Detach +### 驱动程序在分离时崩溃 -Symptom: unplugging the 设备 (or unloading the module) causes a 内核 panic. +症状:拔出设备(或卸载模块)导致内核崩溃。 -Causes and fixes: -- Transfer 回调 running during 分离. You must call `usbd_transfer_unsetup` before destroying the 互斥锁. The 框架's cancellation and wait logic is what makes 分离 safe. -- `/dev` node open when 驱动程序 unloads. If userspace has the node open, the module cannot unload. Run `fstat | grep myfirst_usb` to see which process holds it, and kill the process or close the file. -- Memory freed before all uses complete. If you use deferred work (taskqueue, callout), you must cancel and wait for it before freeing the softc. The `taskqueue_drain` and `callout_drain` functions exist for this. -- Softc use-after-free. If you have code outside the 驱动程序 that holds a pointer to the softc, the softc can be freed while that pointer is still dangling. Redesign to avoid external softc pointers, or add reference counting. +原因和修复: +- 分离期间传输回调仍在运行。你必须在销毁互斥锁之前调用 `usbd_transfer_unsetup`。框架的取消和等待逻辑使分离安全。 +- 驱动程序卸载时 `/dev` 节点仍打开。如果用户态持有节点打开,模块无法卸载。运行 `fstat | grep myfirst_usb` 查看哪个进程持有它,杀死进程或关闭文件。 +- 内存在所有使用完成之前被释放。如果你使用延迟工作(taskqueue、callout),你必须在释放softc之前取消并等待它。`taskqueue_drain` 和 `callout_drain` 函数就是为此而存在的。 +- Softc释放后使用。如果你有驱动程序外部的代码持有指向softc的指针,softc可能在指针仍然悬空时被释放。重新设计以避免外部softc指针,或添加引用计数。 -### Transfers Stall +### 传输停顿 -Symptom: 批量传输 appear to succeed at the submit call but never complete, or they complete with `USB_ERR_STALLED`. +症状:批量传输在提交调用时似乎成功但从未完成,或以 `USB_ERR_STALLED` 完成。 -Causes and fixes: -- Wrong 端点 direction. Verify the direction in your `struct usb_config` against the 端点's `bEndpointAddress` high bit. -- Wrong 端点 type. Verify that the `type` field matches the 端点's `bmAttributes` low bits. -- Transfer too large. If you set a 帧 length larger than the 端点's `wMaxPacketSize`, the 框架 will usually slice it into 数据包, but some 设备 reject a transfer that exceeds an internal 缓冲区. -- Device firmware stall. The remote 设备 is signalling "not ready." The 框架's automatic clear-stall should recover, but a persistent stall usually indicates a protocol error (wrong command, wrong sequence, missing authentication). +原因和修复: +- 端点方向错误。根据端点的 `bEndpointAddress` 高位验证 `struct usb_config` 中的方向。 +- 端点类型错误。验证 `type` 字段匹配端点的 `bmAttributes` 低位。 +- 传输太大。如果你设置的帧长度大于端点的 `wMaxPacketSize`,框架通常会将其切分为数据包,但一些设备拒绝超过内部缓冲区的传输。 +- 设备固件停顿。远端设备正在发出信号 "not ready." 框架的自动清除停顿应该能恢复,但持续的停顿通常表示协议错误(错误的命令、错误的序列、缺少认证)。 -### Serial Characters Garbled +### 串行字符乱码 -Symptom: bytes appear on the wire but are wrong or contain extra characters. +症状:线路上出现字节但内容错误或包含额外字符。 -Causes and fixes: -- Baud rate mismatch. Every stage must agree. Use `stty` to check all stages. -- Byte format mismatch. Set databits, 奇偶校验, and stopbits to match. `stty cs8 -parenb -cstopb` is the most common configuration. -- Incorrect `termios` flag handling in the 驱动程序. If you modify `uart_dev_ns8250.c` and break `param`, the chip will be programmed wrong. Compare against the upstream file. -- Flow-control mismatch. If one side has `CRTSCTS` enabled and the other does not, bytes will be lost under load. Set both sides consistently. -- Cable issue. A bad cable or a cable with unusual pinouts (some RJ45-to-DB9 cables have nonstandard pinouts) can introduce bit errors. Swap cables to rule this out. +原因和修复: +- 波特率不匹配。每个阶段都必须一致。使用 `stty` 检查所有阶段。 +- 字节格式不匹配。设置数据位、奇偶校验和停止位以匹配。`stty cs8 -parenb -cstopb` 是最常见的配置。 +- 驱动程序中 `termios` 标志处理不正确。如果你修改了 `uart_dev_ns8250.c` 并破坏了 `param`,芯片将被错误编程。与上游文件进行比较。 +- 流控制不匹配。如果一端启用了 `CRTSCTS` 而另一端没有,负载下会丢失字节。一致地设置两侧。 +- 电缆问题。坏电缆或具有不寻常引脚排列的电缆(一些RJ45转DB9电缆具有非标准引脚排列)可能引入位错误。更换电缆来排除此问题。 -### A Process is Stuck in `read(2)` and Will Not Exit +### 进程卡在 `read(2)` 中无法退出 -Symptom: a program 块ed on the 驱动程序's `read()` path will not respond to Ctrl+C or `kill`. +症状:一个阻塞在驱动程序 `read()` 路径上的程序不响应Ctrl+C或 `kill`。 -Causes and fixes: -- Driver `d_read` sleeps without checking for signals. Use `msleep(..., PCATCH, ...)` (with the `PCATCH` flag) so the sleep returns `EINTR` when a signal arrives, and propagate the errno back to userspace. -- Driver `d_read` holds a non-interruptible lock. Verify that the sleep is on an interruptible condition variable and that the 互斥锁 is dropped during the sleep. -- Transfer 回调 is never arming the channel. If your `d_read` waits on a flag that only the read 回调 sets, and the read 回调 is never fired, the wait will never complete. Make sure the channel is started on `d_open` or at 附加 time. +原因和修复: +- 驱动程序 `d_read` 在未检查信号的情况下睡眠。使用 `msleep(..., PCATCH, ...)`(带 `PCATCH` 标志),这样当信号到达时睡眠返回 `EINTR`,并将errno传播回用户态。 +- 驱动程序 `d_read` 持有不可中断的锁。验证睡眠是在可中断的条件变量上,且互斥锁在睡眠期间被释放。 +- 传输回调从未重新准备通道。如果你的 `d_read` 等待一个只有读回调设置的标志,而读回调从未被触发,等待将永远不会完成。确保通道在 `d_open` 或附加时启动。 -### High CPU Usage When Idle +### 空闲时CPU使用率高 -Symptom: the 驱动程序 consumes significant CPU even when no data is flowing. +症状:即使没有数据流动,驱动程序也消耗大量CPU。 -Causes and fixes: -- Polling-based implementation. If your 驱动程序 polls a flag in a 总线y loop, rewrite it to sleep on an event. -- Callback firing excessively. The 框架 should not fire a 回调 without a state change, but some misconfigured channels can enter a "retry on error" loop that fires the 回调 as fast as the hardware can respond. Add a retry counter or a rate-limiter. -- Read 回调 with no work but always rearming. If the 设备 sends zero-byte transfers to signal "I have nothing to say," make sure your 回调 handles these gracefully without treating them as normal data. +原因和修复: +- 基于轮询的实现。如果你的驱动程序在忙循环中轮询标志,重写为在事件上睡眠。 +- 回调过度触发。框架不应在没有状态变化时触发回调,但一些配置错误的通道可能进入一个 "retry on error" 循环,以硬件能响应的最快速度触发回调。添加重试计数器或速率限制器。 +- 读回调没有工作但总是重新准备。如果设备发送零字节传输来表示 "I have nothing to say," 确保你的回调优雅地处理这些而不将其视为正常数据。 -### `usbconfig` Shows the Device but `dmesg` Is Silent +### `usbconfig` 显示设备但 `dmesg` 没有输出 -Symptom: `usbconfig list` shows the 设备, but no 驱动程序 附加 message appears. +症状:`usbconfig list` 显示设备,但没有驱动程序附加消息出现。 -Causes and fixes: -- Device 附加ed to `ugen` (the generic 驱动程序) because no specific 驱动程序 matched. This is the normal behaviour when there is no matching 驱动程序. Check the 匹配表s of the available 驱动程序. `pciconf -lv` will not help here because this is USB, not PCI; the USB equivalent is `usbconfig -d ugenN.M dump_设备_desc`. -- `devd` is disabled and auto-load is not happening. Enable `devd` by running `service devd onestart`, then plug the 设备 in again. -- Module file is not in a loadable path. `kldload` can take a full path (`kldload /path/to/module.ko`), but for automatic loading by `devd`, the module has to be in a directory `devd` is configured to search. `/boot/modules/` is the conventional location for out-of-tree modules on a production system. +原因和修复: +- 设备附加到 `ugen`(通用驱动程序),因为没有特定的驱动程序匹配。当没有匹配的驱动程序时,这是正常行为。检查可用驱动程序的匹配表。`pciconf -lv` 在这里没有帮助,因为这是USB,不是PCI;USB等价物是 `usbconfig -d ugenN.M dump_device_desc`。 +- `devd` 被禁用,自动加载没有发生。通过运行 `service devd onestart` 启用 `devd`,然后再次插入设备。 +- 模块文件不在可加载路径中。`kldload` 可以接受完整路径(`kldload /path/to/module.ko`),但对于 `devd` 的自动加载,模块必须在 `devd` 配置搜索的目录中。`/boot/modules/` 是生产系统上树外模块的常规位置。 -### Debugging a Deadlock with `WITNESS` +### 使用 `WITNESS` 调试死锁 -Symptom: the 内核 hangs with the CPU stuck in a specific function, and `WITNESS` is enabled. +症状:内核挂起,CPU卡在特定函数中,且启用了 `WITNESS`。 -Causes and fixes: -- Lock order violation. `WITNESS` will log the violation on the serial console. Read the log: it will tell you which locks were taken in which order, and where the reverse order was observed. Fix by establishing a consistent lock acquisition order throughout your 驱动程序. -- Lock held across a sleep. If you hold a 互斥锁 and then call a function that sleeps, you can deadlock with any other thread that wants the 互斥锁. Identify the sleeping function (often hidden in an allocation or in a USB transfer wait), and restructure to release the 互斥锁 before the sleep. +原因和修复: +- 锁顺序违规。`WITNESS` 将在串行控制台上记录违规。阅读日志:它会告诉你哪些锁以什么顺序获取,以及在哪里观察到相反的顺序。通过在整个驱动程序中建立一致的锁获取顺序来修复。 +- 持有锁时睡眠。如果你持有互斥锁然后调用一个会睡眠的函数,你可能与任何想要该互斥锁的其他线程死锁。识别睡眠函数(通常隐藏在分配或USB传输等待中),并重构以在睡眠之前释放互斥锁。 - Lock taken in interrupt context that was first taken outside interrupt context without `MTX_SPIN`. FreeBSD 互斥锁es have two forms: default (`MTX_DEF`) can sleep, spin (`MTX_SPIN`) cannot. Taking a sleep 互斥锁 from an 中断处理程序 is a bug. -Enabling `WITNESS` during development (by building the 内核 with `options WITNESS` or by using `GENERIC-NODEBUG`'s `INVARIANTS`-enabled counterpart) catches many of these problems before they appear on a user's machine. +在开发期间启用 `WITNESS`(通过用 `options WITNESS` 构建内核或使用 `GENERIC-NODEBUG` 的 `INVARIANTS` 启用版本)可以在这些问题出现在用户机器上之前捕获它们。 -### A Driver That Appears Twice for the Same Device +### 同一设备出现两次的驱动程序 -Symptom: `dmesg` shows your 驱动程序 附加ing twice for a single 设备, creating `myfirst_usb0` and `myfirst_usb1` with the same USB IDs. +症状:`dmesg` 显示你的驱动程序为单个设备附加两次,创建具有相同USB ID的 `myfirst_usb0` 和 `myfirst_usb1`。 -Causes and fixes: -- The 设备 has two 接口 and the 驱动程序 is matching both. Check `bIfaceIndex` in the 探测 method and match only the 接口 you actually support. -- The 设备 has multiple configurations and both are active. This is rare; if so, select the correct configuration explicitly in the 附加 method. -- Another 驱动程序 is 附加ed to one of the 接口. This is not a bug; it just means the 设备 is multi-接口 and different 驱动程序 claim different 接口. If you see `myfirst_usb0` and `ukbd0` for the same 设备, the 设备 has both a vendor-specific 接口 and a HID 接口, and the two 驱动程序 附加 independently. +原因和修复: +- 设备有两个接口,驱动程序匹配了两者。检查探测方法中的 `bIfaceIndex`,只匹配你实际支持的接口。 +- 设备有多个配置且两者都处于活动状态。这很罕见;如果是这样,在附加方法中显式选择正确的配置。 +- 另一个驱动程序附加到了其中一个接口。这不是错误;这只是意味着设备是多接口的,不同的驱动程序声明不同的接口。如果你看到同一设备的 `myfirst_usb0` 和 `ukbd0`,设备既有厂商特定接口又有HID接口,两个驱动程序独立附加。 -### USB Serial Baud Rate Does Not Take Effect +### USB串行波特率不生效 -Symptom: You `stty 115200 -f /dev/cuaU0`, but data exchange happens at a different rate. +症状:你执行 `stty 115200 -f /dev/cuaU0`,但数据交换以不同的速率进行。 -Causes and fixes: -- The 控制传输 to program the 波特率 failed. Check `dmesg` for error messages from `ucom_cfg_param`. Instrument the 驱动程序 to log the result of the 控制传输. -- The chip's divisor encoding is wrong. Different FTDI variants use slightly different divisor formulas; check the variant detection in the 驱动程序. -- The peer is running at a different rate. As noted earlier in the chapter, both ends must agree. -- The cable or adapter is introducing its own rate limitation. Some USB-to-serial adapters silently renegotiate; this is rare but can happen with poor-quality cables. +原因和修复: +- 编程波特率的控制传输失败。检查 `dmesg` 中 `ucom_cfg_param` 的错误消息。为驱动程序添加日志以记录控制传输的结果。 +- 芯片的分频器编码错误。不同的FTDI变体使用略有不同的分频公式;检查驱动程序中的变体检测。 +- 对端以不同的速率运行。如本章前面所述,两端必须一致。 +- 电缆或适配器引入了自己的速率限制。一些USB转串口适配器静默重新协商;这很罕见但可能发生在劣质电缆上。 -### A Kernel Panic with "Spin lock held too long" +### 内核崩溃:"Spin lock held too long" -Symptom: The 内核 panics with this message, usually during high I/O on the 驱动程序. +症状:内核以此消息崩溃,通常在驱动程序高I/O期间。 -Causes and fixes: -- A UART 驱动程序's `uart_ops` method is sleeping or 块ing. The six methods in `uart_ops` run with spin locks held (on some paths) and must not sleep, call non-spin-safe functions, or do long loops. Review the offending method for any expensive calls. -- The 中断处理程序 is not draining the interrupt source fast enough. If the handler takes longer than the interrupt rate, interrupts accumulate. Speed up the handler. -- Lock contention is causing priority inversion. Reduce the scope of the critical section, or break it up. +原因和修复: +- UART驱动程序的 `uart_ops` 方法正在睡眠或阻塞。`uart_ops` 中的六个方法在持有自旋锁的情况下运行(在某些路径上),不能睡眠、调用非自旋安全函数或进行长循环。检查有问题的方法中是否有任何昂贵的调用。 +- 中断处理程序没有足够快地排空中断源。如果处理程序花费的时间超过中断速率,中断会累积。加快处理程序。 +- 锁竞争导致优先级反转。减少临界区的范围,或将其分解。 -### A Device Never Completes Enumeration +### 设备从未完成枚举 -Symptom: Plugging in a 设备 produces a `dmesg` line or two about enumeration starting, but never a completion message. +症状:插入设备产生一两行关于枚举开始的 `dmesg` 消息,但从未有完成消息。 -Causes and fixes: -- The 设备 is violating the USB specification. Some cheap or counterfeit 设备 have buggy firmware. If possible, try a different 设备. -- Insufficient power. Devices that claim more power than the port can supply will fail to enumerate. Try a powered hub. -- Electromagnetic interference. A bad cable or a bad port can cause bit errors during enumeration. Try different cables or ports. -- The USB 主机控制器 is in a confused state. Try unloading and reloading the 主机控制器 驱动程序, or (as a last resort) rebooting. +原因和修复: +- 设备违反USB规范。一些廉价或伪造的设备有缺陷的固件。如果可能,尝试不同的设备。 +- 供电不足。声称需要比端口能提供更多功率的设备将无法枚举。尝试带电源的集线器。 +- 电磁干扰。坏电缆或坏端口可能在枚举期间导致位错误。尝试不同的电缆或端口。 +- USB主机控制器处于混乱状态。尝试卸载和重新加载主机控制器驱动程序,或(作为最后手段)重启。 -### Diagnostic Checklist When You Are Stuck +### 卡住时的诊断检查清单 -When a 驱动程序 under development is not behaving correctly and you do not know why, walk through this checklist in order. Each step eliminates a large class of possible problems. +当开发中的驱动程序行为不正确且你不知道原因时,按顺序走一遍这个检查清单。每一步消除了大量可能的问题。 -1. Compile cleanly with `-Wall -Werror`. Many subtle bugs produce warnings. -2. Load in a 内核 built with `INVARIANTS` and `WITNESS`. Any locking or invariant violations will be caught immediately. -3. Enable your 驱动程序's debug logging. Run a minimal reproduction scenario and capture the logs. -4. Compare the 驱动程序's behaviour against a known-working 驱动程序 for similar hardware. Diffing behaviour reveals bugs that staring at your own code does not. -5. Simplify the scenario. Write a minimal userland test program. Use a minimal USB 设备 (or an `nmdm` pair for serial). Remove every variable you can. -6. Use `dtrace` on the USB 框架 functions. `usbd_transfer_submit:entry` and `usbd_transfer_submit:return` 探测 let you trace exactly which transfers were submitted and what happened to them. -7. Run the 驱动程序 with `WITNESS_CHECKORDER` enabled. Each time a 互斥锁 is taken, the order is verified against the accumulated history. -8. If the issue is intermittent, run under a stress-test harness that generates load for hours. Intermittent bugs become reproducible under sustained load. +1. 使用 `-Wall -Werror` 干净编译。许多微妙的错误会产生警告。 +2. 在用 `INVARIANTS` 和 `WITNESS` 构建的内核中加载。任何锁定或不变量违规将被立即捕获。 +3. 启用驱动程序的调试日志。运行最小复现场景并捕获日志。 +4. 将驱动程序的行为与已知工作的类似硬件的驱动程序进行比较。差异比较能揭示盯着自己代码看不到的错误。 +5. 简化场景。编写一个最小的用户态测试程序。使用最小的USB设备(或用于串行的 `nmdm` 对)。移除你能移除的每个变量。 +6. 在USB框架函数上使用 `dtrace`。`usbd_transfer_submit:entry` 和 `usbd_transfer_submit:return` 探测让你精确跟踪哪些传输被提交以及它们发生了什么。 +7. 在启用 `WITNESS_CHECKORDER` 的情况下运行驱动程序。每次获取互斥锁时,顺序都会与累积的历史进行验证。 +8. 如果问题是间歇性的,在产生负载数小时的压力测试工具下运行。间歇性错误在持续负载下变得可复现。 -This checklist is not exhaustive, but it covers the techniques that find the majority of 驱动程序 bugs. +这个检查清单不是详尽无遗的,但它涵盖了找到大多数驱动程序错误的技术。 -## Reading the FreeBSD USB Source Tree: A Guided Tour +## 阅读FreeBSD USB源代码树:导览 -The `myfirst_usb` skeleton and the FTDI walkthrough have given you the shape of a USB驱动程序. But the real learning happens when you read existing 驱动程序 in the tree. Each one is a small lesson in how to apply the 框架 to a specific class of 设备. This section gives you a guided tour of five 驱动程序, ordered from simplest to most representative, and points out what each one teaches. +`myfirst_usb` 骨架和FTDI演练已经给了你USB驱动程序的形状。但真正的学习发生在你阅读树中现有驱动程序时。每一个都是如何将框架应用于特定类别设备的小课程。本节给你五个驱动程序的导览,从最简单到最具代表性的顺序排列,并指出每个驱动程序教授了什么。 -The pattern we recommend is this. Open each 驱动程序's source file next to this section. Read the opening comment 块 and the structure definitions first; those tell you what the 驱动程序 is for and what state it maintains. Then trace the lifecycle: 匹配表, 探测, 附加, 分离, registration. Only after the lifecycle is clear should you move on to the data path. This ordering mirrors how the 框架 itself treats the 驱动程序: first as a match candidate, then as an 附加ed 驱动程序, and only then as something that moves data. +我们推荐的模式是这样的。在此节旁边打开每个驱动程序的源文件。首先阅读开头的注释块和结构定义;它们告诉你驱动程序是做什么的以及它维护什么状态。然后追踪生命周期:匹配表、探测、附加、分离、注册。只有在生命周期清楚之后才应该进入数据路径。这种排序反映了框架本身如何对待驱动程序:首先作为匹配候选,然后作为已附加的驱动程序,最后才作为移动数据的东西。 -### Tour 1: uled.c, the Simplest USB Driver +### 导览1:uled.c,最简单的USB驱动程序 File: `/usr/src/sys/dev/usb/misc/uled.c`. -Start here. `uled.c` is the Dream Cheeky USB LED 驱动程序. It is under 400 lines. It implements a single output (setting the LED colour) through a single 控制传输. There is no input, no 批量传输, no 中断传输, no concurrent I/O. Everything about it is minimal, and for that reason everything about it is easy to read. +从这里开始。`uled.c` 是Dream Cheeky USB LED驱动程序。它不到400行。它通过单个控制传输实现单个输出(设置LED颜色)。没有输入、没有批量传输、没有中断传输、没有并发I/O。它的一切都是最小的,因此一切都很易读。 -Key things to study in `uled.c`: +在 `uled.c` 中要学习的关键内容: -The 匹配表 has a single entry: `{USB_VPI(USB_VENDOR_DREAM_CHEEKY, USB_PRODUCT_DREAM_CHEEKY_WEBMAIL_NOTIFIER_2, 0)}`. This is the minimal match-by-VID/PID idiom. No subclass or protocol filtering; just vendor and product. +匹配表只有一个条目:`{USB_VPI(USB_VENDOR_DREAM_CHEEKY, USB_PRODUCT_DREAM_CHEEKY_WEBMAIL_NOTIFIER_2, 0)}`。这是最小化的按VID/PID匹配惯用法。没有子类或协议过滤;只有厂商和产品。 -The softc is tiny. It contains a 互斥锁, the `usb_设备` pointer, the `usb_xfer` array, and the LED state. This is the minimum every USB驱动程序 needs. +softc很小。它包含一个互斥锁、`usb_device` 指针、`usb_xfer` 数组和LED状态。这是每个USB驱动程序需要的最小值。 -The 探测 method is two lines: check that the 设备 is in host mode and return the result of `usbd_lookup_id_by_uaa` against the 匹配表. No 接口-index check, no complex matching. For a simple 设备 with a single function, this is enough. +探测方法是两行:检查设备是否处于主机模式,并返回 `usbd_lookup_id_by_uaa` 对匹配表的结果。没有接口索引检查,没有复杂的匹配。对于具有单一功能的简单设备,这足够了。 -The 附加 method allocates the transfer channel, creates a 设备-file entry with `make_dev`, and stores the pointers. No complex negotiation; the 设备 is ready after `附加` returns. +附加方法分配传输通道,用 `make_dev` 创建设备文件条目,并存储指针。没有复杂的协商;设备在 `attach` 返回后就准备好了。 -The I/O path is a single 控制传输 with a fixed setup. The 驱动程序 sets the 帧 length, fills in the color bytes with `usbd_copy_in`, and calls `usbd_transfer_submit`. That is it. +I/O路径是具有固定设置的单个控制传输。驱动程序设置帧长度,用 `usbd_copy_in` 填充颜色字节,然后调用 `usbd_transfer_submit`。就是这样。 -Read `uled.c` first. When you have read it once, the rest of the USB subsystem opens up. Every more complex 驱动程序 is a variation on this pattern. +首先阅读 `uled.c`。当你读了一遍之后,USB子系统的其余部分就会展开。每个更复杂的驱动程序都是这个模式的变化。 -### Tour 2: ugold.c, Adding Interrupt Transfers +### 导览2:ugold.c,添加中断传输 File: `/usr/src/sys/dev/usb/misc/ugold.c`. -`ugold.c` drives a USB thermometer. It is still very short, under 500 lines, but it introduces 中断传输, which are the staple of HID-class 设备. +`ugold.c` 驱动USB温度计。它仍然很短,不到500行,但它引入了中断传输,这是HID类设备的主要传输方式。 -Key things to learn from `ugold.c`: +从 `ugold.c` 中要学习的关键内容: -The 设备 publishes temperature readings periodically via an interrupt 端点. The 驱动程序's job is to listen on that 端点 and deliver the readings to userland via `sysctl`. +设备通过中断端点定期发布温度读数。驱动程序的工作是监听该端点并通过 `sysctl` 将读数传递给用户态。 -The `usb_config` array now has an entry for `UE_INTERRUPT`, with `UE_DIR_IN`. This tells the 框架 to set up a channel that polls the interrupt 端点. +`usb_config` 数组现在有一个 `UE_INTERRUPT` 条目,方向为 `UE_DIR_IN`。这告诉框架设置一个轮询中断端点的通道。 -The interrupt 回调 shows the canonical pattern: on `USB_ST_TRANSFERRED`, extract the received bytes with `usbd_copy_out`, parse them, update the softc. On `USB_ST_SETUP` (including the initial 回调 after `start`), set the 帧 length and submit. On `USB_ST_ERROR`, decide whether to recover or give up. +中断回调展示了经典模式:在 `USB_ST_TRANSFERRED` 时,用 `usbd_copy_out` 提取接收到的字节,解析它们,更新softc。在 `USB_ST_SETUP` 时(包括 `start` 后的初始回调),设置帧长度并提交。在 `USB_ST_ERROR` 时,决定是恢复还是放弃。 -The 驱动程序 exposes readings through `sysctl` nodes created in `附加` and torn down in `分离`. This is a common pattern for 设备 that produce occasional readings: the interrupt 回调 writes to softc state, and userland reads from `sysctl` when it wants a value. +驱动程序通过在附加中创建、在分离中拆除的 `sysctl` 节点暴露读数。这是产生偶尔读数的设备的常见模式:中断回调写入softc状态,用户态在需要值时从 `sysctl` 读取。 -Compare `ugold.c` to `uled.c` after reading both. The control-transfer-only 驱动程序 and the interrupt-transfer 驱动程序 represent the two most common skeleton patterns. Most other USB驱动程序 are composed of variations of these two. +读完两者后比较 `ugold.c` 和 `uled.c`。仅控制传输的驱动程序和中断传输的驱动程序代表了两种最常见的骨架模式。大多数其他USB驱动程序由这两种的变化组合而成。 -### Tour 3: udbp.c, Bidirectional Bulk Transfers +### 导览3:udbp.c,双向批量传输 File: `/usr/src/sys/dev/usb/misc/udbp.c`. -`udbp.c` is the USB Double Bulk Pipe 驱动程序. It exists to test bidirectional bulk data flow between two computers connected by a special USB-to-USB cable. It is about 700 lines and gives you a complete working example of bulk read and bulk write. +`udbp.c` 是USB双批量管道驱动程序。它的存在是为了测试通过特殊USB转USB电缆连接的两台计算机之间的双向批量数据流。它大约700行,给你一个批量读写的完整工作示例。 -Key things to learn from `udbp.c`: +从 `udbp.c` 中要学习的关键内容: -The `usb_config` has two entries: one for `UE_BULK` `UE_DIR_OUT` (host-to-设备) and one for `UE_BULK` `UE_DIR_IN` (设备-to-host). This is the standard bulk-duplex pattern. +`usb_config` 有两个条目:一个用于 `UE_BULK` `UE_DIR_OUT`(主机到设备),一个用于 `UE_BULK` `UE_DIR_IN`(设备到主机)。这是标准的批量双工模式。 -Each 回调 does the same three-state dance. On `USB_ST_SETUP`, set the 帧 length (or if it is a read, just submit). On `USB_ST_TRANSFERRED`, consume the completed data and re-arm. On `USB_ST_ERROR`, decide the recovery policy. +每个回调执行相同的三状态舞步。在 `USB_ST_SETUP` 时,设置帧长度(或者如果是读操作,只需提交)。在 `USB_ST_TRANSFERRED` 时,消费完成的数据并重新准备。在 `USB_ST_ERROR` 时,决定恢复策略。 -The 驱动程序 uses the netgraph 框架 to integrate with higher layers. This is a choice specific to the Double Bulk Pipe 设备. For a simple application, you would expose the bulk channels through a 字符设备, as `myfirst_usb` does. +驱动程序使用netgraph框架与更高层集成。这是Double Bulk Pipe设备特有的选择。对于简单的应用,你会通过字符设备暴露批量通道,如 `myfirst_usb` 所做的那样。 -Trace how the softc maintains the state of each direction independently. The receive 回调 rearms only when a 缓冲区 is available. The transmit 回调 rearms only when there is something to send. The two 回调 coordinate only through shared softc fields (counter of pending operations, queue pointers). +追踪softc如何独立维护每个方向的状态。接收回调仅在缓冲区可用时重新准备。发送回调仅在有待发送内容时重新准备。两个回调仅通过共享的softc字段(待处理操作计数器、队列指针)进行协调。 -### Tour 4: uplcom.c, a USB-to-Serial Bridge +### 导览4:uplcom.c,USB转串口桥接 File: `/usr/src/sys/dev/usb/serial/uplcom.c`. -`uplcom.c` drives the Prolific PL2303, one of the most common USB-to-serial chips. At around 1400 lines, it is more substantial than the previous three, but every part of it maps directly onto the serial-驱动程序 pattern from Section 4 of this chapter. +`uplcom.c` 驱动Prolific PL2303,最常见的USB转串口芯片之一。大约1400行,比前三个更充实,但它的每个部分都直接映射到本章第4节的串行驱动程序模式。 -Key things to learn from `uplcom.c`: +从 `uplcom.c` 中要学习的关键内容: -The `ucom_回调` structure fills in every configuration method you would expect a real 驱动程序 to implement: `ucom_cfg_open`, `ucom_cfg_param`, `ucom_cfg_set_dtr`, `ucom_cfg_set_rts`, `ucom_cfg_set_break`, `ucom_cfg_get_status`, `ucom_cfg_close`. Each of these calls the 框架-provided `ucom` primitives after issuing the chip-specific USB 控制传输. +`ucom_callback` 结构填充了你期望真正驱动程序实现的每个配置方法:`ucom_cfg_open`、`ucom_cfg_param`、`ucom_cfg_set_dtr`、`ucom_cfg_set_rts`、`ucom_cfg_set_break`、`ucom_cfg_get_status`、`ucom_cfg_close`。每一个在发出芯片特定的USB控制传输后调用框架提供的 `ucom` 原语。 -Look at `uplcom_cfg_param`. It takes a `termios` structure, extracts the 波特率 and framing, and constructs a vendor-specific 控制传输 to program the chip. This is how a user's `stty 9600` call propagates through the layers: `stty` updates `termios`, the TTY layer calls `ucom_param`, the 框架 schedules the 控制传输, and `uplcom_cfg_param` programs the chip. +看看 `uplcom_cfg_param`。它接受一个 `termios` 结构,提取波特率和帧格式,并构造一个厂商特定的控制传输来编程芯片。这就是用户的 `stty 9600` 调用如何通过各层传播的:`stty` 更新 `termios`,TTY层调用 `ucom_param`,框架调度控制传输,`uplcom_cfg_param` 编程芯片。 -Compare `uplcom_cfg_param` with the corresponding function in `uftdi.c`. Both translate a `termios` to a vendor-specific control sequence, but the vendor protocols are entirely different. This illustrates why the 框架 insists on per-vendor 驱动程序: each chip has its own command set, and the 框架's job is only to give each 驱动程序 a uniform way to be called. +将 `uplcom_cfg_param` 与 `uftdi.c` 中对应的函数进行比较。两者都将 `termios` 翻译为厂商特定的控制序列,但厂商协议完全不同。这说明了为什么框架坚持每个厂商都有驱动程序:每个芯片有自己的命令集,框架的工作只是给每个驱动程序一个统一的被调用方式。 -Note how the 驱动程序 handles reset, modem signals, and break. Each modem-line operation is a separate USB 控制传输. The cost of changing, say, DTR is one round-trip to the 设备, which on a 12 Mbps 总线 takes about 1 ms. This tells you why line signals change more slowly over USB-to-serial than over a native UART, and why protocols that toggle DTR frequently can behave differently through a USB-to-serial adapter. +注意驱动程序如何处理重置、调制解调器信号和断开。每个调制解调器线路操作是一个独立的USB控制传输。改变,比如说DTR的成本是一次到设备的往返,在12 Mbps总线上大约需要1毫秒。这告诉你为什么线路信号通过USB转串口比通过原生UART变化更慢,以及为什么频繁切换DTR的协议通过USB转串口适配器可能表现不同。 -### Tour 5: uhid.c, the Human Interface Device Driver +### 导览5:uhid.c,人机接口设备驱动程序 File: `/usr/src/sys/dev/usb/input/uhid.c`. -`uhid.c` is the generic HID 驱动程序. HID stands for Human Interface Device; it covers keyboards, mice, gamepads, touchscreens, and countless vendor-specific 设备 that conform to the HID class standard. `uhid.c` is roughly 1000 lines. +`uhid.c` 是通用HID驱动程序。HID代表人机接口设备;它涵盖键盘、鼠标、游戏手柄、触摸屏以及无数符合HID类标准的厂商特定设备。`uhid.c` 大约1000行。 -Key things to learn from `uhid.c`: +从 `uhid.c` 中要学习的关键内容: -The 匹配表 uses class-based matching. Instead of listing every VID/PID, the 驱动程序 matches any 设备 that advertises the HID 接口 class. `UIFACE_CLASS(UICLASS_HID)` tells the 框架 to match any HID 接口, no matter which vendor made the 设备. +匹配表使用基于类的匹配。驱动程序不是列出每个VID/PID,而是匹配任何声明HID接口类的设备。`UIFACE_CLASS(UICLASS_HID)` 告诉框架匹配任何HID接口,无论哪个厂商制造了设备。 -The 驱动程序 exposes the 设备 through a 字符设备, not through `ucom` or a networking 框架. The 字符设备 pattern lets userland programs open `/dev/uhidN` and issue `ioctl` calls to read HID 描述符, read reports, and set feature reports. +驱动程序通过字符设备暴露设备,而不是通过 `ucom` 或网络框架。字符设备模式让用户态程序可以打开 `/dev/uhidN` 并发出 `ioctl` 调用来读取HID描述符、读取报告和设置特性报告。 -The interrupt 端点 delivers HID reports, and the 驱动程序 hands them up to userland through a 环形缓冲区 and `read`. This is the USB equivalent of a character-设备 interrupt-driven read loop. +中断端点传送HID报告,驱动程序通过环形缓冲区和 `read` 将它们传递给用户态。这是字符设备中断驱动读取循环的USB等价物。 -Study how `uhid.c` uses the HID report 描述符 to understand what the 设备 is. The 描述符 is parsed at 附加 time, and the 驱动程序 populates its internal tables from the parse. Every HID 设备 describes itself this way; the 驱动程序 does not hard-code 设备 semantics. +研究 `uhid.c` 如何使用HID报告描述符来理解设备是什么。描述符在附加时解析,驱动程序从解析中填充其内部表。每个HID设备都以这种方式描述自己;驱动程序不硬编码设备语义。 -### How to Study a Driver You Have Never Seen +### 如何研究你从未见过的驱动程序 -Beyond the tour, you will encounter 驱动程序 in the tree that you have never seen. A general-purpose reading strategy helps: +除了导览之外,你还会遇到树中你从未见过的驱动程序。一个通用的阅读策略会有帮助: -Open the source file and scroll to the bottom. The registration macros are there. They tell you what the 驱动程序 附加 to (`uhub`, `usb`) and its name (`udbp`, `uhid`). Already you know where the 驱动程序 fits in the tree. +打开源文件并滚动到底部。注册宏就在那里。它们告诉你驱动程序附加到什么(`uhub`、`usb`)以及它的名称(`udbp`、`uhid`)。你已经知道驱动程序在树中的位置。 -Scroll back up to the `usb_config` array (or the transfer declarations for non-USB驱动程序). Each entry is one channel. Count them; look at their types and directions. You now know the shape of the data path. +向上滚动到 `usb_config` 数组(或非USB驱动程序的传输声明)。每个条目是一个通道。数它们;看它们的类型和方向。你现在知道了数据路径的形状。 -Look at the 探测 method. If it matches by VID/PID, the 设备 is vendor-specific. If it matches by class, the 驱动程序 supports a family of 设备. This tells you the scope of the 驱动程序. +查看探测方法。如果它按VID/PID匹配,设备是厂商特定的。如果它按类匹配,驱动程序支持一系列设备。这告诉你驱动程序的范围。 -Look at the 附加 method. Follow its labelled-goto chain. The labels give you the order of resource allocation: 互斥锁, channels, 字符设备, sysctls, and so on. +查看附加方法。跟随其标签化goto链。标签给你资源分配的顺序:互斥锁、通道、字符设备、sysctl等。 -Finally, look at the data-path 回调. Each one is a three-state state machine. Read `USB_ST_TRANSFERRED` first; that is where the actual work happens. Then read `USB_ST_SETUP`; that is the kickoff. Then read `USB_ST_ERROR`; that is the recovery policy. +最后,查看数据路径回调。每个都是一个三状态状态机。先读 `USB_ST_TRANSFERRED`;那是实际工作发生的地方。然后读 `USB_ST_SETUP`;那是启动。然后读 `USB_ST_ERROR`;那是恢复策略。 -With this reading order, you can make sense of any USB驱动程序 in the tree in about 15 minutes. With practice, you will start to recognise patterns across 驱动程序 and know which ones are idiomatic (the ones to copy) and which ones are historical oddities (the ones to understand but not copy). +通过这种阅读顺序,你可以在大约15分钟内理解树中任何USB驱动程序。通过练习,你会开始识别驱动程序之间的模式,知道哪些是惯用的(要复制的),哪些是历史遗留的(要理解但不复制的)。 -### Where to Go Beyond the Tour +### 导览之外去哪里 -The `/usr/src/sys/dev/usb/` tree has four subdirectories that are worth exploring: +`/usr/src/sys/dev/usb/` 树有四个值得探索的子目录: -`/usr/src/sys/dev/usb/misc/` contains simple, single-purpose 驱动程序: `uled`, `ugold`, `udbp`. If you are writing a new 设备-specific 驱动程序 that does not fit an existing class, read the 驱动程序 here to see how small 驱动程序 are structured. +`/usr/src/sys/dev/usb/misc/` 包含简单的、单一用途的驱动程序:`uled`、`ugold`、`udbp`。如果你正在编写一个不适合现有类的新设备特定驱动程序,阅读这里的驱动程序可以了解小型驱动程序的结构。 -`/usr/src/sys/dev/usb/serial/` contains the USB-to-serial bridge 驱动程序: `uftdi`, `uplcom`, `uslcom`, `u3g` (3G modems, which present as serial to userland), `uark`, `uipaq`, `uchcom`. If you are writing a new USB-to-串行驱动程序, start here. +`/usr/src/sys/dev/usb/serial/` 包含USB转串口桥接驱动程序:`uftdi`、`uplcom`、`uslcom`、`u3g`(3G调制解调器,对用户态表现为串口)、`uark`、`uipaq`、`uchcom`。如果你正在编写新的USB转串行驱动程序,从这里开始。 -`/usr/src/sys/dev/usb/input/` contains keyboard, mouse, and HID 驱动程序. `ukbd`, `ums`, `uhid`. If you are writing a new input 驱动程序, these are the patterns to follow. +`/usr/src/sys/dev/usb/input/` 包含键盘、鼠标和HID驱动程序。`ukbd`、`ums`、`uhid`。如果你正在编写新的输入驱动程序,这些是要遵循的模式。 -`/usr/src/sys/dev/usb/net/` contains USB 网络驱动程序: `axge`, `axe`, `cdce`, `ure`, `smsc`. These are the 驱动程序 that bridge 第26章 to 第27章, because they combine the USB 框架 of this chapter with the `ifnet(9)` 框架 of the next. Reading one of them after finishing 第27章 is a productive exercise. +`/usr/src/sys/dev/usb/net/` 包含USB网络驱动程序:`axge`、`axe`、`cdce`、`ure`、`smsc`。这些是将第26章连接到第27章的驱动程序,因为它们结合了本章的USB框架和下一章的 `ifnet(9)` 框架。读完第27章后阅读其中一个是很有成效的练习。 -The `/usr/src/sys/dev/uart/` tree has fewer files but each is worth reading: +`/usr/src/sys/dev/uart/` 树文件较少但每个都值得阅读: -`/usr/src/sys/dev/uart/uart_core.c` is the 框架 core. Read this to understand what happens above your 驱动程序: how bytes flow in and out, how the TTY layer connects, how interrupts are dispatched. +`/usr/src/sys/dev/uart/uart_core.c` 是框架核心。阅读它来了解驱动程序之上发生了什么:字节如何流入流出、TTY层如何连接、中断如何分发。 -`/usr/src/sys/dev/uart/uart_dev_ns8250.c` is the canonical reference 驱动程序. Read this after the 框架 core so you can see how a 驱动程序 plugs in. +`/usr/src/sys/dev/uart/uart_dev_ns8250.c` 是规范的参考驱动程序。在框架核心之后阅读它,这样你可以看到驱动程序如何插入。 -`/usr/src/sys/dev/uart/uart_总线_pci.c` shows the PCI 总线-附加 glue for UARTs. If you ever need to write a UART 驱动程序 that 附加 to PCI, this is your starting point. +`/usr/src/sys/dev/uart/uart_bus_pci.c` 展示了UART的PCI总线附加胶水代码。如果你需要编写附加到PCI的UART驱动程序,这是你的起点。 -Each of these files is small enough to read in one sitting. Reading the source is not homework; it is how you learn a subsystem. 第26章 has given you the vocabulary and the mental model; the source is where you apply them. +这些文件中的每一个都足够小,可以在一次阅读中完成。阅读源代码不是作业;这是你学习子系统的方式。第26章给了你词汇和心智模型;源代码是你应用它们的地方。 -## 性能考虑 for Transport Drivers +## 传输驱动程序的性能考虑 -Most of 第26章 has focused on correctness: getting a 驱动程序 to 附加, do its work, and 分离 cleanly. Correctness always comes first. But once your 驱动程序 works, you will often want to know how fast it is, and whether its performance matches what the transport can sustain. This section gives you a practical 帧 for thinking about USB and UART performance without turning the chapter into a benchmarking manual. +第26章的大部分内容集中在正确性上:让驱动程序附加、工作并干净地分离。正确性始终是第一位的。但一旦你的驱动程序工作了,你通常会想知道它有多快,以及其性能是否匹配传输能维持的水平。本节给你一个实用的框架来思考USB和UART性能,而不把这一章变成基准测试手册。 -### The USB Bus as a Shared Resource +### USB总线作为共享资源 -Every 设备 on a USB 总线 shares the 总线 with every other 设备. The bandwidth is not divided fairly; it is allocated according to USB's scheduling rules. Control and interrupt 端点 get guaranteed periodic service. Bulk 端点 get what is left over, in a fair-share sense. Isochronous 端点 reserve bandwidth up front; if there is not enough, the allocation fails. +USB总线上的每个设备与每个其他设备共享总线。带宽不是公平分配的;它根据USB的调度规则分配。控制和中断端点获得保证的定期服务。批量端点获得剩余的带宽,在公平分享的意义上。等时端点预先保留带宽;如果不足,分配就会失败。 -For a bulk-transferring 驱动程序, the practical upshot is this. Your effective bandwidth is the theoretical link speed (12, 480, 5000 Mbps) minus the overhead of other 设备' periodic traffic, minus the USB protocol overhead (roughly 10% on full-speed, less on higher speeds), minus the overhead of short transfers. +对于批量传输驱动程序,实际结果是:你的有效带宽是理论链路速度(12、480、5000 Mbps)减去其他设备周期性流量的开销,减去USB协议开销(全速上大约10%,更高速率上更少),减去短传输的开销。 -The last item is the one you can influence. A transfer of 16 KB is not 16 times more expensive than a transfer of 1 KB; the overhead of initiating and completing a transfer is fixed, and the data-transfer portion is close to linear in size. For high-throughput 批量传输, use large 缓冲区. The hardware is designed for this; the 框架 is designed for this; your 驱动程序 should be designed for this. +最后一项是你能够影响的。一个16KB的传输并不比一个1KB的传输昂贵16倍;启动和完成传输的开销是固定的,数据传输部分与大小大致呈线性关系。对于高吞吐量的批量传输,使用大缓冲区。硬件为此设计;框架为此设计;你的驱动程序也应为此设计。 -For an interrupt-transferring 驱动程序, the constraint is different. The interrupt 端点 polls at a fixed interval (configured by the 设备). The 框架 delivers a 回调 whenever the polled transfer completes. The maximum report rate is the 端点's polling rate. If the 设备 has a 1-ms interval, you get at most 1000 reports per second. Planning for interrupt-driven performance means planning around the polling rate. +对于中断传输驱动程序,约束条件有所不同。中断端点以固定间隔轮询(由设备配置)。框架在每次轮询传输完成时传递回调。最大报告速率是端点的轮询速率。如果设备有1毫秒的间隔,你最多每秒获得1000个报告。规划中断驱动的性能意味着围绕轮询率进行规划。 -### Latency: What Costs Microseconds, What Costs Milliseconds +### 延迟:什么花费微秒,什么花费毫秒 -USB is not a low-latency 总线. A single 控制传输 on full-speed USB takes roughly 1 ms round-trip. A single 批量传输 takes roughly 1 ms of framing overhead plus the time to move the data. Interrupt transfers are scheduled at the polling interval, so the minimum latency is the interval itself. +USB不是低延迟总线。在全速USB上,单个控制传输大约需要1毫秒往返时间。单个批量传输大约需要1毫秒的帧开销加上移动数据的时间。中断传输按轮询间隔调度,因此最小延迟就是间隔本身。 -Compare this to native UART, where a character transmission takes roughly 1 ms at 9600 baud, 100 us at 115200 baud, and 10 us at 1 Mbps. A native UART 驱动程序 can push out a byte in hundreds of microseconds if it is well designed; a USB-to-serial bridge cannot match that, because each byte has to traverse USB first. +与此相比,原生UART在9600波特率下字符传输大约需要1毫秒,在115200波特率下需要100微秒,在1 Mbps下需要10微秒。如果设计得当,原生UART驱动程序可以在几百微秒内推送出一个字节;USB转串口桥无法匹敌这一点,因为每个字节必须首先通过USB传输。 -For your 驱动程序, this means: think about where latency matters for your use case. If you are building a monitoring 驱动程序 that reports once a second, USB is fine. If you are building an interactive controller where the user can feel each character round-trip, native UART is much better. If you are building a real-time control loop where characters must traverse in tens of microseconds, neither USB nor general-purpose UART is appropriate; you need a dedicated 总线 with known timing. +对你的驱动程序来说,这意味着:思考你的用例中延迟在哪里重要。如果你正在构建一个每秒报告一次的监控驱动程序,USB就足够了。如果你正在构建一个用户能感受到每个字符往返的交互式控制器,原生UART要好得多。如果你正在构建一个字符必须在几十微秒内传输的实时控制回路,USB和通用UART都不合适;你需要一个具有已知时序的专用总线。 -### When to Rearm: The Classic USB Tradeoff +### 何时重新准备:经典的USB权衡 -A key decision in any streaming USB驱动程序 is where in the 回调 to re-arm the transfer. There are two viable patterns: +任何流式USB驱动程序中的一个关键决策是在回调中的何处重新准备传输。有两种可行的模式: -**Rearm after work.** In `USB_ST_TRANSFERRED`, do the work (parse the data, hand it up, update state), then rearm. Simple to implement. Has a latency cost: the time between the previous completion and the next submission is the time it took to do the work. +**工作后重新准备。** 在 `USB_ST_TRANSFERRED` 中,执行工作(解析数据、向上传递、更新状态),然后重新准备。实现简单。有延迟成本:上次完成和下次提交之间的时间是执行工作所需的时间。 -**Rearm before work, using multiple 缓冲区.** In `USB_ST_TRANSFERRED`, immediately rearm with a fresh 缓冲区, then do the work on the just-completed 缓冲区. This requires multiple `帧` in the `usb_config` (so the 框架 rotates through a pool of 缓冲区) or two parallel transfer channels. Has near-zero latency between transfers because the hardware always has a 缓冲区 ready. +**工作前重新准备,使用多个缓冲区。** 在 `USB_ST_TRANSFERRED` 中,立即用新缓冲区重新准备,然后对刚完成的缓冲区执行工作。这需要在 `usb_config` 中有多个 `帧`(这样框架会在一组缓冲区中轮转)或两条并行的传输通道。传输之间接近零延迟,因为硬件始终有准备好的缓冲区。 -Most 驱动程序 in the tree use the first pattern because it is simpler. The second pattern is used in high-throughput 驱动程序 where hiding the work latency matters. `ugold.c` is the first pattern; some of the USB 以太网 驱动程序 in `/usr/src/sys/dev/usb/net/` are the second. +树中的大多数驱动程序使用第一种模式,因为它更简单。第二种模式用于高吞吐量驱动程序,其中隐藏工作延迟很关键。`ugold.c` 是第一种模式;`/usr/src/sys/dev/usb/net/` 中的一些USB以太网驱动程序是第二种模式。 -### Buffer Sizing +### 缓冲区大小 -For 批量传输, the 缓冲区 size is a knob. Larger 缓冲区 amortise the per-transfer overhead, but they also delay the delivery of partial data and increase memory usage. The typical values in the tree are between 1 KB and 64 KB. +对于批量传输,缓冲区大小是一个可调节的参数。较大的缓冲区可以分摊每次传输的开销,但它们也会延迟部分数据的交付并增加内存使用。树中的典型值在1 KB到64 KB之间。 -For 中断传输, the 缓冲区 size is usually small (8 to 64 bytes) because the 端点 itself limits the report size. Do not make this larger than the 端点's `wMaxPacketSize`; the extra 缓冲区 is wasted. +对于中断传输,缓冲区大小通常很小(8到64字节),因为端点本身限制了报告大小。不要将其设置为大于端点的 `wMaxPacketSize`;额外的缓冲区是浪费。 -For 控制传输, the 缓冲区 size is determined by the protocol of the specific operation. The `usb_设备_request` header is always 8 bytes; the data portion depends on the request. +对于控制传输,缓冲区大小由特定操作的协议决定。`usb_device_request` 头部始终是8字节;数据部分取决于请求。 -### UART Performance +### UART性能 -For a UART 驱动程序, performance is usually a question of interrupt efficiency. A 16550A with a FIFO depth of 16 bytes at 115200 baud needs to be serviced roughly every 1.4 ms in the worst case. If your 中断处理程序 takes longer than that, the FIFO overflows and data is lost. Modern UARTs (16750, 16950, ns16550 variants on embedded SoCs) often have deeper FIFOs (64, 128, or 256 bytes) specifically to relax this constraint. +对于UART驱动程序,性能通常是一个中断效率问题。一个FIFO深度为16字节、波特率为115200的16550A在最坏情况下大约每1.4毫秒需要被服务一次。如果你的中断处理程序花费的时间比这更长,FIFO就会溢出并丢失数据。现代UART(16750、16950、嵌入式SoC上的ns16550变体)通常有更深的FIFO(64、128或256字节),专门用来放宽这一约束。 -The `uart(4)` 框架 handles the FIFO management for you through `uart_ops->rxready` and the 环形缓冲区. What you control as the 驱动程序 author is: how fast your implementation of `getc` is, how fast `putc` is, and whether your 中断处理程序 is sharing the CPU with other work. +`uart(4)` 框架通过 `uart_ops->rxready` 和环形缓冲区为你处理FIFO管理。你作为驱动程序作者可以控制的是:你的 `getc` 实现有多快,`putc` 有多快,以及你的中断处理程序是否与其他工作共享CPU。 -For higher 波特率s (921600, 1.5M, 3M), a raw 16550A is not enough. These rates require either a chip with a larger FIFO or a 驱动程序 that uses DMA to move characters directly to memory. The `uart(4)` 框架 supports DMA-backed 驱动程序, but the vast majority of 驱动程序 (including `ns8250`) do not use it. DMA support is usually reserved for embedded platforms that specifically provide it. +对于更高的波特率(921600、1.5M、3M),原始的16550A是不够的。这些速率需要具有更大FIFO的芯片,或者使用DMA直接将字符移动到内存的驱动程序。`uart(4)` 框架支持DMA-backed的驱动程序,但绝大多数驱动程序(包括 `ns8250`)不使用它。DMA支持通常保留给专门提供它的嵌入式平台。 -### Concurrency and Lock Hold Times +### 并发和锁持有时间 -A USB 回调 runs with the 驱动程序's 互斥锁 held. If the 回调 takes a long time (copying a large 缓冲区, doing complex processing), no other 回调 can run, and no 分离 can complete. Keep 回调 work short. +USB回调在持有驱动程序互斥锁的情况下运行。如果回调花费很长时间(复制大缓冲区、执行复杂处理),其他回调就无法运行,也无法完成分离。保持回调工作简短。 +非平凡工作的惯用模式是:在回调中,将数据从框架缓冲区复制到softc中的私有缓冲区,然后将数据标记为就绪并唤醒消费者。消费者(通过 `read` 的用户态,或工作者taskqueue)在没有驱动程序互斥锁的情况下执行繁重处理。 -The idiomatic pattern for non-trivial work is: in the 回调, copy the data out of the 框架 缓冲区 into a private 缓冲区 in softc, then mark the data as ready and wake a consumer. The consumer (userland via `read`, or a worker taskqueue) does the heavy processing without the 驱动程序 互斥锁. +对于UART驱动程序,同样的原则适用。`rxready` 和 `getc` 方法必须快速,因为它们在中端上下文中运行。繁重处理稍后在中端外部由TTY层和用户进程完成。 -For a UART 驱动程序, the same principle applies. The `rxready` and `getc` methods must be fast because they run in interrupt context. Heavy processing is done later, outside the interrupt, by the TTY layer and user processes. +### 测量,而非猜测 -### Measuring, Not Guessing +回答性能问题的最佳方法是测量。`usbd_transfer_submit` 及相关函数上的 `dtrace` 钩子让你能够以微秒精度计时传输。`sysctl -a | grep usb` 暴露每设备统计信息。对于UART,`sysctl -a dev.uart` 和 `vmstat` 中的TTY统计信息告诉你时间花在哪里。 -The best way to answer a performance question is to measure. The `dtrace` hooks on `usbd_transfer_submit` and related functions let you time transfers to microsecond precision. `sysctl -a | grep usb` exposes per-设备 statistics. For UARTs, `sysctl -a dev.uart` and the TTY statistics in `vmstat` tell you where time is going. +不要盲目优化驱动程序。运行工作负载、测量、找到瓶颈,并修复真正重要的问题。对于大多数驱动程序,瓶颈不是传输本身而是其周围的问题:内存分配、锁定或大小不当的缓冲区。 -Do not optimise a 驱动程序 blindly. Run the workload, measure, find the bottleneck, and fix what actually matters. For most 驱动程序, the bottleneck is not the transfer itself but something surrounding it: memory allocation, locking, or a poorly sized 缓冲区. +## 编写第一个传输驱动程序时的常见错误 -## 常见错误 When Writing Your First Transport Driver +本章中的模式是编写传输驱动程序的正确方法。但模式描述起来容易应用起来难。大多数初学者的驱动程序在原则上正确地遵循了每个模式,但在实践中却误用了它们。本节列出了某人第一次编写USB或UART驱动程序时最常出现的具体错误。每个错误都配对了纠正方法和为什么纠正方法必要的简短说明。 -The patterns in this chapter are the right way to write a transport 驱动程序. But patterns are easier to describe than to apply. Most first-time 驱动程序 are written with every pattern followed correctly in principle but misapplied in practice. This section lists the specific mistakes that appear most often when someone sits down to write a USB or UART 驱动程序 for the first time. Each mistake is paired with the correction and a short explanation of why the correction is necessary. +在编写第一个驱动程序之前阅读本部分一次,在调试驱动程序时再读一次。这些错误惊人地普遍;几乎每个有经验的FreeBSD驱动程序作者都曾在某个时候犯过其中几个。 -Read this section once before you write your first 驱动程序, and again when you are debugging one. The mistakes are surprisingly universal; almost every experienced FreeBSD 驱动程序 author has made several of them at some point. +### 错误1:在回调中显式获取框架互斥锁 -### Mistake 1: Taking the Framework Mutex Explicitly in a Callback - -The mistake looks like this: +该错误看起来是这样的: ```c static void @@ -3391,13 +3391,13 @@ my_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) } ``` -The 框架 has already acquired the 互斥锁 before calling the 回调. Taking it a second time is a self-deadlock on most 互斥锁 implementations and an extra uncontested acquisition on others. On some 内核 configurations, it will panic immediately with a "recursive lock" assertion from WITNESS. +框架在调用回调之前已经获取了互斥锁。在大多数互斥锁实现中第二次获取它会导致自死锁,而在其他实现中则是一次额外的无争议获取。在某些内核配置上,它会立即因WITNESS的"递归锁"断言而panic。 -The correction is to simply not lock. The 框架 guarantees that 回调 are invoked with the softc 互斥锁 held. Your 回调 just does its work and returns; the 框架 releases the 互斥锁 on return. +纠正方法就是不加锁。框架保证回调在持有softc互斥锁的情况下被调用。你的回调只需执行工作然后返回;框架在返回时释放互斥锁。 -### Mistake 2: Calling Framework Primitives Without the Mutex Held +### 错误2:在未持有互斥锁的情况下调用框架原语 -The opposite mistake is also common: +相反的错误也很常见: ```c static int @@ -3411,9 +3411,9 @@ my_userland_write(struct cdev *dev, struct uio *uio, int ioflag) } ``` -Most 框架 primitives (`usbd_transfer_start`, `usbd_transfer_stop`, `usbd_transfer_submit`) expect the caller to hold the associated 互斥锁. Calling them without the 互斥锁 is a race: the 框架's own state can be modified by a concurrent 回调 while you are issuing the primitive. +大多数框架原语(`usbd_transfer_start`、`usbd_transfer_stop`、`usbd_transfer_submit`)期望调用者持有相关的互斥锁。在没有互斥锁的情况下调用它们会导致竞态:在你发出原语时,框架自身的状态可能被并发回调修改。 -The correction is to take the 互斥锁 around the call: +纠正方法是在调用周围获取互斥锁: ```c mtx_lock(&sc->sc_mtx); @@ -3421,72 +3421,72 @@ usbd_transfer_start(sc->sc_xfer[MY_BULK_TX]); mtx_unlock(&sc->sc_mtx); ``` -This is the idiomatic pattern. The 框架 provides the locking; the 驱动程序 provides the 互斥锁. +这是惯用模式。框架提供锁定的调用约定;驱动程序提供互斥锁。 -### Mistake 3: Forgetting `USB_ERR_CANCELLED` Handling +### 错误3:忘记处理 `USB_ERR_CANCELLED` -The 框架 uses `USB_ERR_CANCELLED` to tell a 回调 that its transfer is being torn down (typically during 分离). If your 回调 handles this error the same way it handles other errors (for example by rearming the transfer), 分离 will hang forever because the transfer never actually stops. +框架使用 `USB_ERR_CANCELLED` 来通知回调其传输正在被拆除(通常在分离期间)。如果你的回调以与其他错误相同的方式处理此错误(例如通过重新准备传输),分离将永远挂起,因为传输从未真正停止。 -The correct pattern is: +正确的模式是: ```c case USB_ST_ERROR: if (error == USB_ERR_CANCELLED) { - return; /* do not rearm; the framework is tearing us down */ + return; /* 不要重新准备;框架正在拆除我们 */ } - /* handle other errors, possibly rearm */ + /* 处理其他错误,可能重新准备 */ break; ``` -Omitting the cancellation check is one of the most common reasons a 驱动程序 分离 cleanly in development (because the ref count happens to be zero) but hangs in production (because a read was in-flight when 分离 ran). +省略取消检查是驱动程序在开发中能干净分离(因为引用计数恰好为零)但在生产中挂起(因为分离运行时读操作正在进行中)的最常见原因之一。 -### Mistake 4: Submitting to a Channel That Has Not Been Started +### 错误4:向尚未启动的通道提交传输 -A transfer channel is inert until `usbd_transfer_start` has been called on it. Calling `usbd_transfer_submit` on an inactive channel is a no-op in some 框架 versions and a panic in others. +传输通道在调用 `usbd_transfer_start` 之前是惰性的。在未激活的通道上调用 `usbd_transfer_submit` 在某些框架版本中是空操作,在其他版本中会导致panic。 -The correct pattern is to call `usbd_transfer_start` from userland-initiated work (in response to an open, for instance) and leave the channel active until 分离. Do not call `usbd_transfer_submit` directly; let `usbd_transfer_start` schedule the first 回调, and rearm from `USB_ST_SETUP` or `USB_ST_TRANSFERRED`. +正确的模式是从用户态发起的工作中调用 `usbd_transfer_start`(例如响应open),并保持通道活跃直到分离。不要直接调用 `usbd_transfer_submit`;让 `usbd_transfer_start` 调度第一个回调,并从 `USB_ST_SETUP` 或 `USB_ST_TRANSFERRED` 重新准备。 -### Mistake 5: Assuming `USB_GET_STATE` Returns the Real Hardware State +### 错误5:假设 `USB_GET_STATE` 返回真实硬件状态 -`USB_GET_STATE(xfer)` returns the state the 框架 wants the 回调 to handle at this moment. It does not report the underlying hardware state. The three states `USB_ST_SETUP`, `USB_ST_TRANSFERRED`, and `USB_ST_ERROR` are 框架 concepts, not hardware concepts. +`USB_GET_STATE(xfer)` 返回框架希望回调在此刻处理的状态。它不报告底层硬件状态。三个状态 `USB_ST_SETUP`、`USB_ST_TRANSFERRED` 和 `USB_ST_ERROR` 是框架概念,而不是硬件概念。 -In particular, `USB_ST_TRANSFERRED` means "the 框架 thinks this transfer completed." If the hardware is misbehaving (spurious transfer complete interrupts, split completions), the 回调 may be called with `USB_ST_TRANSFERRED` even when the actual transfer has not fully drained. This is rare, but when debugging, do not assume the 框架 state is ground truth about the hardware. +特别是,`USB_ST_TRANSFERRED` 意味着"框架认为此传输已完成。"如果硬件行为异常(虚假传输完成中断、拆分完成),即使实际传输尚未完全排空,回调也可能以 `USB_ST_TRANSFERRED` 被调用。这很少见,但在调试时,不要假设框架状态是硬件的真实情况。 -### Mistake 6: Using `M_WAITOK` in a Callback +### 错误6:在回调中使用 `M_WAITOK` -A USB 回调 runs in an environment where sleeping is not allowed. Memory allocations in a 回调 must use `M_NOWAIT`. Using `M_WAITOK` will assert or panic. +USB回调在不允许睡眠的环境中运行。回调中的内存分配必须使用 `M_NOWAIT`。使用 `M_WAITOK` 会导致断言失败或panic。 -A more subtle version of this mistake is calling a helper that internally uses `M_WAITOK`. For example, some 框架 helpers sleep; calling them from a 回调 is forbidden. If you need to do work that would require sleeping (DNS lookup, disk I/O, USB 控制传输 from a USB 回调), queue it to a taskqueue and let the taskqueue worker do the work outside the 回调. +这种错误的一个更微妙的版本是调用一个内部使用 `M_WAITOK` 的辅助函数。例如,一些框架辅助函数会睡眠;从回调中调用它们是被禁止的。如果你需要执行需要睡眠的工作(DNS查找、磁盘I/O、从USB回调中发起USB控制传输),将其排队到taskqueue,让taskqueue工作者在回调外部执行该工作。 -### Mistake 7: Forgetting `MODULE_DEPEND` on `usb` +### 错误7:忘记在 `usb` 上声明 `MODULE_DEPEND` -A USB驱动程序 module that does not declare `MODULE_DEPEND(my, usb, 1, 1, 1)` will fail to load with a cryptic unresolved-symbol error: +未声明 `MODULE_DEPEND(my, usb, 1, 1, 1)` 的USB驱动程序模块将加载失败,并出现难以理解的未解析符号错误: ```text link_elf_obj: symbol usbd_transfer_setup undefined ``` -The symbol is undefined because the `usb` module has not been loaded, and the linker cannot resolve the 驱动程序's dependency on it. Adding the correct `MODULE_DEPEND` directive causes the 内核模块 loader to automatically load `usb` before your 驱动程序, which resolves the symbol and lets your 驱动程序 附加. +该符号未定义是因为 `usb` 模块尚未加载,链接器无法解析驱动程序对它的依赖。添加正确的 `MODULE_DEPEND` 指令会使内核模块加载器在加载你的驱动程序之前自动加载 `usb`,从而解析符号并让你的驱动程序能够附加。 -Every USB驱动程序 must have `MODULE_DEPEND(驱动程序name, usb, 1, 1, 1)`. Every UART-框架 驱动程序 must have `MODULE_DEPEND(驱动程序name, uart, 1, 1, 1)`. Every `ucom(4)` 驱动程序 must depend on both `usb` and `ucom`. +每个USB驱动程序必须有 `MODULE_DEPEND(驱动程序名, usb, 1, 1, 1)`。每个UART框架驱动程序必须有 `MODULE_DEPEND(驱动程序名, uart, 1, 1, 1)`。每个 `ucom(4)` 驱动程序必须同时依赖 `usb` 和 `ucom`。 -### Mistake 8: Mutable State in a Read-Only Path +### 错误8:只读路径中的可变状态 -Imagine a 驱动程序 that exposes a status field through a `sysctl`. The sysctl handler reads the field from the softc without taking the 互斥锁: +想象一个通过 `sysctl` 暴露状态字段的驱动程序。sysctl处理程序在未获取互斥锁的情况下从softc读取字段: ```c static int my_sysctl_status(SYSCTL_HANDLER_ARGS) { struct my_softc *sc = arg1; - int val = sc->sc_status; /* <-- unlocked read */ + int val = sc->sc_status; /* <-- 未加锁的读取 */ return (SYSCTL_OUT(req, &val, sizeof(val))); } ``` -If the field can be updated by a 回调 (which runs under the 互斥锁), and read by the sysctl handler (which does not take the 互斥锁), you have a data race. On modern platforms, word-sized reads are usually atomic, so the race is often invisible. But on platforms where they are not, or when the field is wider than a word, you can get torn reads. +如果该字段可以被回调(在互斥锁下运行)更新,并且被sysctl处理程序(不获取互斥锁)读取,就存在数据竞态。在现代平台上,字大小的读取通常是原子的,因此竞态通常不可见。但在非原子平台上,或者当字段宽度超过一个字时,你可能会得到撕裂的读取。 -The correction is to take the 互斥锁 for the read: +纠正方法是为读取获取互斥锁: ```c mtx_lock(&sc->sc_mtx); @@ -3494,28 +3494,28 @@ val = sc->sc_status; mtx_unlock(&sc->sc_mtx); ``` -Even if the race is invisible on x86, taking the lock documents your intent and protects against future changes (like widening the field to 64 bits). +即使竞态在x86上不可见,获取锁也能记录你的意图并防止未来变更(如将字段扩展到64位)。 -### Mistake 9: Stale Pointers After `usbd_transfer_unsetup` +### 错误9:`usbd_transfer_unsetup` 后的悬空指针 -`usbd_transfer_unsetup` frees the transfer channels. The pointer in `sc->sc_xfer[i]` is no longer valid after the call returns. If any other code in your 驱动程序 uses that pointer after unsetup, the behaviour is undefined. +`usbd_transfer_unsetup` 释放传输通道。调用返回后 `sc->sc_xfer[i]` 中的指针不再有效。如果驱动程序中的任何其他代码在取消设置后使用该指针,行为是未定义的。 -The correction is to zero the array after unsetup: +纠正方法是在取消设置后将数组归零: ```c usbd_transfer_unsetup(sc->sc_xfer, MY_N_TRANSFERS); -memset(sc->sc_xfer, 0, sizeof(sc->sc_xfer)); /* optional but defensive */ +memset(sc->sc_xfer, 0, sizeof(sc->sc_xfer)); /* 可选但防御性 */ ``` -More importantly, structure your 分离 so that nothing in the 驱动程序 can observe the stale pointers. This usually means setting a "分离ing" flag in the softc before calling unsetup, and having every other code path check the flag before using the pointers. +更重要的是,组织你的分离,使驱动程序中的任何内容都无法观察到悬空指针。这通常意味着在调用unsetup之前在softc中设置"分离中"标志,并让所有其他代码路径在使用指针之前检查该标志。 -### Mistake 10: Not Zeroing the Softc's `分离ing` Flag at Attach Time +### 错误10:在附加时未将Softc的"分离中"标志归零 -If your softc uses a `分离ing` flag to coordinate 分离, the flag must start at zero when 附加 is called. This is normally automatic (the 框架 zero-fills the softc), but if you have any field that needs a non-zero initial value, be careful not to accidentally initialise `分离ing` to a nonzero value. +如果你的softc使用"分离中"标志来协调分离,该标志在调用附加时必须从零开始。这通常是自动的(框架将softc零填充),但如果你有任何需要非零初始值的字段,注意不要意外将"分离中"初始化为非零值。 -A 驱动程序 that starts with `分离ing = 1` will appear to "分离 before it ever 附加ed," which shows up as a 驱动程序 that 附加 normally but refuses to respond to any I/O. +一个以 `分离中 = 1` 开始的驱动程序将表现为"在附加之前就分离了",表现为驱动程序正常附加但拒绝响应任何I/O。 -### Mistake 11: Forgetting to Destroy the Device Node on Detach +### 错误11:忘记在分离时销毁设备节点 If your 驱动程序 creates a 字符设备 with `make_dev` in 附加, you must destroy it with `destroy_dev` in 分离. Forgetting this leaves a stale `/dev` entry that points to freed memory. Userland programs that open the stale node will panic the 内核. @@ -3523,92 +3523,90 @@ The correction is to call `destroy_dev(sc->sc_cdev)` in 分离, and always befor A stronger pattern is to order the `destroy_dev` call first in 分离 (before any other cleanup). This 块 new opens and waits for existing opens to close, so that by the time the rest of 分离 runs, no userland code can reach the 驱动程序. -### Mistake 12: Racing on the Character Device Open +### 错误12:字符设备打开时的竞态 -Even with `destroy_dev` in the right place, there is a window between 附加 succeeding and the first `open()` succeeding where the 驱动程序's state is being initialised. If your open handler assumes certain softc fields are valid, and 附加 has not finished initialising them when the first open arrives, the open will see garbage. +即使 `destroy_dev` 放在正确的位置,在附加成功和第一个 `open()` 成功之间,存在驱动程序状态正在被初始化的窗口。如果你的open处理程序假设某些softc字段是有效的,而附加在第一个open到达时尚未完成它们的初始化,open将看到垃圾数据。 -The correction is to call `make_dev` last in 附加, only after everything else is fully initialised. This way, the `/dev` entry does not appear until the 驱动程序 is ready to service opens. Correspondingly, call `destroy_dev` first in 分离, before tearing anything down. +纠正方法是在附加中最后调用 `make_dev`,只有在所有其他内容完全初始化之后。这样,`/dev` 条目在驱动程序准备好服务打开之前不会出现。相应地,在分离中首先调用 `destroy_dev`,在拆除任何其他内容之前。 -### Mistake 13: Overlooking the TTY Layer's Own Locking +### 错误13:忽略TTY层自身的锁定 -UART 驱动程序 integrate with the TTY layer, which has its own locking rules. In particular, the TTY layer holds `tty_lock` when it calls into the 驱动程序's `tsw_param`, `tsw_open`, and `tsw_close` methods. If the 驱动程序 then takes another lock inside these methods, the lock order is `tty_lock -> 驱动程序_互斥锁`. If any other code path takes the 驱动程序 互斥锁 and then the tty lock, you have a lock order inversion, and WITNESS will catch it. +UART驱动程序与TTY层集成,而TTY层有自己的锁定规则。特别是,当TTY层调用驱动程序的 `tsw_param`、`tsw_open` 和 `tsw_close` 方法时,它持有 `tty_lock`。如果驱动程序在这些方法内部再获取另一个锁,锁顺序是 `tty_lock -> 驱动程序互斥锁`。如果任何其他代码路径先获取驱动程序互斥锁再获取tty锁,就存在锁顺序反转,WITNESS会捕获它。 -The correction is to respect the lock order that the 框架 establishes. For UART 驱动程序, the order is documented in `/usr/src/sys/dev/uart/uart_core.c`. When in doubt, run under WITNESS with `WITNESS_CHECKORDER` enabled; it will detect any violation immediately. +纠正方法是尊重框架建立的锁顺序。对于UART驱动程序,顺序记录在 `/usr/src/sys/dev/uart/uart_core.c` 中。如有疑问,在启用了 `WITNESS_CHECKORDER` 的WITNESS下运行;它会立即检测到任何违规。 -### Mistake 14: Not Handling Zero-Length Data in Read or Write +### 错误14:未处理读或写中的零长度数据 -A userland `read` or `write` with a zero-length 缓冲区 is legal. Your 驱动程序 must handle it, either by immediately returning zero or by propagating the zero-length request through the 框架. Forgetting this case often produces a 驱动程序 that "mostly works" but fails weird test scenarios. +用户态使用零长度缓冲区进行 `read` 或 `write` 是合法的。你的驱动程序必须处理它,要么立即返回零,要么通过框架传播零长度请求。忘记这种情况通常会产生一个"大部分时间能工作"但在奇怪测试场景中失败的驱动程序。 -The simplest correction is: +最简单的纠正方法是在读写函数的顶部添加: ```c if (uio->uio_resid == 0) return (0); ``` -at the top of your read and write functions. +### 错误15:在检查传输状态之前复制数据 -### Mistake 15: Copying Data Before Checking the Transfer Status - -In a read path, a common mistake is to unconditionally copy data out of the USB 缓冲区: +在读路径中,一个常见错误是无条件地从USB缓冲区复制数据: ```c case USB_ST_TRANSFERRED: usbd_copy_out(pc, 0, sc->sc_rx_buf, actlen); - /* hand data up to userland */ + /* 将数据向上传递给用户态 */ break; ``` -If the transfer was a short read (`actlen < wMaxPacketSize`), the copy is correct for exactly `actlen` bytes but the 驱动程序 code may assume more. If the transfer was empty (`actlen == 0`), the copy does nothing and any subsequent code that operates on "just-received data" works on stale data from the previous transfer. +如果传输是短读取(`actlen < wMaxPacketSize`),复制对于恰好 `actlen` 字节是正确的,但驱动程序代码可能假设更多。如果传输是空的(`actlen == 0`),复制不做任何事情,任何后续对"刚接收到的数据"进行操作的代码将在上一次传输的陈旧数据上工作。 -The correction is to always check `actlen` before acting on the data: +纠正方法是在对数据执行操作之前始终检查 `actlen`: ```c case USB_ST_TRANSFERRED: if (actlen == 0) - goto rearm; /* nothing received */ + goto rearm; /* 未收到任何内容 */ usbd_copy_out(pc, 0, sc->sc_rx_buf, actlen); - /* work with exactly actlen bytes */ + /* 使用恰好 actlen 个字节 */ rearm: - /* re-submit */ + /* 重新提交 */ break; ``` -### Mistake 16: Assuming `termios` Values Are in Standard Units +### 错误16:假设 `termios` 值是标准单位 -The `termios` structure's `c_ispeed` and `c_ospeed` fields contain 波特率 values, but the encoding has historical oddities. On FreeBSD, speeds are integer values (9600, 38400, 115200). On some other systems, they are indices into a table. Porting code that assumed index-based speeds to FreeBSD without checking is a common source of "the 驱动程序 thinks the 波特率 is 13 instead of 115200" bugs. +`termios` 结构的 `c_ispeed` 和 `c_ospeed` 字段包含波特率值,但编码有历史遗留的怪癖。在FreeBSD上,速度是整数值(9600、38400、115200)。在其他一些系统上,它们是表的索引。移植假定基于索引的速度的代码到FreeBSD而不进行检查是"驱动程序认为波特率是13而不是115200"类错误的常见来源。 -The correction is to look at the actual FreeBSD implementation: `/usr/src/sys/sys/termios.h` and `/usr/src/sys/kern/tty.c`. The 波特率 in FreeBSD `termios` is an integer bit rate. When your 驱动程序 receives a `termios` in `param`, read `c_ispeed` and `c_ospeed` as integers. +纠正方法是查看实际的FreeBSD实现:`/usr/src/sys/sys/termios.h` 和 `/usr/src/sys/kern/tty.c`。FreeBSD `termios` 中的波特率是整数比特率。当你的驱动程序在 `param` 中收到 `termios` 时,将 `c_ispeed` 和 `c_ospeed` 作为整数读取。 -### Mistake 17: Missing `设备_set_desc` or `设备_set_desc_copy` +### 错误17:缺少 `device_set_desc` 或 `device_set_desc_copy` -The `设备_set_desc` family of calls sets the human-readable description that `dmesg` shows when the 设备 附加. Without it, `dmesg` shows a generic label (like "my_drv0: "), which is confusing for users and for your own debugging. +`device_set_desc` 系列调用设置了设备附加时 `dmesg` 显示的人类可读描述。没有它,`dmesg` 会显示通用标签(如"my_drv0: "),这对用户和你自己的调试都很混乱。 -The correction is to call `设备_set_desc` in 探测 (not 附加), before returning `BUS_PROBE_GENERIC` or similar: +纠正方法是在探测(而非附加)中调用 `device_set_desc`,在返回 `BUS_PROBE_GENERIC` 或类似值之前: ```c static int my_probe(device_t dev) { - /* ... match check ... */ + /* ... 匹配检查 ... */ device_set_desc(dev, "My Device"); return (BUS_PROBE_DEFAULT); } ``` -Use `设备_set_desc_copy` when the string is dynamic (constructed from 设备 data); the 框架 will free the copy when the 设备 is 分离ed. +当字符串是动态的(从设备数据构建)时使用 `device_set_desc_copy`;框架会在设备分离时释放副本。 -### Mistake 18: `设备_printf` in the Data Path Without Rate Limiting +### 错误18:数据路径中无速率限制的 `device_printf` -The `设备_printf` call is fine for occasional messages. In a data-path 回调, it is not, because every single transfer prints a line to `dmesg` and to the console. A 1 Mbps stream of characters becomes a flood of log messages. +`device_printf` 调用对偶尔的消息没问题。但在数据路径回调中则不行,因为每次传输都会向 `dmesg` 和控制台打印一行。1 Mbps的字符流会变成日志消息的洪水。 -The correction is the `DLOG_RL` pattern from 第25章: rate-limit data-path log messages to one per second, or one per thousand events, whichever is appropriate. Keep full logging in the configuration and error paths; rate-limit in the data path. +纠正方法是第25章的 `DLOG_RL` 模式:将数据路径日志消息限制为每秒一条,或每千个事件一条,视情况而定。在配置和错误路径中保留完整日志;在数据路径中进行速率限制。 -### Mistake 19: Not Waking Readers on Device Removal +### 错误19:设备移除时未唤醒读取者 -If a userland program is 块ed in `read()` waiting for data, and the 设备 is unplugged, the 驱动程序 must wake the reader and return an error (typically `ENXIO` or `ENODEV`). Forgetting to do this leaves the read 块ed forever, which is a resource leak and a hang. +如果用户态程序阻塞在 `read()` 中等待数据,而设备被拔掉,驱动程序必须唤醒读取者并返回错误(通常为 `ENXIO` 或 `ENODEV`)。忘记这样做会使读取永远阻塞,这既是资源泄漏也是挂起。 -The correction is to wake all sleepers in 分离 before returning: +纠正方法是在返回之前在分离中唤醒所有睡眠者: ```c mtx_lock(&sc->sc_mtx); @@ -3618,7 +3616,7 @@ wakeup(&sc->sc_tx_queue); mtx_unlock(&sc->sc_mtx); ``` -And in the read path, check the flag after waking: +在读路径中,唤醒后检查标志: ```c while (sc->sc_rx_head == sc->sc_rx_tail && !sc->sc_detaching) { @@ -3630,401 +3628,401 @@ if (sc->sc_detaching) return (ENXIO); ``` -This is the idiomatic pattern and avoids the classic "userland process hangs after you unplug the 设备" bug. +这是惯用模式,避免了经典的"拔掉设备后用户态进程挂起"的错误。 -### Mistake 20: Thinking "It Works on My Machine" Is Enough +### 错误20:认为"在我的机器上能工作"就足够了 -Driver bugs can be hardware-dependent. A 驱动程序 that works on one machine may fail on another because of timing differences, interrupt delivery differences, or hardware quirks in the USB controller. A 驱动程序 that works with one model of a 设备 may fail with another model of the same family because of firmware differences. +驱动程序错误可能是硬件相关的。在一个机器上能工作的驱动程序可能因为时序差异、中断传递差异或USB控制器中的硬件怪癖而在另一个机器上失败。与一种设备型号能正常工作的驱动程序,可能因为固件差异而与同一系列的另一型号失败。 -The correction is to test on multiple machines, multiple USB hosts (xHCI, EHCI, OHCI), and multiple 设备 if possible. When something works on one and fails on another, the difference is information. Trace both, compare, and the bug usually becomes clear. +纠正方法是在多台机器、多个USB主机(xHCI、EHCI、OHCI)和多个设备(如果可能)上进行测试。当某个东西在一台机器上工作而在另一台上失败时,差异就是信息。追踪两者,进行比较,错误通常就会变得清晰。 -### What To Do After You Make One of These Mistakes +### 犯了这些错误之一后该怎么办 -You will make several of these mistakes. This is normal. The way to learn is: debug the failure, identify which mistake it was, understand why it caused the specific symptom, and add the correction to your mental toolkit. Keep a note of which mistakes you have made in practice. When you see a new 驱动程序 failure, check your note; the answer is usually a mistake you have already solved once. +你会犯其中几个错误。这是正常的。学习的方法是:调试失败,识别是哪个错误,理解它为什么会引起特定的症状,并将纠正方法添加到你的心智工具箱中。记录你在实践中犯过哪些错误。当你看到一个新的驱动程序失败时,查看你的笔记;答案通常是你已经解决过一次的错误。 -The specific mistakes above are collected from the author's own experience writing and debugging USB and UART 驱动程序 on FreeBSD. They are not exhaustive, but they are representative of the kinds of issues that come up. Reading 驱动程序 in the tree, attending FreeBSD developer forums, and submitting your work for code review are all ways to accelerate this kind of learning. +以上具体错误收集自在FreeBSD上编写和调试USB及UART驱动程序的作者亲身经验。它们并非详尽无遗,但代表了可能出现的问题类型。阅读树中的驱动程序、参加FreeBSD开发者论坛以及提交你的工作供代码审查都是加速这种学习的方式。 ## 总结 -第26章 has taken you on a long tour. It began with the idea that a transport-specific 驱动程序 is a New总线 驱动程序 plus a set of rules about how the transport works. It then built out the two transport-specific layers we are focusing on in 第6部分: USB and serial. +第26章带你进行了一次长途导览。它从传输专用驱动程序是New总线驱动程序加上一套关于传输如何工作的规则这一概念开始。然后它构建了我们在第6部分中关注的两个传输专用层:USB和串行。 -On the USB side, you learned the host-and-设备 model, the 描述符 hierarchy, the four transfer types, and the 热插拔 lifecycle. You walked through a complete 驱动程序 skeleton: the 匹配表, the 探测 method, the 附加 method, the softc, the 分离 method, and the registration macros. You saw how `struct usb_config` declares transfer channels and how `usbd_transfer_setup` brings them to life. You followed the three-state 回调 state machine through bulk, interrupt, and 控制传输, and you saw how `usbd_copy_in` and `usbd_copy_out` move data between the 驱动程序 and the 框架's 缓冲区. You learned the locking rules around transfer operations and the retry policies 驱动程序 should choose. By the end of Section 3, you had a mental model that would let you write a bulk-loopback 驱动程序 from scratch. +在USB方面,你学习了主机和设备模型、描述符层次结构、四种传输类型和热插拔生命周期。你完整地走过了一个驱动程序骨架:匹配表、探测方法、附加方法、softc、分离方法和注册宏。你看到了 `struct usb_config` 如何声明传输通道以及 `usbd_transfer_setup` 如何赋予它们生命。你跟随三状态回调状态机经历了批量、中断和控制传输,并看到了 `usbd_copy_in` 和 `usbd_copy_out` 如何在驱动程序和框架缓冲区之间移动数据。你学习了围绕传输操作的锁定规则以及驱动程序应选择的重试策略。到第3节结束时,你拥有了一个可以从零编写批量环回驱动程序的心智模型。 -On the serial side, you learned that the TTY layer sits on top of two distinct 框架: `uart(4)` for 总线-附加ed UARTs and `ucom(4)` for USB-to-serial bridges. You saw the six-method structure of a `uart(4)` 驱动程序, the role of `uart_ops` and `uart_class`, and how the `ns8250` canonical 驱动程序 implements each method. You learned how `termios` settings flow from `stty` through the TTY layer into the 驱动程序's `param` path, and how hardware 流控制 is implemented at the 注册 level. For USB-to-serial 设备, you saw the distinct `ucom_回调` structure and how configuration methods translate termios changes into vendor-specific USB 控制传输. +在串行方面,你学习了TTY层位于两个不同的框架之上:`uart(4)` 用于总线附加的UART,以及 `ucom(4)` 用于USB转串口桥接。你看到了 `uart(4)` 驱动程序的六方法结构、`uart_ops` 和 `uart_class` 的作用,以及 `ns8250` 规范驱动程序如何实现每个方法。你学习了 `termios` 设置如何从 `stty` 通过TTY层流入驱动程序的 `param` 路径,以及硬件流控制如何在寄存器级别实现。对于USB转串口设备,你看到了独特的 `ucom_callback` 结构,以及配置方法如何将termios更改转换为厂商特定的USB控制传输。 -For testing, you learned about `nmdm(4)` for pure-TTY testing, QEMU USB redirection for USB development, and a handful of userland tools (`cu`, `tip`, `stty`, `comcontrol`, `usbconfig`) that make 驱动程序 development manageable even without constant hardware access. You saw that much of 驱动程序 work is not 注册-level wrestling but careful arrangement of data flow through well-defined abstractions. +在测试方面,你了解了用于纯TTY测试的 `nmdm(4)`、用于USB开发的QEMU USB重定向,以及一系列用户态工具(`cu`、`tip`、`stty`、`comcontrol`、`usbconfig`),这些工具使驱动程序开发即使没有持续硬件访问也变得可控。你看到驱动程序工作的大部分不是寄存器级别的搏斗,而是通过明确定义的抽象对数据流进行精心安排。 -The hands-on labs and challenge exercises gave you concrete problems to work on. Each lab is short enough to finish in a sitting, and each challenge extends one of the core ideas from the main text. +动手实验和挑战练习为你提供了具体的问题来解决。每个实验都足够短,可以一次完成,每个挑战都扩展了正文中的核心思想之一。 -Three habits from earlier chapters extended naturally into 第26章. The labelled-goto cleanup chain from 第25章 is the same pattern used in USB and UART 附加 routines. The softc-as-single-source-of-truth discipline from 第25章 is applied identically to USB and UART 驱动程序 state. The errno-returning helper function pattern is unchanged. What 第26章 added was transport-specific vocabulary and transport-specific abstractions built on top of those habits. +来自前几章的三个习惯自然地延伸到了第26章。第25章的标签化goto清理链与USB和UART附加例程中使用的模式相同。第25章的softc作为唯一真相来源的纪律同样应用于USB和UART驱动程序状态。返回errno的辅助函数模式保持不变。第26章新增的是传输专用词汇和建立在这些习惯之上的传输专用抽象。 -There is also a habit that 第26章 has introduced which will stay with you: the three-state 回调 state machine (`USB_ST_SETUP`, `USB_ST_TRANSFERRED`, `USB_ST_ERROR`). Every USB驱动程序 uses it. Learning to read this state machine is learning to read every USB 回调 in the tree. When you open `uftdi.c`, `ucycom.c`, `uchcom.c`, or any other USB驱动程序, you will see the same pattern. Recognising it is recognising the USB 框架's core abstraction. +第26章还引入了一个将伴随你的习惯:三状态回调状态机(`USB_ST_SETUP`、`USB_ST_TRANSFERRED`、`USB_ST_ERROR`)。每个USB驱动程序都使用它。学会阅读这个状态机就是学会阅读树中的每个USB回调。当你打开 `uftdi.c`、`ucycom.c`、`uchcom.c` 或任何其他USB驱动程序时,你会看到相同的模式。识别它就是识别USB框架的核心抽象。 -Transport-specific 驱动程序 are where the book's abstract 框架 concepts become concrete. From here on, every chapter in 第6部分 will deepen your practical skill with one more transport or one more kind of 内核 service. The New总线 foundation from Part 3, the character-设备 basics from Part 4, and the discipline themes from 第5部分 are all in play simultaneously. You are no longer learning concepts in isolation; you are using them together. +传输专用驱动程序是本书抽象框架概念变得具体的地方。从这里开始,第6部分中的每章都将通过更多一种传输或更多一种内核服务来深化你的实践技能。第3部分的New总线基础、第4部分的字符设备基础知识以及第5部分的纪律主题都在同时发挥作用。你不再孤立地学习概念;你将它们一起使用。 -## 通往第 27 +## 通往第27章 -第27章 turns to 网络驱动程序. Much of the structure will feel familiar: there is a New总线 附加ment, there is per-设备 state (called `if_softc` in 网络驱动程序), there is a 匹配表, there is a 探测-and-附加 sequence, there are 热插拔 considerations, and there is an integration with a higher 框架. But the higher 框架 here is `ifnet(9)`, the 接口-框架 abstraction for network 设备, and its idioms are different from those of USB and serial. +第27章转向网络驱动程序。许多结构会让人感到熟悉:有New总线附加、有每设备状态(在网络驱动程序中称为 `if_softc`)、有匹配表、有探测和附加序列、有热插拔考虑因素,以及与更高级框架的集成。但这里的高级框架是 `ifnet(9)`,即网络设备的接口框架抽象,其惯用法与USB和串行不同。 -A 网络驱动程序 does not expose a 字符设备. It exposes an 接口, which is visible to userland through `ifconfig(8)`, through `netstat -i`, and through the 套接字 layer. Instead of `read(2)` and `write(2)`, 网络驱动程序 handle 数据包 input and 数据包 output through the network stack's pipeline. Instead of `termios` for configuration, they handle `SIOCSIFFLAGS`, `SIOCADDMULTI`, `SIOCSIFMEDIA`, and a host of other network-specific ioctls. +网络驱动程序不暴露字符设备。它暴露接口,用户态可以通过 `ifconfig(8)`、`netstat -i` 和套接字层看到该接口。网络驱动程序不处理 `read(2)` 和 `write(2)`,而是通过网络栈的管道处理数据包输入和数据包输出。它们不通过 `termios` 进行配置,而是处理 `SIOCSIFFLAGS`、`SIOCADDMULTI`、`SIOCSIFMEDIA` 以及大量其他网络特定的ioctl。 -Many network cards also happen to use USB or PCIe as their underlying transport. A USB 以太网 adapter, for example, sits on USB (via `if_cdce` or a vendor-specific 驱动程序) and exposes an `ifnet(9)` 接口. A PCIe 以太网 card sits on PCIe and also exposes an `ifnet(9)` 接口. 第27章 will show how the same `ifnet(9)` 框架 sits on top of these very different transports, and how the separation lets you write a 驱动程序 that focuses on the 数据包-level protocol without worrying about the details of its transport. +许多网卡恰好也使用USB或PCIe作为其底层传输。例如,USB以太网适配器位于USB之上(通过 `if_cdce` 或厂商特定的驱动程序),并暴露 `ifnet(9)` 接口。PCIe以太网卡位于PCIe之上,也暴露 `ifnet(9)` 接口。第27章将展示相同的 `ifnet(9)` 框架如何位于这些非常不同的传输之上,以及这种分离如何让你编写专注于数据包级协议而无需担心传输细节的驱动程序。 -One specific thing to look forward to is the contrast between how USB delivers 数据包 (as transfer completions, one 缓冲区 at a time, with explicit 流控制 at the transfer level) and how PCIe-based network cards deliver 数据包 (as DMA-from-hardware events with 描述符 rings). The 数据包 pipeline in the network stack is designed to hide this difference from the upper layers, but a 驱动程序 author has to understand both models because they determine the 驱动程序's internal structure. +一个值得期待的具体事情是USB如何传递数据包(作为传输完成,一次一个缓冲区,在传输级别有明确的流控制)与基于PCIe的网卡如何传递数据包(作为来自硬件的DMA事件,使用描述符环)之间的对比。网络栈中的数据包管道旨在向上层隐藏这种差异,但驱动程序作者必须理解两种模型,因为它们决定了驱动程序的内部结构。 -第27章 will then turn to 块 设备驱动程序 (storage). That chapter will cover the GEOM 框架, which is FreeBSD's layered 块-设备 infrastructure. Block 驱动程序 have their own idioms: a different way of matching 设备, a different way of exposing state (through GEOM providers and consumers), and a fundamentally different data flow model (read and write operations on 扇区, with a strong consistency model). +第27章然后转向块设备驱动程序(存储)。那一章将涵盖GEOM框架,即FreeBSD的分层块设备基础设施。块驱动程序有自己的惯用法:不同的设备匹配方式、不同的状态暴露方式(通过GEOM提供者和消费者),以及根本不同的数据流模型(对扇区的读写操作,具有强一致性模型)。 -Parts 7, 8, and 9 then cover the more specialised topics: 内核 services and advanced 内核 idioms, debugging and testing in depth, and distribution and packaging. By the end of the book, you will have written and maintained 驱动程序 across several transport layers and several 内核 subsystems. The foundation you have built in Chapters 21 through 26 will be the common ground across all of that work. +第7、8和9部分然后涵盖更专业的主题:内核服务和高级内核惯用法、深入调试和测试,以及分发和打包。到本书结束时,你将在多个传输层和多个内核子系统上编写和维护驱动程序。你在第21章到第26章中建立的基础将是所有这些工作的共同基础。 -For now, keep your `myfirst_usb` 驱动程序. You will not extend it in later chapters, but the patterns it demonstrates will appear again in network, storage, and 内核-service contexts. Having your own working example on hand, something you wrote and understand completely, is a resource that pays back many times over as the book progresses. +现在,保留你的 `myfirst_usb` 驱动程序。你不会在后续章节中扩展它,但它展示的模式将再次出现在网络、存储和内核服务的上下文中。手头有你自己的工作示例,一些你编写并完全理解的东西,是一种随着书籍的进展而多次回报的资源。 ## 快速参考 -This reference collects the most important APIs, constants, and file locations from 第26章 into one place. Keep it open while writing or reading a 驱动程序; it is faster than rediscovering each name from the source tree. +本参考将第26章中最重要的API、常量和文件位置收集到一处。在编写或阅读驱动程序时保持打开;它比从源代码树中重新发现每个名称更快。 -### USB Driver APIs +### USB驱动程序API -| Function | Purpose | +| 函数 | 用途 | |----------|---------| -| `usbd_lookup_id_by_uaa(table, size, uaa)` | Match 附加 arg against 匹配表 | -| `usbd_transfer_setup(udev, &ifidx, xfer, config, n, priv, mtx)` | Allocate transfer channels | -| `usbd_transfer_unsetup(xfer, n)` | Free transfer channels | -| `usbd_transfer_submit(xfer)` | Queue a transfer for execution | -| `usbd_transfer_start(xfer)` | Activate a channel | -| `usbd_transfer_stop(xfer)` | Deactivate a channel | -| `usbd_transfer_pending(xfer)` | Query whether a transfer is outstanding | -| `usbd_transfer_drain(xfer)` | Wait for any pending transfer to complete | -| `usbd_xfer_softc(xfer)` | Retrieve the softc from a transfer | -| `usbd_xfer_status(xfer, &actlen, &sumlen, &a帧, &n帧)` | Query transfer results | -| `usbd_xfer_get_帧(xfer, i)` | Get page-cache pointer for 帧 i | -| `usbd_xfer_set_帧_len(xfer, i, len)` | Set length of 帧 i | -| `usbd_xfer_set_帧(xfer, n)` | Set total 帧 count | -| `usbd_xfer_max_len(xfer)` | Query max transfer length | -| `usbd_xfer_set_stall(xfer)` | Schedule clear-stall on this pipe | -| `usbd_copy_in(pc, offset, src, len)` | Copy into 框架 缓冲区 | -| `usbd_copy_out(pc, offset, dst, len)` | Copy out of 框架 缓冲区 | -| `usbd_errstr(err)` | Error code to string | -| `USB_GET_STATE(xfer)` | Current 回调 state | -| `USB_VPI(vendor, product, info)` | Compact 匹配表 entry | +| `usbd_lookup_id_by_uaa(table, size, uaa)` | 将附加参数与匹配表匹配 | +| `usbd_transfer_setup(udev, &ifidx, xfer, config, n, priv, mtx)` | 分配传输通道 | +| `usbd_transfer_unsetup(xfer, n)` | 释放传输通道 | +| `usbd_transfer_submit(xfer)` | 将传输排队等待执行 | +| `usbd_transfer_start(xfer)` | 激活通道 | +| `usbd_transfer_stop(xfer)` | 停用通道 | +| `usbd_transfer_pending(xfer)` | 查询传输是否正在进行 | +| `usbd_transfer_drain(xfer)` | 等待任何待处理传输完成 | +| `usbd_xfer_softc(xfer)` | 从传输中检索softc | +| `usbd_xfer_status(xfer, &actlen, &sumlen, &a帧, &n帧)` | 查询传输结果 | +| `usbd_xfer_get_帧(xfer, i)` | 获取帧i的页缓存指针 | +| `usbd_xfer_set_帧_len(xfer, i, len)` | 设置帧i的长度 | +| `usbd_xfer_set_帧(xfer, n)` | 设置总帧数 | +| `usbd_xfer_max_len(xfer)` | 查询最大传输长度 | +| `usbd_xfer_set_stall(xfer)` | 在此管道上安排清除停顿 | +| `usbd_copy_in(pc, offset, src, len)` | 复制到框架缓冲区 | +| `usbd_copy_out(pc, offset, dst, len)` | 从框架缓冲区复制出来 | +| `usbd_errstr(err)` | 将错误码转为字符串 | +| `USB_GET_STATE(xfer)` | 当前回调状态 | +| `USB_VPI(vendor, product, info)` | 紧凑的匹配表条目 | -### USB Transfer Types (`usb.h`) +### USB传输类型 (`usb.h`) -- `UE_CONTROL`: 控制传输 (request-response) -- `UE_ISOCHRONOUS`: isochronous (periodic, no retry) -- `UE_BULK`: bulk (reliable, no timing guarantee) -- `UE_INTERRUPT`: interrupt (periodic, reliable) +- `UE_CONTROL`: 控制传输(请求-响应) +- `UE_ISOCHRONOUS`: 等时传输(周期性,无重试) +- `UE_BULK`: 批量传输(可靠,无时序保证) +- `UE_INTERRUPT`: 中断传输(周期性,可靠) -### USB Transfer Direction +### USB传输方向 -- `UE_DIR_IN`: 设备 to host -- `UE_DIR_OUT`: host to 设备 -- `UE_ADDR_ANY`: 框架 picks any matching 端点 +- `UE_DIR_IN`: 设备到主机 +- `UE_DIR_OUT`: 主机到设备 +- `UE_ADDR_ANY`: 框架选择任何匹配的端点 -### USB Callback States (`usbdi.h`) +### USB回调状态 (`usbdi.h`) -- `USB_ST_SETUP`: ready to submit a new transfer -- `USB_ST_TRANSFERRED`: previous transfer succeeded -- `USB_ST_ERROR`: previous transfer failed +- `USB_ST_SETUP`: 准备提交新传输 +- `USB_ST_TRANSFERRED`: 前一次传输成功 +- `USB_ST_ERROR`: 前一次传输失败 -### USB Error Codes (`usbdi.h`) +### USB错误码 (`usbdi.h`) -- `USB_ERR_NORMAL_COMPLETION`: success -- `USB_ERR_PENDING_REQUESTS`: outstanding work -- `USB_ERR_NOT_STARTED`: transfer not started -- `USB_ERR_CANCELLED`: transfer cancelled (e.g., 分离) -- `USB_ERR_STALLED`: 端点 stalled -- `USB_ERR_TIMEOUT`: timeout expired -- `USB_ERR_SHORT_XFER`: received less data than requested -- `USB_ERR_NOMEM`: out of memory -- `USB_ERR_NO_PIPE`: no matching 端点 +- `USB_ERR_NORMAL_COMPLETION`: 成功 +- `USB_ERR_PENDING_REQUESTS`: 有未完成的工作 +- `USB_ERR_NOT_STARTED`: 传输未启动 +- `USB_ERR_CANCELLED`: 传输被取消(例如分离时) +- `USB_ERR_STALLED`: 端点停顿 +- `USB_ERR_TIMEOUT`: 超时已过期 +- `USB_ERR_SHORT_XFER`: 接收到的数据少于请求量 +- `USB_ERR_NOMEM`: 内存不足 +- `USB_ERR_NO_PIPE`: 没有匹配的端点 -### Registration Macros +### 注册宏 -- `DRIVER_MODULE(name, parent, 驱动程序, evh, arg)`: 注册 驱动程序 with 内核 -- `MODULE_DEPEND(name, dep, min, pref, max)`: declare module dependency -- `MODULE_VERSION(name, version)`: declare module version -- `USB_PNP_HOST_INFO(table)`: export 匹配表 to `devd` -- `DEVMETHOD(name, func)`: declare method in method table -- `DEVMETHOD_END`: terminate method table +- `DRIVER_MODULE(name, parent, 驱动程序, evh, arg)`: 在内核中注册驱动程序 +- `MODULE_DEPEND(name, dep, min, pref, max)`: 声明模块依赖 +- `MODULE_VERSION(name, version)`: 声明模块版本 +- `USB_PNP_HOST_INFO(table)`: 向 `devd` 导出匹配表 +- `DEVMETHOD(name, func)`: 在方法表中声明方法 +- `DEVMETHOD_END`: 终止方法表 -### UART Framework APIs +### UART框架API -| Function | Header | Purpose | +| 函数 | 头文件 | 用途 | |----------|--------|---------| -| `uart_getreg(bas, offset)` | `uart.h` | Read a UART 注册 | -| `uart_setreg(bas, offset, value)` | `uart.h` | Write a UART 注册 | -| `uart_barrier(bas)` | `uart.h` | Memory barrier for 注册 access | -| `uart_总线_探测(dev, regshft, regiowidth, rclk, rid, chan, quirks)` | `uart_总线.h` | Framework 探测 helper | -| `uart_总线_附加(dev)` | `uart_总线.h` | Framework 附加 helper | -| `uart_总线_分离(dev)` | `uart_总线.h` | Framework 分离 helper | +| `uart_getreg(bas, offset)` | `uart.h` | 读取UART寄存器 | +| `uart_setreg(bas, offset, value)` | `uart.h` | 写入UART寄存器 | +| `uart_barrier(bas)` | `uart.h` | 寄存器访问的内存屏障 | +| `uart_bus_probe(dev, regshft, regiowidth, rclk, rid, chan, quirks)` | `uart_bus.h` | 框架探测辅助函数 | +| `uart_bus_attach(dev)` | `uart_bus.h` | 框架附加辅助函数 | +| `uart_bus_detach(dev)` | `uart_bus.h` | 框架分离辅助函数 | -### `uart_ops` Methods +### `uart_ops` 方法 -- `探测(bas)`: chip present? -- `init(bas, baud, databits, stopbits, 奇偶校验)`: initialise chip -- `term(bas)`: shut down chip -- `putc(bas, c)`: send one character (polling) -- `rxready(bas)`: is data available? -- `getc(bas, mtx)`: read one character (polling) +- `probe(bas)`: 芯片是否存在? +- `init(bas, baud, databits, stopbits, parity)`: 初始化芯片 +- `term(bas)`: 关闭芯片 +- `putc(bas, c)`: 发送一个字符(轮询) +- `rxready(bas)`: 数据是否可用? +- `getc(bas, mtx)`: 读取一个字符(轮询) -### `ucom_回调` Methods +### `ucom_callback` 方法 -- `ucom_cfg_open`, `ucom_cfg_close`: open/close hooks -- `ucom_cfg_param`: termios changed -- `ucom_cfg_set_dtr`, `ucom_cfg_set_rts`, `ucom_cfg_set_break`, `ucom_cfg_set_ring`: signal control -- `ucom_cfg_get_status`: read line and modem status bytes -- `ucom_pre_open`, `ucom_pre_param`: validation hooks (return errno) -- `ucom_ioctl`: chip-specific ioctl handler -- `ucom_start_read`, `ucom_stop_read`: enable/disable read -- `ucom_start_write`, `ucom_stop_write`: enable/disable write -- `ucom_tty_name`: customise the TTY 设备-node name -- `ucom_poll`: poll for events -- `ucom_free`: final cleanup +- `ucom_cfg_open`, `ucom_cfg_close`: 打开/关闭钩子 +- `ucom_cfg_param`: termios已更改 +- `ucom_cfg_set_dtr`, `ucom_cfg_set_rts`, `ucom_cfg_set_break`, `ucom_cfg_set_ring`: 信号控制 +- `ucom_cfg_get_status`: 读取线路和调制解调器状态字节 +- `ucom_pre_open`, `ucom_pre_param`: 验证钩子(返回errno) +- `ucom_ioctl`: 芯片特定的ioctl处理程序 +- `ucom_start_read`, `ucom_stop_read`: 启用/禁用读取 +- `ucom_start_write`, `ucom_stop_write`: 启用/禁用写入 +- `ucom_tty_name`: 自定义TTY设备节点名称 +- `ucom_poll`: 轮询事件 +- `ucom_free`: 最终清理 -### Key Source Files +### 关键源文件 -- `/usr/src/sys/dev/usb/usb.h`: USB protocol definitions -- `/usr/src/sys/dev/usb/usbdi.h`: USB驱动程序 接口, `USB_ERR_*` codes -- `/usr/src/sys/dev/usb/usbdi_util.h`: convenience helpers -- `/usr/src/sys/dev/usb/usbdevs.h`: Vendor/product constants (build-generated by the FreeBSD build system from `/usr/src/sys/dev/usb/usbdevs`; not present in a clean source tree until the 内核 or 驱动程序 is built) -- `/usr/src/sys/dev/usb/controller/`: Host controller 驱动程序 -- `/usr/src/sys/dev/usb/misc/uled.c`: Simple LED 驱动程序 (reference) -- `/usr/src/sys/dev/usb/serial/uftdi.c`: FTDI 驱动程序 (reference) -- `/usr/src/sys/dev/usb/serial/usb_serial.h`: `ucom_回调` definition -- `/usr/src/sys/dev/usb/serial/usb_serial.c`: ucom 框架 +- `/usr/src/sys/dev/usb/usb.h`: USB协议定义 +- `/usr/src/sys/dev/usb/usbdi.h`: USB驱动程序接口, `USB_ERR_*` 错误码 +- `/usr/src/sys/dev/usb/usbdi_util.h`: 便利辅助函数 +- `/usr/src/sys/dev/usb/usbdevs.h`: 厂商/产品常量(由FreeBSD构建系统从 `/usr/src/sys/dev/usb/usbdevs` 构建生成;在干净源代码树中不存在,直到内核或驱动程序被构建) +- `/usr/src/sys/dev/usb/controller/`: 主机控制器驱动程序 +- `/usr/src/sys/dev/usb/misc/uled.c`: 简单LED驱动程序(参考) +- `/usr/src/sys/dev/usb/serial/uftdi.c`: FTDI驱动程序(参考) +- `/usr/src/sys/dev/usb/serial/usb_serial.h`: `ucom_callback` 定义 +- `/usr/src/sys/dev/usb/serial/usb_serial.c`: ucom框架 - `/usr/src/sys/dev/uart/uart.h`: `uart_getreg`, `uart_setreg`, `uart_barrier` -- `/usr/src/sys/dev/uart/uart_总线.h`: `uart_class`, `uart_softc`, 总线 helpers -- `/usr/src/sys/dev/uart/uart_cpu.h`: `uart_ops`, CPU-side glue -- `/usr/src/sys/dev/uart/uart_core.c`: UART 框架 body -- `/usr/src/sys/dev/uart/uart_tty.c`: UART-TTY integration -- `/usr/src/sys/dev/uart/uart_dev_ns8250.c`: ns8250 reference 驱动程序 -- `/usr/src/sys/dev/ic/ns16550.h`: 16550 注册 definitions -- `/usr/src/sys/dev/nmdm/nmdm.c`: null-modem 驱动程序 +- `/usr/src/sys/dev/uart/uart_bus.h`: `uart_class`, `uart_softc`, 总线辅助函数 +- `/usr/src/sys/dev/uart/uart_cpu.h`: `uart_ops`, CPU侧胶水代码 +- `/usr/src/sys/dev/uart/uart_core.c`: UART框架主体 +- `/usr/src/sys/dev/uart/uart_tty.c`: UART-TTY集成 +- `/usr/src/sys/dev/uart/uart_dev_ns8250.c`: ns8250参考驱动程序 +- `/usr/src/sys/dev/ic/ns16550.h`: 16550寄存器定义 +- `/usr/src/sys/dev/nmdm/nmdm.c`: 空调制解调器驱动程序 -### Userland Diagnostic Commands +### 用户态诊断命令 -| Command | Purpose | +| 命令 | 用途 | |---------|---------| -| `usbconfig list` | List USB 设备 | -| `usbconfig -d ugenN.M dump_all_config_desc` | Dump 描述符 | -| `usbconfig -d ugenN.M dump_stats` | Transfer statistics | -| `usbconfig -d ugenN.M reset` | Reset 设备 | -| `stty -a -f /dev/设备` | Show termios settings | -| `stty 115200 -f /dev/设备` | Set 波特率 | -| `comcontrol /dev/设备` | Show modem signals | -| `cu -l /dev/设备 -s speed` | Interactive session | -| `tip name` | Named connection (via `/etc/remote`) | -| `kldload mod.ko` | Load 内核模块 | -| `kldunload mod` | Unload 内核模块 | -| `kldstat` | List loaded modules | -| `dmesg -w` | Stream 内核 messages | -| `sysctl hw.usb.*` | Query USB 框架 | -| `sysctl dev.uart.*` | Query UART instances | +| `usbconfig list` | 列出USB设备 | +| `usbconfig -d ugenN.M dump_all_config_desc` | 转储描述符 | +| `usbconfig -d ugenN.M dump_stats` | 传输统计信息 | +| `usbconfig -d ugenN.M reset` | 重置设备 | +| `stty -a -f /dev/设备` | 显示termios设置 | +| `stty 115200 -f /dev/设备` | 设置波特率 | +| `comcontrol /dev/设备` | 显示调制解调器信号 | +| `cu -l /dev/设备 -s speed` | 交互式会话 | +| `tip name` | 命名连接(通过 `/etc/remote`) | +| `kldload mod.ko` | 加载内核模块 | +| `kldunload mod` | 卸载内核模块 | +| `kldstat` | 列出已加载模块 | +| `dmesg -w` | 流式传输内核消息 | +| `sysctl hw.usb.*` | 查询USB框架 | +| `sysctl dev.uart.*` | 查询UART实例 | -### Standard Development Flags +### 标准开发选项 -Debug-mode 内核 options to enable during development: -- `options INVARIANTS`: assertion checking -- `options INVARIANT_SUPPORT`: required alongside INVARIANTS -- `options WITNESS`: lock order checking -- `options WITNESS_SKIPSPIN`: skip spin locks in WITNESS (perf) -- `options WITNESS_CHECKORDER`: verify every lock acquisition -- `options DDB`: 内核 debugger -- `options KDB`: 内核 debugger support -- `options USB_DEBUG`: extensive USB logging +开发期间应启用的调试模式内核选项: +- `options INVARIANTS`: 断言检查 +- `options INVARIANT_SUPPORT`: 与INVARIANTS一同需要 +- `options WITNESS`: 锁顺序检查 +- `options WITNESS_SKIPSPIN`: 在WITNESS中跳过自旋锁(性能) +- `options WITNESS_CHECKORDER`: 验证每次锁获取 +- `options DDB`: 内核调试器 +- `options KDB`: 内核调试器支持 +- `options USB_DEBUG`: 广泛的USB日志记录 -These options should be enabled on development machines, not production. +这些选项应在开发机器上启用,而不是生产环境。 ## 术语表 -The following terms appeared in this chapter. Some are new; others were introduced earlier and are repeated here for convenience. Definitions are brief and intended as a quick reminder, not as a replacement for the main-text explanations. +以下术语出现在本章中。有些是新术语;其他在之前已介绍过,为方便起见在此重复。定义简洁明了,旨在作为快速提醒,而非替代正文中的解释。 -**Address (USB).** A number from 1 to 127 that the host assigns to a 设备 during enumeration. Each physical 设备 on a 总线 has a unique address. +**Address (地址,USB)。** 主机在枚举期间分配给设备的1到127之间的数字。总线上的每个物理设备都有唯一地址。 -**Attach.** The 框架-called method where a 驱动程序 takes ownership of a newly discovered 设备, allocates resources, initialises state, and begins operation. Paired with `分离`. +**Attach (附加)。** 框架调用的方法,驱动程序在此获取新发现设备的所有权、分配资源、初始化状态并开始操作。与 `分离` 配对。 -**Bulk transfer.** A USB transfer type designed for reliable, high-throughput, non-time-critical data. Used for mass storage, printers, network adapters. +**Bulk transfer (批量传输)。** 一种USB传输类型,专为可靠、高吞吐量、非时间关键的数据设计。用于大容量存储、打印机、网络适配器。 -**Callout.** A FreeBSD mechanism for scheduling a function to run after a specific delay. Used by 驱动程序 for timeouts and periodic tasks. +**Callout (超时回调)。** FreeBSD的一种机制,用于在特定延迟后调度函数运行。驱动程序用于超时和周期性任务。 -**Callin node.** A TTY 设备 node (usually `/dev/ttyuN`) where opening 块 until carrier detect is asserted. Historically used for answering incoming modem calls. +**Callin node (呼入节点)。** TTY设备节点(通常是 `/dev/ttyuN`),打开时会阻塞直到载波检测信号有效。历史上用于应答传入的调制解调器呼叫。 -**Callout node.** A TTY 设备 node (usually `/dev/cuauN`) where opening does not wait for carrier detect. Used for initiating connections or for non-modem 设备. +**Callout node (呼出节点)。** TTY设备节点(通常是 `/dev/cuauN`),打开时不等待载波检测。用于发起连接或非调制解调器设备。 -**CDC ACM.** Communication Device Class, Abstract Control Model. The USB standard for virtual 串行端口s. Handled in FreeBSD by the `u3g` 驱动程序. +**CDC ACM。** 通信设备类,抽象控制模型。虚拟串行端口的USB标准。在FreeBSD中由 `u3g` 驱动程序处理。 -**Character 设备.** A UNIX 设备 abstraction for byte-oriented 设备. Exposed to userland through `/dev` entries. Introduced in Chapter 24. +**Character device (字符设备)。** UNIX中面向字节设备的设备抽象。通过 `/dev` 条目向用户态暴露。在第24章介绍。 -**Class 驱动程序.** A USB驱动程序 that handles an entire class of 设备 (all HID 设备, all mass-storage 设备) rather than a single vendor's product. Matches on 接口 class/subclass/protocol. +**Class driver (类驱动程序)。** 处理整个设备类别(所有HID设备、所有大容量存储设备)而非单个厂商产品的USB驱动程序。通过接口类/子类/协议进行匹配。 -**Clear-stall.** A USB operation that clears a stall condition on an 端点. Handled by the FreeBSD USB 框架 when `usbd_xfer_set_stall` is called. +**Clear-stall (清除停顿)。** 清除端点上停顿条件的USB操作。当调用 `usbd_xfer_set_stall` 时由FreeBSD USB框架处理。 -**Configuration (USB).** A named set of 接口 and 端点 a USB 设备 can expose. A 设备 usually has one configuration but may have several. +**Configuration (配置,USB)。** USB设备可以暴露的一组命名的接口和端点。设备通常有一个配置,但可能有多个。 -**Control transfer.** A USB transfer type designed for small, infrequent, request-response exchanges. Used for configuration and status. +**Control transfer (控制传输)。** 一种USB传输类型,专为小规模、不频繁的请求-响应交换设计。用于配置和状态。 -**`cuau`.** Naming prefix for the callout-side TTY 设备 of a 总线-附加ed UART. Example: `/dev/cuau0`. +**`cuau`。** 总线附加的UART的呼出端TTY设备的命名前缀。示例:`/dev/cuau0`。 -**`cuaU`.** Naming prefix for the callout-side TTY 设备 of a USB-provided 串行端口. Example: `/dev/cuaU0`. +**`cuaU`。** USB提供的串行端口的呼出端TTY设备的命名前缀。示例:`/dev/cuaU0`。 -**Descriptor (USB).** A small data structure a USB 设备 provides, describing itself or one of its components. Types include 设备, configuration, 接口, 端点, and string 描述符. +**Descriptor (描述符,USB)。** USB设备提供的小型数据结构,描述自身或其组件之一。类型包括设备、配置、接口、端点和字符串描述符。 -**Detach.** The 框架-called method where a 驱动程序 releases all resources and prepares for the 设备 to vanish. Paired with `附加`. +**Detach (分离)。** 框架调用的方法,驱动程序在此释放所有资源并为设备消失做准备。与 `附加` 配对。 -**`devd`.** The FreeBSD 设备-event daemon that reacts to 内核 notifications about 设备 附加 and 分离. Responsible for auto-loading modules for newly-discovered 设备. +**`devd`。** FreeBSD设备事件守护进程,响应内核关于设备附加和分离的通知。负责为新发现的设备自动加载模块。 -**Device (USB).** A single physical USB peripheral connected to a port. Contains one or more configurations. +**Device (设备,USB)。** 连接到端口的单个物理USB外设。包含一个或多个配置。 -**DMA.** Direct Memory Access. A mechanism where hardware can read or write memory without CPU involvement. Used by high-performance USB 主机控制器s and PCIe network cards. +**DMA。** 直接内存访问。硬件无需CPU参与即可读写内存的机制。由高性能USB主机控制器和PCIe网卡使用。 -**Echo loopback.** A test configuration in which a 设备 echoes whatever it receives, used to validate bidirectional data flow. +**Echo loopback (回环)。** 一种测试配置,设备回显其收到的任何内容,用于验证双向数据流。 -**Endpoint.** A USB communication channel within an 接口. Each 端点 has a direction (IN or OUT) and a transfer type. Matches one hardware FIFO on the 设备. +**Endpoint (端点)。** 接口内的USB通信通道。每个端点有方向(IN或OUT)和传输类型。匹配设备上的一个硬件FIFO。 -**Enumeration.** The USB process by which a newly 附加ed 设备 is discovered, assigned an address, and has its 描述符 read by the host. +**Enumeration (枚举)。** USB过程,新附加的设备被发现、分配地址,并由主机读取其描述符。 -**FIFO (hardware).** A small 缓冲区 on a UART or USB chip that holds bytes during transfer. Typical 16550 FIFO is 16 bytes; many modern UARTs have 64 or 128. +**FIFO (硬件)。** UART或USB芯片上的小型缓冲区,在传输期间保存字节。典型的16550 FIFO为16字节;许多现代UART有64或128字节。 -**FTDI.** A company that makes popular USB-to-serial adapter chips. Drivers for FTDI chips are in `/usr/src/sys/dev/usb/serial/uftdi.c`. +**FTDI。** 一家制造流行的USB转串口适配器芯片的公司。FTDI芯片的驱动程序在 `/usr/src/sys/dev/usb/serial/uftdi.c` 中。 -**`ifnet(9)`.** The FreeBSD 框架 for network 设备驱动程序. Covered in 第27章. +**`ifnet(9)`。** FreeBSD的网络设备驱动程序框架。在第27章中介绍。 -**Interface (USB).** A logical grouping of 端点 within a USB 设备. A multi-function 设备 can expose multiple 接口. +**Interface (接口,USB)。** USB设备内端点的逻辑分组。多功能设备可以暴露多个接口。 -**Interrupt handler.** A function the 内核 runs in response to a hardware interrupt. In the UART context, the 框架 provides a default 中断处理程序. +**Interrupt handler (中断处理程序)。** 内核响应硬件中断而运行的函数。在UART上下文中,框架提供了默认的中断处理程序。 -**Interrupt transfer.** A USB transfer type designed for low-bandwidth, periodic, latency-critical data. Used for keyboards, mice, HIDs. +**Interrupt transfer (中断传输)。** 一种USB传输类型,专为低带宽、周期性、延迟关键的数据设计。用于键盘、鼠标、HID设备。 -**Isochronous transfer.** A USB transfer type designed for real-time streams with guaranteed bandwidth but no delivery guarantee. Used for audio and video. +**Isochronous transfer (等时传输)。** 一种USB传输类型,专为实时流设计,保证带宽但不保证交付。用于音频和视频。 -**`kldload`, `kldunload`.** FreeBSD commands for loading and unloading 内核模块. +**`kldload`, `kldunload`。** 用于加载和卸载内核模块的FreeBSD命令。 -**`kobj`.** FreeBSD's object-oriented 内核 框架. Used for method dispatch in New总线 and other subsystems. +**`kobj`。** FreeBSD的面向对象内核框架。用于New总线和其他子系统中的方法分发。 -**Match table.** An array of `STRUCT_USB_HOST_ID` (for USB) or equivalent entries that a 驱动程序 uses to declare which 设备 it supports. +**Match table (匹配表)。** `STRUCT_USB_HOST_ID`(对于USB)或等效条目的数组,驱动程序用于声明其支持的设备。 -**Modem control 注册 (MCR).** A 16550 注册 that controls modem output signals (DTR, RTS). +**Modem control register (调制解调器控制寄存器,MCR)。** 控制调制解调器输出信号(DTR、RTS)的16550寄存器。 -**Modem status 注册 (MSR).** A 16550 注册 that reports modem input signals (CTS, DSR, CD, RI). +**Modem status register (调制解调器状态寄存器,MSR)。** 报告调制解调器输入信号(CTS、DSR、CD、RI)的16550寄存器。 -**`nmdm(4)`.** FreeBSD's null-modem 驱动程序. Creates pairs of linked virtual TTYs for testing. Loaded with `kldload nmdm`. +**`nmdm(4)`。** FreeBSD的空调制解调器驱动程序。创建一对链接的虚拟TTY用于测试。使用 `kldload nmdm` 加载。 -**ns8250.** A canonical 16550-compatible UART 驱动程序 for FreeBSD. At `/usr/src/sys/dev/uart/uart_dev_ns8250.c`. +**ns8250。** FreeBSD的规范16550兼容UART驱动程序。位于 `/usr/src/sys/dev/uart/uart_dev_ns8250.c`。 -**Pipe.** A term for a bidirectional USB transfer channel from the host's perspective. A host has one pipe per 端点. +**Pipe (管道)。** 从主机的角度表示双向USB传输通道的术语。每个端点主机有一个管道。 -**Port (USB).** A downstream 附加ment point on a hub. Each port can have one 设备 (which may itself be a hub). +**Port (端口,USB)。** 集线器上的下游连接点。每个端口可以有一个设备(其本身可能是一个集线器)。 -**Probe.** The 框架-called method where a 驱动程序 examines a candidate 设备 and decides whether to 附加. Returns zero for a match, nonzero errno for a reject. +**Probe (探测)。** 框架调用的方法,驱动程序在此检查候选设备并决定是否附加。匹配时返回零,拒绝时返回非零errno。 -**Probe-and-附加.** The two-phase handshake by which New总线 binds 驱动程序 to 设备. Probe tests the match; 附加 does the work. +**Probe-and-attach (探测和附加)。** New总线将驱动程序绑定到设备的两阶段握手。探测测试匹配;附加执行工作。 -**Retry policy.** A 驱动程序's rule for what to do when a transfer fails. Common policies: rearm on every error, rearm up to N times then give up, rearm only for specific errors. +**Retry policy (重试策略)。** 驱动程序在传输失败时采取的动作规则。常见策略:每次错误都重新准备、重试N次后放弃、仅对特定错误重新准备。 -**Ring 缓冲区.** A fixed-size circular 缓冲区 used by the UART 框架 to 缓冲区 data between the chip and the TTY layer. +**Ring buffer (环形缓冲区)。** UART框架使用的固定大小循环缓冲区,用于在芯片和TTY层之间缓冲数据。 -**RTS/CTS.** Request To Send / Clear To Send. Hardware flow-control signals on a 串行端口. +**RTS/CTS。** 请求发送/清除发送。串行端口上的硬件流控制信号。 -**Softc.** The per-设备 state a 驱动程序 maintains. Named after "software context" by analogy with hardware 注册 state. +**Softc。** 驱动程序维护的每设备状态。名称源自"software context"(软件上下文),与硬件寄存器状态类似。 -**Stall (USB).** A signal from a USB 端点 that it is not ready to accept more data until explicitly cleared by the host. +**Stall (停顿,USB)。** USB端点发出的信号,表示在主机显式清除之前无法接受更多数据。 -**`stty(1)`.** Userland utility for inspecting and changing TTY settings. Maps directly onto `termios` fields. +**`stty(1)`。** 用于检查和更改TTY设置的用户态工具。直接映射到 `termios` 字段。 -**Taskqueue.** A FreeBSD mechanism for deferring work to a worker thread. Used by 驱动程序 that need to do something that cannot run in an interrupt context. +**Taskqueue。** FreeBSD用于将工作延迟到工作者线程的机制。由需要执行无法在中断上下文中运行的操作的驱动程序使用。 -**`termios`.** A POSIX structure that describes a TTY's configuration: 波特率, 奇偶校验, 流控制, line discipline flags, and many others. Set and queried by `tcsetattr(3)` and `tcgetattr(3)` from userland, or by `stty(1)`. +**`termios`。** 描述TTY配置的POSIX结构:波特率、奇偶校验、流控制、线路规程标志等。由用户态的 `tcsetattr(3)` 和 `tcgetattr(3)` 或 `stty(1)` 设置和查询。 -**Transfer (USB).** A single logical operation on a USB channel. Can be a single 数据包 or many. +**Transfer (传输,USB)。** USB通道上的单个逻辑操作。可以是单个数据包或多个数据包。 -**TTY.** Teletype. The UNIX abstraction for a serial 设备. Character-at-a-time I/O, line discipline, signal generation, terminal control. +**TTY。** 电传打字机。UNIX中串行设备的抽象。逐字符I/O、线路规程、信号生成、终端控制。 -**`ttydevsw`.** The structure a TTY 驱动程序 uses to 注册 its operations with the TTY layer. Analogous to `cdevsw` for 字符设备. +**`ttydevsw`。** TTY驱动程序用于向TTY层注册其操作的结构。类似于字符设备的 `cdevsw`。 -**`ttyu`.** Naming prefix for the callin-side TTY 设备 of a 总线-附加ed UART. Example: `/dev/ttyu0`. +**`ttyu`。** 总线附加的UART的呼入端TTY设备的命名前缀。示例:`/dev/ttyu0`。 -**`uart(4)`.** FreeBSD's 框架 for UART 驱动程序. Handles registration, 缓冲区ing, TTY integration. Drivers implement `uart_ops` hardware methods. +**`uart(4)`。** FreeBSD的UART驱动程序框架。处理注册、缓冲、TTY集成。驱动程序实现 `uart_ops` 硬件方法。 -**`uart_bas`.** "UART Bus Access Structure." The 框架's abstraction for 注册 access to a UART, hiding whether the 寄存器 are in I/O space or memory-mapped. +**`uart_bas`。** "UART总线访问结构。"框架对UART寄存器访问的抽象,隐藏寄存器是在I/O空间还是内存映射中。 -**`uart_class`.** The 框架 描述符 that identifies a UART chip family. Pairs with `uart_ops` to give the 框架 everything it needs. +**`uart_class`。** 标识UART芯片系列的框架描述符。与 `uart_ops` 配对,为框架提供所需的一切。 -**`uart_ops`.** The table of six hardware-specific methods (`探测`, `init`, `term`, `putc`, `rxready`, `getc`) that a UART 驱动程序 implements. +**`uart_ops`。** UART驱动程序实现的六个硬件特定方法(`probe`、`init`、`term`、`putc`、`rxready`、`getc`)的表格。 -**`ucom(4)`.** FreeBSD's 框架 for USB-to-serial 设备驱动程序. Sits on top of USB transfers, provides TTY integration. +**`ucom(4)`。** FreeBSD的USB转串口设备驱动程序框架。位于USB传输之上,提供TTY集成。 -**`ucom_回调`.** The structure a `ucom(4)` client uses to 注册 its 回调 with the 框架. +**`ucom_callback`。** `ucom(4)` 客户端用于向框架注册其回调的结构。 -**`ugen(4)`.** FreeBSD's generic USB驱动程序. Exposes raw USB access through `/dev/ugenN.M` for userland programs. Used when no specific 驱动程序 matches. +**`ugen(4)`。** FreeBSD的通用USB驱动程序。通过 `/dev/ugenN.M` 为用户态程序暴露原始USB访问。用于没有特定驱动程序匹配时。 -**`uhub`.** The FreeBSD 驱动程序 for USB hubs (including the root hub). A class 驱动程序 附加 to `uhub`, not to the USB 总线 directly. +**`uhub`。** FreeBSD的USB集线器驱动程序(包括根集线器)。附加到 `uhub` 的类驱动程序,而非直接附加到USB总线。 -**`usbconfig(8)`.** Userland utility for inspecting and controlling USB 设备. Can dump 描述符, reset 设备, enumerate state. +**`usbconfig(8)`。** 用于检查和控制USB设备的用户态工具。可以转储描述符、重置设备、枚举状态。 -**`usb_config`.** A C structure a USB驱动程序 uses to declare each of its transfer channels: type, 端点, direction, 缓冲区 size, flags, 回调. +**`usb_config`。** USB驱动程序用于声明其每个传输通道的C结构:类型、端点、方向、缓冲区大小、标志、回调。 -**`usb_fifo`.** A USB 框架 abstraction for byte-stream `/dev` nodes. Generic alternative to writing a custom `cdevsw`. +**`usb_fifo`。** USB框架对字节流 `/dev` 节点的抽象。编写自定义 `cdevsw` 的通用替代方案。 -**`usb_template(4)`.** FreeBSD's USB 设备-side (gadget) 框架. Used on hardware that can act as both USB host and USB 设备. +**`usb_template(4)`。** FreeBSD的USB设备端(gadget)框架。用于可以同时充当USB主机和USB设备的硬件。 -**`usb_xfer`.** An opaque structure representing a single USB transfer channel. Allocated by `usbd_transfer_setup`, freed by `usbd_transfer_unsetup`. +**`usb_xfer`。** 表示单个USB传输通道的不透明结构。由 `usbd_transfer_setup` 分配,由 `usbd_transfer_unsetup` 释放。 -**`usbd_copy_in`, `usbd_copy_out`.** Helpers for copying data between plain C 缓冲区 and USB 框架 缓冲区. Must be used instead of direct pointer access. +**`usbd_copy_in`, `usbd_copy_out`。** 在普通C缓冲区和USB框架缓冲区之间复制数据的辅助函数。必须使用而非直接指针访问。 -**`usbd_lookup_id_by_uaa`.** Framework helper that compares a USB 附加 argument against a 匹配表 and returns zero on match. +**`usbd_lookup_id_by_uaa`。** 将USB附加参数与匹配表比较并在匹配时返回零的框架辅助函数。 -**`usbd_transfer_setup`, `_unsetup`.** The calls that allocate and free transfer channels. Called from `附加` and `分离` respectively. +**`usbd_transfer_setup`, `_unsetup`。** 分配和释放传输通道的调用。分别从 `附加` 和 `分离` 中调用。 -**`usbd_transfer_submit`.** The call that hands a transfer to the 框架 for execution on the hardware. +**`usbd_transfer_submit`。** 将传输交给框架在硬件上执行的调用。 -**`usbd_transfer_start`, `_stop`.** The calls that activate or deactivate a channel. Activate triggers a 回调 in `USB_ST_SETUP`; deactivate cancels in-flight transfers. +**`usbd_transfer_start`, `_stop`。** 激活或停用通道的调用。激活在 `USB_ST_SETUP` 中触发回调;停用取消正在进行的传输。 -**`USB_ST_SETUP`, `_TRANSFERRED`, `_ERROR`.** The three states of a USB 传输回调, as returned by `USB_GET_STATE(xfer)`. +**`USB_ST_SETUP`, `_TRANSFERRED`, `_ERROR`。** USB传输回调的三种状态,由 `USB_GET_STATE(xfer)` 返回。 -**`USB_ERR_CANCELLED`.** The error code the 框架 passes to a 回调 when a transfer is being torn down (typically during 分离). +**`USB_ERR_CANCELLED`。** 传输被拆除时(通常在分离期间)框架传递给回调的错误码。 -**`USB_ERR_STALLED`.** The error code when a USB 端点 returns a STALL handshake. Usually handled by calling `usbd_xfer_set_stall`. +**`USB_ERR_STALLED`。** USB端点返回STALL握手时的错误码。通常通过调用 `usbd_xfer_set_stall` 处理。 -**VID/PID.** Vendor ID / Product ID. A pair of 16-bit numbers that uniquely identifies a USB 设备 model. +**VID/PID。** 厂商ID/产品ID。唯一标识USB设备型号的一对16位数字。 -**`WITNESS`.** A FreeBSD 内核 debugging option that tracks lock acquisition order and warns about violations. +**`WITNESS`。** FreeBSD的内核调试选项,跟踪锁获取顺序并警告违规。 -**Callin 设备.** A TTY 设备 (named `/dev/ttyuN` or `/dev/ttyUN`) that 块 on open until the modem's carrier detect (CD) signal is asserted. Used by programs that accept incoming calls. +**Callin device (呼入设备)。** TTY设备(名为 `/dev/ttyuN` 或 `/dev/ttyUN`),打开时会阻塞直到调制解调器的载波检测(CD)信号有效。由接受传入呼叫的程序使用。 -**Callout 设备.** A TTY 设备 (named `/dev/cuauN` or `/dev/cuaUN`) that opens immediately without waiting for carrier detect. Used by programs that initiate connections. +**Callout device (呼出设备)。** TTY设备(名为 `/dev/cuauN` 或 `/dev/cuaUN`),立即打开而不等待载波检测。由发起连接的程序使用。 -**`comcontrol(8)`.** Userland utility for controlling TTY options (drain behaviour, DTR, 流控制) that are not exposed through `stty`. +**`comcontrol(8)`。** 用于控制TTY选项(排空行为、DTR、流控制)的用户态工具,这些选项不通过 `stty` 暴露。 -**Descriptor (USB).** A data structure that a USB 设备 returns when the host asks for its identity, configuration, 接口, or 端点. Hierarchical: 设备 描述符 contains configuration 描述符; configurations contain 接口; 接口 contain 端点. +**Descriptor (描述符,USB)。** USB设备在主机询问其标识、配置、接口或端点时返回的数据结构。层次结构:设备描述符包含配置描述符;配置包含接口;接口包含端点。 -**Endpoint (USB).** A named, typed communication channel inside a USB 设备. Has an address (1 through 15), a direction (IN or OUT), a type (control, bulk, interrupt, isochronous), and a maximum 数据包 size. +**Endpoint (端点,USB)。** USB设备内部命名的、类型化的通信通道。有地址(1到15)、方向(IN或OUT)、类型(控制、批量、中断、等时)和最大数据包大小。 -**Line discipline.** The TTY layer's pluggable layer between the 驱动程序 and userland. Standard disciplines include `termios` (canonical and raw modes). Line disciplines translate between raw bytes and the behaviour a user program expects. +**Line discipline (线路规程)。** TTY层在驱动程序和用户态之间的可插拔层。标准规程包括 `termios`(规范模式和原始模式)。线路规程在原始字节和用户程序期望的行为之间进行转换。 -**`msleep(9)`.** The 内核 sleep primitive used to 块 a thread on a channel with a 互斥锁 held. Paired with `wakeup(9)`, it implements producer-consumer patterns inside 驱动程序. +**`msleep(9)`。** 内核睡眠原语,用于在持有互斥锁的情况下将线程阻塞在通道上。与 `wakeup(9)` 配对,在驱动程序内部实现生产者-消费者模式。 -**`mtx_sleep`.** A synonym for `msleep` used in some parts of the tree. Functionally identical. +**`mtx_sleep`。** 树中某些部分使用的 `msleep` 的同义词。功能上相同。 -**Open/close pair.** The 字符设备 methods `d_open` and `d_close`. Every 驱动程序 that exposes a `/dev` node must handle these. Opens are usually where channels are started; closes are usually where channels are stopped. +**Open/close pair (打开/关闭对)。** 字符设备方法 `d_open` 和 `d_close`。每个暴露 `/dev` 节点的驱动程序必须处理这些。打开通常是启动通道的地方;关闭通常是停止通道的地方。 -**Short transfer.** A USB transfer that completes with fewer bytes than requested. Normal for bulk IN (where the 设备 sends a short 数据包 to signal "end of message") and for interrupt IN (where the 设备 sends a short 数据包 when it has less data than the maximum). Always check `actlen`. +**Short transfer (短传输)。** 以少于请求的字节数完成的USB传输。对于批量IN(设备发送短数据包以表示"消息结束")和中断IN(设备在数据少于最大值时发送短数据包)是正常的。始终检查 `actlen`。 -**`USETW`.** A FreeBSD macro for setting a little-endian 16-bit field inside a USB 描述符 缓冲区. The USB wire format is always little-endian, so `USETW` hides the byte-swap. +**`USETW`。** FreeBSD的宏,用于在USB描述符缓冲区中设置小端16位字段。USB线路格式始终是小端,因此 `USETW` 隐藏了字节交换。 -This glossary is not exhaustive; it covers the terms this chapter actually used. For a broader FreeBSD USB reference, the `usbdi(9)` manual page is the definitive source. For the UART 框架, the source in `/usr/src/sys/dev/uart/` is the reference. When you encounter an unfamiliar term in either place, check here first; if not defined, go to the source. +本术语表并非详尽无遗;它涵盖了本章实际使用的术语。对于更广泛的FreeBSD USB参考,`usbdi(9)` 手册页是权威来源。对于UART框架,`/usr/src/sys/dev/uart/` 中的源代码是参考。当你在这两者中的任一处遇到不熟悉的术语时,先在这里查找;如果未定义,则查看源代码。 -### A Closing Note on Terminology Precision +### 关于术语精度的结束语 -One last piece of advice on vocabulary. The USB, TTY, and FreeBSD communities each have their own careful distinctions between terms that sound like synonyms. Confusing these in conversation with more experienced developers is a quick way to sound unsure; using them precisely is a quick way to sound at home. +关于词汇的最后一条建议。USB、TTY和FreeBSD社区各自对听起来像同义词的术语有谨慎的区分。在与更有经验的开发者交流时混淆这些术语是显得不确定的快速方式;而精确地使用它们则是显得熟练的快速方式。 -"Device" in the USB context means the whole USB peripheral (the keyboard, the mouse, the serial adapter). "Interface" means a logical grouping of 端点 inside the 设备. An 接口 implements one function; a 设备 can have multiple 接口. When you say "the USB 设备 is a composite 设备," you are saying it has multiple 接口. +"Device"(设备)在USB上下文中指整个USB外设(键盘、鼠标、串行适配器)。"Interface"(接口)指设备内端点的逻辑分组。一个接口实现一个功能;一个设备可以有多个接口。当你说"USB设备是复合设备"时,你是在说它有多个接口。 -"Endpoint" and "pipe" are related but distinct. An 端点 is on the 设备; a pipe is the host's view of a connection to that 端点. In FreeBSD 驱动程序 code, the term "transfer channel" is often used in place of "pipe," because "pipe" overloads a more common meaning in UNIX. +"Endpoint"(端点)和"pipe"(管道)相关但不同。端点在设备上;管道是主机对该端点连接的视图。在FreeBSD驱动程序代码中,术语"transfer channel"(传输通道)常用来替代"pipe",因为"pipe"在UNIX中重载了更常见的含义。 -"Transfer" and "transaction" are also distinct. A transfer is a logical operation (a read request for N bytes); a transaction is the USB-level 数据包 exchange that realises it. A 批量传输 of 64 bytes to an 端点 with a maximum 数据包 size of 64 is one transfer and one transaction. A 批量传输 of 512 bytes to the same 端点 is one transfer and eight transactions. +"Transfer"(传输)和"transaction"(事务)也不同。传输是逻辑操作(对N字节的读取请求);事务是实现它的USB级数据包交换。对最大数据包大小为64的端点进行64字节的批量传输是一次传输和一次事务。对同一端点进行512字节的批量传输是一次传输和八次事务。 -"UART" and "串行端口" are closely related but not identical. A UART is the chip (or the chip's logic 块); a 串行端口 is the physical connector and its wiring. One UART can back multiple 串行端口s in some configurations; one 串行端口 is always backed by exactly one UART. +"UART"和"串行端口"密切相关但不相同。UART是芯片(或芯片的逻辑块);串行端口是物理连接器及其布线。在某些配置中,一个UART可以支持多个串行端口;一个串行端口总是恰好由一个UART支持。 -"TTY" and "terminal" are related. A TTY is the 内核 abstraction for character-at-a-time I/O; a terminal is the userland view. A TTY has a controlling terminal property; a terminal has a TTY that it uses. In 驱动程序 code, TTY is almost always the more precise term. +"TTY"和"terminal"(终端)相关。TTY是内核中逐字符I/O的抽象;终端是用户态视角。TTY有控制终端属性;终端有其使用的TTY。在驱动程序代码中,TTY几乎总是更精确的术语。 -Getting these right in writing and in code comments signals that you understand the design. And when you read someone else's code or documentation, noticing which term they chose tells you which layer of abstraction they are thinking about. +在写作和代码注释中正确使用这些术语表明你理解设计。当你阅读别人的代码或文档时,注意他们选择了哪个术语会告诉你他们在思考哪个抽象层。 diff --git a/translations/zh_CN/chapters/part6/chapter-27.md b/translations/zh_CN/chapters/part6/chapter-27.md index 44244b5..ecdf877 100644 --- a/translations/zh_CN/chapters/part6/chapter-27.md +++ b/translations/zh_CN/chapters/part6/chapter-27.md @@ -17,135 +17,135 @@ language: "zh-CN" ## 引言 -In the previous chapter, we walked carefully through the life of a USB 串行驱动程序. We followed the 设备 from the moment the 内核 noticed it on the 总线, through 探测 and 附加, into its active life as a 字符设备, and finally out through 分离 when the hardware was unplugged. That walkthrough taught us how transport-specific 驱动程序 live inside FreeBSD. They participate in a 总线, they expose a user-facing abstraction, and they accept that they may vanish at any moment because the underlying hardware is removable. +在上一章中,我们仔细地走过了USB串行驱动程序的生命周期。我们从内核在总线上发现设备的那一刻开始,跟踪它经过探测和附加,进入其作为字符设备的活跃生命周期,最终在硬件被拔出时通过分离退出。那次完整的演练教会了我们特定传输层驱动程序如何在FreeBSD中生存。它们参与总线,暴露面向用户的抽象,并接受自己可能随时消失的事实,因为底层硬件是可移除的。 -Storage 驱动程序 live in a very different country. The hardware is still real, and many storage 设备 can still be removed unexpectedly, but the role of the 驱动程序 shifts in an important way. A USB serial adapter offers a stream of bytes to one process at a time. A storage 设备 offers a 块-addressable, long-lived, structured surface on which 文件系统 are built. When a user plugs in a USB serial adapter, they might immediately open `/dev/cuaU0` and begin a session. When a user plugs in a disk, they almost never read it as a raw stream. They 挂载 it, and from that moment on the disk disappears behind a 文件系统, behind a cache, behind the Virtual File System layer, and behind the many processes that share files on it. +存储驱动程序生活在一个完全不同的世界里。硬件仍然是真实的,许多存储设备仍然可能被意外移除,但驱动程序的角色以一种重要的方式发生了转变。USB串行适配器一次为一个进程提供字节流。而存储设备提供的是一个块可寻址的、持久的、结构化的表面,文件系统就建立在它之上。当用户插入USB串行适配器时,他们可能会立即打开`/dev/cuaU0`并开始一个会话。当用户插入磁盘时,他们几乎从不会将其作为原始流来读取。他们会挂载它,从那一刻起,磁盘就消失在文件系统之后、消失在缓存之后、消失在虚拟文件系统层之后,以及消失在共享其文件的众多进程之后。 -This chapter teaches you what happens on the 驱动程序 side of that arrangement. You will learn what the VFS layer is, how it differs from `devfs`, and how 存储驱动程序 plug into the GEOM 框架 rather than speaking to the VFS layer directly. You will write a small pseudo 块设备 from scratch, expose it as a GEOM provider, give it a working backing store, watch `newfs_ufs` format it, 挂载 the result, create files on it, 卸载 it cleanly, and 分离 it without leaving footprints in the 内核. By the end of the chapter you will have a working mental model of the storage stack and a concrete example 驱动程序 that exercises every layer we discuss. +本章将教你这种安排在驱动程序一侧发生了什么。你将了解VFS层是什么,它与`devfs`有何不同,以及存储驱动程序如何插入GEOM框架而不是直接与VFS层对话。你将从零开始编写一个小型伪块设备,将其暴露为GEOM提供者,赋予它一个可用的后备存储,观察`newfs_ufs`对其进行格式化,挂载结果,在其上创建文件,干净地卸载它,并在不留下内核足迹的情况下分离它。到本章结束时,你将拥有一个可用的存储栈心智模型和一个练习我们讨论的每一层的具体示例驱动程序。 -The chapter is long because the topic is layered. Unlike a character 驱动程序, where the main unit of interaction is a single `read` or `write` call from a process, a 存储驱动程序 lives inside a chain of 框架. Requests travel from a process through VFS, through the 缓冲区 cache, through the 文件系统, through GEOM, and only then reach the 驱动程序. Replies travel back the other way. Understanding that chain is essential before writing any real storage code, and it is essential again when diagnosing the kind of subtle failures that appear only under load or during 卸载. We will move slowly through the foundations, then gradually bring more layers into view. +本章很长,因为主题是分层的。与字符驱动程序的主要交互单元是来自进程的单个`read`或`write`调用不同,存储驱动程序生活在一个框架链中。请求从进程出发,经过VFS,经过缓冲区缓存,经过文件系统,经过GEOM,然后才到达驱动程序。回复则沿相反方向返回。在编写任何真正的存储代码之前,理解这条链是至关重要的,在诊断仅在负载下或在卸载期间出现的细微故障时,这种理解同样重要。我们将缓慢地推进基础部分,然后逐渐引入更多的层。 -As with 第26章, the goal here is not to ship a production 块 驱动程序. The goal is to give you a sturdy, correct, readable first 块 驱动程序 that you understand completely. Real production 存储驱动程序, for SATA disks, NVMe drives, SCSI controllers, SD cards, or virtual 块设备, build on the same patterns. Once the foundations are clear, the step from pseudo to real is mostly a matter of replacing the backing store with code that talks to hardware 寄存器 and DMA engines, and of handling the much richer error and recovery surface that real disks expose. +与第26章一样,本章的目标不是交付一个生产级块驱动程序。目标是给你一个坚固、正确、可读的第一个块驱动程序,让你完全理解它。真正的生产级存储驱动程序——无论是SATA磁盘、NVMe驱动器、SCSI控制器、SD卡还是虚拟块设备——都建立在相同的模式之上。一旦基础清晰了,从伪设备到真实设备的步骤主要就是用与硬件寄存器和DMA引擎对话的代码替换后备存储,以及处理真实磁盘暴露的更丰富的错误和恢复面。 -You will also see how 存储驱动程序 interact with tools the reader already knows from the user side of FreeBSD. `mdconfig(8)` will appear as a close cousin of our 驱动程序, since the 内核's `md(4)` RAM disk is exactly the kind of thing we are building. `newfs_ufs(8)`, `挂载(8)`, `u挂载(8)`, `diskinfo(8)`, `gstat(8)`, and `geom(8)` will become tools of verification, not just tools that other people use. The chapter is structured so that by the time you finish, you can look at the output of `gstat -I 1` while running `dd` against your 设备 and read it with understanding. +你还将看到存储驱动程序如何与读者已经从FreeBSD用户侧了解的工具交互。`mdconfig(8)`将作为我们驱动程序的近亲出现,因为内核的`md(4)` RAM磁盘正是我们要构建的东西。`newfs_ufs(8)`、`mount(8)`、`umount(8)`、`diskinfo(8)`、`gstat(8)`和`geom(8)`将成为验证工具,而不仅仅是其他人使用的工具。本章的结构确保在你完成时,你可以在对你的设备运行`dd`的同时查看`gstat -I 1`的输出,并带着理解来阅读它。 -Finally, a note on what we will not cover here. We will not write a real 总线 驱动程序 that talks to a physical storage controller. We will not discuss the internals of UFS, ZFS, FUSE, or other specific 文件系统 beyond what is needed to understand how they meet a 块设备 at the boundary. We will not cover DMA, PCIe, NVMe queues, or SCSI command sets. All of those topics deserve their own treatment and, where relevant, will appear in later chapters that cover specific 总线es and specific subsystems. What we will do here is give you a complete, self-contained 块-layer experience that is representative of how all 存储驱动程序 in FreeBSD integrate with the 内核. +最后,关于我们不会涵盖的内容的一点说明。我们不会编写与物理存储控制器对话的真正总线驱动程序。我们不会讨论UFS、ZFS、FUSE或其他特定文件系统的内部机制——超出理解它们在边界处如何与块设备相遇所需的范围。我们不会涵盖DMA、PCIe、NVMe队列或SCSI命令集。所有这些主题都值得单独讨论,在相关的地方,它们将出现在涵盖特定总线和特定子系统的后续章节中。我们在这里要做的是给你一个完整的、自包含的块层体验,它代表了FreeBSD中所有存储驱动程序如何与内核集成。 -Take your time with this chapter. Read slowly, type the code, boot the module, format it, 挂载 it, break it on purpose, watch what happens. The storage stack rewards patience and punishes shortcuts. You are not in a race. +慢慢来阅读本章。慢慢读,输入代码,启动模块,格式化它,挂载它,故意破坏它,观察会发生什么。存储栈奖励耐心,惩罚走捷径。你不是在比赛。 -## How 第6部分 Differs from Parts 1 Through 5 +## 第6部分与第1至第5部分有何不同 -A short framing note before the chapter begins. 第27章 sits inside a Part that asks you to change one specific habit, and that shift is easier to make when it is named up front. +在本章开始之前,先做一个简短的框架说明。第27章位于一个要求你改变一个特定习惯的部分中,而这种转变在一开始就明确命名会更容易接受。 -Parts 1 through 5 built a single running 驱动程序, `myfirst`, through twenty consecutive chapters, each adding one discipline to the same source tree. 第26章 extended that family with `myfirst_usb` as a transport sibling so the step into real hardware would not also be a step into unfamiliar source. **From 第27章 onward, the running `myfirst` 驱动程序 pauses as the backbone of the book.** 第6部分 shifts to new, self-contained demos that fit each subsystem it teaches: a pseudo 块设备 for storage here in 第27章, and a pseudo 网络接口 for networking in 第28章. These demos are parallel to `myfirst` in spirit but distinct in code, because the patterns that define a 存储驱动程序 or a 网络驱动程序 do not fit the character-设备 mould that `myfirst` grew from. +第1至第5部分通过连续二十章构建了一个持续运行的驱动程序`myfirst`,每一章都在同一个源码树中增加一项规范。第26章通过`myfirst_usb`作为传输层的兄弟扩展了这个家族,这样迈向真实硬件的步骤不会同时也是迈向陌生源码的步骤。**从第27章开始,持续运行的`myfirst`驱动程序作为本书的主干暂停了。**第6部分转向新的、自包含的演示程序,以适应它所教授的每个子系统:第27章中的伪块设备用于存储,第28章中的伪网络接口用于网络。这些演示程序在精神上与`myfirst`平行,但在代码上是独立的,因为定义存储驱动程序或网络驱动程序的模式不适合`myfirst`所成长的字符设备模具。 -The **discipline and didactic shape continue unchanged**. Each chapter still walks you through 探测, 附加, the primary data path, the cleanup path, labs, challenge exercises, troubleshooting, and a bridge to the next chapter. Each chapter still grounds its examples in real FreeBSD source under `/usr/src`. The habits you built in Chapters 25 and earlier, the labelled-goto cleanup chain, rate-limited logging, `INVARIANTS` and `WITNESS`, the production-readiness checklist, carry over without modification. What changes is the code artefact in front of you: a small, focused 驱动程序 whose shape matches the subsystem under study, rather than one more stage in the `myfirst` timeline. +**训练规范和教学形态保持不变。**每一章仍然引导你完成探测、附加、主数据路径、清理路径、实验、挑战练习、故障排除和通往下一章的桥梁。每一章仍然将示例建立在`/usr/src`下的真实FreeBSD源码之上。你在第25章及更早章节中建立的习惯——带标签的goto清理链、限速日志、`INVARIANTS`和`WITNESS`、生产就绪检查清单——无需修改即可延续。改变的是你面前的代码产物:一个小型、专注的驱动程序,其形状与所研究的子系统相匹配,而不是`myfirst`时间线中的又一个阶段。 -This is a deliberate didactic choice, not an accident of scope. A 存储驱动程序 and a 网络驱动程序 each have their own lifecycle, their own data flow, their own preferred idioms, and their own 框架 to plug into. Teaching them as fresh 驱动程序, rather than as further mutations of `myfirst`, keeps the focus on what makes each subsystem distinctive. A reader who tries to stretch `myfirst` into a 块设备 or a 网络接口 quickly ends up with code that teaches nothing about storage or networking. Fresh demos are the cleaner path, and they are the path this Part takes. +这是一个经过深思熟虑的教学选择,而非范围上的偶然。存储驱动程序和网络驱动程序各自拥有自己的生命周期、自己的数据流、自己偏好的惯用法,以及自己要插入的框架。将它们作为全新的驱动程序来教授,而不是作为`myfirst`的进一步变体,可以保持对每个子系统的独特之处的关注。试图将`myfirst`延伸为块设备或网络接口的读者,很快就会得到一段关于存储或网络什么也教不了的代码。全新的演示程序是更清晰的路径,也是本部分所采取的路径。 -Part 7 returns to cumulative learning, but rather than resuming a single running 驱动程序, it revisits the 驱动程序 you have already written (`myfirst`, `myfirst_usb`, and the 第6部分 demos) and teaches the production-minded topics that matter once a first version of a 驱动程序 exists: portability across architectures, advanced debugging, performance tuning, security review, and contribution to the upstream project. The habit of building cumulatively stays with you; only the specific artefact in front of you changes. +第7部分回归累积式学习,但它不是恢复单一运行中的驱动程序,而是回顾你已经编写过的驱动程序(`myfirst`、`myfirst_usb`和第6部分的演示程序),并教授一旦驱动程序的第一个版本存在后就变得重要的面向生产力的主题:跨架构的可移植性、高级调试、性能调优、安全审查和对上游项目的贡献。累积构建的习惯将伴随你;改变的只是你面前的具体产物。 -Keep this framing in mind as 第27章 unfolds. If the switch from `myfirst` to a new pseudo 块设备 feels jarring after twenty chapters of the same source tree, that reaction is expected and passes quickly, usually by the end of Section 3. +在第27章展开的过程中,请记住这个框架。如果在二十章相同源码树之后,从`myfirst`切换到新的伪块设备感觉有些突兀,这种反应是正常的,通常会很快过去,一般到第3节结束时就会消失。 -## 读者指南: How to Use This Chapter +## 读者指南:如何使用本章 -This chapter is designed as a guided course through the storage side of the FreeBSD 内核. It is one of the longer chapters in the book because the subject matter is layered and every layer has its own vocabulary, its own concerns, and its own failure modes. You do not need to rush through it. +本章被设计为FreeBSD内核存储方面的引导式课程。它是本书中较长的章节之一,因为主题是分层的,每一层都有自己的词汇、自己的关注点和自己的故障模式。你不需要急于求成。 -If you choose the **reading-only path**, expect to spend around two to three hours going through the chapter carefully. You will come away with a clear picture of how VFS, the 缓冲区 cache, 文件系统, GEOM, and the 块设备 boundary fit together, and you will have a concrete 驱动程序 in front of you as an anchor for your mental model. This is a legitimate way to use the chapter, especially on a first pass. +如果你选择**仅阅读路径**,预计需要花费大约两到三个小时仔细阅读本章。你将获得关于VFS、缓冲区缓存、文件系统、GEOM和块设备边界如何组合在一起的清晰图景,并且你面前将有一个具体的驱动程序作为心智模型的锚点。这是使用本章的合理方式,尤其是在第一次阅读时。 -If you choose the **reading-plus-labs path**, plan for four to six hours spread across one or two evenings, depending on your comfort with 内核模块 from 第26章. You will build the 驱动程序, format it, 挂载 it, watch it under load, and take it apart safely. Expect the mechanics of `kldload`, `kldunload`, `newfs_ufs`, and `挂载` to become second nature by the end. +如果你选择**阅读加实验路径**,计划在连续一到两个晚上花费四到六个小时,具体取决于你对第26章中内核模块的熟悉程度。你将构建驱动程序、格式化它、挂载它、在负载下观察它,并安全地拆解它。预计到本章结束时,`kldload`、`kldunload`、`newfs_ufs`和`mount`的操作将变得轻车熟路。 -If you choose the **reading-plus-labs-plus-challenges path**, plan for a weekend or two evenings spread over a week. The challenges extend the 驱动程序 in small directions that matter in practice: adding optional flush semantics, responding to `BIO_DELETE` with zeroing, supporting multiple units, exporting extra attributes through `disk_getattr`, and enforcing read-only mode cleanly. Each challenge is self-contained and uses only what the chapter has already covered. +如果你选择**阅读加实验加挑战路径**,计划在一个周末或分散在一个月内的两个晚上。这些挑战在实际重要的方向上扩展了驱动程序:添加可选的刷新语义、用清零响应`BIO_DELETE`、支持多个单元、通过`disk_getattr`导出额外属性、以及干净地强制只读模式。每个挑战都是自包含的,只使用本章已经涵盖的内容。 -Whichever path you choose, do not skip the troubleshooting section. Storage bugs tend to look alike from the outside, and the ability to recognise them by symptom is far more useful in practice than memorising the names of every function in GEOM. The troubleshooting material is placed near the end for readability, but you may find yourself turning back to it while working through the labs. +无论你选择哪条路径,都不要跳过故障排除部分。存储bug从外部看往往很相似,通过症状识别它们的能力在实践中远比记住GEOM中每个函数的名字有用。故障排除材料放在接近末尾的位置以便于阅读,但你可能会在做实验时回过头来查阅它。 -A word on prerequisites. This chapter builds directly on 第26章, so at minimum you should be comfortable writing a small 内核模块, declaring a softc, allocating and freeing resources, and walking through the load and unload path. You should also be comfortable enough with the shell to run `kldload`, `kldstat`, `dmesg`, `挂载`, and `u挂载` without stopping to look up flags. If any of that feels unfamiliar, it is worth revisiting Chapters 5, 14, and 26 before continuing. +关于先决条件的说明。本章直接建立在第26章之上,因此你至少应该能够熟练编写小型内核模块、声明softc、分配和释放资源,以及走过加载和卸载路径。你还应该足够熟悉shell,能够在不停下来查找标志的情况下运行`kldload`、`kldstat`、`dmesg`、`mount`和`umount`。如果其中任何内容感觉不熟悉,值得在继续之前回顾第5、14和26章。 -You should work on a throwaway FreeBSD 14.3 system, a virtual machine, or a branch where you do not mind the occasional 内核 panic. A panic is unlikely if you follow the text carefully, but the cost of a mistake on your development laptop is much higher than the cost of a mistake on a VM snapshot you can roll back. We have said this before and we will keep saying it: 内核 work is safe when you work in a safe place. +你应该在一个一次性的FreeBSD 14.3系统、虚拟机或不介意偶尔内核崩溃的分支上工作。如果你仔细按照文本操作,崩溃是不太可能的,但在开发笔记本电脑上犯错的代价远高于在可以回滚的VM快照上犯错的代价。我们之前说过这话,我们会继续说:内核工作在安全的地方进行时是安全的。 -### Work Section by Section +### 按节逐读 -The chapter is organised as a progression. Section 1 introduces VFS. Section 2 contrasts `devfs` with VFS and positions our 驱动程序 in that contrast. Section 3 寄存器 a minimal pseudo 块设备. Section 4 exposes it as a GEOM provider. Section 5 implements real read and write paths. Section 6 挂载s a 文件系统 on top. Section 7 gives the 设备 persistence. Section 8 teaches safe 卸载 and cleanup. Section 9 talks about refactoring, versioning, and what to do as the 驱动程序 grows. +本章按循序渐进的方式组织。第1节介绍VFS。第2节对比`devfs`和VFS,并将我们的驱动程序定位在这种对比之中。第3节注册一个最小的伪块设备。第4节将其暴露为GEOM提供者。第5节实现真正的读写路径。第6节在顶部挂载文件系统。第7节赋予设备持久性。第8节教授安全的卸载和清理。第9节讨论重构、版本管理以及驱动程序增长时该怎么做。 -You are meant to read them in order. Each section assumes the previous sections are fresh in your mind, and the labs build on each other. If you jump in the middle, pieces will look strange. +你应该按顺序阅读它们。每一节都假设前面的章节内容在你脑海中仍然清晰,实验也是相互构建的。如果你跳到中间,内容会显得很奇怪。 -### Type the Code +### 输入代码 -Typing the code by hand remains the most effective way to internalise 内核 idioms. The companion files under `examples/part-06/ch27-storage-vfs/` exist so that you can check your work, not so that you can skip the typing. Reading code is not the same as writing it. +手动输入代码仍然是内化内核惯用法的最有效方式。`examples/part-06/ch27-storage-vfs/`下的配套文件是为了让你检查工作,而不是让你跳过输入。阅读代码和编写代码不是一回事。 -### Open the FreeBSD Source Tree +### 打开FreeBSD源码树 -You will be asked several times to open real FreeBSD source files, not only the companion examples. The files of interest include `/usr/src/sys/geom/geom.h`, `/usr/src/sys/sys/bio.h`, `/usr/src/sys/geom/geom_disk.h`, `/usr/src/sys/dev/md/md.c`, and `/usr/src/sys/geom/zero/g_zero.c`. Each of these is a primary reference, and the prose in this chapter will often refer back to them. If you have not already cloned or installed the 14.3 source tree, now is a good moment to do so. +你将被多次要求打开真正的FreeBSD源文件,而不仅仅是配套示例。感兴趣的文件包括`/usr/src/sys/geom/geom.h`、`/usr/src/sys/sys/bio.h`、`/usr/src/sys/geom/geom_disk.h`、`/usr/src/sys/dev/md/md.c`和`/usr/src/sys/geom/zero/g_zero.c`。每一个都是主要参考,本章的文字经常会引用它们。如果你还没有克隆或安装14.3源码树,现在是个好时机。 -### Use Your Lab Logbook +### 使用你的实验日志 -Keep your lab logbook from 第26章 open while you work. You will want to record the output of `gstat -I 1`, the messages emitted by `dmesg` when you load and unload the module, the time it takes to format the 设备, and any warnings or panics you see. Kernel work is much easier when you keep notes, because many symptoms look similar at first glance and the logbook lets you compare across sessions. +在工作时保持第26章的实验日志打开。你会想记录`gstat -I 1`的输出、加载和卸载模块时`dmesg`发出的消息、格式化设备所需的时间,以及你看到的任何警告或崩溃。当你做笔记时,内核工作会变得容易得多,因为许多症状乍一看很相似,日志让你可以跨会话进行比较。 -### Pace Yourself +### 掌握节奏 -If you feel your understanding blurring in a particular section, stop. Read it again. Try a small experiment on the running module. Do not push through a section that has not settled. Storage 驱动程序 punish confusion more severely than character 驱动程序, because confusion at the 块 layer often becomes 文件系统 corruption at the higher layer, and 文件系统 corruption takes time and care to repair even in a throwaway VM. +如果你感觉在某一节中理解变得模糊,停下来。重新阅读它。在运行中的模块上尝试一个小实验。不要硬撑过尚未理解的小节。存储驱动程序比字符驱动程序更严厉地惩罚混乱,因为块层的混乱往往会变成上层的文件系统损坏,而文件系统损坏即使在一次性虚拟机中也需要时间和精力来修复。 -## How to Get the Most Out of This Chapter +## 如何从本章获得最大收益 -The chapter is structured so that every section adds exactly one new concept on top of what came before. To make the most of that structure, treat the chapter as a workshop rather than as a reference. You are not here to find a quick answer. You are here to build a correct mental model. +本章的结构使得每一节都恰好在前一节的基础上增加一个新概念。为了充分利用这种结构,把本章当作研讨会而不是参考手册。你不是来这里找快速答案的。你是来这里构建正确的心智模型的。 -### Work in Sections +### 按节学习 -Do not read the whole chapter end to end without stopping. Read one section, then pause. Try the experiment or lab that goes with it. Look at the related FreeBSD source. Write a few lines in your logbook. Only then move on. Storage programming in the 内核 is strongly cumulative, and skipping ahead usually means that you will be confused about the next thing for a reason that was explained two sections ago. +不要一口气从头到尾读完整个章节。读一节,然后暂停。尝试与之配套的实验或练习。查看相关的FreeBSD源码。在日志中写几行。然后再继续。内核中的存储编程是高度累积性的,跳过前进通常意味着你会因为两节之前解释过的原因而对下一个内容感到困惑。 -### Keep the Driver Running +### 保持驱动程序运行 -Once you have loaded the 驱动程序 in Section 3, keep it loaded as much as possible while you read. Modify it, reload, poke it with `gstat`, run `dd` against it, call `diskinfo` on it. Having a live, observable example is far more valuable than any 挂载 of reading. You will notice things that no chapter could ever tell you about, because no chapter can show you real timing, real jitter, or real corner cases in your particular setup. +一旦你在第3节加载了驱动程序,在阅读时尽量保持它处于加载状态。修改它,重新加载,用`gstat`探查它,对它运行`dd`,对它调用`diskinfo`。拥有一个活生生的、可观察的示例远比任何数量的阅读都更有价值。你会注意到没有任何章节能告诉你的事情,因为没有章节能向你展示真实的时序、真实的抖动或你特定设置中的真实边界情况。 -### Consult Manual Pages +### 查阅手册页 -FreeBSD's manual pages are part of the teaching material, not a separate formality. Section 9 of the manual is where the 内核 接口 live. We will refer several times to pages such as `g_bio(9)`, `geom(4)`, `DEVICE_IDENTIFY(9)`, `disk(9)`, `总线_dma(9)`, and `devstat(9)`. Read them alongside this chapter. They are shorter than they look, and they are written by the same community that wrote the 内核 you are working inside. +FreeBSD的手册页是教学材料的一部分,而不是额外的形式要求。手册的第9节是内核接口所在的地方。我们将多次引用`g_bio(9)`、`geom(4)`、`DEVICE_IDENTIFY(9)`、`disk(9)`、`bus_dma(9)`和`devstat(9)`等页面。与本章一起阅读它们。它们比你想象的要短,而且它们是由编写你正在使用的内核的同一社区编写的。 -### Type the Code, Then Mutate It +### 输入代码,然后修改它 -When you build the 驱动程序 from the companion examples, type it first. Once it works, start changing things. Rename a method and watch the build fail. Remove an `if` branch and watch what happens when you load the module. Hardcode a smaller media size and watch `newfs_ufs` react. Kernel code becomes understandable through deliberate mutation far more than through pure reading. +当你从配套示例构建驱动程序时,先输入它。一旦它工作了,就开始修改它。重命名一个方法,观察构建失败。删除一个`if`分支,观察加载模块时发生什么。硬编码一个更小的介质大小,观察`newfs_ufs`的反应。内核代码通过有意的修改变得可理解,远比纯粹阅读更有效。 -### Trust the Tooling +### 信任工具 -FreeBSD gives you a wealth of tools for inspecting the storage stack: `geom`, `gstat`, `diskinfo`, `dd`, `mdconfig`, `dmesg`, `kldstat`, `sysctl`. Use them. When something goes wrong, the first move is almost never to read more source. It is to ask the system what state it is in. `geom disk list` and `geom part show` are often more informative than five minutes of grep. +FreeBSD为你提供了丰富的工具来检查存储栈:`geom`、`gstat`、`diskinfo`、`dd`、`mdconfig`、`dmesg`、`kldstat`、`sysctl`。使用它们。当出现问题时,第一步几乎从不是阅读更多源码。而是询问系统当前处于什么状态。`geom disk list`和`geom part show`通常比五分钟的grep更有信息量。 -### Take Breaks +### 适当休息 -Kernel work is cognitively dense. Two or three focused hours are usually more productive than a seven-hour sprint. If you catch yourself making the same typo three times, or copy-pasting without reading, that is your cue to stand up for ten minutes. +内核工作在认知上是密集的。两到三个专注的小时通常比七个小时的冲刺更有效率。如果你发现自己犯了三次同样的打字错误,或者不看就复制粘贴,那就是你该站起来休息十分钟的信号。 -With those habits established, let us begin. +建立了这些习惯后,让我们开始吧。 -## 第1节: What Is the Virtual File System Layer? +## 第1节:什么是虚拟文件系统层? -When a process opens a file on FreeBSD, it calls `open(2)` with a path. That path might resolve to a file on UFS, a file on ZFS, a file on a remotely 挂载ed NFS share, a pseudo-file in `devfs`, a file under `procfs`, or even a file inside a FUSE-挂载ed userland 文件系统. The process cannot tell. The process receives a file 描述符 and then reads and writes as if there were only one kind of file in the world. That uniformity is not an accident. It is the work of the Virtual File System layer. +当进程在FreeBSD上打开文件时,它会带着路径调用`open(2)`。该路径可能解析为UFS上的文件、ZFS上的文件、远程挂载的NFS共享上的文件、`devfs`中的伪文件、`procfs`下的文件,甚至FUSE挂载的用户态文件系统中的文件。进程无法区分。进程收到一个文件描述符,然后像世界上只有一种文件一样进行读写。这种统一性并非偶然。这是虚拟文件系统层的工作。 -### The Problem VFS Solves +### VFS解决的问题 -Before VFS, UNIX 内核s generally knew how to talk to one 文件系统 only. If you wanted a new 文件系统, you modified the code paths for `open`, `read`, `write`, `stat`, `unlink`, `rename`, and every other system call that touched files. That approach worked for a while, but it did not scale. New 文件系统 arrived: NFS, for remote access. MFS, for in-memory scratch space. Procfs, for exposing process state. ISO 9660, for CD-ROM media. FAT, for interoperability. Every addition meant new forks in every file-related system call. +在VFS出现之前,UNIX内核通常只知道如何与一种文件系统对话。如果你想要一个新的文件系统,你必须修改`open`、`read`、`write`、`stat`、`unlink`、`rename`以及每个涉及文件的系统调用的代码路径。这种方法在一段时间内有效,但无法扩展。新的文件系统到来了:用于远程访问的NFS,用于内存暂存空间的MFS,用于暴露进程状态的Procfs,用于CD-ROM介质的ISO 9660,用于互操作的FAT。每次添加都意味着在每个与文件相关的系统调用中出现新的分支。 -Sun Microsystems introduced the Virtual File System architecture in the mid-1980s as a way out of this mess. The idea is simple. The 内核 talks to a single abstract 接口, defined in terms of generic operations on generic file objects. Each concrete 文件系统 寄存器 implementations of those operations, and the 内核 calls them through function pointers. When the 内核 needs to read a file, it does not know or care whether the file lives on UFS or NFS or ZFS. It knows there is a node with a `VOP_READ` method, and it calls that method. +Sun Microsystems在1980年代中期引入了虚拟文件系统架构,作为摆脱这种困境的方法。思路很简单。内核与一个单一抽象接口对话,该接口以通用文件对象上的通用操作来定义。每个具体的文件系统注册这些操作的实现,内核通过函数指针调用它们。当内核需要读取文件时,它不知道也不关心文件存储在UFS还是NFS还是ZFS上。它知道有一个带有`VOP_READ`方法的节点,然后调用该方法。 -FreeBSD adopted this architecture and has extended it significantly over the decades. The result is that adding a 文件系统 to FreeBSD no longer requires modifying the core system calls. A 文件系统 is a separate 内核模块 that 寄存器 a set of operations with VFS, and from that moment VFS routes the right requests to it. +FreeBSD采用了这种架构,并在数十年间对其进行了显著扩展。结果是,向FreeBSD添加文件系统不再需要修改核心系统调用。文件系统是一个独立的内核模块,它向VFS注册一组操作,从那一刻起,VFS将正确的请求路由给它。 -### The VFS Object Model +### VFS对象模型 -VFS defines three main kinds of objects. +VFS定义了三种主要对象。 -The first is the **挂载 point**, represented in the 内核 by `struct 挂载`. Every 挂载ed 文件系统 has one, and it records where in the namespace the 文件系统 is 附加ed, what flags it has, and which 文件系统 code is responsible for it. +第一种是**挂载点**,在内核中用`struct mount`表示。每个挂载的文件系统都有一个挂载点,它记录了文件系统附加在命名空间中的位置、它有什么标志,以及哪个文件系统代码负责它。 -The second is the **vnode**, represented by `struct vnode`. A vnode is the 内核's handle on a single file or directory within a 挂载ed 文件系统. It is not the file itself. It is the 内核's runtime representation of that file for as long as something in the 内核 cares about it. Every file that a process has open has a vnode. Every directory the 内核 is walking through has a vnode. When nothing holds a reference to a vnode, it can be reclaimed, and the 内核 keeps a pool of them to avoid pressure on small-inode cases. +第二种是**vnode**,用`struct vnode`表示。vnode是内核对已挂载文件系统中单个文件或目录的句柄。它不是文件本身。它是内核对该文件的运行时表示,只要内核中有东西关心它就存在。每个进程打开的文件都有一个vnode。内核遍历的每个目录都有一个vnode。当没有任何东西持有对vnode的引用时,它就可以被回收,内核保留一个vnode池以避免小inode情况下的压力。 -The third is the **vnode operations vector**, represented by `struct vop_vector`, which lists the operations each 文件系统 must implement on vnodes. The operations have names like `VOP_LOOKUP`, `VOP_READ`, `VOP_WRITE`, `VOP_CREATE`, `VOP_REMOVE`, `VOP_GETATTR`, and `VOP_SETATTR`. Each 文件系统 provides a pointer to its own vector, and the 内核 invokes operations through these vectors whenever it needs to do anything to a file. +第三种是**vnode操作向量**,用`struct vop_vector`表示,它列出了每个文件系统必须在vnode上实现的操作。这些操作有`VOP_LOOKUP`、`VOP_READ`、`VOP_WRITE`、`VOP_CREATE`、`VOP_REMOVE`、`VOP_GETATTR`和`VOP_SETATTR`等名称。每个文件系统提供指向自己向量的指针,内核在需要对文件执行任何操作时通过这些向量调用操作。 -The elegant thing about this design is that from the system call side of the 内核, only the abstract 接口 matters. The system call layer calls `VOP_READ(vp, uio, ioflag, cred)` and does not care whether `vp` belongs to UFS, ZFS, NFS, or tmpfs. From the 文件系统 side, only the abstract 接口 matters too. UFS implements the vnode operations and never sees the system call code. +这种设计的优雅之处在于,从内核的系统调用一侧看,只有抽象接口重要。系统调用层调用`VOP_READ(vp, uio, ioflag, cred)`,不关心`vp`属于UFS、ZFS、NFS还是tmpfs。从文件系统一侧看,也只有抽象接口重要。UFS实现vnode操作,永远不会看到系统调用代码。 -### Where Storage Drivers Fit +### 存储驱动程序的位置 -Here is the question that matters for this chapter. If VFS is where 文件系统 live, where do 存储驱动程序 live? +这是本章的关键问题。如果VFS是文件系统所在的地方,那么存储驱动程序在哪里? -The answer is: not directly inside VFS. A 存储驱动程序 does not implement `VOP_READ`. It implements a much lower-level abstraction that looks like a disk. Filesystems then sit on top, consuming the disk-like abstraction, translating file-level operations into 块-level operations, and calling down. +答案是:不直接在VFS内部。存储驱动程序不实现`VOP_READ`。它实现的是一个看起来像磁盘的低得多层的抽象。然后文件系统位于其上,消费类似磁盘的抽象,将文件级操作转换为块级操作,并向下调用。 -The chain of layers between a process and a 块设备 in FreeBSD typically looks like this. +FreeBSD中进程和块设备之间的层链通常如下所示。 ```text +------------------+ @@ -190,152 +190,152 @@ The chain of layers between a process and a 块设备 in FreeBSD typically looks +------------------+ ``` -Each layer in this stack has a job. VFS hides 文件系统 differences from system calls. The 文件系统 translates files into 块. The 缓冲区 cache holds recently used 块 in RAM. GEOM routes 块 requests through transforms, 分区s, and mirrors. The 存储驱动程序 converts 块 requests into real I/O. The hardware does the work. +这个栈中的每一层都有各自的职责。VFS向系统调用隐藏文件系统的差异。文件系统将文件转换为块。缓冲区缓存在RAM中保存最近使用的块。GEOM通过变换、分区和镜像来路由块请求。存储驱动程序将块请求转换为实际的I/O。硬件执行具体工作。 -For this chapter, almost everything we do happens at the bottom two layers: GEOM and the 存储驱动程序. We will touch the 文件系统 layer briefly when we 挂载 UFS on our 设备, and we will touch VFS only in the sense that `挂载(8)` calls it. The layers above GEOM are not our code. +在本章中,我们几乎所有的操作都发生在最底部的两层:GEOM和存储驱动程序。我们将在设备上挂载UFS时简要涉及文件系统层,而VFS仅在`mount(8)`调用它的意义上会涉及到。GEOM以上的层不是我们的代码。 -### VFS in the Kernel Source +### 内核源码中的VFS -If you want to look at VFS directly, the entry points are under `/usr/src/sys/kern/vfs_*.c`. The vnode layer lives in `vfs_vnops.c` and `vfs_subr.c`. The 挂载 side lives in `vfs_挂载.c`. The vnode operations vector is defined and handled in `vfs_default.c`. UFS, our primary 文件系统 in this chapter, lives under `/usr/src/sys/ufs/ufs/` and `/usr/src/sys/ufs/ffs/`. You do not need to read any of those to follow this chapter. You should know where they are so that you understand what sits above the code you are about to write. +如果你想直接查看VFS,入口点在`/usr/src/sys/kern/vfs_*.c`下。vnode层在`vfs_vnops.c`和`vfs_subr.c`中。挂载侧在`vfs_mount.c`中。vnode操作向量在`vfs_default.c`中定义和处理。UFS,本章的主要文件系统,位于`/usr/src/sys/ufs/ufs/`和`/usr/src/sys/ufs/ffs/`下。你不需要阅读其中任何一个来跟随本章。你应该知道它们在哪里,以便理解你即将编写的代码之上有什么。 -### What This Means for Our Driver +### 这对我们的驱动程序意味着什么 -Because VFS is not our direct caller, we do not need to implement `VOP_` methods. We need to implement the 块-layer 接口 that the 文件系统 ultimately calls into. That 接口 is defined by GEOM and, for disk-like 设备 in particular, by the `g_disk` subsystem. Our 驱动程序 will expose a GEOM provider. A 文件系统 will consume it. The flow of I/O will go through `struct bio` rather than through `struct uio`, and the unit of work will be a 块 rather than a byte range. +因为VFS不是我们的直接调用者,我们不需要实现`VOP_`方法。我们需要实现的是文件系统最终调用到的块层接口。该接口由GEOM定义,对于类似磁盘的设备,由`g_disk`子系统定义。我们的驱动程序将暴露一个GEOM提供者。文件系统将消费它。I/O的流动将通过`struct bio`而不是`struct uio`,工作单元将是块而不是字节范围。 -This is also why 存储驱动程序 rarely interact with `cdevsw` or `make_dev` directly the way character 驱动程序 do. The `/dev` node for a disk is created by GEOM, not by the 驱动程序. The 驱动程序 describes itself to GEOM, and GEOM publishes a provider, which then appears in `/dev` with an automatically generated name. +这也解释了为什么存储驱动程序很少像字符驱动程序那样直接与`cdevsw`或`make_dev`交互。磁盘的`/dev`节点是由GEOM创建的,而不是由驱动程序创建的。驱动程序向GEOM描述自己,GEOM发布一个提供者,该提供者随后以自动生成的名称出现在`/dev`中。 -### The VFS Call Chain in Practice +### VFS调用链实践 -Let us trace what happens when a user runs `cat /mnt/myfs/hello.txt`, assuming `/mnt/myfs` is 挂载ed on our future 块设备. +让我们追踪一下当用户运行`cat /mnt/myfs/hello.txt`时会发生什么,假设`/mnt/myfs`挂载在我们未来的块设备上。 -First, the process calls `open("/mnt/myfs/hello.txt", O_RDONLY)`. That goes to `sys_openat` in the system call layer, which asks VFS to resolve the path. VFS walks the path one component at a time, calling `VOP_LOOKUP` on each directory vnode. When it reaches `myfs`, it notices that the vnode is a 挂载 point and crosses into the 挂载ed 文件系统. It eventually arrives at the vnode for `hello.txt` and returns a file 描述符. +首先,进程调用`open("/mnt/myfs/hello.txt", O_RDONLY)`。这会进入系统调用层的`sys_openat`,后者要求VFS解析路径。VFS逐个组件地遍历路径,在每个目录vnode上调用`VOP_LOOKUP`。当到达`myfs`时,它注意到vnode是一个挂载点并跨越到已挂载的文件系统中。它最终到达`hello.txt`的vnode并返回一个文件描述符。 -Second, the process calls `read(fd, buf, 64)`. That goes to `sys_read`, which calls `vn_read`, which calls `VOP_READ` on the vnode. The UFS implementation of `VOP_READ` consults its inode, figures out which disk 块 hold the requested bytes, and asks the 缓冲区 cache for those 块. If the 块 are not cached, the 缓冲区 cache calls `bread`, which ultimately builds a `struct bio` and hands it to GEOM. +第二步,进程调用`read(fd, buf, 64)`。这进入`sys_read`,后者调用`vn_read`,再调用vnode上的`VOP_READ`。UFS的`VOP_READ`实现查阅其inode,找出哪些磁盘块保存了请求的字节,然后向缓冲区缓存请求这些块。如果块未被缓存,缓冲区缓存调用`bread`,最终构建一个`struct bio`并将其交给GEOM。 -Third, GEOM looks at the provider the 文件系统 is consuming. Through a chain of providers and consumers, the `bio` ends up at the bottom provider, which is our 驱动程序's provider. Our strategy function receives the `bio`, reads the requested bytes from our backing store, and calls `biodone` or `g_io_deliver` to complete the request. +第三步,GEOM查看文件系统正在消费的提供者。通过提供者和消费者的链条,`bio`最终到达最底层的提供者,也就是我们驱动程序的提供者。我们的策略函数接收`bio`,从后备存储中读取请求的字节,并调用`biodone`或`g_io_deliver`来完成请求。 -Fourth, the reply travels back the other way. The 缓冲区 cache gets its data, the 文件系统 returns to `vn_read`, `vn_read` copies the data into the user 缓冲区, and `sys_read` returns. +第四步,回复沿相反方向返回。缓冲区缓存获取其数据,文件系统返回到`vn_read`,`vn_read`将数据复制到用户缓冲区中,`sys_read`返回。 -None of that code is ours except the last hop. But understanding the whole chain is what lets you make sensible design choices when you write the last hop. +除了最后一跳,所有这些代码都不是我们的。但理解整个链路能让你在编写最后一跳时做出合理的设计选择。 ### 总结 Section 1 -VFS is the layer that unifies 文件系统 in FreeBSD. It sits between the system call 接口 and the various concrete 文件系统, and it provides the abstraction that makes files look identical regardless of where they live. Storage 驱动程序 do not live inside VFS. They live at the bottom of the stack, far below VFS, behind GEOM and the 缓冲区 cache. Our job in this chapter is to write a 驱动程序 that participates correctly in that lower layer, and to understand enough about the upper layers to avoid confusion when diagnosing problems. +VFS是FreeBSD中统一文件系统的层。它位于系统调用接口和各种具体文件系统之间,提供了使文件无论存储在哪里看起来都相同的抽象。存储驱动程序不在VFS内部。它们位于栈的底部,远在VFS之下,在GEOM和缓冲区缓存之后。我们在本章的任务是编写一个正确参与该底层的驱动程序,并充分理解上层以避免在诊断问题时产生困惑。 -In the next section, we will sharpen the distinction between `devfs` and VFS, because that distinction determines which mental model applies when you think about a given 设备 node. +在下一节中,我们将明确`devfs`和VFS之间的区别,因为该区别决定了你在考虑给定设备节点时适用哪种心智模型。 -## 第2节: devfs vs VFS +## 第2节:devfs与VFS -Beginners often assume that `devfs` and the Virtual File System layer are two names for the same thing. They are not. They are related, but they play very different roles. Getting this distinction right early saves a great deal of confusion later, especially when thinking about 存储驱动程序, because 存储驱动程序 straddle both of them. +初学者常常认为`devfs`和虚拟文件系统层是同一事物的两个名称。它们不是。它们有关联,但扮演着非常不同的角色。尽早弄清这个区别可以在以后省去很多困惑,特别是在考虑存储驱动程序时,因为存储驱动程序横跨两者。 -### What devfs Is +### 什么是devfs -`devfs` is a 文件系统. That sounds circular, but it is true. `devfs` is implemented as a 文件系统 module, 注册ed with VFS, and 挂载ed at `/dev` on every FreeBSD system. When you read a file under `/dev`, you are reading through VFS, which hands the request to `devfs`, which recognises that the "file" you are reading is really a 内核 设备 node and routes the call to the appropriate 驱动程序. +`devfs`是一个文件系统。这听起来像是循环论证,但确实如此。`devfs`被实现为一个文件系统模块,向VFS注册,并在每个FreeBSD系统上挂载到`/dev`。当你在`/dev`下读取文件时,你是通过VFS进行读取的,VFS将请求交给`devfs`,`devfs`识别出你正在读取的"文件"实际上是一个内核设备节点,并将调用路由到相应的驱动程序。 -`devfs` has several special properties that distinguish it from an ordinary 文件系统 like UFS. +`devfs`有几个特殊属性,使它区别于像UFS这样的普通文件系统。 -First, its contents are not stored on disk. The "files" in `devfs` are synthesised by the 内核 based on which 驱动程序 are currently loaded and which 设备 are currently present. When a 驱动程序 calls `make_dev(9)` to create `/dev/mybox`, `devfs` adds the corresponding node to its view. When the 驱动程序 destroys that 设备 with `destroy_dev(9)`, `devfs` removes the node. The user sees `/dev/mybox` appear and disappear in real time. +第一,其内容不存储在磁盘上。`devfs`中的"文件"是由内核根据当前加载的驱动程序和当前存在的设备合成的。当驱动程序调用`make_dev(9)`创建`/dev/mybox`时,`devfs`将相应的节点添加到其视图中。当驱动程序用`destroy_dev(9)`销毁该设备时,`devfs`移除该节点。用户会实时看到`/dev/mybox`出现和消失。 -Second, the read and write paths for `devfs` nodes are not file data paths. When you write to `/dev/myserial0`, you are not appending bytes to a stored file. You are invoking the 驱动程序's `d_write` function through `cdevsw`, and that function decides what those bytes mean. In the case of a USB 串行驱动程序, they mean bytes to transmit on the wire. In the case of a pseudo 设备 like `/dev/null`, they mean bytes to discard. +第二,`devfs`节点的读路径和写路径不是文件数据路径。当你写入`/dev/myserial0`时,你不是在向存储的文件追加字节。你是在通过`cdevsw`调用驱动程序的`d_write`函数,该函数决定这些字节的含义。对于USB串行驱动程序,它们意味着要在传输线上发送的字节。对于像`/dev/null`这样的伪设备,它们意味着要丢弃的字节。 -Third, the metadata of `devfs` nodes, such as permissions and ownership, is managed by a policy layer in the 内核 rather than by the 文件系统 itself. `devfs_ruleset(8)` and the `devd` 框架 configure that policy. +第三,`devfs`节点的元数据(如权限和所有权)由内核中的策略层管理,而不是由文件系统本身管理。`devfs_ruleset(8)`和`devd`框架配置该策略。 -Fourth, `devfs` supports cloning, which character 驱动程序 like `pty`, `tun`, and `bpf` use to create a new minor 设备 whenever a process opens the node. This is how `/dev/ptyp0`, `/dev/ptyp1`, and their successors come into existence on demand. +第四,`devfs`支持克隆,字符驱动程序如`pty`、`tun`和`bpf`利用克隆在进程打开节点时创建新的次设备。这就是`/dev/ptyp0`、`/dev/ptyp1`及其后继者按需产生的方式。 -### What VFS Is +### 什么是VFS -VFS, as we saw in Section 1, is the abstract 文件系统 layer. Every 文件系统 on a FreeBSD system, including `devfs`, is 注册ed with VFS and invoked through VFS. VFS is not a 文件系统. It is the 框架 that 文件系统 plug into. +正如我们在第1节中看到的,VFS是抽象的文件系统层。FreeBSD系统上的每个文件系统,包括`devfs`,都向VFS注册并通过VFS调用。VFS不是文件系统。它是文件系统插入的框架。 -When you open a file on UFS, the chain is: system call -> VFS -> UFS -> 缓冲区 cache -> GEOM -> 驱动程序. When you open a node in `devfs`, the chain is: system call -> VFS -> devfs -> 驱动程序. Both go through VFS. Only the UFS chain involves GEOM. +当你在UFS上打开文件时,链路是:系统调用 -> VFS -> UFS -> 缓冲区缓存 -> GEOM -> 驱动程序。当你在`devfs`中打开节点时,链路是:系统调用 -> VFS -> devfs -> 驱动程序。两者都经过VFS。只有UFS链路涉及GEOM。 -### Why Storage Drivers Live on Both Sides +### 存储驱动程序为何横跨两端 -This is where 存储驱动程序 become interesting. +这就是存储驱动程序变得有趣的地方。 -A 存储驱动程序 exposes a 块设备, and that 块设备 eventually appears as a node under `/dev`. For example, if we 注册 our 驱动程序 and tell GEOM about it, a node called `/dev/myblk0` may appear in `devfs`. When a user writes `dd if=image.iso of=/dev/myblk0`, they are writing through `devfs` to a special character 接口 that GEOM provides on top of our disk. The requests flow as BIO through GEOM and into our strategy function. +存储驱动程序暴露一个块设备,该块设备最终以`/dev`下的节点形式出现。例如,如果我们注册驱动程序并告知GEOM,`devfs`中可能会出现一个名为`/dev/myblk0`的节点。当用户写入`dd if=image.iso of=/dev/myblk0`时,他们正在通过`devfs`写入GEOM在我们磁盘之上提供的特殊字符接口。请求以BIO的形式通过GEOM流入我们的策略函数。 -But when a user runs `newfs_ufs /dev/myblk0` and then `挂载 /dev/myblk0 /mnt`, the usage pattern changes. The 内核 now 挂载s UFS on top of the 设备. When a process later reads a file under `/mnt`, the path is: system call -> VFS -> UFS -> 缓冲区 cache -> GEOM -> 驱动程序. The `/dev/myblk0` node in `devfs` is not even involved in the hot path. UFS and the 缓冲区 cache talk directly to the GEOM provider. The `devfs` node is essentially a handle that tools use to refer to the 设备, not the pipe that file data flows through during normal operation. +但当用户运行`newfs_ufs /dev/myblk0`然后`mount /dev/myblk0 /mnt`时,使用模式就改变了。内核现在在设备之上挂载UFS。当进程随后在`/mnt`下读取文件时,路径是:系统调用 -> VFS -> UFS -> 缓冲区缓存 -> GEOM -> 驱动程序。`devfs`中的`/dev/myblk0`节点甚至不参与热路径。UFS和缓冲区缓存直接与GEOM提供者对话。`devfs`节点本质上是工具用来引用设备的句柄,而不是正常操作期间文件数据流经的管道。 -### A Closer Look at the Buffer Cache +### 深入了解缓冲区缓存 -Between the 文件系统 and GEOM in the storage path sits the 缓冲区 cache. We have mentioned it several times without pausing to describe it. Let us pause now, because it explains several of the behaviours you will observe when testing your 驱动程序. +在存储路径中,文件系统和GEOM之间是缓冲区缓存。我们已经提到过它好几次但没有停下来描述。现在让我们停下来,因为它解释了你在测试驱动程序时会观察到的几种行为。 -The 缓冲区 cache is a pool of fixed-size 缓冲区 in 内核 memory, each of which holds one 文件系统 块. When a 文件系统 reads a 块, the 缓冲区 cache gets involved: the 文件系统 asks the cache for the 块, and the cache either returns a hit (the 块 is already in memory) or issues a miss (the cache allocates a 缓冲区, calls down through GEOM to fetch the data, and returns the 缓冲区 once the read completes). When a 文件系统 writes a 块, the same cache path applies in reverse: the write fills a 缓冲区, the 缓冲区 is marked dirty, and the cache schedules a write-back at some later point. +缓冲区缓存是内核内存中固定大小缓冲区的池,每个缓冲区保存一个文件系统块。当文件系统读取一个块时,缓冲区缓存就会参与:文件系统向缓存请求该块,缓存要么返回命中(该块已在内存中),要么发出未命中(缓存分配一个缓冲区,通过GEOM向下调用获取数据,并在读取完成后返回该缓冲区)。当文件系统写入一个块时,相同的缓存路径以相反方式应用:写入填充一个缓冲区,该缓冲区被标记为脏,缓存安排在稍后的某个时间点进行回写。 -The 缓冲区 cache is why consecutive reads of the same file data do not always hit the 驱动程序. The first read misses, causing a BIO to travel to the 驱动程序. The second read hits the cache and returns immediately. This is a great feature for performance. It can be mildly confusing when you are first debugging a 驱动程序, because your `printf` in the strategy function does not fire on every user-space read. +缓冲区缓存就是为什么对同一文件数据的连续读取并不总是到达驱动程序的原因。第一次读取未命中,导致BIO传输到驱动程序。第二次读取命中缓存并立即返回。这是一个很好的性能特性。在你第一次调试驱动程序时,这可能会让人有些困惑,因为策略函数中的`printf`不会在每次用户空间读取时触发。 -The 缓冲区 cache is also why writes can appear to happen faster than the underlying 驱动程序. A `dd if=/dev/zero of=/mnt/myblk/big bs=1m count=16` may appear to complete in a fraction of a second because the writes land in the cache and the cache defers the actual BIOs for a while. The 文件系统 issues the real writes to GEOM over the next second or two. If the system crashes before that happens, the file on disk is incomplete. `sync(2)` forces the cache to flush to the underlying 设备. `fsync(2)` flushes only the 缓冲区 associated with a single file 描述符. +缓冲区缓存也是为什么写入看起来比底层驱动程序更快的原因。一个`dd if=/dev/zero of=/mnt/myblk/big bs=1m count=16`可能在几分之一秒内就看似完成了,因为写入进入了缓存,缓存将实际的BIO延迟了一段时间。文件系统在接下来的一两秒内向GEOM发出真正的写入。如果系统在此之前崩溃,磁盘上的文件是不完整的。`sync(2)`强制缓存刷新到底层设备。`fsync(2)`仅刷新与单个文件描述符关联的缓冲区。 -The 缓冲区 cache is distinct from the page cache. FreeBSD has both, and they cooperate. The page cache holds memory pages that back memory-mapped files and anonymous memory. The 缓冲区 cache holds 缓冲区 that back 文件系统-块 operations. Modern FreeBSD has largely unified them for many data paths, but the distinction still shows up in the source tree, particularly around `bread`, `bwrite`, `getblk`, and `brelse`, which are the 缓冲区-cache side of the 接口. +缓冲区缓存与页缓存是不同的。FreeBSD两者都有,它们相互协作。页缓存保存支持内存映射文件和匿名内存的内存页。缓冲区缓存保存支持文件系统块操作的缓冲区。现代FreeBSD在许多数据路径上已经基本统一了它们,但这种区别仍然出现在源码树中,特别是在`bread`、`bwrite`、`getblk`和`brelse`周围,它们是接口的缓冲区缓存侧。 -The 缓冲区 cache has a single most important implication for our 驱动程序: we will almost never see completely synchronous BIO traffic. When a 文件系统 wants to read a 块, a BIO arrives in our strategy function; when a 文件系统 wants to write a 块, another BIO arrives, but usually some time later than the write system call that prompted it. BIOs also arrive in bursts when the cache flushes. This is normal, and your 驱动程序 must not make assumptions about timing or ordering across BIOs other than what is strictly documented. Each BIO is an independent request. +缓冲区缓存对我们的驱动程序有一个最重要的含义:我们几乎永远不会看到完全同步的BIO流量。当文件系统想要读取一个块时,一个BIO到达我们的策略函数;当文件系统想要写入一个块时,另一个BIO到达,但通常比触发它的写入系统调用晚一些。BIO也会在缓存刷新时以突发方式到达。这是正常的,你的驱动程序不能对BIO之间的时序或顺序做出假设,除非严格文档化的情况。每个BIO都是独立的请求。 -### The Read and Write Paths +### 读路径和写路径 -Let us trace a concrete example through the whole chain. +让我们追踪一个贯穿整个链路的具体示例。 -When a user runs `cat /mnt/myblk/hello.txt`, the shell runs `cat`, which calls `open("/mnt/myblk/hello.txt", O_RDONLY)`. The `open` goes to `sys_openat`, which hands off to VFS. VFS calls `namei` to walk the path. For each path component, VFS calls `VOP_LOOKUP` on the current directory's vnode. When VFS reaches the `myblk` 挂载, it crosses into UFS, which walks the UFS directory structure to find `hello.txt`. UFS returns the vnode for that file, and VFS returns a file 描述符. +当用户运行`cat /mnt/myblk/hello.txt`时,shell运行`cat`,`cat`调用`open("/mnt/myblk/hello.txt", O_RDONLY)`。`open`进入`sys_openat`,后者交给VFS。VFS调用`namei`遍历路径。对于每个路径组件,VFS在当前目录的vnode上调用`VOP_LOOKUP`。当VFS到达`myblk`挂载点时,它跨越到UFS中,UFS遍历其目录结构来找到`hello.txt`。UFS返回该文件的vnode,VFS返回一个文件描述符。 -The user then calls `read(fd, buf, 64)`. `sys_read` calls `vn_read`, which calls `VOP_READ` on the vnode. UFS's `VOP_READ` consults the inode to find the 块 address of the requested bytes, then calls `bread` on the 缓冲区 cache to fetch the 块. The 缓冲区 cache either returns a hit or issues a BIO. +然后用户调用`read(fd, buf, 64)`。`sys_read`调用`vn_read`,后者在vnode上调用`VOP_READ`。UFS的`VOP_READ`查阅inode以找到请求字节的块地址,然后在缓冲区缓存上调用`bread`来获取该块。缓冲区缓存要么返回命中,要么发出一个BIO。 -If it is a cache miss, the 缓冲区 cache allocates a fresh 缓冲区, builds a BIO that asks for the relevant 块 from the underlying GEOM provider, and hands it off. The BIO travels down through GEOM, through our strategy function, and back. When the BIO completes, the 缓冲区 cache un块 the waiting `bread` call. UFS then copies the requested bytes from the 缓冲区 into the user's `buf`. `read` returns. +如果是缓存未命中,缓冲区缓存分配一个新缓冲区,构建一个向底层GEOM提供者请求相关块的BIO,并将其发出。BIO向下通过GEOM,通过我们的策略函数,然后返回。当BIO完成时,缓冲区缓存解除等待中的`bread`调用的阻塞。然后UFS将请求的字节从缓冲区复制到用户的`buf`中。`read`返回。 -For writes, the chain is symmetric but the timing is different. UFS's `VOP_WRITE` calls `bread` or `getblk` to obtain the target 缓冲区, copies the user's data into the 缓冲区, marks the 缓冲区 dirty, and calls `bdwrite` or `bawrite` to schedule the write-back. The user's `write` call returns long before the BIO is issued to the 驱动程序. Later, the 缓冲区 cache's syncer thread picks up dirty 缓冲区 and issues BIO_WRITE requests to the 驱动程序. +对于写入,链路是对称的,但时序不同。UFS的`VOP_WRITE`调用`bread`或`getblk`来获取目标缓冲区,将用户数据复制到缓冲区中,将缓冲区标记为脏,然后调用`bdwrite`或`bawrite`来安排回写。用户的`write`调用在BIO向驱动程序发出之前很久就返回了。稍后,缓冲区缓存的同步线程拾取脏缓冲区并向驱动程序发出BIO_WRITE请求。 -The net effect is that our 驱动程序's strategy function sees a stream of BIOs that is related to, but not identical to, the stream of user-space reads and writes. The 缓冲区 cache mediates the two. +最终效果是,我们驱动程序的策略函数看到的是一系列BIO,这些BIO与用户空间读写流相关但不完全相同。缓冲区缓存是两者之间的中介。 -In other words, the same 存储驱动程序 can be reached two different ways. +换句话说,同一个存储驱动程序可以通过两种不同的方式到达。 -1. **Raw access through `/dev`**: a user-space program opens `/dev/myblk0` and issues `read(2)` or `write(2)` calls. Those calls go through `devfs` and the GEOM character 接口, ending up in our strategy function. -2. **Filesystem access through 挂载**: the 内核 挂载s a 文件系统 on the 设备. File I/O flows through VFS, the 文件系统, the 缓冲区 cache, and GEOM. `devfs` is not part of the hot path for those requests. +1. **通过`/dev`的原始访问**:用户空间程序打开`/dev/myblk0`并发出`read(2)`或`write(2)`调用。这些调用通过`devfs`和GEOM字符接口,最终到达我们的策略函数。 +2. **通过挂载的文件系统访问**:内核在设备上挂载文件系统。文件I/O流经VFS、文件系统、缓冲区缓存和GEOM。`devfs`不是这些请求的热路径的一部分。 -Both paths converge at the GEOM provider, which is why GEOM is the correct abstraction for 存储驱动程序 even though character 驱动程序 typically deal with `devfs` more directly. +两条路径在GEOM提供者处汇合,这就是为什么GEOM是存储驱动程序的正确抽象,尽管字符驱动程序通常更直接地与`devfs`打交道。 -### Why This Distinction Matters +### 这种区分为何重要 -This matters for two reasons. +这之所以重要有两个原因。 -First, it clarifies why we will not use `make_dev` for our 块 驱动程序. `make_dev` is the right call for character 驱动程序 that want to publish a `cdevsw` under `/dev`. It is the wrong call for a 块设备, because GEOM creates the `/dev` node for us as soon as we publish a provider. If you call `make_dev` in a 存储驱动程序, you typically end up with two `/dev` nodes competing for the same 设备, one of which is not connected to the GEOM topology, which leads to confusing behaviour. +第一,它澄清了为什么我们不会为块驱动程序使用`make_dev`。`make_dev`是字符驱动程序想要在`/dev`下发布`cdevsw`时的正确调用。它对块设备来说是错误的调用,因为GEOM在我们发布提供者时会立即为我们创建`/dev`节点。如果你在存储驱动程序中调用`make_dev`,通常会得到两个竞争同一设备的`/dev`节点,其中一个未连接到GEOM拓扑,这会导致令人困惑的行为。 -Second, the distinction explains why the 内核 has two sets of tools for inspecting 设备 state. `devfs_ruleset(8)`, `devfs.rules`, and per-node permissions belong to `devfs`. `geom(8)`, `gstat(8)`, `diskinfo(8)`, and the GEOM class tree belong to GEOM. When you are diagnosing a permissions problem, you look at `devfs`. When you are diagnosing an I/O problem, you look at GEOM. +第二,这种区别解释了为什么内核有两套用于检查设备状态的工具。`devfs_ruleset(8)`、`devfs.rules`和每个节点的权限属于`devfs`。`geom(8)`、`gstat(8)`、`diskinfo(8)`和GEOM类树属于GEOM。当你诊断权限问题时,你查看`devfs`。当你诊断I/O问题时,你查看GEOM。 -### A Concrete Example: /dev/null and /dev/ada0 +### 具体示例:/dev/null与/dev/ada0 -Compare two examples you already know. +比较你已经知道的两个示例。 -`/dev/null` is a classic 字符设备. It lives under `/dev` because `devfs` creates it. The 驱动程序 is `null(4)`, and its source is in `/usr/src/sys/dev/null/null.c`. When you write to `/dev/null`, `devfs` routes the request through `cdevsw` to the `null` 驱动程序's write function, which simply discards the bytes. There is no GEOM, no 缓冲区 cache, no 文件系统. It is a raw `devfs` character node. +`/dev/null`是一个经典的字符设备。它存在于`/dev`下是因为`devfs`创建了它。驱动程序是`null(4)`,其源码在`/usr/src/sys/dev/null/null.c`中。当你写入`/dev/null`时,`devfs`通过`cdevsw`将请求路由到`null`驱动程序的写入函数,该函数只是丢弃字节。没有GEOM,没有缓冲区缓存,没有文件系统。它是一个原始的`devfs`字符节点。 -`/dev/ada0` is a 块设备. It also lives under `/dev`. But the node is created by GEOM, not by a direct `make_dev` call in the `ada` 驱动程序. When you read raw bytes from `/dev/ada0`, those bytes flow through GEOM's character 接口 layer and arrive at the `ada` 驱动程序's strategy function. When you 挂载 UFS on `/dev/ada0` and then read a file, the file data flows through VFS, UFS, the 缓冲区 cache, and GEOM, and ends up in the same strategy function, without passing through `devfs` for each request. +`/dev/ada0`是一个块设备。它也存在于`/dev`下。但该节点是由GEOM创建的,而不是由`ada`驱动程序中的直接`make_dev`调用创建的。当你从`/dev/ada0`读取原始字节时,这些字节通过GEOM的字符接口层流到`ada`驱动程序的策略函数中。当你在`/dev/ada0`上挂载UFS然后读取文件时,文件数据流经VFS、UFS、缓冲区缓存和GEOM,最终到达相同的策略函数,而不会为每个请求通过`devfs`。 -The node in `devfs` is the same. The usage pattern is different. The 驱动程序 must handle both. +`devfs`中的节点是相同的。使用模式不同。驱动程序必须处理两者。 -### How We Will Proceed +### 我们将如何继续 -We will not write a character 驱动程序 in this chapter. We already wrote one in 第26章. Instead, we will write a 驱动程序 that 寄存器 with GEOM as a disk, and we will let GEOM create the `/dev` node for us. The devfs integration will be automatic. +我们不会在本章编写字符驱动程序。我们在第26章已经写过了。相反,我们将编写一个以磁盘形式向GEOM注册的驱动程序,并让GEOM为我们创建`/dev`节点。devfs集成将是自动的。 -This is the dominant pattern for 块 驱动程序 in FreeBSD 14.3. You can see it in `md(4)`, in `ata(4)`, in `nvme(4)`, and in almost every other 存储驱动程序. Each of them 寄存器 with GEOM, each of them receives `bio` requests, and each of them lets GEOM handle the `/dev` node. +这是FreeBSD 14.3中块驱动程序的主流模式。你可以在`md(4)`、`ata(4)`、`nvme(4)`以及几乎每个其他存储驱动程序中看到它。它们每一个都向GEOM注册,每一个都接收`bio`请求,每一个都让GEOM处理`/dev`节点。 ### 总结 Section 2 -`devfs` and VFS are distinct layers. `devfs` is a 文件系统 挂载ed at `/dev`, and VFS is the abstract 框架 that all 文件系统 plug into, including `devfs`. Storage 驱动程序 interact with both, but through GEOM, which takes care of creating the `/dev` node and of routing requests from both raw-access and 文件系统-access paths. For this chapter, we will use GEOM as our entry point and let it manage `devfs` on our behalf. +`devfs`和VFS是不同的层。`devfs`是挂载到`/dev`的文件系统,VFS是所有文件系统(包括`devfs`)插入的抽象框架。存储驱动程序与两者交互,但通过GEOM,GEOM负责创建`/dev`节点以及从原始访问路径和文件系统访问路径路由请求。在本章中,我们将使用GEOM作为入口点,让它代表我们管理`devfs`。 -In the next section, we will begin building the 驱动程序. We will start with the minimum needed to 注册 a pseudo 块设备 with GEOM, without yet implementing real I/O. Once that is in place, we will add the backing store, the `bio` handler, and everything else in later sections. +在下一节中,我们将开始构建驱动程序。我们将从向GEOM注册伪块设备所需的最少内容开始,暂不实现真正的I/O。一旦完成,我们将在后续小节中添加后备存储、`bio`处理程序和所有其他内容。 -## 第3节: Registering a Pseudo Block Device +## 第3节:注册伪块设备 -In this section we will create a skeleton 驱动程序 that 寄存器 a pseudo 块设备 with the 内核. We will not yet implement read or write. We will not yet wire it up to a backing store. Our goal is more modest and more important: we want to understand exactly what it takes to make the 内核 recognise our code as a 存储驱动程序, publish a `/dev` node for it, and let tools like `geom(8)` see it. +在本节中,我们将创建一个骨架驱动程序,向内核注册一个伪块设备。我们暂时不实现读取或写入。我们暂时不将其连接到后备存储。我们的目标更加温和但也更加重要:我们想确切了解让内核将我们的代码识别为存储驱动程序、为其发布`/dev`节点并让`geom(8)`等工具看到它需要什么。 -Once that is working, everything we add later will be purely incremental. The registration itself is the step that feels most mysterious, and it is the one the rest of the 驱动程序 builds on. +一旦这个工作完成,我们之后添加的一切都将纯粹是增量的。注册本身是最令人感到神秘的步骤,也是驱动程序其余部分构建的基础。 -### The g_disk API +### g_disk API -FreeBSD gives 存储驱动程序 a high-level registration API called `g_disk`. It lives in `/usr/src/sys/geom/geom_disk.c` and `/usr/src/sys/geom/geom_disk.h`. The API wraps the lower-level GEOM class machinery and exposes a simpler 接口 that matches what disk 驱动程序 usually need. +FreeBSD为存储驱动程序提供了一个称为`g_disk`的高级注册API。它位于`/usr/src/sys/geom/geom_disk.c`和`/usr/src/sys/geom/geom_disk.h`中。该API封装了较低层的GEOM类机制,暴露了更简单的接口,与磁盘驱动程序通常需要的相匹配。 -Using `g_disk` saves us from implementing a full `g_class` by hand. With `g_disk`, we allocate a `struct disk`, fill in a handful of fields and 回调 pointers, and call `disk_create`. The API takes care of building the GEOM class, creating the geom, publishing the provider, wiring up the character 接口, starting devstat accounting, and making our 设备 visible to userland through `/dev`. +使用`g_disk`使我们免于手工实现完整的`g_class`。使用`g_disk`时,我们分配一个`struct disk`,填充少量字段和回调指针,然后调用`disk_create`。该API负责构建GEOM类、创建geom、发布提供者、连接字符接口、启动devstat统计,以及使我们的设备通过`/dev`对用户空间可见。 -Not every 存储驱动程序 uses `g_disk`. GEOM classes that do transformations on other providers, like `g_nop`, `g_mirror`, `g_stripe`, or `g_eli`, are built directly on the lower-level `g_class` machinery because they are not disk-shaped. But for anything that looks like a disk, and certainly for a pseudo-disk like ours, `g_disk` is the right starting point. +并非每个存储驱动程序都使用`g_disk`。对其他提供者进行变换的GEOM类,如`g_nop`、`g_mirror`、`g_stripe`或`g_eli`,直接构建在较低层的`g_class`机制上,因为它们不是磁盘形状的。但对于任何看起来像磁盘的东西,当然也对于像我们这样的伪磁盘,`g_disk`是正确的起点。 -You can see the public structure in `/usr/src/sys/geom/geom_disk.h`. The shape is roughly the following, abbreviated for clarity. +你可以在`/usr/src/sys/geom/geom_disk.h`中看到公共结构。其形状大致如下,为清晰起见进行了缩略。 ```c struct disk { @@ -365,19 +365,19 @@ struct disk { }; ``` -The fields break down into three groups. +这些字段分为三组。 -**Identification**: `d_name` is a short string like `"myblk"` that names the disk class, and `d_unit` is a small integer that distinguishes multiple instances. Together they form the `/dev` node name. A 驱动程序 with `d_name = "myblk"` and `d_unit = 0` publishes `/dev/myblk0`. +**标识**:`d_name`是命名磁盘类的短字符串,如`"myblk"`,`d_unit`是区分多个实例的小整数。它们一起构成`/dev`节点名。`d_name = "myblk"`且`d_unit = 0`的驱动程序发布`/dev/myblk0`。 -**Callbacks**: the `d_open`, `d_close`, `d_strategy`, `d_ioctl`, `d_getattr`, and `d_gone` pointers are the functions the 内核 will call into our 驱动程序. Of these, only `d_strategy` is strictly required, because that is the function that handles actual I/O. The others are optional and we will discuss them as they become relevant. +**回调**:`d_open`、`d_close`、`d_strategy`、`d_ioctl`、`d_getattr`和`d_gone`指针是内核将调用到我们驱动程序中的函数。其中只有`d_strategy`是严格要求的,因为它是处理实际I/O的函数。其他都是可选的,我们将在它们变得相关时讨论。 -**Geometry**: `d_扇区ize`, `d_mediasize`, `d_fw扇区`, `d_fwheads`, and `d_maxsize` describe the disk's physical and logical shape. `d_扇区ize` is the size of a 扇区 in bytes, typically 512 or 4096. `d_mediasize` is the total size of the 设备 in bytes. `d_fw扇区` and `d_fwheads` are advisory hints used by 分区ing tools. `d_maxsize` is the largest single I/O the 驱动程序 can accept, which GEOM will use to split large requests. +**几何参数**:`d_sectorsize`、`d_mediasize`、`d_fwsectors`、`d_fwheads`和`d_maxsize`描述磁盘的物理和逻辑形状。`d_sectorsize`是扇区大小(字节),通常为512或4096。`d_mediasize`是设备的总大小(字节)。`d_fwsectors`和`d_fwheads`是分区工具使用的建议性提示。`d_maxsize`是驱动程序可以接受的最大单个I/O,GEOM将使用它来拆分大请求。 -**Driver state**: `d_drv1` is a generic pointer for the 驱动程序 to stash its own context. It is the closest equivalent to `设备_get_softc(dev)` in the New总线 world. +**驱动程序状态**:`d_drv1`是驱动程序用于存放自己上下文的通用指针。它相当于Newbus世界中`device_get_softc(dev)`的最近等价物。 -### A Minimum Skeleton +### 最小骨架 -Let us now sketch a minimum skeleton. We will place this in `examples/part-06/ch27-storage-vfs/myfirst_blk.c`. This initial version does almost nothing useful. It 寄存器 a disk, returns success on every operation, and un寄存器 cleanly on unload. But it is enough to appear in `/dev`, to be visible in `geom disk list`, and to be 探测d by `newfs_ufs` or `fdisk` without the 内核 crashing. +现在让我们勾画一个最小的骨架。我们将把它放在`examples/part-06/ch27-storage-vfs/myfirst_blk.c`中。这个初始版本几乎不做任何有用的事情。它注册一个磁盘,在每个操作上返回成功,并在卸载时干净地注销。但它足以出现在`/dev`中,在`geom disk list`中可见,并且可以被`newfs_ufs`或`fdisk`探测而不会导致内核崩溃。 ```c /* @@ -505,27 +505,27 @@ DECLARE_MODULE(myblk, myblk_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(myblk, 1); ``` -Take a moment to read this through. Only a handful of moving pieces are visible, but each of them is doing real work. +花一点时间仔细阅读这段代码。只有少量的活动部件可见,但每一个都在做真正的工作。 -The `myblk_softc` structure is the 驱动程序-local context. It holds a pointer to our `struct disk`, a 互斥锁 for future use, and the unit number. We allocate it on module load and free it on unload. +`myblk_softc`结构是驱动程序的本地上下文。它保存了指向`struct disk`的指针、一个供未来使用的互斥锁和单元号。我们在模块加载时分配它,在卸载时释放它。 -The `myblk_strategy` function is the 回调 that GEOM will invoke whenever a `bio` is directed at our 设备. In this first version, we simply fail every request with `ENXIO`. That is not polite, but it is correct as a placeholder: the 内核 will not 块 waiting for us, and we will not pretend that I/O succeeded when it did not. In Section 5 we will replace this with a working handler. +`myblk_strategy`函数是GEOM在`bio`指向我们的设备时将调用的回调函数。在这个第一个版本中,我们简单地对每个请求返回`ENXIO`失败。这不太礼貌,但作为占位符是正确的:内核不会阻塞等待我们,我们也不会在I/O未成功时假装成功了。在第5节中,我们将用可工作的处理程序替换它。 -The `myblk_附加_unit` function allocates a `struct disk`, fills in the identification, 回调, and geometry fields, and publishes it with `disk_create`. The call to `disk_create` is what actually produces the `/dev` node and 寄存器 the disk in the GEOM topology. +`myblk_attach_unit`函数分配一个`struct disk`,填充标识、回调和几何参数字段,然后用`disk_create`发布它。对`disk_create`的调用是实际产生`/dev`节点并在GEOM拓扑中注册磁盘的操作。 -The `myblk_分离_unit` function reverses that. `disk_destroy` asks GEOM to wither the provider, cancel any pending I/O, and remove the `/dev` node. We set `sc->disk` to `NULL` so that subsequent unload attempts do not try to free an already-freed structure, though in the load/unload path we follow that cannot happen. +`myblk_detach_unit`函数逆转该过程。`disk_destroy`请求GEOM使提供者枯萎,取消任何待处理的I/O,并移除`/dev`节点。我们将`sc->disk`设置为`NULL`,以便后续的卸载尝试不会试图释放已经释放的结构,尽管在我们遵循的加载/卸载路径中这不可能发生。 -The module loader is a standard `moduledata_t` boilerplate that you saw in 第26章. On `MOD_LOAD` it allocates the softc and calls `myblk_附加_unit`. On `MOD_UNLOAD` it calls `myblk_分离_unit`, frees the softc, and returns. +模块加载器是你在第26章中看到的标准`moduledata_t`模板。在`MOD_LOAD`时,它分配softc并调用`myblk_attach_unit`。在`MOD_UNLOAD`时,它调用`myblk_detach_unit`,释放softc,然后返回。 -One line deserves special attention. +有一行值得特别注意。 -The call `disk_create(sc->disk, DISK_VERSION)` passes the current ABI version of the disk structure. `DISK_VERSION` is defined in `/usr/src/sys/geom/geom_disk.h` and increments every time the `g_disk` ABI changes incompatibly. If you compile a 驱动程序 against the wrong tree, the 内核 will refuse to 注册 the disk and will print a diagnostic. This versioning is what allows the 内核 to evolve without silently breaking out-of-tree 驱动程序. +调用`disk_create(sc->disk, DISK_VERSION)`传递了磁盘结构的当前ABI版本。`DISK_VERSION`在`/usr/src/sys/geom/geom_disk.h`中定义,每当`g_disk` ABI不兼容地变更时递增。如果你针对错误的源码树编译驱动程序,内核将拒绝注册磁盘并打印诊断信息。这种版本控制机制允许内核在不静默破坏树外驱动程序的情况下演进。 -You may wonder why we do not use `MODULE_DEPEND` to declare a dependency on `g_disk`. The reason is that `g_disk` is not a loadable 内核模块 in the usual sense. It is a GEOM class declared in the 内核 via `DECLARE_GEOM_CLASS(g_disk_class, g_disk)` in `/usr/src/sys/geom/geom_disk.c`, and it is always present whenever GEOM itself is compiled into the 内核. There is no separate `g_disk.ko` file you can unload or reload independently, and `MODULE_DEPEND(myblk, g_disk, ...)` would not resolve to a real module. The symbols we call (`disk_alloc`, `disk_create`, `disk_destroy`) come from the 内核 itself. +你可能想知道为什么我们不使用`MODULE_DEPEND`来声明对`g_disk`的依赖。原因是`g_disk`在通常意义上不是一个可加载的内核模块。它是通过`/usr/src/sys/geom/geom_disk.c`中的`DECLARE_GEOM_CLASS(g_disk_class, g_disk)`在内核中声明的GEOM类,每当GEOM本身被编译进内核时它就存在。没有可以独立卸载或重新加载的单独`g_disk.ko`文件,`MODULE_DEPEND(myblk, g_disk, ...)`不会解析到一个真实的模块。我们调用的符号(`disk_alloc`、`disk_create`、`disk_destroy`)来自内核本身。 -### The Makefile +### Makefile -The Makefile for this module is almost identical to the one from 第26章. +这个模块的Makefile与第26章中的几乎相同。 ```make # Makefile for myfirst_blk. @@ -540,11 +540,11 @@ SRCS = myfirst_blk.c .include ``` -Place this in the same directory as `myfirst_blk.c`. Running `make` will build `myblk.ko`. Running `make load` will load it if you have the 内核 sources installed in the usual place. Running `make unload` will unload it. +将此文件放在与`myfirst_blk.c`相同的目录中。运行`make`将构建`myblk.ko`。如果你将内核源码安装在常规位置,运行`make load`将加载它。运行`make unload`将卸载它。 -### Loading and Inspecting the Skeleton +### 加载和检查骨架 -Once the module is loaded, the 内核 will have created a pseudo disk and a `/dev` node for it. Let us walk through what you should see. +模块加载后,内核将创建一个伪磁盘和对应的`/dev`节点。让我们浏览一下你应该看到的内容。 ```console # kldload ./myblk.ko @@ -562,9 +562,9 @@ crw-r----- 1 root operator 0x8b Apr 19 18:04 /dev/myblk0 myblk0 # Disk ident. ``` -The `c` at the beginning of the permissions string tells us that GEOM has created a 字符设备 node, which is how FreeBSD exposes 块-oriented 设备 under `/dev` in the modern 内核. The 设备 major number, here `0x8b`, is assigned dynamically. +权限字符串开头的`c`告诉我们GEOM创建了一个字符设备节点,这是现代内核在`/dev`下暴露面向块的设备的方式。设备主设备号,这里是`0x8b`,是动态分配的。 -Now let us look at the GEOM topology. +现在让我们看看GEOM拓扑。 ```console # geom disk list myblk0 @@ -581,9 +581,9 @@ Providers: fwheads: 0 ``` -`Mode: r0w0e0` means zero readers, zero writers, zero exclusive holders. Nobody is using the disk. +`Mode: r0w0e0`表示零个读取者、零个写入者、零个独占持有者。没有人正在使用磁盘。 -Now try something harmless. +现在尝试一些无害的操作。 ```console # dd if=/dev/myblk0 of=/dev/null bs=512 count=1 @@ -593,9 +593,9 @@ dd: /dev/myblk0: Device not configured 0 bytes transferred in 0.000123 secs (0 bytes/sec) ``` -The `Device not configured` error is the `ENXIO` we deliberately returned. Our strategy function ran, marked the BIO as failed, and `dd` faithfully reported the failure. This is the first real evidence that our 驱动程序 is being reached by the 内核's 块-layer code. +`Device not configured`错误是我们故意返回的`ENXIO`。我们的策略函数运行了,将BIO标记为失败,`dd`忠实地报告了失败。这是我们的驱动程序被内核块层代码到达的第一个真正证据。 -Try a read that expects success to fail loudly. +尝试一个期望成功的读取来大声失败。 ```console # newfs_ufs /dev/myblk0 @@ -607,9 +607,9 @@ super-block backups (for fsck_ffs -b #) at: 192, 832, 1472, 2112 ``` -The `-N` flag tells `newfs` to plan the 文件系统 layout without writing anything. We can see that it thinks of our 设备 as a small disk with 2048 扇区 of 512 bytes each. That matches the geometry we declared. It is not yet actually writing anything because our strategy function would still fail, but the planning works. +`-N`标志告诉`newfs`规划文件系统布局但不写入任何内容。我们可以看到它将我们的设备视为一个小型磁盘,有2048个512字节的扇区。这与我们声明的几何参数匹配。它实际上还没有写入任何内容,因为我们的策略函数仍然会失败,但规划是有效的。 -Finally, let us unload the module cleanly. +最后,让我们干净地卸载模块。 ```console # kldunload myblk @@ -619,89 +619,89 @@ myblk: unloaded ls: /dev/myblk0: No such file or directory ``` -That is the complete life cycle of the skeleton. +这就是骨架的完整生命周期。 -### Why the Failures Are Expected +### 为何这些失败是预期的 -At this stage, any user-space tool that actually tries to read or write data will fail. That is correct. Our strategy function does not yet know how to do anything, and we must not fake success. Faking success would lead to corruption the moment a 文件系统 tried to read back what it thought it had written. +在这个阶段,任何实际尝试读取或写入数据的用户空间工具都会失败。这是正确的。我们的策略函数还不知道如何做任何事情,我们绝不能伪造成功。伪造成功会在文件系统试图读回它认为已经写入的内容时导致数据损坏。 -The fact that the 内核 and the tools gracefully handle our failure is evidence that the 块 layer is doing its job. A `bio` came down, the 驱动程序 rejected it, the error propagated back up to user space, and no one crashed. That is the kind of behaviour we want. +内核和工具能够优雅地处理我们的失败这一事实证明块层正在正确地工作。一个`bio`传下来,驱动程序拒绝了它,错误传播回用户空间,没有人崩溃。这就是我们想要的行为。 -### How Things Fit Together +### 各部分如何组合 -Before moving on, let us name the pieces so we can refer to them later without ambiguity. +在继续之前,让我们命名这些部件,以便我们以后可以毫无歧义地引用它们。 -Our **驱动程序 module** is `myblk.ko`. It is what the user loads with `kldload`. +我们的**驱动程序模块**是`myblk.ko`。它是用户用`kldload`加载的东西。 -Our **softc** is `struct myblk_softc`. It holds 驱动程序-local state. There is exactly one instance in this first version. +我们的**softc**是`struct myblk_softc`。它保存驱动程序的本地状态。在第一个版本中恰好有一个实例。 -Our **disk** is a `struct disk` allocated by `disk_alloc` and 注册ed with `disk_create`. The 内核 owns its memory. We do not free it directly. We ask the 内核 to free it by calling `disk_destroy`. +我们的**磁盘**是由`disk_alloc`分配并用`disk_create`注册的`struct disk`。内核拥有它的内存。我们不直接释放它。我们通过调用`disk_destroy`请求内核释放它。 -Our **geom** is the GEOM object the `g_disk` subsystem creates on our behalf. We do not see it directly in our code. It exists in the GEOM topology as the parent of our provider. +我们的**geom**是`g_disk`子系统代表我们创建的GEOM对象。我们在代码中不直接看到它。它作为我们提供者的父级存在于GEOM拓扑中。 -Our **provider** is the producer-facing face of our 设备. It is what other GEOM classes consume when they connect to us. GEOM automatically creates a 字符设备 node for our provider under `/dev`. +我们的**提供者**是我们设备面向生产者的一面。它是其他GEOM类连接到我们时消费的东西。GEOM自动在`/dev`下为我们的提供者创建字符设备节点。 -Our **consumer** is still empty. We have no one connected to us yet. Consumers are how GEOM classes that sit above us, like a 分区ing layer or a 文件系统's GEOM consumer, 附加. +我们的**消费者**目前还是空的。还没有人连接到我们。消费者是位于我们之上的GEOM类(如分区层或文件系统的GEOM消费者)附加的方式。 -Our **/dev node** is `/dev/myblk0`. It is a live handle that user-space tools can use to issue raw I/O. When a 文件系统 is later 挂载ed on the 设备, it will also refer to the 设备 by this name, even though the hot I/O path will not pass through `devfs` for each request. +我们的**/dev节点**是`/dev/myblk0`。它是一个活跃的句柄,用户空间工具可以使用它来发出原始I/O。当文件系统后来挂载到设备上时,它也会通过这个名称引用设备,即使热I/O路径不会为每个请求通过`devfs`。 ### 总结 Section 3 -We built the smallest possible 驱动程序 that participates in the FreeBSD storage stack. It 寄存器 a pseudo disk with the `g_disk` subsystem, publishes a `/dev` node through GEOM, accepts BIO requests, and declines them politely. It loads, it appears in `geom disk list`, and it unloads without leaks. +我们构建了参与FreeBSD存储栈的最小可能驱动程序。它向`g_disk`子系统注册一个伪磁盘,通过GEOM发布`/dev`节点,接受BIO请求并礼貌地拒绝它们。它加载,它出现在`geom disk list`中,它卸载无泄漏。 -In the next section, we will look at GEOM more directly. We will understand what a provider really is, what a consumer really is, and how the class-based design lets transformations like 分区ing, mirroring, encryption, and compression compose with our 驱动程序 for free. That understanding will set us up for Section 5, where we replace the placeholder strategy function with one that actually serves reads and writes from a backing store. +在下一节中,我们将更直接地了解GEOM。我们将理解提供者到底是什么,消费者到底是什么,以及基于类的设计如何让分区、镜像、加密和压缩等变换与我们的驱动程序自由组合。这种理解将为我们进入第5节做好准备,在那里我们将用实际从后备存储提供读写的处理程序替换占位符策略函数。 -## 第4节: Exposing a GEOM-Backed Provider +## 第4节:暴露GEOM支持的提供者 -The previous section let us 注册 a disk with `g_disk` and take the word of the 框架 for what happens under the hood. That is a reasonable first step, and for many 驱动程序 it is all the involvement with GEOM that they ever need. But storage work rewards understanding the layer you are sitting on. When a 文件系统 挂载 fails, when `gstat` shows requests piling up, or when a `kldunload` 块 for longer than you expect, you will want to know the vocabulary of GEOM well enough to ask the right questions. +上一节让我们用`g_disk`注册了一个磁盘,并接受了框架关于底层发生的事情的说法。这是一个合理的起点,对于许多驱动程序来说,这就是它们与GEOM的全部交互。但存储工作需要对所坐的层有深入的理解。当文件系统挂载失败时,当`gstat`显示请求堆积时,或者当`kldunload`阻塞的时间超过你的预期时,你会希望足够了解GEOM的词汇来提出正确的问题。 -This section is a tour of GEOM from the storage-驱动程序 perspective. It is not an exhaustive reference. There are entire chapters in the FreeBSD Developer's Handbook devoted to GEOM, and we will not duplicate them. What we will do is describe the concepts and objects that matter to a 驱动程序 author, and show how `g_disk` fits into that picture. +本节是从存储驱动程序角度对GEOM的导览。它不是详尽的参考。FreeBSD开发者手册中有整章专门介绍GEOM,我们不会重复。我们要做的是描述对驱动程序作者重要的概念和对象,并展示`g_disk`如何融入这幅图景。 -### GEOM in One Page +### GEOM一页概览 -GEOM is a storage 框架. It sits between 文件系统 and the 块 驱动程序 that talk to real hardware, and it composes by design. That composition is the whole point. +GEOM是一个存储框架。它位于文件系统和与真实硬件对话的块驱动程序之间,按设计可组合。这种组合是其全部意义所在。 -The idea is that a storage stack is built out of small transformations. One transformation presents a raw disk. Another transformation splits it into 分区s. Another transformation mirrors two disks into one. Another transformation encrypts a 分区. Another transformation compresses a 文件系统. Each transformation is a small piece of code that takes in I/O requests from above, does something to them, and either returns a result directly or passes them along to the next layer below. +其理念是存储栈由小的变换构建而成。一个变换呈现原始磁盘。另一个变换将其拆分为分区。另一个变换将两个磁盘镜像为一个。另一个变换加密一个分区。另一个变换压缩一个文件系统。每个变换都是一小段代码,从上方接收I/O请求,对其进行处理,然后要么直接返回结果,要么将其传递给下一层。 -In GEOM's vocabulary, each transformation is a **class**. Each instance of a class is a **geom**. Each geom has some number of **providers**, which are its outputs, and some number of **consumers**, which are its inputs. Providers face upward toward the next layer. Consumers face downward toward the previous layer. A geom with no consumer is at the bottom of the stack: it must produce I/O on its own. A geom with no provider is at the top of the stack: it must terminate I/O and deliver it somewhere outside GEOM, typically into a 文件系统 or into a `devfs` 字符设备. +在GEOM的词汇中,每个变换是一个**类**。类的每个实例是一个**geom**。每个geom有若干**提供者**(其输出)和若干**消费者**(其输入)。提供者面向上方的下一层。消费者面向下方的前一层。没有消费者的geom位于栈的底部:它必须自己产生I/O。没有提供者的geom位于栈的顶部:它必须终止I/O并将其传递到GEOM之外的某个地方,通常是文件系统或`devfs`字符设备。 -Requests flow from providers to consumers through the stack. Replies flow back. The unit of I/O is a `struct bio`, which we will study in detail in Section 5. +请求从提供者通过栈流向消费者。回复沿相反方向流回。I/O的单位是`struct bio`,我们将在第5节详细研究。 -### A Concrete Example of Composition +### 组合的具体示例 -Imagine you have a 1 TB SATA SSD. The 内核's `ada(4)` 驱动程序 runs on the SATA controller and publishes a disk provider called `ada0`. That is a geom with no consumer at the bottom and one provider at the top. +假设你有一个1 TB的SATA SSD。内核的`ada(4)`驱动程序在SATA控制器上运行,发布一个名为`ada0`的磁盘提供者。那是一个底部没有消费者、顶部有一个提供者的geom。 -You slice the SSD with `gpart`. The `PART` class creates a geom whose single consumer is 附加ed to `ada0`, and which publishes multiple providers, one per 分区: `ada0p1`, `ada0p2`, `ada0p3`, and so on. +你用`gpart`对SSD进行切片。`PART`类创建一个geom,其单个消费者附加到`ada0`,并发布多个提供者,每个分区一个:`ada0p1`、`ada0p2`、`ada0p3`等等。 -You encrypt `ada0p2` with `geli`. The `ELI` class creates a geom whose single consumer is 附加ed to `ada0p2`, and which publishes a single provider called `ada0p2.eli`. +你用`geli`加密`ada0p2`。`ELI`类创建一个geom,其单个消费者附加到`ada0p2`,并发布一个名为`ada0p2.eli`的提供者。 -You 挂载 UFS on `ada0p2.eli`. UFS opens that provider, reads its super块, and begins serving files. +你在`ada0p2.eli`上挂载UFS。UFS打开该提供者,读取其超级块,并开始提供文件服务。 -When a process reads a file, the request travels from UFS, to `ada0p2.eli`, through the `geli` geom which decrypts the relevant 块, to `ada0p2`, through the `PART` geom which offsets the 块 addresses, to `ada0`, where the `ada` 驱动程序 talks to the SATA controller. +当进程读取文件时,请求从UFS出发,到`ada0p2.eli`,通过`geli` geom解密相关块,到`ada0p2`,通过`PART` geom偏移块地址,到`ada0`,`ada`驱动程序与SATA控制器通信。 -At no point does UFS know that its underlying storage is encrypted, 分区ed, or even a physical disk. It just sees a provider. The layers below it can be as simple or as elaborate as the administrator chooses. +UFS始终不知道其底层存储是加密的、分区的,甚至是一个物理磁盘。它只看到一个提供者。它下面的层可以简单也可以复杂,由管理员选择。 -That composition is the reason GEOM exists. A single 存储驱动程序 only needs to know how to be a reliable bottom-of-stack producer of I/O. Everything above it is reusable. +这种组合就是GEOM存在的原因。单个存储驱动程序只需要知道如何成为可靠的栈底I/O生产者。它上面的所有东西都是可重用的。 -### Providers and Consumers in Code +### 代码中的提供者和消费者 -In the 内核, a provider is a `struct g_provider` and a consumer is a `struct g_consumer`. Both are defined in `/usr/src/sys/geom/geom.h`. As a disk 驱动程序 author, you almost never allocate either directly. `g_disk` allocates a provider on your behalf when you call `disk_create`, and you never need a consumer, because a disk 驱动程序 does not 附加 to anything underneath. +在内核中,提供者是`struct g_provider`,消费者是`struct g_consumer`。两者都在`/usr/src/sys/geom/geom.h`中定义。作为磁盘驱动程序作者,你几乎从不直接分配它们中的任何一个。`g_disk`在你调用`disk_create`时代表你分配一个提供者,而你从不需要消费者,因为磁盘驱动程序不附加到下面的任何东西。 -What you do need is a mental model of what they mean. +你确实需要的是对它们含义的心智模型。 -A provider is a named, seekable, 块-addressable surface that something can read and write. It has a size, a 扇区 size, a name, and some access counters. GEOM publishes providers in `/dev` via its character-设备 integration, so the administrator can refer to them by name. +提供者是一个命名的、可寻址的、块可寻址的表面,可供读写。它有大小、扇区大小、名称和一些访问计数器。GEOM通过其字符设备集成在`/dev`中发布提供者,因此管理员可以通过名称引用它们。 -A consumer is a channel from one geom into another geom's provider. The consumer is where the upper geom issues I/O requests, and it is where the upper geom 寄存器 access rights. When you 挂载 UFS on `ada0p2.eli`, the 挂载 operation causes a consumer to be 附加ed inside UFS's GEOM hook, and that consumer acquires access rights on the `ada0p2.eli` provider. +消费者是从一个geom到另一个geom的提供者的通道。消费者是上层geom发出I/O请求的地方,也是上层geom注册访问权限的地方。当你在`ada0p2.eli`上挂载UFS时,挂载操作导致一个消费者被附加在UFS的GEOM钩子内,该消费者获取对`ada0p2.eli`提供者的访问权限。 -### Access Rights +### 访问权限 -Providers have three access counters: read (`r`), write (`w`), and exclusive (`e`). They are visible in `gstat` and `geom disk list` as `r0w0e0` or similar. Each number is incremented when a consumer asks for that kind of access and decremented when the consumer releases it. +提供者有三个访问计数器:读取(`r`)、写入(`w`)和独占(`e`)。它们在`gstat`和`geom disk list`中可见,显示为`r0w0e0`或类似的格式。每个数字在消费者请求该类型的访问时递增,在消费者释放时递减。 -An exclusive access is what `挂载`, `newfs`, and similar administrative tools acquire when they need to be sure no other process is writing the 设备. An exclusive count of zero means no exclusive access is held. An exclusive count greater than zero means the provider is 总线y. +独占访问是`mount`、`newfs`等管理工具在需要确保没有其他进程正在写入设备时获取的。独占计数为零意味着没有持有独占访问。独占计数大于零意味着提供者正忙。 -The access counts are not trivia. They are a real synchronisation tool. When you call `disk_destroy` to remove a disk, the 内核 will refuse to destroy the provider if it still has open users, because destroying it under the feet of a 挂载ed 文件系统 would be catastrophic. This is the same mechanism that makes `kldunload` 块 if the module is in use, but it operates at the GEOM layer, one level higher than the module subsystem. +访问计数不是琐碎的细节。它们是真正的同步工具。当你调用`disk_destroy`移除磁盘时,如果提供者仍有打开的用户,内核将拒绝销毁它,因为在已挂载的文件系统脚下销毁它将是灾难性的。这与`kldunload`在模块使用中时阻塞的机制相同,但它在GEOM层操作,比模块子系统高一级。 -You can watch the access counters change in real time. +你可以实时观察访问计数器的变化。 ```console # geom disk list myblk0 | grep Mode @@ -711,88 +711,88 @@ You can watch the access counters change in real time. Mode: r1w0e0 ``` -When `dd` finishes, the mode returns to `r0w0e0`. +当`dd`完成时,模式返回到`r0w0e0`。 -### The BIO Object and Its Life Cycle +### BIO对象及其生命周期 -The unit of work in GEOM is the BIO, defined as `struct bio` in `/usr/src/sys/sys/bio.h`. A BIO represents one I/O request. It has a command (`bio_cmd`), an offset (`bio_offset`), a length (`bio_length`), a data pointer (`bio_data`), a byte count (`bio_bcount`), a residual (`bio_resid`), an error (`bio_error`), flags (`bio_flags`), and a number of other fields that we will meet as we need them. +GEOM中的工作单位是BIO,在`/usr/src/sys/sys/bio.h`中定义为`struct bio`。一个BIO代表一个I/O请求。它有一个命令(`bio_cmd`)、一个偏移量(`bio_offset`)、一个长度(`bio_length`)、一个数据指针(`bio_data`)、一个字节计数(`bio_bcount`)、一个剩余量(`bio_resid`)、一个错误(`bio_error`)、标志(`bio_flags`),以及我们将在需要时遇到的其他一些字段。 -The `bio_cmd` values tell the 驱动程序 what kind of I/O is being requested. The most common values are `BIO_READ`, `BIO_WRITE`, `BIO_DELETE`, `BIO_GETATTR`, and `BIO_FLUSH`. `BIO_READ` and `BIO_WRITE` are what you expect. `BIO_DELETE` asks the 驱动程序 to release the 块 in the range, the way `TRIM` does on SSDs or `mdconfig -d` does on a memory disk. `BIO_GETATTR` queries an attribute by name and is how GEOM layers discover 分区 types, media labels, and other metadata. `BIO_FLUSH` asks the 驱动程序 to commit outstanding writes to stable storage. +`bio_cmd`的值告诉驱动程序正在请求什么类型的I/O。最常见的值是`BIO_READ`、`BIO_WRITE`、`BIO_DELETE`、`BIO_GETATTR`和`BIO_FLUSH`。`BIO_READ`和`BIO_WRITE`如你所预期。`BIO_DELETE`要求驱动程序释放范围内的块,就像SSD上的`TRIM`或内存磁盘上的`mdconfig -d`所做的那样。`BIO_GETATTR`通过名称查询属性,是GEOM层发现分区类型、介质标签和其他元数据的方式。`BIO_FLUSH`要求驱动程序将未完成的写入提交到稳定存储。 -A BIO travels downward from one geom to the next via `g_io_request`. When it reaches the bottom of the stack, the 驱动程序's strategy function is called. When the 驱动程序 is done, it completes the BIO by calling `biodone` or, at the GEOM class level, `g_io_deliver`. The completion call releases the BIO back up the stack. +BIO通过`g_io_request`从一个geom向下传递到下一个。当它到达栈底时,驱动程序的策略函数被调用。当驱动程序完成时,它通过调用`biodone`或在GEOM类级别调用`g_io_deliver`来完成BIO。完成调用将BIO沿栈向上释放。 -`g_disk` 驱动程序 get a slightly simpler view because the `g_disk` infrastructure translates GEOM-level BIO handling into `biodone`-style completion. When you implement `d_strategy`, you receive a `struct bio` and you must eventually call `biodone(bp)` to complete it. You do not call `g_io_deliver` directly. The 框架 does. +`g_disk`驱动程序得到稍微简化的视图,因为`g_disk`基础设施将GEOM级别的BIO处理转换为`biodone`风格的完成方式。当你实现`d_strategy`时,你接收一个`struct bio`,最终必须调用`biodone(bp)`来完成它。你不直接调用`g_io_deliver`。框架来做。 -### The GEOM Topology Lock +### GEOM拓扑锁 -GEOM has a global lock called the topology lock. It protects modifications to the tree of geoms, providers, and consumers. When a provider is created or destroyed, when a consumer is 附加ed or 分离ed, when access counts change, or when GEOM walks the tree to route a request, the topology lock is taken. +GEOM有一个称为拓扑锁的全局锁。它保护geom、提供者和消费者树的修改。当提供者被创建或销毁时,当消费者被附加或分离时,当访问计数变化时,或当GEOM遍历树来路由请求时,都会获取拓扑锁。 -The topology lock is held across operations that can take time, which is unusual for 内核 locks, so GEOM operates much of its real work asynchronously through a dedicated thread called the event queue. When you look at `g_class` definitions in the source tree, the `init`, `fini`, `access`, and similar methods are invoked in the context of the GEOM event thread, not in the context of the user process that triggered the operation. +拓扑锁在可能耗时的操作期间被持有,这对内核锁来说是不寻常的,所以GEOM通过称为事件队列的专用线程异步执行其大部分实际工作。当你在源码树中查看`g_class`定义时,`init`、`fini`、`access`和类似方法是在GEOM事件线程的上下文中调用的,而不是在触发操作的用户进程的上下文中。 -For a 驱动程序 using `g_disk`, this matters in one specific way. You should not hold your own 驱动程序 lock across a call into GEOM-level functions, because GEOM may acquire the topology lock inside those functions, and nested locking in the wrong order leads to deadlock. `g_disk` is written carefully enough that you do not usually have to think about this as long as you follow the patterns we show. But the fact is worth knowing. +对于使用`g_disk`的驱动程序,这在一个特定方面很重要。你不应该在调用GEOM级别函数时持有自己的驱动程序锁,因为GEOM可能在那些函数内部获取拓扑锁,错误的嵌套锁定顺序会导致死锁。`g_disk`编写得足够仔细,只要你遵循我们展示的模式,通常不需要考虑这一点。但这个事实值得了解。 -### The GEOM Event Queue +### GEOM事件队列 -GEOM processes many events on a single dedicated 内核 thread called `g_event`. If you have the 内核 running with debugging enabled, you can see it in `procstat -kk`. This thread picks up events placed on its queue and processes them one at a time. Typical events include creating a geom, destroying a geom, 附加ing a consumer, 分离ing a consumer, and retasting a provider. +GEOM在名为`g_event`的单一专用内核线程上处理许多事件。如果你在启用调试的情况下运行内核,你可以在`procstat -kk`中看到它。该线程从其队列中拾取事件并逐个处理。典型事件包括创建geom、销毁geom、附加消费者、分离消费者和重新品尝提供者。 -A practical consequence is that some actions you take from your 驱动程序, such as `disk_destroy`, do not happen synchronously in the context of the calling thread. They get queued for the event thread, and the actual destruction happens a moment later. `disk_destroy` handles the waiting correctly so that by the time it returns, the disk is gone. But if you are chasing a subtle ordering bug, remembering that GEOM has its own thread can help. +一个实际的后果是,你从驱动程序采取的某些操作(如`disk_destroy`)不会在调用线程的上下文中同步发生。它们被排队等待事件线程处理,实际的销毁在稍后发生。`disk_destroy`正确处理了等待,所以在它返回时,磁盘已经消失了。但如果你在追踪一个微妙的排序bug,记住GEOM有自己的线程可能会有帮助。 -### How g_disk Wraps All of This +### g_disk如何封装这一切 -With that vocabulary in hand, we can now describe what `g_disk` does for us more precisely. +有了这些词汇,我们现在可以更精确地描述`g_disk`为我们做了什么。 -When we call `disk_alloc`, we receive a `struct disk` that is pre-initialised enough to be filled in. We set the name, unit, 回调, and geometry, then call `disk_create`. +当我们调用`disk_alloc`时,我们收到一个已经预初始化到足以填充的`struct disk`。我们设置名称、单元、回调和几何参数,然后调用`disk_create`。 -`disk_create` does the following for us, through the event queue: +`disk_create`通过事件队列为我们执行以下操作: -1. creates a GEOM class if one does not already exist for this disk name, -2. creates a geom under that class, -3. creates a provider associated with the geom, -4. sets up devstat accounting so that `iostat` and `gstat` have data, -5. wires up GEOM's character-设备 接口 so that `/dev/` appears, -6. arranges for BIO requests to flow into our `d_strategy` 回调. +1. 如果该磁盘名称的GEOM类不存在,则创建一个, +2. 在该类下创建一个geom, +3. 创建与geom关联的提供者, +4. 设置devstat统计,使`iostat`和`gstat`有数据, +5. 连接GEOM的字符设备接口,使`/dev/`出现, +6. 安排BIO请求流入我们的`d_strategy`回调。 -It also sets up a few optional behaviours. If we provide a `d_ioctl`, the 内核 routes user-space `ioctl` calls on the `/dev` node through to our function. If we provide a `d_getattr`, GEOM routes `BIO_GETATTR` requests through to it. If we provide a `d_gone`, the 内核 calls it if something outside our 驱动程序 decides the disk is gone, such as a hotplug removal event. +它还设置了一些可选行为。如果我们提供`d_ioctl`,内核将`/dev`节点上的用户空间`ioctl`调用路由到我们的函数。如果我们提供`d_getattr`,GEOM将`BIO_GETATTR`请求路由到它。如果我们提供`d_gone`,当我们驱动程序之外的东西决定磁盘已消失(如热插拔移除事件)时,内核会调用它。 -On the teardown side, `disk_destroy` queues the removal, waits for all pending I/O to drain, releases the provider, destroys the geom, and frees the `struct disk`. We do not call `free` on the disk ourselves. The 框架 does that. +在拆解侧,`disk_destroy`排队移除,等待所有待处理的I/O排干,释放提供者,销毁geom,并释放`struct disk`。我们不自己调用`free`释放磁盘。框架来做。 -### Where to Read Source +### 在哪里阅读源码 -You now have enough vocabulary to benefit from reading the `g_disk` source directly. Open `/usr/src/sys/geom/geom_disk.c` and look for the following. +你现在有足够的词汇来直接从阅读`g_disk`源码中受益了。打开`/usr/src/sys/geom/geom_disk.c`并查找以下内容。 -The function `disk_alloc` is early in the file. It is a simple allocator that returns a zeroed `struct disk`. Nothing dramatic. +函数`disk_alloc`在文件的开头。它是一个简单的分配器,返回一个清零的`struct disk`。没什么戏剧性的。 -The function `disk_create` is longer. Skim it and notice the event-based approach: most of the real work is queued rather than performed inline. Also notice the sanity checks on the disk's fields, which catch 驱动程序 that forget to set the 扇区 size, the media size, or the strategy function. +函数`disk_create`更长。略读它并注意基于事件的方法:大部分实际工作是排队的,而不是内联执行的。同时注意对磁盘字段的健全性检查,它们能捕获忘记设置扇区大小、介质大小或策略函数的驱动程序。 -The function `disk_destroy` is similarly event-queued. It guards the teardown with an access-count check, because destroying a disk that is still open would be a bug. +函数`disk_destroy`同样是事件排队的。它用访问计数检查来保护拆解,因为销毁仍然打开的磁盘将是一个bug。 -The function `g_disk_start` is the inner strategy function. It validates a BIO, updates devstat, and calls the 驱动程序's `d_strategy`. +函数`g_disk_start`是内部策略函数。它验证BIO,更新devstat,并调用驱动程序的`d_strategy`。 -Take a moment to look at the code. You do not need to understand every branch. You do need to recognise the overall shape: events for structural changes, inline work for I/O. That is the shape of most GEOM-based code. +花一点时间看看代码。你不需要理解每个分支。你确实需要识别整体形状:结构变更用事件,I/O用内联工作。这就是大多数基于GEOM的代码的形状。 -### Comparing md(4) and g_zero +### 比较md(4)和g_zero -Two real 驱动程序 make good reading as counterpoints to `g_disk`. The first is the `md(4)` 驱动程序, in `/usr/src/sys/dev/md/md.c`. This is a memory-disk 驱动程序 that uses both `g_disk` and directly managed GEOM structures. It is the most thorough example of a 存储驱动程序 in the tree, supporting multiple backing-store types, resizing, dumping, and many other features. It is a large file, but it is the closest relative of what we are building. +两个真实的驱动程序是作为`g_disk`对照的良好阅读材料。第一个是`md(4)`驱动程序,在`/usr/src/sys/dev/md/md.c`中。这是一个内存磁盘驱动程序,同时使用`g_disk`和直接管理的GEOM结构。它是源码树中最全面的存储驱动程序示例,支持多种后备存储类型、调整大小、转储和许多其他功能。它是一个大文件,但它是我们正在构建的东西的最近亲。 -The second is `g_zero`, in `/usr/src/sys/geom/zero/g_zero.c`. This is a minimal GEOM class that reads always return zeroed memory and writes are discarded. It is roughly 145 lines and uses the lower-level `DECLARE_GEOM_CLASS` API directly rather than `g_disk`. It is a great counterpoint because it shows the GEOM class mechanics without any of the disk-specific adornment. When you want to understand what `g_disk` hides, read `g_zero`. +第二个是`g_zero`,在`/usr/src/sys/geom/zero/g_zero.c`中。这是一个最小的GEOM类,读取总是返回清零的内存,写入被丢弃。它大约145行,直接使用较低层的`DECLARE_GEOM_CLASS` API而不是`g_disk`。它是一个很好的对照,因为它展示了没有任何磁盘特定装饰的GEOM类机制。当你想理解`g_disk`隐藏了什么时,阅读`g_zero`。 -### Why Our Driver Uses g_disk +### 我们的驱动程序为何使用g_disk -You might ask whether we should build our 驱动程序 directly on the lower-level `g_class` API, the way `g_zero` does, to expose more of the machinery. We will not, for three reasons. +你可能会问我们是否应该像`g_zero`那样直接在较低层的`g_class` API上构建驱动程序,以暴露更多机制。我们不会,有三个原因。 -First, `g_disk` is the idiomatic choice for anything that looks like a disk, which our pseudo 块设备 does. Reviewers of real FreeBSD 驱动程序 patches would push back on a 驱动程序 that used `g_class` directly when `g_disk` would do. +第一,`g_disk`是任何看起来像磁盘的东西的惯用选择,而我们的伪块设备就是如此。真正的FreeBSD驱动程序补丁的审查者会对在`g_disk`可用时直接使用`g_class`的驱动程序提出反对。 -Second, `g_disk` gives us devstat integration, standard ioctls, and `/dev` node management for free. Re-implementing those by hand would be a substantial distraction from the teaching goal of this chapter. +第二,`g_disk`免费为我们提供devstat集成、标准ioctl和`/dev`节点管理。手工重新实现这些将是对本章教学目标的重大干扰。 -Third, the simpler the first working 驱动程序, the easier it is to reason about. We have plenty of code to write in the next few sections. We do not need to spend pages on class-level GEOM plumbing that `g_disk` already gets right. +第三,第一个可工作的驱动程序越简单,就越容易推理。我们在接下来的几个小节中有很多代码要写。我们不需要在`g_disk`已经正确处理的类级别GEOM管道上花费篇幅。 -That said, if you are curious, you should absolutely read `g_zero.c`. It is a small file and it reveals the mechanics that `g_disk` abstracts. The 总结 for this section will point you to it one last time. +话虽如此,如果你好奇,绝对应该阅读`g_zero.c`。它是一个小文件,揭示了`g_disk`抽象的机制。本节的总结将最后一次指向它。 -### A Walk Through g_class +### g_class详解 -For readers who want a little more of the underlying machinery, let us walk through what a `g_class` structure looks like in code, without yet building one of our own. +对于想要更多底层机制的读者,让我们走一遍`g_class`结构在代码中的样子,先不构建我们自己的。 -The following is reproduced (slightly simplified) from `/usr/src/sys/geom/zero/g_zero.c`. +以下内容(略有简化)摘自`/usr/src/sys/geom/zero/g_zero.c`。 ```c static struct g_class g_zero_class = { @@ -807,71 +807,71 @@ static struct g_class g_zero_class = { DECLARE_GEOM_CLASS(g_zero_class, g_zero); ``` -`.name` is the class name, used in `geom -t` output. `.version` must match `G_VERSION` for the running 内核; mismatched versions are rejected at load time. `.start` is the function called when a BIO arrives at a provider of this class. `.init` is called when the class is first instantiated, typically to create the initial geom and its provider. `.fini` is the teardown counterpart to `.init`. `.destroy_geom` is called when a specific geom under this class is being removed. +`.name`是类名,用于`geom -t`输出。`.version`必须与运行内核的`G_VERSION`匹配;版本不匹配在加载时被拒绝。`.start`是当BIO到达该类的提供者时调用的函数。`.init`在类首次实例化时调用,通常用于创建初始geom及其提供者。`.fini`是`.init`的拆解对应物。`.destroy_geom`在该类下的特定geom被移除时调用。 -`DECLARE_GEOM_CLASS` is a macro that expands to a module declaration that loads this class into the 内核 when the module is loaded. It hides the `moduledata_t`, the `SYSINIT`, and the `g_modevent` wiring behind a single line. +`DECLARE_GEOM_CLASS`是一个宏,展开为一个模块声明,在模块加载时将该类加载到内核中。它在单行后面隐藏了`moduledata_t`、`SYSINIT`和`g_modevent`的连接。 -Our 驱动程序 does not use `g_class` directly. `g_disk` does it for us, and the class it declares under the hood is the universal `DISK` class that all disk-shaped 驱动程序 share. But understanding the structure is useful because, if you ever write a transformation class (a GEOM-level encrypt, compress, or 分区 layer), you will define your own `g_class`. +我们的驱动程序不直接使用`g_class`。`g_disk`为我们做了,它在底层声明的类是所有磁盘形状的驱动程序共享的通用`DISK`类。但理解这个结构是有用的,因为如果你以后要编写变换类(GEOM级别的加密、压缩或分区层),你将定义自己的`g_class`。 -### The Life of a BIO, In Detail +### BIO的生命周期详解 -We covered the BIO life cycle briefly earlier. Here it is in more detail, because every storage-驱动程序 bug touches this life cycle at some point. +我们之前简要介绍了BIO的生命周期。这里更详细地说明,因为每个存储驱动程序的bug都会在某个时候触及这个生命周期。 -A BIO originates somewhere above the 驱动程序. For our 驱动程序, the most common origins are: +BIO在驱动程序之上的某个地方产生。对于我们的驱动程序,最常见的来源是: -1. **A 文件系统's 缓冲区-cache write-back**. UFS calls `bwrite` or `bawrite` on a 缓冲区, which builds a BIO and hands it to GEOM through `g_io_request`. -2. **A 文件系统's 缓冲区-cache read**. UFS calls `bread`, which checks the cache and, on a miss, issues a BIO. -3. **A raw access through `/dev/myblk0`**. A program calls `read(2)` or `write(2)` on the node. `devfs` and GEOM's character-设备 integration build a BIO and issue it. -4. **A tool-issued operation**. `newfs_ufs`, `diskinfo`, `dd`, and similar tools issue BIOs the same way as a raw access. +1. **文件系统的缓冲区缓存回写**。UFS在缓冲区上调用`bwrite`或`bawrite`,构建一个BIO并通过`g_io_request`将其交给GEOM。 +2. **文件系统的缓冲区缓存读取**。UFS调用`bread`,检查缓存,在未命中时发出BIO。 +3. **通过`/dev/myblk0`的原始访问**。程序在节点上调用`read(2)`或`write(2)`。`devfs`和GEOM的字符设备集成构建一个BIO并发出它。 +4. **工具发出的操作**。`newfs_ufs`、`diskinfo`、`dd`和类似工具以与原始访问相同的方式发出BIO。 -Once built, the BIO is routed through GEOM's topology. Each consumer -> provider hop along the way may transform or validate the BIO. For a simple stack (our 驱动程序 with no intermediate geoms), there are no intermediate hops; the BIO arrives at our provider and is dispatched to our strategy function. +BIO构建后,通过GEOM的拓扑路由。沿途的每个消费者->提供者跳转可能会变换或验证BIO。对于简单的栈(我们的驱动程序没有中间geom),没有中间跳转;BIO到达我们的提供者并被分派到我们的策略函数。 -Inside `g_disk`, the strategy function is preceded by three small pieces of bookkeeping: +在`g_disk`内部,策略函数之前有三个小的簿记步骤: -1. Some sanity checks (for instance, verifying that the BIO's offset and length are within the media). -2. A call to `devstat_start_transaction_bio` to start timing the request. -3. A call to the 驱动程序's `d_strategy`. +1. 一些健全性检查(例如,验证BIO的偏移量和长度在介质范围内)。 +2. 调用`devstat_start_transaction_bio`开始为请求计时。 +3. 调用驱动程序的`d_strategy`。 -On completion, `g_disk` intercepts the `biodone` call, records the end time with `devstat_end_transaction_bio`, and forwards the completion up the stack. +在完成时,`g_disk`拦截`biodone`调用,用`devstat_end_transaction_bio`记录结束时间,并将完成沿栈向上转发。 -From the 驱动程序's point of view, the only thing that matters is that `d_strategy` gets called, and that `biodone` is called once per BIO. Everything else is plumbing. +从驱动程序的角度看,唯一重要的是`d_strategy`被调用,并且每个BIO恰好调用一次`biodone`。其他一切都是管道。 -### Error Propagation +### 错误传播 -When a BIO fails, the 驱动程序 sets `bio_error` to an `errno` value and sets the `BIO_ERROR` flag in `bio_flags`. `biodone` is then called as normal. +当BIO失败时,驱动程序将`bio_error`设置为一个`errno`值,并在`bio_flags`中设置`BIO_ERROR`标志。然后像平常一样调用`biodone`。 -Above the 驱动程序, GEOM's completion code checks for the error. If set, the error is propagated up the stack. The 文件系统 sees the error and decides what to do; typically, a read error on metadata is fatal and the 文件系统 reports EIO to user space. A write error is often delayed; the 文件系统 may retry, or may mark the associated 缓冲区 as needing attention on the next sync. +在驱动程序之上,GEOM的完成代码检查错误。如果设置了错误,错误沿栈向上传播。文件系统看到错误并决定怎么做;通常,元数据上的读取错误是致命的,文件系统向用户空间报告EIO。写入错误通常被延迟;文件系统可能重试,或者可能将关联的缓冲区标记为需要在下次同步时注意。 -Common `errno` values in the BIO path: +BIO路径中常见的`errno`值: -- `EIO`: a generic I/O error. The 内核 assumes the 设备 is having trouble. -- `ENXIO`: the 设备 is not configured or has gone away. -- `EOPNOTSUPP`: the 驱动程序 does not support this operation. -- `EROFS`: the medium is read-only. -- `ENOSPC`: no space available. -- `EFAULT`: an address in the request is invalid. Very rare in the BIO path. +- `EIO`:通用I/O错误。内核假设设备遇到问题。 +- `ENXIO`:设备未配置或已消失。 +- `EOPNOTSUPP`:驱动程序不支持此操作。 +- `EROFS`:介质是只读的。 +- `ENOSPC`:没有可用空间。 +- `EFAULT`:请求中的地址无效。在BIO路径中非常罕见。 -For our in-memory 驱动程序, the only errors that should ever appear are the bounds-check error (`EIO`) and the unknown-command error (`EOPNOTSUPP`). +对于我们的内存驱动程序,唯一应该出现的错误是边界检查错误(`EIO`)和未知命令错误(`EOPNOTSUPP`)。 -### What g_disk Does That You Do Not See +### g_disk为你做的你看不到的事 -We have mentioned that `g_disk` takes care of several things on our behalf. Here is a fuller list. +我们提到过`g_disk`代表我们处理了几件事情。这里是更完整的列表。 -- It creates the GEOM class for the `DISK` type if it does not already exist, and it shares this class among all disk 驱动程序. -- It creates a geom under that class when we call `disk_create`. -- It creates a provider on the geom and publishes it in `/dev`. -- It wires up devstat accounting automatically. -- It handles the GEOM access protocol, converting user-space `open` and `close` calls on `/dev/myblk0` into provider access-count changes. -- It handles the GEOM character-设备 接口, converting read and write on `/dev/myblk0` into BIOs to our strategy function. -- It handles the BIO_GETATTR default cases (most attributes have sensible defaults). -- It handles withering on `disk_destroy`, waiting for in-flight BIOs. -- It forwards `d_ioctl` calls for ioctls it does not handle itself. +- 如果`DISK`类型的GEOM类不存在,它会创建它,并在所有磁盘驱动程序之间共享该类。 +- 当我们调用`disk_create`时,它在该类下创建一个geom。 +- 它在geom上创建一个提供者并在`/dev`中发布。 +- 它自动连接devstat统计。 +- 它处理GEOM访问协议,将`/dev/myblk0`上的用户空间`open`和`close`调用转换为提供者访问计数变化。 +- 它处理GEOM字符设备接口,将`/dev/myblk0`上的读写转换为到我们策略函数的BIO。 +- 它处理BIO_GETATTR的默认情况(大多数属性有合理的默认值)。 +- 它处理`disk_destroy`时的枯萎,等待飞行中的BIO。 +- 它转发它自己不处理的ioctl的`d_ioctl`调用。 -Each of these is a piece of code you would have to write if you built directly on `g_class`. Reading `/usr/src/sys/geom/geom_disk.c` is a good way to appreciate just how much `g_disk` does for us. +这些中的每一项都是如果你直接在`g_class`上构建就必须编写的代码。阅读`/usr/src/sys/geom/geom_disk.c`是感受`g_disk`为我们做了多少的好方法。 -### Inspecting Our Provider +### 检查我们的提供者 -Let us take our skeleton 驱动程序 from Section 3, load it, and inspect it through GEOM's eyes. +让我们从第3节中取出我们的骨架驱动程序,加载它,并通过GEOM的眼睛检查它。 ```console # kldload ./myblk.ko @@ -889,7 +889,7 @@ Providers: fwheads: 0 ``` -`geom disk list` shows us only the `DISK` class's geoms. Each of those geoms has one provider. We can also see the full class tree. +`geom disk list`只向我们显示`DISK`类的geom。这些geom每个都有一个提供者。我们还可以看到完整的类树。 ```console # geom -t | head -n 40 @@ -901,13 +901,13 @@ ada0 DISK ada0 myblk0 DISK myblk0 ``` -Our geom is a sibling of the real disks, without any upper-layer class 附加ed to it yet. In later sections we will see what happens when a 文件系统 附加. +我们的geom是真实磁盘的兄弟,还没有附加任何上层类。在后续小节中,我们将看到当文件系统附加时会发生什么。 ```console # geom stats myblk0 ``` -`geom stats` returns detailed performance counters. On an idle, unused 设备 like ours, all the counters are zero. +`geom stats`返回详细的性能计数器。在像我们这样空闲、未使用的设备上,所有计数器都是零。 ```console # gstat -I 1 @@ -917,25 +917,25 @@ dT: 1.002s w: 1.000s 0 0 0 0 0.0 0 0 0.0 0.0| myblk0 ``` -`gstat` is a more compact view that updates live. We will use this heavily in later sections. +`gstat`是一个更紧凑的实时更新视图。我们将在后续小节中大量使用它。 ### 总结 Section 4 -GEOM is a composable 块-layer 框架 made of classes, geoms, providers, and consumers. Requests flow through it as `struct bio` objects, with `BIO_READ`, `BIO_WRITE`, and a handful of other commands. Access rights, topology locking, and event-driven structure management are the mechanisms that keep the 框架 safe to evolve under load. `g_disk` wraps all of this for disk-shaped 驱动程序 and gives them a friendlier 接口 with little loss of expressiveness. +GEOM是一个由类、geom、提供者和消费者组成的可组合块层框架。请求以`struct bio`对象流经它,带有`BIO_READ`、`BIO_WRITE`和少量其他命令。访问权限、拓扑锁定和事件驱动的结构管理是保持框架在负载下安全演进的机制。`g_disk`为磁盘形状的驱动程序封装了所有这些,给它们一个更友好的接口,几乎没有表达能力的损失。 -Our skeleton 驱动程序 is now a first-class GEOM participant, even though it cannot yet do any real I/O. In the next section, we will give it that missing piece. We will allocate a backing 缓冲区, implement a strategy function that actually reads and writes, and watch the 内核's storage stack exercise our code from both raw-access and 文件系统-access directions. +我们的骨架驱动程序现在是一流的GEOM参与者,尽管它还不能做任何真正的I/O。在下一节中,我们将给它那个缺失的部分。我们将分配一个后备缓冲区,实现一个实际读写的策略函数,并观察内核的存储栈从原始访问和文件系统访问两个方向测试我们的代码。 -## 第5节: Implementing Basic Read and Write +## 第5节:实现基本读写 -In Section 3 we returned `ENXIO` for every BIO. In Section 4 we learned enough about GEOM to know exactly what kind of request our strategy function receives and what its obligations are. In this section we will replace that placeholder with a working handler that reads and writes real bytes against an in-memory backing store. By the end, our 驱动程序 will serve traffic through `dd`, will return sane data, and will survive being formatted by `newfs_ufs`. +在第3节中,我们对每个BIO返回`ENXIO`。在第4节中,我们学到了足够多的关于GEOM的知识,确切地知道我们的策略函数接收什么样的请求以及它的义务是什么。在本节中,我们将用一个可工作的处理程序替换那个占位符,该处理程序针对内存后备存储读写真实的字节。到本节结束时,我们的驱动程序将通过`dd`服务流量,返回合理的数据,并在被`newfs_ufs`格式化后存活。 -### The Backing Store +### 后备存储 -Our backing store for now is simply an array of bytes in 内核 memory, sized to match `d_mediasize`. It is the simplest possible representation of a disk: a flat 缓冲区. Real 存储驱动程序 replace this with hardware DMA, with a vnode-backed file, or with a swap-backed VM object, but a flat 缓冲区 is enough to teach every other concept in this chapter without distraction. +我们目前的后备存储只是内核内存中的一个字节数组,大小与`d_mediasize`匹配。这是磁盘的最简单可能表示:一个扁平缓冲区。真正的存储驱动程序用硬件DMA、vnode支持的文件或交换支持的VM对象替换它,但扁平缓冲区足以无干扰地教授本章中的其他概念。 -For 1 MiB we can simply `malloc` the 缓冲区. For larger sizes we would need a different allocator, because the 内核 heap does not scale gracefully to contiguous allocations of tens or hundreds of megabytes. `md(4)` avoids the issue for large memory disks by using page-at-a-time allocation and a custom indirection structure. We do not need that level of sophistication yet, but we will note the limitation in the code. +对于1 MiB,我们可以简单地用`malloc`分配缓冲区。对于更大的大小,我们需要不同的分配器,因为内核堆不能优雅地扩展到几十或几百兆字节的连续分配。`md(4)`通过使用逐页分配和自定义间接结构来避免大型内存磁盘的这个问题。我们目前还不需要那种复杂程度,但我们会在代码中注明这个限制。 -Let us update `myblk_softc` to include the backing store. +让我们更新`myblk_softc`以包含后备存储。 ```c struct myblk_softc { @@ -947,9 +947,9 @@ struct myblk_softc { }; ``` -Two new fields: `backing` is the pointer to the 内核 memory we allocated, and `backing_size` is the number of bytes we allocated. These should always be equal to `d_mediasize`, but storing the size explicitly is cleaner than relying on indirection through `disk->d_mediasize`. +两个新字段:`backing`是我们分配的内核内存的指针,`backing_size`是我们分配的字节数。这些应该始终等于`d_mediasize`,但显式存储大小比通过`disk->d_mediasize`间接引用更干净。 -Now, in `myblk_附加_unit`, allocate the backing 缓冲区. +现在,在`myblk_attach_unit`中,分配后备缓冲区。 ```c static int @@ -973,9 +973,9 @@ myblk_attach_unit(struct myblk_softc *sc) } ``` -`malloc` with `M_WAITOK | M_ZERO` returns a zeroed 缓冲区 or sleeps until one is available. It cannot fail for small allocations on a healthy system, which is why we do not check the return value here. If we were allocating a very large 缓冲区 we might want `M_NOWAIT` and explicit error handling, but for 1 MiB `M_WAITOK` is the idiomatic choice. +带有`M_WAITOK | M_ZERO`的`malloc`返回一个清零的缓冲区或睡眠直到有可用的。在健康的系统上,小分配不可能失败,这就是为什么我们不在这里检查返回值。如果我们要分配一个非常大的缓冲区,我们可能需要`M_NOWAIT`和显式错误处理,但对于1 MiB,`M_WAITOK`是惯用的选择。 -`myblk_分离_unit` must free the backing store after destroying the disk. +`myblk_detach_unit`必须在销毁磁盘后释放后备存储。 ```c static void @@ -994,11 +994,11 @@ myblk_detach_unit(struct myblk_softc *sc) } ``` -Order matters here. We destroy the disk first, which ensures there are no more BIOs in flight. Only then do we free the backing 缓冲区. If we freed the 缓冲区 first, an in-flight BIO might try to `memcpy` into or out of a pointer that no longer refers to our memory, and the 内核 would crash on the next I/O. +顺序很重要。我们首先销毁磁盘,这确保没有更多的BIO在飞行中。然后我们才释放后备缓冲区。如果我们先释放缓冲区,一个飞行中的BIO可能试图`memcpy`到或从一个不再引用我们内存的指针,内核将在下一次I/O时崩溃。 -### The Strategy Function +### 策略函数 -Now for the heart of the change. Replace the placeholder `myblk_strategy` with a function that actually services BIOs. +现在是变更的核心。用实际服务BIO的函数替换占位符`myblk_strategy`。 ```c static void @@ -1063,43 +1063,43 @@ myblk_strategy(struct bio *bp) } ``` -Let us read this carefully. It is not a long function, but every line is doing something that matters. +让我们仔细阅读这段代码。它不是一个很长的函数,但每一行都在做一些重要的事情。 -The first line finds our softc. GEOM gives us the BIO with a pointer to the disk in `bp->bio_disk`. We stashed our softc in `d_drv1` during `disk_create`, so we retrieve it from there. This is the 块-驱动程序 equivalent of `设备_get_softc(dev)` in the New总线 world. +第一行找到我们的softc。GEOM在`bp->bio_disk`中给了我们一个指向磁盘的指针的BIO。我们在`disk_create`期间将softc存放在`d_drv1`中,所以我们从那里取回它。这是Newbus世界中`device_get_softc(dev)`在块驱动程序中的等价物。 -The second pair of lines extract the offset and length of the request. `bio_offset` is a byte offset into the media. `bio_bcount` is the number of bytes to transfer. GEOM has already translated file-level operations through whatever layers sit above us into a linear byte range. +第二对行提取请求的偏移量和长度。`bio_offset`是介质中的字节偏移量。`bio_bcount`是要传输的字节数。GEOM已经通过我们上面的任何层将文件级操作转换为线性字节范围。 -The bounds check that follows is defensive programming. GEOM will not normally send us a request that exceeds the media size, because it splits and validates BIOs on our behalf. But defensive 驱动程序 check anyway, because a silently accepted out-of-bounds write can smash 内核 memory, and because the cost of the check is a few instructions per request. We also guard against arithmetic overflow by rewriting the obvious `offset + len > backing_size` check as `len > backing_size - offset`, which cannot overflow because `offset <= backing_size` at this point. +随后的边界检查是防御性编程。GEOM通常不会向我们发送超过介质大小的请求,因为它代表我们拆分和验证BIO。但防御性驱动程序无论如何都会检查,因为静默接受的越界写入可能破坏内核内存,而且检查的成本是每个请求几条指令。我们还通过将明显的`offset + len > backing_size`检查重写为`len > backing_size - offset`来防止算术溢出,这不可能溢出,因为此时`offset <= backing_size`。 -The switch is where the real work happens. Each BIO command gets its own case. +switch是真正工作发生的地方。每个BIO命令有自己的case。 -`BIO_READ` copies `len` bytes from our backing store at `offset` into `bp->bio_data`. GEOM has allocated `bp->bio_data` for us, and it will be released when the BIO completes. Our job is just to fill it. +`BIO_READ`从后备存储的`offset`处复制`len`字节到`bp->bio_data`。GEOM已经为我们分配了`bp->bio_data`,它将在BIO完成时释放。我们的工作只是填充它。 -`BIO_WRITE` copies `len` bytes from `bp->bio_data` into our backing store at `offset`. Symmetrical to the read case. +`BIO_WRITE`从`bp->bio_data`复制`len`字节到后备存储的`offset`处。与读取情况对称。 -`BIO_DELETE` zeroes the range. For a real disk, `BIO_DELETE` is how 文件系统 signal that a range of 块 is no longer in use, and the disk is free to reclaim it. SSDs use it to drive TRIM. For our in-memory 驱动程序, there is nothing to reclaim, but zeroing the range is a reasonable response because it reflects the "data is gone" semantics. +`BIO_DELETE`将范围清零。对于真实磁盘,`BIO_DELETE`是文件系统通知一定范围的块不再使用的方式,磁盘可以自由回收它。SSD用它来驱动TRIM。对于我们的内存驱动程序,没有什么可以回收的,但将范围清零是合理的响应,因为它反映了"数据已消失"的语义。 -`BIO_FLUSH` is a request to commit outstanding writes to stable storage. Our storage is never volatile in the sense that a FLUSH would help: every `memcpy` is already visible to the next `memcpy` in the same order it was issued. We return success with nothing to do. +`BIO_FLUSH`是将未完成的写入提交到稳定存储的请求。我们的存储从不具有FLUSH会有帮助的那种易失性:每个`memcpy`已经按照发出的顺序对下一个`memcpy`可见。我们返回成功,无需做任何事情。 -Any other command we do not recognise gets `EOPNOTSUPP`. GEOM layers above us will see this and react accordingly. +我们不认识的任何其他命令获得`EOPNOTSUPP`。我们上面的GEOM层将看到这个并相应地反应。 -At the end, `biodone(bp)` completes the BIO. This is not optional. Every BIO that enters the strategy function must leave through `biodone` exactly once, or the BIO will be leaked, the caller will 块 forever, and you will have a difficult time diagnosing the issue. +最后,`biodone(bp)`完成BIO。这不是可选的。每个进入策略函数的BIO必须恰好通过`biodone`一次离开,否则BIO将被泄漏,调用者将永远阻塞,你将很难诊断这个问题。 -### The Role of bio_resid +### bio_resid的作用 -Notice the handling of `bp->bio_resid`. This field represents the number of bytes remaining to transfer after the 驱动程序 is done. When the full transfer succeeds, `bio_resid` is zero. When the transfer fails completely, `bio_resid` equals `bio_bcount`. When the transfer partially succeeds, `bio_resid` is the number of bytes that did not make it. +注意`bp->bio_resid`的处理。这个字段代表驱动程序完成后剩余要传输的字节数。当完整传输成功时,`bio_resid`为零。当传输完全失败时,`bio_resid`等于`bio_bcount`。当传输部分成功时,`bio_resid`是未成功传输的字节数。 -Our 驱动程序 either transfers everything or nothing, so we set `bio_resid` to either `0` (success) or `len` (error). A real hardware 驱动程序 might set it to an intermediate value if a transfer stopped partway through. Filesystems and user-space tools use `bio_resid` to figure out how much data actually moved. +我们的驱动程序要么传输全部,要么什么也不传输,所以我们将`bio_resid`设置为`0`(成功)或`len`(错误)。真正的硬件驱动程序可能在传输中途停止时将其设置为中间值。文件系统和用户空间工具使用`bio_resid`来计算实际移动了多少数据。 -### The Lock +### 锁 -We take `sc->lock` around the `memcpy`. For an in-memory 驱动程序 that services one request at a time, the lock is not doing much visible work: the 内核's BIO scheduling makes truly concurrent requests unlikely on our toy 设备. But the lock is good hygiene. GEOM does not promise that your strategy function will be invoked serially, and even if it did, a future change to the 驱动程序 to add an asynchronous worker thread would require the lock anyway. Adding it now is cheaper than adding it later. +我们在`memcpy`周围获取`sc->lock`。对于一次服务一个请求的内存驱动程序,锁并没有做太多可见的工作:内核的BIO调度使得真正的并发请求在我们的玩具设备上不太可能。但锁是良好的卫生习惯。GEOM不承诺你的策略函数会被串行调用,即使承诺了,将来为驱动程序添加异步工作线程的更改也无论如何都需要锁。现在添加比以后添加更便宜。 -A more sophisticated 驱动程序 might use a fine-grained lock, or might use an MPSAFE approach that relies on atomic operations. For now, a coarse 互斥锁 around the `memcpy` is fine. It is correct, it is easy to reason about, and it does not hurt performance on a pseudo 设备. +更复杂的驱动程序可能使用细粒度锁,或者可能使用依赖原子操作的MPSAFE方法。目前,`memcpy`周围的粗粒度互斥锁就可以了。它是正确的,容易推理,并且不会损害伪设备的性能。 -### Rebuilding and Reloading +### 重新构建和重新加载 -After updating the source and `kldunload`-ing the old version, rebuild and reload. +更新源码并`kldunload`旧版本后,重新构建并重新加载。 ```console # make @@ -1110,7 +1110,7 @@ cc -O2 -pipe -fno-strict-aliasing ... myblk: loaded, /dev/myblk0 size=1048576 bytes ``` -Now let us try some real I/O. +现在让我们尝试一些真正的I/O。 ```console # dd if=/dev/zero of=/dev/myblk0 bs=4096 count=16 @@ -1123,7 +1123,7 @@ Now let us try some real I/O. 65536 bytes transferred in 0.000512 secs (128 MB/sec) ``` -We wrote 64 KiB of zeros and read them back. The speeds you see will depend on your hardware and on how much the 缓冲区 cache helps, but any speed above a few MB/sec is fine for a first run. +我们写入了64 KiB的零并将其读回。你看到的速度取决于你的硬件和缓冲区缓存帮助了多少,但任何超过几MB/秒的速度对于第一次运行都是可以的。 ```console # dd if=/dev/random of=/dev/myblk0 bs=4096 count=16 @@ -1140,20 +1140,20 @@ We wrote 64 KiB of zeros and read them back. The speeds you see will depend on y # ``` -We wrote random data, read it back twice, and confirmed that both reads return the same content. Our 驱动程序 is now a coherent store. +我们写入了随机数据,读回两次,确认两次读取返回相同的内容。我们的驱动程序现在是一个一致的存储。 -### A Quick Look Under Load +### 负载下的快速观察 -Let us run a short stress test and watch `gstat`. +让我们运行一个短的压力测试并观察`gstat`。 -In one terminal: +在一个终端中: ```console # while true; do dd if=/dev/urandom of=/dev/myblk0 bs=4096 \ count=256 2>/dev/null; done ``` -In another terminal: +在另一个终端中: ```console # gstat -I 1 -f myblk0 @@ -1162,13 +1162,13 @@ dT: 1.002s w: 1.000s 0 251 0 0 0.0 251 1004 0.0 2.0| myblk0 ``` -About 250 write operations per second at 4 KiB each, approximately 1 MB/sec. The latency is very low because the backing store is RAM. For a real disk the numbers would be very different, but the structure of what you are watching is the same. +大约每秒250次写入操作,每次4 KiB,大约1 MB/秒。延迟非常低,因为后备存储是RAM。对于真实磁盘,数字会非常不同,但你正在观察的结构是相同的。 -Stop the stress test with `Ctrl-C` on the first terminal. +在第一个终端上用`Ctrl-C`停止压力测试。 -### Refining the Driver with ioctl Support +### 通过ioctl支持完善驱动程序 -Many storage tools send an ioctl to the 设备 to query geometry or to issue commands. GEOM handles the common ones for us, but if we provide a `d_ioctl` 回调, the 内核 will route unknown ioctls through to our function. For now we do not implement any custom ioctl. We only note that the hook exists. +许多存储工具向设备发送ioctl来查询几何参数或发出命令。GEOM为我们处理常见的ioctl,但如果我们提供`d_ioctl`回调,内核会将未知的ioctl路由到我们的函数。目前我们不实现任何自定义ioctl。我们只注意到钩子存在。 ```c static int @@ -1186,11 +1186,11 @@ myblk_ioctl(struct disk *d, u_long cmd, void *data, int flag, } ``` -We 注册 the 回调 by assigning `sc->disk->d_ioctl = myblk_ioctl;` before calling `disk_create`. Returning `ENOIOCTL` from the default case tells GEOM that we do not handle the command and gives it the chance to pass the request to its own default handler. +我们在调用`disk_create`之前通过赋值`sc->disk->d_ioctl = myblk_ioctl;`注册回调。从默认case返回`ENOIOCTL`告诉GEOM我们不处理该命令,并给它将请求传递给自己默认处理器的机会。 -### Refining the Driver with getattr Support +### 通过getattr支持完善驱动程序 -GEOM uses `BIO_GETATTR` to ask storage 设备 for named attributes. A 文件系统 might ask for `GEOM::rotation_rate` to know whether it is on spinning media. The 分区ing layer might ask for `GEOM::ident` to get a stable identifier. A `d_getattr` 回调 is the hook that lets us respond. +GEOM使用`BIO_GETATTR`向存储设备请求命名属性。文件系统可能会询问`GEOM::rotation_rate`以了解它是否在旋转介质上。分区层可能会询问`GEOM::ident`以获取稳定标识符。`d_getattr`回调是让我们响应的钩子。 ```c static int @@ -1214,73 +1214,73 @@ myblk_getattr(struct bio *bp) } ``` -The return-value convention for `d_getattr` is worth pausing on, because it trips up many first-time readers. Returning `0` with `bio_completed` set tells `g_disk` that we handled the attribute successfully. Returning a positive errno value (such as `EFAULT` for a too-small 缓冲区) tells `g_disk` that we handled the attribute but the operation failed. Returning `-1` tells `g_disk` that we did not recognise the attribute and it should try its built-in default handler. That is why we return `-1` at the bottom: we want `g_disk` to answer standard attributes such as `GEOM::fw扇区` on our behalf. For our 驱动程序, responding to `GEOM::ident` with a short string is enough to show up in `diskinfo -v`. Register this with `sc->disk->d_getattr = myblk_getattr;` before `disk_create`. +`d_getattr`的返回值约定值得停下来思考,因为它让许多首次阅读者绊倒。返回`0`并设置`bio_completed`告诉`g_disk`我们成功处理了属性。返回一个正的errno值(如太小的缓冲区的`EFAULT`)告诉`g_disk`我们处理了属性但操作失败了。返回`-1`告诉`g_disk`我们不认识该属性,它应该尝试其内建的默认处理器。这就是为什么我们在底部返回`-1`:我们希望`g_disk`代表我们回答标准属性如`GEOM::fwsectors`。对于我们的驱动程序,用短字符串响应`GEOM::ident`足以在`diskinfo -v`中显示。在`disk_create`之前用`sc->disk->d_getattr = myblk_getattr;`注册。 -### Partial Writes and Short Reads +### 部分写入和短读取 -Our 驱动程序 does not actually produce partial writes or short reads, because the backing store is in RAM and every transfer either fully succeeds or fully fails. But for a real hardware 驱动程序, partial transfers are normal: a disk may return a few 扇区 successfully and then fail on a bad 扇区. The BIO 框架 supports this through `bio_resid`, and a 驱动程序 should set `bio_resid` to the number of bytes that did not complete. +我们的驱动程序实际上不会产生部分写入或短读取,因为后备存储在RAM中,每次传输要么完全成功要么完全失败。但对于真正的硬件驱动程序,部分传输是正常的:磁盘可能成功返回几个扇区然后在一个坏扇区上失败。BIO框架通过`bio_resid`支持这一点,驱动程序应该将`bio_resid`设置为未完成的字节数。 -The practical guidance is to always set `bio_resid` explicitly before calling `biodone`. If the transfer fully succeeded, set it to zero. If it partially succeeded, set it to the residual. If it fully failed, set it to `bio_bcount`. Forgetting to set `bio_resid` leaves whatever garbage was in the field when the BIO was allocated, which can confuse callers. +实际的指导是在调用`biodone`之前始终显式设置`bio_resid`。如果传输完全成功,将其设置为零。如果部分成功,设置为剩余量。如果完全失败,设置为`bio_bcount`。忘记设置`bio_resid`会在BIO分配时留下字段中的任何垃圾,这可能使调用者困惑。 ### 常见错误 in Strategy Functions -Before we continue, let us name three common mistakes that appear in first-time strategy functions. +在我们继续之前,让我们指出首次编写策略函数时出现的三个常见错误。 -**Forgetting `biodone`.** Every path out of the strategy function must call `biodone(bp)` on the BIO. If you forget, the BIO is leaked and the caller hangs. This is the single most common source of "my 挂载 hangs" problems. +**忘记`biodone`。**策略函数的每条退出路径都必须对BIO调用`biodone(bp)`。如果你忘记了,BIO被泄漏,调用者挂起。这是"我的挂载挂起"问题最常见的单一来源。 -**Holding a lock across `biodone`.** `biodone` may call upward into GEOM or into a 文件系统's completion handler. Those handlers may take other locks, or may need to acquire locks you already hold, leading to lock-order reversal and potential deadlock. The safest pattern is to drop your lock before calling `biodone`. Our simple version does this implicitly: the `mtx_unlock` is always inside the switch, and `biodone` runs after the switch. +**在`biodone`之间持锁。**`biodone`可能向上调用到GEOM或文件系统的完成处理器。这些处理器可能获取其他锁,或者可能需要获取你已经持有的锁,导致锁顺序反转和潜在死锁。最安全的模式是在调用`biodone`之前释放你的锁。我们的简单版本隐式地做到了这一点:`mtx_unlock`总是在switch内部,`biodone`在switch之后运行。 -**Returning from the strategy function with an error code.** `d_strategy` is a `void` function. Errors are reported by setting `bio_error` and the `BIO_ERROR` flag on the BIO, not by returning. Compilers catch this if you declare the function correctly, but beginners sometimes write it as returning `int`, which causes compiler warnings that should not be ignored. +**从策略函数返回错误码。**`d_strategy`是一个`void`函数。错误通过在BIO上设置`bio_error`和`BIO_ERROR`标志来报告,而不是通过返回值。如果你正确声明了函数,编译器会捕获这个错误,但初学者有时会将其写为返回`int`,这会产生不应被忽略的编译器警告。 ### Chained BIOs and BIO Hierarchies -A BIO can have a child. GEOM uses this when a transformation class needs to split, combine, or transform a request into one or more downstream requests. For example, a mirror class might take a BIO_WRITE and issue two child BIOs, one to each mirror member. A 分区 class might take a BIO_READ and issue a single child BIO with the offset shifted into the underlying provider's address space. +BIO可以有一个子级。GEOM在变换类需要将请求拆分、组合或变换为一个或多个下游请求时使用它。例如,镜像类可能接收一个BIO_WRITE并发出两个子BIO,每个镜像成员一个。分区类可能接收一个BIO_READ并发出一个偏移量已移入底层提供者地址空间的单个子BIO。 -The parent-child relationship is recorded in `bio_parent`. When a child completes, its error is propagated to the parent by `biodone`, which accumulates errors and delivers the parent when all children have completed. +父子关系记录在`bio_parent`中。当子级完成时,其错误由`biodone`传播到父级,`biodone`累积错误并在所有子级完成后交付父级。 -Our 驱动程序 does not produce child BIOs. It receives them as leaves of the chain. From the 驱动程序's perspective, every BIO is self-contained: it has an offset, a length, and a data 缓冲区, and our job is to service it. +我们的驱动程序不产生子BIO。它作为链的叶级接收它们。从驱动程序的角度看,每个BIO都是自包含的:它有偏移量、长度和数据缓冲区,我们的工作是服务它。 -But if you ever find yourself needing to split a BIO inside your 驱动程序 (for example, if a request spans a boundary that your backing store handles in separate chunks), you can use `g_clone_bio` to create a child BIO, `g_io_request` to dispatch it, and `g_std_done` or a custom completion handler to reassemble the parent. The pattern is visible in several places in the 内核, including `g_mirror` and `g_raid`. +但如果你发现自己需要在驱动程序内部分割BIO(例如,如果请求跨越了后备存储以单独块处理的边界),你可以使用`g_clone_bio`创建子BIO,`g_io_request`分派它,`g_std_done`或自定义完成处理器来重组父级。该模式在内核中的多个地方可见,包括`g_mirror`和`g_raid`。 -### The Thread Context of the Strategy Function +### 策略函数的线程上下文 -The strategy function runs in whatever thread submitted the BIO. For 文件系统-originated BIOs, that is typically the 文件系统's syncer thread or a 缓冲区-cache worker. For direct user-space access, it is the user thread that called `read` or `write` on `/dev/myblk0`. For GEOM transformations, it might be the GEOM event thread or a class-specific worker thread. +策略函数在提交BIO的任何线程中运行。对于文件系统产生的BIO,通常是文件系统的同步线程或缓冲区缓存工作线程。对于直接的用户空间访问,是调用`/dev/myblk0`上`read`或`write`的用户线程。对于GEOM变换,可能是GEOM事件线程或类特定的工人线程。 -What this means for your 驱动程序 is that `d_strategy` can run in many different thread contexts. You cannot assume that `curthread` belongs to any particular process, and you cannot 块 for a long time or the calling 文件系统 (or user program) will stall. +这对你的驱动程序意味着`d_strategy`可以在许多不同的线程上下文中运行。你不能假设`curthread`属于任何特定进程,你不能长时间阻塞,否则调用的文件系统(或用户程序)将停滞。 -If your strategy function needs to do something slow (I/O against a vnode, waiting for hardware, or complex locking), the right pattern is to enqueue the BIO on an internal queue and have a dedicated worker thread process it. This is what `md(4)` does for all backing types, because vnode I/O (for instance) can 块 arbitrarily long. +如果你的策略函数需要做慢的事情(对vnode的I/O、等待硬件或复杂的锁定),正确的模式是将BIO排队到内部队列并让专门的工人线程处理它。这就是`md(4)`对所有后备类型所做的,因为vnode I/O(例如)可能任意长时间阻塞。 -Our 驱动程序 is entirely in-memory and does `memcpy` only, so we do not need a worker thread. But understanding the pattern is important for the future. +我们的驱动程序完全在内存中且只做`memcpy`,所以我们不需要工人线程。但理解这个模式对未来很重要。 -### A Worked Example: Reading Across a Boundary +### 实例演练:跨边界读取 -Suppose a 文件系统 issues a BIO_READ with offset 100000 and length 8192. That spans bytes 100000 through 108191. Let us trace how our strategy function handles it. +假设一个文件系统发出一个偏移量100000、长度8192的BIO_READ。它跨越字节100000到108191。让我们追踪策略函数如何处理它。 -1. `bp->bio_cmd` is `BIO_READ`. -2. `bp->bio_offset` is 100000. -3. `bp->bio_bcount` is 8192. -4. `bp->bio_data` points to a 内核 缓冲区 (or a user 缓冲区 mapped into the 内核) where the 8192 bytes should go. +1. `bp->bio_cmd`是`BIO_READ`。 +2. `bp->bio_offset`是100000。 +3. `bp->bio_bcount`是8192。 +4. `bp->bio_data`指向一个内核缓冲区(或映射到内核的用户缓冲区),8192字节应该放入其中。 -Our code computes `offset = 100000` and `len = 8192`. The bounds check passes: `100000 + 8192 = 108192`, which is less than our `backing_size` of 32 MiB (33554432). +我们的代码计算`offset = 100000`和`len = 8192`。边界检查通过:`100000 + 8192 = 108192`,小于我们的`backing_size`32 MiB(33554432)。 -The switch enters the `BIO_READ` case. We acquire the lock, `memcpy` 8192 bytes from `sc->backing + 100000` into `bp->bio_data`, and release the lock. We set `bp->bio_resid = 0` to indicate a complete transfer. We fall through to `biodone(bp)`, which completes the BIO. +switch进入`BIO_READ` case。我们获取锁,从`sc->backing + 100000`将8192字节`memcpy`到`bp->bio_data`中,然后释放锁。我们设置`bp->bio_resid = 0`表示完整传输。我们落入`biodone(bp)`,完成BIO。 -The 文件系统 receives the completion, notices the error is zero, and uses the 8192 bytes. The read is complete. +文件系统收到完成通知,注意到错误为零,并使用这8192字节。读取完成。 -Now suppose, instead, the offset was 33554431 and the length was 2 bytes. That is one byte inside the backing store and one byte past the end. +现在假设偏移量是33554431,长度是2字节。即一个字节在后备存储内,一个字节超出末尾。 -1. `offset = 33554431`. -2. `len = 2`. +1. `offset = 33554431`。 +2. `len = 2`。 -The bounds check: `offset > sc->backing_size` evaluates `33554431 > 33554432`, which is false. `len > sc->backing_size - offset` evaluates `2 > 33554432 - 33554431`, which evaluates to `2 > 1`, which is true. The check fails, and we fall into the error path: set `bio_error = EIO`, set the `BIO_ERROR` flag, set `bio_resid = 2`, and call `biodone`. The 文件系统 sees the error and handles it. +边界检查:`offset > sc->backing_size`计算为`33554431 > 33554432`,为假。`len > sc->backing_size - offset`计算为`2 > 33554432 - 33554431`,即`2 > 1`,为真。检查失败,我们落入错误路径:设置`bio_error = EIO`,设置`BIO_ERROR`标志,设置`bio_resid = 2`,然后调用`biodone`。文件系统看到错误并处理它。 -Notice how we used subtraction to avoid the overflow risk. Had we written `offset + len > sc->backing_size`, and had `offset` and `len` both been close to the maximum of `off_t`, the addition could wrap around to a small number and the check would silently pass for a malformed request. Defensive bounds checks always rearrange arithmetic to avoid overflow. +注意我们是如何使用减法来避免溢出风险的。如果我们写成`offset + len > sc->backing_size`,并且`offset`和`len`都接近`off_t`的最大值,加法可能回绕为一个小数字,检查会静默通过一个格式错误的请求。防御性边界检查总是重新排列算术以避免溢出。 -### The Devstat Side Effect +### Devstat的副作用 -One pleasant feature of using `g_disk` is that devstat accounting is automatic. Every BIO we service is counted by `iostat` and `gstat`. No extra code is needed. +使用`g_disk`的一个令人愉快的特性是devstat统计是自动的。我们服务的每个BIO都被`iostat`和`gstat`计数。不需要额外代码。 -You can verify this with `iostat -x 1` in another terminal while running the stress loop. +你可以在运行压力循环时在另一个终端中用`iostat -x 1`验证这一点。 ```text extended device statistics @@ -1289,46 +1289,46 @@ ada0 0 2 0 48 0.0 0.1 0.0 0.1 0 0 myblk0 0 251 0 1004 0.0 0.0 0.0 0.0 0 2 ``` -If our 驱动程序 were built on the raw `g_class` API rather than `g_disk`, we would have to wire up devstat ourselves. This is one of the small quality-of-life features that `g_disk` gives us for free. +如果我们的驱动程序构建在原始`g_class` API而不是`g_disk`上,我们将不得不自己连接devstat。这是`g_disk`免费给我们的小生活质量特性之一。 ### 总结 Section 5 -We replaced the placeholder strategy function with a working handler. Our 驱动程序 now services `BIO_READ`, `BIO_WRITE`, `BIO_DELETE`, and `BIO_FLUSH` correctly against an in-memory backing store. It participates in devstat, it cooperates with `gstat`, and it accepts real traffic from `dd`. +我们将占位符策略函数替换为可工作的处理程序。我们的驱动程序现在正确地对内存后备存储服务`BIO_READ`、`BIO_WRITE`、`BIO_DELETE`和`BIO_FLUSH`。它参与devstat,与`gstat`协作,并接受来自`dd`的真实流量。 -In the next section, we will cross the boundary from raw 块 access to 文件系统 access. We will format the 设备 with `newfs_ufs`, 挂载 it, create files on it, and observe how the request path changes when a real 文件系统 sits above the provider. +在下一节中,我们将跨越从原始块访问到文件系统访问的边界。我们将用`newfs_ufs`格式化设备,挂载它,在其上创建文件,并观察当真正的文件系统位于提供者之上时请求路径如何变化。 -## Section 6: Mounting a Filesystem on the Device +## 第6节:在设备上挂载文件系统 -Up to this point, our 驱动程序 has been exercised through raw access: `dd`, `diskinfo`, and similar tools reading and writing the entire surface as a flat byte range. That is a valuable mode, but it is not the mode most storage 设备 live in. Storage 设备 in real life serve 文件系统. This section takes our 驱动程序 the last mile: we will format it, 挂载 a real 文件系统 on it, create files, and observe how the 内核's 块-layer plumbing routes requests when a 文件系统 is in the picture. +到目前为止,我们的驱动程序通过原始访问进行测试:`dd`、`diskinfo`和类似工具将整个表面作为扁平字节范围进行读写。这是一种有价值的模式,但不是大多数存储设备生活的模式。现实生活中的存储设备为文件系统服务。本节将我们的驱动程序带到最后一英里:我们将格式化它,在上面挂载真正的文件系统,创建文件,并观察当文件系统出现时内核的块层管道如何路由请求。 -This is also the first section where the theoretical distinction between raw access and 文件系统 access becomes concrete. Understanding the difference, and being able to see it in action, is one of the most useful insights a storage-驱动程序 author can acquire. +这也是理论上的原始访问和文件系统访问之间的区别变得具体的第一节。理解这种差异并能够看到它在实践中运行,是存储驱动程序作者可以获得的最有用的洞察之一。 -### The Plan +### 计划 -We will do the following in this section, in order. +我们将在本节中按顺序执行以下操作。 -1. Increase the media size of our 驱动程序 from 1 MiB to something large enough to hold a usable UFS 文件系统. -2. Build and load the updated 驱动程序. -3. Run `newfs_ufs` against the 设备 to create a 文件系统. -4. Mount the 文件系统 on a scratch directory. -5. Create some files and verify that the data is read back correctly. -6. Un挂载 the 文件系统. -7. Reload the module and watch what happens. +1. 将驱动程序的介质大小从1 MiB增加到足以容纳可用UFS文件系统的大小。 +2. 构建并加载更新后的驱动程序。 +3. 对设备运行`newfs_ufs`以创建文件系统。 +4. 将文件系统挂载到临时目录上。 +5. 创建一些文件并验证数据正确读回。 +6. 卸载文件系统。 +7. 重新加载模块并观察发生了什么。 -By the end, you will have seen a complete 文件系统 on top of your own 块 驱动程序. +到本节结束时,你将在自己的块驱动程序上看到一个完整的文件系统。 -### Increasing the Media Size +### 增加介质大小 -UFS has a minimum practical size. You can create tiny UFS 文件系统, but the overhead of the super块, cylinder groups, and inode tables takes a noticeable fraction of the space on anything smaller than a few megabytes. For our purposes, 32 MiB is a comfortable size: it is small enough that the backing store still fits in a plain `malloc`, and large enough that UFS has room to breathe. +UFS有一个最小的实际大小。你可以创建很小的UFS文件系统,但超级块、柱面组和inode表的开销在任何小于几兆字节的东西上都占据明显的空间比例。对于我们的目的,32 MiB是一个舒适的大小:它足够小,后备存储仍然适合普通的`malloc`,也足够大,UFS有呼吸的空间。 -Update the size definitions at the top of `myfirst_blk.c`. +更新`myfirst_blk.c`顶部的尺寸定义。 ```c #define MYBLK_SECTOR 512 #define MYBLK_MEDIASIZE (32 * 1024 * 1024) /* 32 MiB */ ``` -Rebuild. +重新构建。 ```console # make clean @@ -1344,11 +1344,11 @@ Rebuild. 0 # stripeoffset ``` -32 MiB is enough. +32 MiB足够了。 -### Formatting with newfs_ufs +### 使用newfs_ufs格式化 -`newfs_ufs` is the standard UFS formatter on FreeBSD. It lays down the super块, the cylinder groups, the root inode, and all the other structures a UFS 文件系统 requires. Let us run it on our 设备. +`newfs_ufs`是FreeBSD上的标准UFS格式化工具。它放置超级块、柱面组、根inode和UFS文件系统所需的所有其他结构。让我们在我们的设备上运行它。 ```console # newfs_ufs /dev/myblk0 @@ -1358,18 +1358,18 @@ super-block backups (for fsck_ffs -b #) at: 192, 16576, 32960, 49344 ``` -A few things happened under the hood. +幕后发生了几件事。 -`newfs_ufs` opened `/dev/myblk0` for writing, which caused the GEOM access count to tick up. Our strategy function then received a stream of writes: the super块 first, then the cylinder groups, then the empty root directory, then the several backup super块. Each of those writes is a BIO, and each BIO was handled by our 驱动程序. +`newfs_ufs`为写入打开了`/dev/myblk0`,这导致GEOM访问计数增加。然后我们的策略函数收到了一连串写入:先是超级块,然后是柱面组,然后是空根目录,然后是几个备份超级块。每次写入都是一个BIO,每个BIO都由我们的驱动程序处理。 -You can verify that `newfs_ufs` really wrote to the 设备 by reading a few bytes back. +你可以通过读回几个字节来验证`newfs_ufs`确实写入了设备。 ```console # dd if=/dev/myblk0 bs=1 count=16 2>/dev/null | hexdump -C 00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` -The first few bytes of a UFS 分区 are deliberately zero because the super块 does not sit at offset zero: it is at offset 65536 (块 128) to leave room for boot 块 and other preambles. Let us peek there. +UFS分区的前几个字节故意为零,因为超级块不在偏移零处:它在偏移65536(块128)处,以留出启动块和其他前导的空间。让我们看看那里。 ```console # dd if=/dev/myblk0 bs=512 count=2 skip=128 2>/dev/null | hexdump -C | head @@ -1378,11 +1378,11 @@ The first few bytes of a UFS 分区 are deliberately zero because the super块 d ... ``` -You should see non-zero bytes now. That is the super块 that `newfs_ufs` laid down on our backing store. +你现在应该看到非零字节了。那就是`newfs_ufs`放置在我们后备存储上的超级块。 -### Mounting the Filesystem +### 挂载文件系统 -Create a 挂载 point and 挂载 the 文件系统. +创建一个挂载点并挂载文件系统。 ```console # mkdir -p /mnt/myblk @@ -1394,18 +1394,18 @@ Filesystem Size Used Avail Capacity Mounted on /dev/myblk0 31M 8.0K 28M 0% /mnt/myblk ``` -Our pseudo 设备 is now a real 文件系统. Watch the GEOM access counts. +我们的伪设备现在是一个真正的文件系统了。观察GEOM访问计数。 ```console # geom disk list myblk0 | grep Mode Mode: r1w1e1 ``` -`r1w1e1` means one reader, one writer, one exclusive holder. The exclusive hold is UFS: it has told GEOM that it is the sole authority over writes to the 设备 until it is 卸载ed. +`r1w1e1`表示一个读取者、一个写入者、一个独占持有者。独占持有者是UFS:它已经告诉GEOM它是对设备写入的唯一权威,直到被卸载。 -### Creating and Reading Files +### 创建和读取文件 -Let us actually use the 文件系统. +让我们实际使用文件系统。 ```console # echo "hello from myblk" > /mnt/myblk/hello.txt @@ -1416,9 +1416,9 @@ total 4 hello from myblk ``` -Note what just happened. The call `echo "hello from myblk" > /mnt/myblk/hello.txt` traveled through the system call layer to `sys_openat`, then to VFS, then to UFS, which opened the root directory's inode, created a new inode for `hello.txt`, allocated a data 块, copied the 17 bytes into the 缓冲区 cache, and scheduled a write-back. The 缓冲区 cache eventually called down to GEOM, which called down to our strategy function, which copied those bytes into our backing store. +注意刚才发生了什么。调用`echo "hello from myblk" > /mnt/myblk/hello.txt`通过系统调用层传到`sys_openat`,然后到VFS,然后到UFS,UFS打开根目录的inode,为`hello.txt`创建新inode,分配数据块,将17字节复制到缓冲区缓存中,并安排回写。缓冲区缓存最终向下调用GEOM,GEOM向下调用我们的策略函数,策略函数将那些字节复制到我们的后备存储中。 -When you then ran `cat`, the request traveled down the same stack. Except, because the data was still in the 缓冲区 cache from the recent write, UFS did not actually need to read from our 设备. The 缓冲区 cache served the read from RAM. If you 卸载 and re挂载, you will see an actual read. +当你运行`cat`时,请求沿相同的栈向下传输。只不过,由于数据仍然在缓冲区缓存中(来自最近的写入),UFS实际上不需要从我们的设备读取。缓冲区缓存从RAM提供读取服务。如果你卸载并重新挂载,你会看到实际的读取。 ```console # umount /mnt/myblk @@ -1427,11 +1427,11 @@ When you then ran `cat`, the request traveled down the same stack. Except, becau hello from myblk ``` -That second `cat` probably did cause BIO_READ requests to reach our 驱动程序, because the 卸载-and-re挂载 cycle invalidated the 缓冲区 cache for that 文件系统. +第二次`cat`可能确实导致了BIO_READ请求到达我们的驱动程序,因为卸载和重新挂载的循环使该文件系统的缓冲区缓存失效了。 -### Watching the Traffic +### 观察流量 -`gstat` shows us the BIO traffic in real time. Open another terminal and run `gstat -I 1 -f myblk0`. Then in the first terminal, create a big file. +`gstat`实时显示BIO流量。打开另一个终端并运行`gstat -I 1 -f myblk0`。然后在第一个终端中,创建一个大文件。 ```console # dd if=/dev/zero of=/mnt/myblk/big bs=1m count=16 @@ -1440,14 +1440,14 @@ That second `cat` probably did cause BIO_READ requests to reach our 驱动程序 16777216 bytes transferred in 0.150 secs (112 MB/sec) ``` -In the `gstat` terminal, you should see a burst of writes, perhaps spread across a second or two depending on how quickly the 缓冲区 cache flushes. +在`gstat`终端中,你应该看到写入的突发,可能分布在一两秒内,取决于缓冲区缓存刷新的速度。 ```text L(q) ops/s r/s kBps ms/r w/s kBps ms/w %busy Name 0 128 0 0 0.0 128 16384 0.0 12.0| myblk0 ``` -These are the 4 KiB or 32 KiB (depending on UFS's 块 size) writes that UFS is issuing to fill the file. We can verify the file's presence. +这些是UFS为填充文件而发出的4 KiB或32 KiB(取决于UFS的块大小)的写入。我们可以验证文件的存在。 ```console # ls -lh /mnt/myblk @@ -1460,17 +1460,17 @@ total 16460 16M /mnt/myblk ``` -And we can delete it again to watch the BIO_DELETE traffic. +我们可以再次删除它来观察BIO_DELETE流量。 ```console # rm /mnt/myblk/big ``` -UFS by default does not issue `BIO_DELETE` unless the 文件系统 was 挂载ed with the `trim` option, so on a plain 挂载 you will see almost no BIO traffic on delete: UFS just marks the 块 as free in its own metadata. To see `BIO_DELETE`, we would need to 挂载 with `-o trim`, which we will cover briefly in the labs. +UFS默认不发出`BIO_DELETE`,除非文件系统以`trim`选项挂载,所以在普通挂载上,你几乎不会在删除时看到BIO流量:UFS只是在自己的元数据中将块标记为空闲。要看到`BIO_DELETE`,我们需要以`-o trim`挂载,我们将在实验中简要介绍。 -### Un挂载ing +### 卸载 -Un挂载 the 文件系统 before unloading the module. +在卸载模块之前卸载文件系统。 ```console # umount /mnt/myblk @@ -1478,11 +1478,11 @@ Un挂载 the 文件系统 before unloading the module. Mode: r0w0e0 ``` -The access count dropped back to zero as soon as UFS released its exclusive hold. Our 驱动程序 is now free to be unloaded or further mucked with. +访问计数在UFS释放其独占持有时立即降回零。我们的驱动程序现在可以自由卸载或进一步操作。 -### Attempting to Unload While Mounted +### 在挂载状态下尝试卸载 -What happens if you forget the `u挂载` and try to unload the module? +如果你忘记`umount`并尝试卸载模块会怎样? ```console # mount /dev/myblk0 /mnt/myblk @@ -1490,11 +1490,11 @@ What happens if you forget the `u挂载` and try to unload the module? kldunload: can't unload file: Device busy ``` -The 内核 refuses. The `g_disk` subsystem knows that our provider still has an active exclusive holder, and it will not let `disk_destroy` proceed until the hold is released. This is the same mechanism we saw in 第26章 protecting the USB serial 设备 during an active session, lifted to the GEOM layer. +内核拒绝了。`g_disk`子系统知道我们的提供者仍然有一个活跃的独占持有者,在持有者释放之前它不会让`disk_destroy`继续。这与我们在第26章中看到的保护活跃会话中USB串行设备的机制相同,只是提升到了GEOM层。 -This is a safety feature. Unloading the module while a 文件系统 is 挂载ed on the backing 设备 would cause the 内核 to panic on the next BIO: the strategy function would no longer exist, but UFS would still try to call into it. +这是一个安全特性。在后备设备上挂载文件系统时卸载模块会导致内核在下一次BIO时崩溃:策略函数将不再存在,但UFS仍会尝试调用它。 -Un挂载 first, then unload. +先卸载,再卸载模块。 ```console # umount /mnt/myblk @@ -1503,78 +1503,78 @@ Un挂载 first, then unload. # ``` -Clean. +干净。 -### A Brief Anatomy of UFS on Top of Our Driver +### 我们的驱动程序上UFS的简要剖析 -Now that we have UFS 挂载ed on our 设备, it is worth pausing to notice what is actually on the backing store. UFS is a well-documented 文件系统, and seeing its structures in place on a 设备 we control is illuminating. +现在我们已经将UFS挂载到我们的设备上,值得停下来注意后备存储上实际有什么。UFS是一个文档完善的文件系统,在我们可以控制的设备上看到其结构就位是很有启发性的。 -The first 65535 bytes of a UFS 文件系统 are reserved for the boot area. On our 设备, these bytes are all zero because `newfs_ufs` does not write a boot 扇区 by default. +UFS文件系统的前65535字节保留给启动区。在我们的设备上,这些字节全为零,因为`newfs_ufs`默认不写入启动扇区。 -At offset 65536 lives the super块. The super块 is a fixed-size structure that describes the geometry of the 文件系统: the 块 size, the fragment size, the number of cylinder groups, the location of the root inode, and many other invariants. `newfs_ufs` writes the super块 first, and it also writes backup copies at predictable offsets in case the primary is corrupted. +偏移65536处是超级块。超级块是一个固定大小的结构,描述文件系统的几何参数:块大小、片段大小、柱面组数量、根inode的位置和许多其他不变量。`newfs_ufs`首先写入超级块,它还在可预测的偏移处写入备份副本,以防主副本损坏。 -Following the super块 come the cylinder groups. Each cylinder group holds inodes, data 块, and metadata for a chunk of the 文件系统's address space. The number and size of cylinder groups depends on the 文件系统 size. Our 32 MiB 文件系统 has four cylinder groups of 8 MiB each. +超级块之后是柱面组。每个柱面组保存inode、数据块和文件系统地址空间一部分的元数据。柱面组的数量和大小取决于文件系统大小。我们的32 MiB文件系统有四个柱面组,每个8 MiB。 -Within each cylinder group sit inode 块. Each inode is a small structure (256 bytes on FreeBSD UFS2) that describes a single file or directory: its type, owner, permissions, timestamps, size, and the 块 addresses of its data. +每个柱面组内有inode块。每个inode是一个小结构(FreeBSD UFS2上为256字节),描述单个文件或目录:其类型、所有者、权限、时间戳、大小和数据的块地址。 -Finally, the data 块 themselves hold file contents. These are allocated from the free-块 map in the cylinder group. +最后,数据块本身保存文件内容。它们从柱面组的空闲块映射中分配。 -When we wrote `"hello from myblk"` into `/mnt/myblk/hello.txt`, the 内核 did roughly the following: +当我们写入`"hello from myblk"`到`/mnt/myblk/hello.txt`时,内核大致执行了以下操作: -1. VFS asked UFS to create a new file `hello.txt` in the root directory. -2. UFS allocated an inode from the root cylinder group's inode table. -3. UFS updated the root directory's inode to include an entry for `hello.txt`. -4. UFS allocated a data 块 for the file. -5. UFS wrote the 17 bytes of content into that data 块. -6. UFS wrote the updated inode back. -7. UFS wrote the updated directory entry back. -8. UFS updated its internal bookkeeping. +1. VFS请求UFS在根目录中创建新文件`hello.txt`。 +2. UFS从根柱面组的inode表中分配了一个inode。 +3. UFS更新根目录的inode以包含`hello.txt`的条目。 +4. UFS为文件分配了一个数据块。 +5. UFS将17字节的内容写入该数据块。 +6. UFS将更新的inode写回。 +7. UFS将更新的目录条目写回。 +8. UFS更新了其内部簿记。 -Each of those steps turned into one or more BIOs to our 驱动程序. Most were small writes on metadata 块. The file content itself was one BIO. UFS's Soft Updates feature orders the writes to ensure crash consistency. +这些步骤中的每一个都转换为到我们驱动程序的一个或多个BIO。大多数是对元数据块的小写入。文件内容本身是一个BIO。UFS的Soft Updates特性对写入进行排序以确保崩溃一致性。 -If you want to see these BIOs in action, run your DTrace one-liner from Lab 7 while creating a file. You will see a small burst of writes around the time of the `echo`. +如果你想看到这些BIO的实际运行,可以在创建文件时运行实验7中的DTrace单行命令。你会在`echo`的时间附近看到一小阵写入。 -### How Mount Actually Works +### 挂载实际上是如何工作的 -The `挂载(8)` command is a wrapper around the `挂载(2)` system call. That system call takes a 文件系统 type, a source 设备, and a target 挂载 point, and it asks the 内核 to perform the 挂载. +`mount(8)`命令是`mount(2)`系统调用的包装器。该系统调用接受一个文件系统类型、一个源设备和一个目标挂载点,然后请求内核执行挂载。 -The 内核's response is to find the appropriate 文件系统 code by type (UFS, ZFS, tmpfs, etc.) and to call its 挂载 handler, which in UFS's case is `ufs_挂载` in `/usr/src/sys/ufs/ffs/ffs_vfsops.c`. The 挂载 handler validates the source, opens it as a GEOM consumer, reads the super块, verifies that it is well-formed, allocates an in-memory 挂载 structure, and installs it in the namespace. +内核的响应是按类型找到相应的文件系统代码(UFS、ZFS、tmpfs等)并调用其挂载处理器,UFS的情况下是`/usr/src/sys/ufs/ffs/ffs_vfsops.c`中的`ufs_mount`。挂载处理器验证源设备,将其作为GEOM消费者打开,读取超级块,验证其格式正确,分配一个内存中的挂载结构,并将其安装到命名空间中。 -From our 驱动程序's point of view, none of this is visible. We see a series of BIOs: first a few reads for the super块, then whatever UFS needs to bootstrap its in-memory state. Once 挂载 has succeeded, UFS issues BIOs on its own schedule as the 文件系统 is used. +从我们驱动程序的角度看,这些都不可见。我们看到的是一系列BIO:先是几次超级块读取,然后是UFS引导其内存状态所需的任何内容。挂载成功后,UFS在使用文件系统时按自己的时间表发出BIO。 -If 挂载 fails, UFS reports an error and the 内核's 挂载 code cleans up. The GEOM consumer is 分离ed, the access count drops, and the namespace is left alone. Our 驱动程序 does not need to do anything special on 挂载 failure. +如果挂载失败,UFS报告错误,内核的挂载代码进行清理。GEOM消费者被分离,访问计数下降,命名空间保持不变。我们的驱动程序不需要在挂载失败时做任何特殊处理。 -### The GEOM Character Interface +### GEOM字符接口 -Earlier in the chapter we said that raw access through `/dev/myblk0` goes through "GEOM's character 接口". Here is what that means in more detail. +在本章前面我们说通过`/dev/myblk0`的原始访问经过"GEOM的字符接口"。以下是更详细的含义。 -GEOM publishes a 字符设备 for every provider. This is not the same as a `cdev` created with `make_dev`; it is a specialised path within GEOM that presents a provider as a 字符设备 to `devfs`. The code for this lives in `/usr/src/sys/geom/geom_dev.c`. +GEOM为每个提供者发布一个字符设备。这与用`make_dev`创建的`cdev`不同;它是GEOM内部的一个专门路径,将提供者作为字符设备呈现给`devfs`。其代码位于`/usr/src/sys/geom/geom_dev.c`。 -When a user program opens `/dev/myblk0`, `devfs` routes the `open` to GEOM's character-接口 code, which 附加 a consumer to our provider with the requested access mode. When the program writes, GEOM's character-接口 code builds a BIO and issues it to our provider, which routes it to our strategy function. When the program closes the file 描述符, GEOM 分离 the consumer, releasing the access. +当用户程序打开`/dev/myblk0`时,`devfs`将`open`路由到GEOM的字符接口代码,该代码以请求的访问模式将一个消费者附加到我们的提供者。当程序写入时,GEOM的字符接口代码构建一个BIO并向我们的提供者发出,后者将其路由到我们的策略函数。当程序关闭文件描述符时,GEOM分离消费者,释放访问权限。 -The character-接口 layer translates between `struct uio` (the user-space I/O 描述符) and `struct bio` (the 块-layer I/O 描述符). It splits large user I/O into multiple BIOs when necessary, respecting the `d_maxsize` we specified. +字符接口层在`struct uio`(用户空间I/O描述符)和`struct bio`(块层I/O描述符)之间转换。必要时,它将大型用户I/O拆分为多个BIO,尊重我们指定的`d_maxsize`。 -All of this is invisible to our 驱动程序. We just receive BIOs. But knowing that the character 接口 exists helps you understand why certain user-space operations map to certain BIO patterns, and why `d_maxsize` matters. +所有这些对我们的驱动程序都是不可见的。我们只是接收BIO。但知道字符接口的存在有助于你理解为什么某些用户空间操作映射到某些BIO模式,以及为什么`d_maxsize`重要。 -### What Filesystems Need from a Block Driver +### 文件系统从块驱动程序中需要什么 -Now that we have actually 挂载ed a 文件系统 on our 驱动程序, we can describe more precisely what a 文件系统 requires from a 块 驱动程序 underneath. +现在我们已经在驱动程序上实际挂载了文件系统,我们可以更精确地描述文件系统从底层块驱动程序需要什么。 -A 文件系统 needs **correct reads and writes**. If a write at offset X is followed by a read at offset X, the read must return what the write put there, up to the granularity of the 扇区 size. We guaranteed this with `memcpy` into and out of our backing store. +文件系统需要**正确的读写**。如果在偏移X处的写入后跟在偏移X处的读取,读取必须返回写入放在那里的内容,精度到扇区大小的粒度。我们通过`memcpy`进出后备存储来保证这一点。 -A 文件系统 needs **correct bounds**. The 块 驱动程序 must not accept reads or writes that extend beyond the media size. We check this explicitly in the strategy function. +文件系统需要**正确的边界**。块驱动程序不能接受超出介质大小的读取或写入。我们在策略函数中显式检查这一点。 -A 文件系统 needs **stable media size**. The size of the 设备 must not change under the 文件系统's feet once it is 挂载ed, because 文件系统 metadata encodes offsets and counts that assume a fixed size. Our 驱动程序 holds the media size constant. +文件系统需要**稳定的介质大小**。设备的大小在文件系统挂载后不能在文件系统脚下改变,因为文件系统元数据编码了假设固定大小的偏移和计数。我们的驱动程序保持介质大小不变。 -A 文件系统 needs **crash safety**, to the extent the underlying storage provides it. UFS can recover from an unclean shutdown if the backing store does not lose previously committed writes. Our RAM-backed 驱动程序 loses everything on reboot, but it is at least self-consistent while running. In Section 7, we will introduce options for persistence. +文件系统需要**崩溃安全**,在底层存储提供的范围内。如果后备存储不丢失先前提交的写入,UFS可以从不干净的关机中恢复。我们的RAM后备驱动程序在重启时丢失所有内容,但至少在运行时是自洽的。在第7节中,我们将介绍持久性选项。 -A 文件系统 sometimes needs **flush semantics**. A call to `BIO_FLUSH` should ensure that all previously issued writes are durable before returning. Our RAM-backed 驱动程序 trivially satisfies this, because there is no deferred writeback in its path. +文件系统有时需要**刷新语义**。对`BIO_FLUSH`的调用应确保在返回之前所有先前发出的写入都是持久的。我们的RAM后备驱动程序平凡地满足这一点,因为它的路径中没有延迟回写。 -Finally, a 文件系统 benefits from **fast sequential access**. This is a quality-of-service matter rather than a correctness matter, but our 驱动程序 is fine in this regard because `memcpy` is fast. +最后,文件系统受益于**快速顺序访问**。这是一个服务质量问题而非正确性问题,但我们的驱动程序在这方面很好,因为`memcpy`很快。 -### Raw Access Versus Filesystem Access, Visualised +### 原始访问与文件系统访问可视化 -Let us draw the two access paths side by side, using our actual 驱动程序 as the anchor. +让我们将两条访问路径并排画出,以我们的实际驱动程序作为锚点。 ```text Raw access: Filesystem access: @@ -1607,145 +1607,145 @@ Raw access: Filesystem access: myblk_strategy (BIO_READ) myblk_strategy (BIO_READ) ``` -The last two hops are identical. Our strategy function is called exactly the same way regardless of whether the request came from `dd` or from `cat` on a 挂载ed file. This is the great advantage of living at the 块 layer: we do not need to distinguish between the two paths. The upper layers sort out how to translate file-level operations into 块-level operations, and we deal in 块. +最后两跳是相同的。无论请求来自`dd`还是来自已挂载文件上的`cat`,我们的策略函数都以完全相同的方式被调用。这是位于块层的巨大优势:我们不需要区分两条路径。上层负责将文件级操作转换为块级操作,而我们只处理块。 -### Watching the Request Path with DTrace +### 使用DTrace观察请求路径 -If you want to see the request path explicitly, DTrace can help. +如果你想显式地看到请求路径,DTrace可以帮助。 ```console # dtrace -n 'fbt::myblk_strategy:entry { printf("cmd=%d off=%lld len=%u", \ args[0]->bio_cmd, args[0]->bio_offset, args[0]->bio_bcount); }' ``` -With the 探测 running, do something on the 挂载ed 文件系统 in another terminal and watch the BIOs arrive. You will see reads come through in 512-byte to 32 KiB chunks, depending on UFS's 块 size and what operation you performed. Running `dd if=/dev/zero of=/mnt/myblk/test bs=1m count=1` produces a burst of 32 KiB writes. +在探测运行时,在另一个终端中对已挂载的文件系统做一些操作并观察BIO的到来。你会看到读取以512字节到32 KiB的块到达,取决于UFS的块大小和你执行的操作。运行`dd if=/dev/zero of=/mnt/myblk/test bs=1m count=1`会产生一阵32 KiB的写入。 -DTrace is one of the most capable observability tools FreeBSD provides, and it comes alive with storage work because the BIO path is so instrumented. We will use it more in later chapters, but even a one-liner like the above is enough to make the abstract path concrete. +DTrace是FreeBSD提供的最强可观测性工具之一,它在存储工作中活跃起来是因为BIO路径被充分仪器化。我们将在后面的章节中更多地使用它,但即使像上面那样的单行命令也足以使抽象路径具体化。 ### 总结 Section 6 -Our pseudo 块设备 now plays the full role of a storage 设备: raw access through `dd`, 文件系统 access through UFS, and safe coexistence with 内核 卸载 protections. The strategy function we wrote in Section 5 did not need to change at all for UFS to work, because UFS and `dd` share the same 块-layer protocol below them. +我们的伪块设备现在扮演存储设备的完整角色:通过`dd`的原始访问,通过UFS的文件系统访问,以及与内核卸载保护的安全共存。我们在第5节编写的策略函数完全不需要改变就能让UFS工作,因为UFS和`dd`在它们下面共享相同的块层协议。 -We have also seen the end-to-end flow: VFS at the top, UFS just below, the 缓冲区 cache between, GEOM below that, and our 驱动程序 at the very bottom. That flow is the same for every 存储驱动程序 in FreeBSD. You now know how to occupy the bottom of it. +我们也看到了端到端的流程:VFS在顶部,UFS紧随其后,中间是缓冲区缓存,下面是GEOM,最底部是我们的驱动程序。这个流程对FreeBSD中的每个存储驱动程序都是相同的。你现在知道如何占据它的底部了。 -In the next section, we will turn our attention to persistence. A RAM-backed 设备 is convenient for testing but loses its contents on every reload. We will discuss options for making the backing store persistent, what trade-offs each option brings, and how to add one of them to our 驱动程序. +在下一节中,我们将把注意力转向持久性。RAM后备设备便于测试,但在每次重新加载时都会丢失内容。我们将讨论使后备存储持久化的选项,每个选项带来什么权衡,以及如何将其中之一添加到我们的驱动程序中。 -## Section 7: Persistence and In-Memory Backing Stores +## 第7节:持久性与内存后备存储 -Our 驱动程序 is self-consistent while running. If you write a byte at offset X, you can read it back at offset X moments later. If you create a file on the 挂载ed 文件系统, you can read it again until you 卸载 or unload. This is already useful for testing and for short-lived workloads. +我们的驱动程序在运行时是自洽的。如果你在偏移X处写入一个字节,稍后你可以在偏移X处读回它。如果你在已挂载的文件系统上创建一个文件,你可以再次读取它直到你卸载或卸载模块。这对于测试和短期工作负载已经很有用了。 -It is not, however, durable. Unload the module and the backing 缓冲区 is freed. Reboot the machine and every byte vanishes. For a teaching 驱动程序 that is arguably a feature: it reboots clean, it does not accumulate state across runs, and it cannot silently corrupt a previous session. But understanding the options for making storage persistent is essential for real 驱动程序 work, so this section walks through the major choices and then shows how to add the simplest kind of persistence to our 驱动程序. +然而,它不是持久的。卸载模块后,后备缓冲区被释放。重启机器后,每个字节都消失了。对于教学驱动程序来说,这可以说是一个特性:它重启后是干净的,不会跨运行累积状态,也不会静默损坏之前的会话。但理解使存储持久化的选项对于真正的驱动程序工作是至关重要的,因此本节遍历主要选择,然后展示如何向我们的驱动程序添加最简单的持久性。 -### Why Persistence Is Hard +### 持久性为何困难 -Storage persistence is not just about where the bytes live. It is about three intertwined properties. +存储持久性不仅仅是字节存储在哪里的问题。它涉及三个相互关联的属性。 -**Durability** means that once a write returns, the data is safe against a crash. On a hardware disk, durability is typically coupled with the disk's own cache policy: the write hits the drive's internal 缓冲区, then the platter, then the drive reports completion. `BIO_FLUSH` is the hook that gives 文件系统 a way to demand flush-to-platter semantics. +**持久性**意味着一旦写入返回,数据在崩溃时是安全的。在硬件磁盘上,持久性通常与磁盘自身的缓存策略相关联:写入到达驱动器的内部缓冲区,然后是盘片,然后驱动器报告完成。`BIO_FLUSH`是给文件系统一种要求刷新到盘片语义的钩子。 -**Consistency** means that a read at offset X returns the most recent write at offset X, not some earlier or partial version. Consistency is usually provided by the hardware or by careful locking in the 驱动程序. +**一致性**意味着在偏移X处的读取返回在偏移X处的最近写入,而不是某个更早或部分的版本。一致性通常由硬件或驱动程序中的仔细锁定提供。 -**Crash safety** means that after an unclean shutdown, the state of the storage is usable. Either it reflects all committed writes, or it reflects a well-defined prefix of them. UFS has SU+J (Soft Updates with Journaling) to help recover from a crash; ZFS uses copy-on-write and atomic transactions. All of that relies on a 块 layer that behaves predictably. +**崩溃安全**意味着在不干净关机后,存储的状态是可用的。它要么反映所有提交的写入,要么反映它们的良好定义的前缀。UFS有SU+J(带日志的Soft Updates)来帮助从崩溃中恢复;ZFS使用写时复制和原子事务。所有这些都依赖于可预测地行为的块层。 -For a teaching 驱动程序, we do not need to address all three with full rigour. We need to understand what the choices are and to pick one that fits our goals. +对于教学驱动程序,我们不需要以完全的严谨性来解决所有三个问题。我们需要理解选择是什么,并选择一个适合我们目标的。 -### The Options +### 各种选择 -There are four common ways to back a pseudo 块设备. +有四种常见的伪块设备后备方式。 -**In-memory backing (our current choice)**. Fast, simple, lost on reload. Implemented as a `malloc`'d 缓冲区. Scales poorly past a few MiB because it demands contiguous 内核 memory. +**内存后备(我们目前的选择)**。快速、简单,重新加载时丢失。实现为`malloc`分配的缓冲区。在几MiB以上扩展性差,因为它需要连续的内核内存。 -**Page-at-a-time in-memory backing**. `md(4)` uses this internally for large memory disks. Instead of one big 缓冲区, the 驱动程序 keeps an indirection table of page-sized allocations and fills them on demand. This scales to very large sizes and avoids wasting memory on sparse regions, but it is more complex. +**逐页内存后备**。`md(4)`在内部将其用于大型内存磁盘。不是一个大的缓冲区,驱动程序维护一个页大小分配的间接表并按需填充。这可以扩展到非常大的大小,避免在稀疏区域浪费内存,但更复杂。 -**Vnode backing**. The 驱动程序 opens a file in the host 文件系统 and uses it as the backing store. `mdconfig -t vnode` is the classic example. Reads and writes go through the host's 文件系统, which gives persistence at the cost of speed and of a dependency on the host 文件系统's correctness. This is how FreeBSD often boots from a memory-disk image embedded in the 内核: the 内核 loads the image, presents it as `/dev/md0`, and the root 文件系统 runs on it. +**Vnode后备**。驱动程序在主机文件系统中打开一个文件并将其用作后备存储。`mdconfig -t vnode`是经典示例。读写经过主机的文件系统,以速度和对主机文件系统正确性的依赖为代价提供持久性。这是FreeBSD经常从嵌入内核的内存磁盘镜像启动的方式:内核加载镜像,将其呈现为`/dev/md0`,根文件系统在其上运行。 -**Swap backing**. The 驱动程序 uses a swap-backed VM object as the backing store. `mdconfig -t swap` uses this. It provides persistence across reboots only to the extent that swap is persistent, which on most systems it is not. But it provides a very large sparse address space without consuming physical memory until touched, which is useful for scratch storage. +**交换后备**。驱动程序使用交换支持的VM对象作为后备存储。`mdconfig -t swap`使用这种方式。它只在交换是持久性的程度上提供跨重启的持久性,而在大多数系统上交换不是持久性的。但它提供了非常大的稀疏地址空间,而不在被触及之前消耗物理内存,这对于临时存储很有用。 -For this chapter, we will stick with the in-memory option. It is the simplest, it is enough for the labs, and it demonstrates every other concept cleanly. We will discuss how to switch to vnode-backed storage as an exercise, and we will point to `md(4)` for those who want to see a full-featured implementation. +在本章中,我们将坚持使用内存选项。它是最简单的,对实验足够了,并且干净地演示了每个其他概念。我们将讨论如何切换到vnode后备存储作为练习,并向那些想看到完整功能实现的人指出`md(4)`。 -### Saving and Restoring the Buffer +### 保存和恢复缓冲区 -If we want our 设备 to remember its contents across reloads, without changing the backing approach, we can save the 缓冲区 to a file on unload and restore it on load. This is not elegant, but it is direct, and it illustrates the contract clearly: the 驱动程序 is responsible for getting the backing bytes into memory before the first BIO arrives and for flushing them to safety before the last BIO leaves. +如果我们想让设备在重新加载后记住其内容,而不改变后备方式,我们可以在卸载时将缓冲区保存到文件中,在加载时恢复它。这不够优雅,但很直接,它清楚地说明了契约:驱动程序负责在第一个BIO到达之前将后备字节放入内存,并在最后一个BIO离开之前将它们刷新到安全的地方。 -In our case, the mechanics would look like this. +在我们的情况下,机制大致如下。 -On module load, after allocating the backing 缓冲区 but before calling `disk_create`, optionally read a file on the host 文件系统 into the 缓冲区. On module unload, after `disk_destroy` has completed, optionally write the 缓冲区 back to that file. +在模块加载时,在分配后备缓冲区之后但在调用`disk_create`之前,可选择将主机文件系统上的文件读入缓冲区。在模块卸载时,在`disk_destroy`完成后,可选择将缓冲区写回该文件。 -Doing this cleanly from inside the 内核 requires the vnode API. The 内核 provides `vn_open`, `vn_rdwr`, and `vn_close`, which together let a module read or write a path in the host 文件系统. These are not APIs we want to use casually, because they are not designed for high-throughput I/O from inside a 驱动程序, and because they run on whatever 文件系统 happens to be 挂载ed at that path, which is not always safe. But for a one-shot save and restore at load and unload time, they are acceptable. +从内核内部干净地执行此操作需要vnode API。内核提供`vn_open`、`vn_rdwr`和`vn_close`,它们共同让模块读取或写入主机文件系统中的路径。这些不是我们想随意使用的API,因为它们不是为驱动程序内部的高吞吐量I/O设计的,而且它们运行在挂载到该路径的任何文件系统上,这并不总是安全的。但对于加载和卸载时的一次性保存和恢复,它们是可以接受的。 -For teaching purposes we will not implement this. The correct way to persist a 块设备's contents is to use a real backing store, not to snapshot a RAM 缓冲区. But understanding the technique helps clarify the contract. +出于教学目的,我们不会实现这个。持久化块设备内容的正确方式是使用真正的后备存储,而不是快照RAM缓冲区。但理解该技术有助于澄清契约。 -### The Contract With Upper Layers +### 与上层的契约 -Whatever your backing store, the contract with upper layers is precise. +无论你的后备存储是什么,与上层的契约都是精确的。 -**A BIO_WRITE that completes successfully must be visible to all subsequent BIO_READ requests**, regardless of 缓冲区ing layers. Our in-memory 驱动程序 satisfies this because `memcpy` is the visible effect. +**成功完成的BIO_WRITE必须对所有后续的BIO_READ请求可见**,无论中间有什么缓冲层。我们的内存驱动程序满足这一点,因为`memcpy`是可见的效果。 -**A BIO_FLUSH that completes successfully must have made all previously successful BIO_WRITE requests durable**. Our in-memory 驱动程序 satisfies this trivially because there is no lower layer between our `memcpy` and the backing memory; all writes are "durable" in the sense we can offer. A real disk 驱动程序 typically issues a cache-flush command to the hardware in response to `BIO_FLUSH`. +**成功完成的BIO_FLUSH必须使所有先前成功的BIO_WRITE请求变为持久的**。我们的内存驱动程序平凡地满足这一点,因为我们的`memcpy`和后备内存之间没有更低的层;在我们能提供的意义上,所有写入都是"持久的"。真正的磁盘驱动程序通常在响应`BIO_FLUSH`时向硬件发出缓存刷新命令。 -**A BIO_DELETE may discard data but must not corrupt neighbouring 块**. Our in-memory 驱动程序 satisfies this by zeroing only the requested range. A real SSD 驱动程序 might issue TRIM for the range; a real HDD 驱动程序 typically has no hardware support for DELETE and can safely ignore it. +**BIO_DELETE可以丢弃数据但不能损坏相邻块**。我们的内存驱动程序通过仅清零请求的范围来满足这一点。真正的SSD驱动程序可能为该范围发出TRIM;真正的HDD驱动程序通常没有DELETE的硬件支持,可以安全地忽略它。 -**A BIO_READ must return the media contents or an error; it must not return uninitialised memory, stale cached data from a different transaction, or random bytes**. Our in-memory 驱动程序 satisfies this by zeroing the backing on allocation and writing only through the strategy function. +**BIO_READ必须返回介质内容或错误;它不能返回未初始化的内存、来自不同事务的陈旧缓存数据或随机字节**。我们的内存驱动程序通过在分配时清零后备存储并仅通过策略函数写入来满足这一点。 -If you keep these four rules in mind as you design a new 驱动程序, you will avoid nearly every correctness bug that plagues new 存储驱动程序. +如果你在设计新驱动程序时牢记这四条规则,你将避免困扰新存储驱动程序的几乎每一个正确性bug。 -### What md(4) Does Differently +### md(4)的不同之处 -The 内核's `md(4)` 驱动程序 is a mature, multi-type memory-disk 驱动程序. It supports five backing types: malloc, preload, swap, vnode, and null. Each type has its own strategy function that knows how to serve requests for that backing kind. Reading `/usr/src/sys/dev/md/md.c` is a valuable follow-up to this chapter because it shows how a real 驱动程序 handles all of the cases we are glossing over. +内核的`md(4)`驱动程序是一个成熟的、多类型的内存磁盘驱动程序。它支持五种后备类型:malloc、preload、swap、vnode和null。每种类型都有自己的策略函数,知道如何为该后备类型服务请求。阅读`/usr/src/sys/dev/md/md.c`是本章有价值的后续,因为它展示了真正的驱动程序如何处理我们略过的所有情况。 -A few specific things `md(4)` does that we do not. +`md(4)`做了一些我们没有做的具体事情。 -`md(4)` uses a dedicated worker thread per unit. Incoming BIOs are queued on the softc, and the worker thread dequeues them one by one and dispatches them. This lets the strategy function be very simple: just enqueue and signal. It also isolates 块ing work in the worker, which matters for the vnode backing type because `vn_rdwr` can 块. +`md(4)`为每个单元使用一个专用的工作线程。传入的BIO被排队在softc上,工作线程逐个出列并分派它们。这使得策略函数非常简单:只需入队和发信号。它还将阻塞工作隔离在工作线程中,这对vnode后备类型很重要,因为`vn_rdwr`可能阻塞。 -`md(4)` uses `DEV_BSHIFT` (which is `9`, meaning 512-byte 扇区) consistently and uses integer arithmetic rather than floating point to handle offsets. This is standard practice in the 块 layer. +`md(4)`一致使用`DEV_BSHIFT`(即`9`,表示512字节扇区),并使用整数算术而不是浮点来处理偏移。这是块层的标准做法。 -`md(4)` has a full ioctl surface for configuration. The `mdconfig` tool talks to the 内核 through ioctls on `/dev/mdctl`, and the 驱动程序 supports `MDIOCATTACH`, `MDIOCDETACH`, `MDIOCQUERY`, and `MDIOCRESIZE`. We have not implemented anything comparable, because for our pseudo 设备 the configuration is baked in at compile time. +`md(4)`有一个完整的ioctl配置接口。`mdconfig`工具通过`/dev/mdctl`上的ioctl与内核通信,驱动程序支持`MDIOCATTACH`、`MDIOCDETACH`、`MDIOCQUERY`和`MDIOCRESIZE`。我们没有实现任何类似的东西,因为对于我们的伪设备,配置是在编译时固定的。 -`md(4)` uses `DISK_VERSION_06`, which is the current version of the `g_disk` ABI. Our 驱动程序 does the same, through the `DISK_VERSION` macro. +`md(4)`使用`DISK_VERSION_06`,这是`g_disk` ABI的当前版本。我们的驱动程序通过`DISK_VERSION`宏做同样的事情。 -If you want to see a production-quality pseudo 块设备, `md(4)` is the canonical reference. Almost everything we are building would, in a real 驱动程序, grow to resemble the shape of `md(4)` over time. +如果你想看到一个生产质量的伪块设备,`md(4)`是规范的参考。我们正在构建的几乎所有东西,在真正的驱动程序中,最终都会随着时间推移而类似于`md(4)`的形状。 -### A Note on Swap-Backed Memory +### 关于交换支持的内存的说明 -One technique worth naming, even though we will not use it here, is swap-backed memory. Instead of a `malloc`'d 缓冲区, a 驱动程序 can allocate a VM object of type `OBJT_SWAP` and map pages from it on demand. The pages are backed by swap space, which means they can be paged out when the system is under memory pressure and paged back in when touched. This gives you a very large, sparse, on-demand backing store that behaves like RAM when hot and like disk when cold. +有一种值得提及的技术,尽管我们不会在这里使用它,那就是交换支持的内存。不是用`malloc`分配的缓冲区,驱动程序可以分配一个`OBJT_SWAP`类型的VM对象并按需映射页面。页面由交换空间支持,这意味着它们可以在系统内存压力大时被换出,在被触及 时换入。这给你一个非常大的、稀疏的、按需的后备存储,热时行为像RAM,冷时行为像磁盘。 -`md(4)` uses exactly this approach for its swap-backed memory disks. The swap VM object acts as a backing store that the 内核's VM subsystem manages for us, without the 驱动程序 needing to allocate contiguous physical memory up front. The `OBJT_SWAP` object can hold terabytes of addressable space on a system with only gigabytes of RAM, because most of that space is never touched. +`md(4)`正是对其交换支持的内存磁盘使用了这种方法。交换VM对象作为后备存储,由内核的VM子系统为我们管理,驱动程序不需要预先分配连续的物理内存。`OBJT_SWAP`对象可以持有TB级的可寻址空间,而系统上只有GB级的RAM,因为该空间的大部分从未被触及。 -If you ever need to prototype a 块设备 larger than a few hundred MiB, swap-backed memory is likely the right tool. The VM API for it lives in `/usr/src/sys/vm/swap_pager.c`. Reading it is not light work, but it is educational. +如果你需要原型化一个大于几百MiB的块设备,交换支持的内存可能是正确的工具。它的VM API位于`/usr/src/sys/vm/swap_pager.c`。阅读它不是轻松的工作,但很有教育意义。 -### A Note on Preloaded Images +### 关于预加载镜像的说明 -FreeBSD has a mechanism called **preloaded modules**. During boot, the loader can bring in not just 内核模块 but also arbitrary data blobs, which are made available to the 内核 through `preload_fetch_addr` and `preload_fetch_size`. `md(4)` uses this to expose preloaded 文件系统 images as `/dev/md*` 设备, which is one of the ways FreeBSD can boot entirely from a memory-disk root. +FreeBSD有一个称为**预加载模块**的机制。在启动期间,加载器不仅可以引入内核模块,还可以引入任意数据blob,这些通过`preload_fetch_addr`和`preload_fetch_size`对内核可用。`md(4)`使用它将预加载的文件系统镜像暴露为`/dev/md*`设备,这是FreeBSD可以完全从内存磁盘根启动的方式之一。 -Preloaded images are not a persistence mechanism per se. They are a way to ship data with a 内核模块. But they are often used in embedded systems, where the root 文件系统 is too precious to live on writable storage. +预加载镜像本身不是持久化机制。它们是与内核模块一起发布数据的一种方式。但它们经常用于嵌入式系统,其中根文件系统太珍贵而不能存储在可写存储上。 -### A Small Extension: Persisting Across Module Reloads Only +### 小扩展:仅在模块重新加载时持久化 -We are not going to add real persistence to our 驱动程序, but this is a good moment to talk about what it would actually take to make a backing store survive a module unload and reload within the same 内核 boot. The naive first idea, and one that beginners reach for quickly, is to put the backing pointer in a file-scope `static` variable and simply not free it in the unload handler. Let us look at why that does not work and what does. +我们不会向驱动程序添加真正的持久性,但现在是讨论后备存储在同一内核启动中存活模块卸载和重新加载实际需要什么的好时机。最天真的第一个想法(也是初学者很快会想到的)是将后备指针放在文件作用域的`static`变量中,并在卸载处理器中简单地不释放它。让我们看看为什么这不起作用以及什么才起作用。 -Consider this sketch: +考虑这个草拟: ```c static uint8_t *myblk_persistent_backing; /* wishful thinking */ static size_t myblk_persistent_size; ``` -The intuition is that if we allocate `myblk_persistent_backing` on first 附加 and refuse to free it on 分离, a subsequent `kldload` will see the pointer still set and reuse the 缓冲区. The problem is that this picture ignores how a KLD is actually loaded and unloaded. When `kldunload` removes our module, the 内核 reclaims the module's text, data, and `.bss` segments along with the rest of its image. Our static pointer does not persist in some stable location; it vanishes together with the module. When `kldload` then brings the module back, the 内核 allocates a fresh `.bss`, zeroes it, and our pointer starts life as `NULL` again. The `malloc`'d 缓冲区 we allocated on the previous 附加 is still sitting in 内核 heap somewhere, but we have lost every handle to it. We have leaked it. +直觉是,如果我们在首次附加时分配`myblk_persistent_backing`并拒绝在分离时释放它,随后的`kldload`将看到指针仍然设置并重用缓冲区。问题在于,这个图景忽略了KLD实际是如何加载和卸载的。当`kldunload`移除我们的模块时,内核回收模块的文本、数据和`.bss`段以及其映像的其余部分。我们的静态指针不会持久存在于某个稳定的位置;它与模块一起消失。当`kldload`随后带回模块时,内核分配一个新的`.bss`,将其清零,我们的指针从`NULL`开始。我们在上次附加时分配的`malloc`缓冲区仍然在内核堆中某处,但我们已经丢失了对它的每个句柄。我们泄漏了它。 -`SYSUNINIT` does not help either, because in a KLD context it fires on `kldunload`, not on some later "final tear-down" event. Registering a `SYSUNINIT` to free the 缓冲区 would free it on every unload, which is exactly what we did not want. There is no KLD-level hook that means "the module file is really, truly being removed from memory for good" distinct from plain `kldunload`. +`SYSUNINIT`也没有帮助,因为在KLD上下文中,它在`kldunload`时触发,而不是在某个稍后的"最终拆解"事件上。注册`SYSUNINIT`来释放缓冲区会在每次卸载时释放它,这正是我们不想要的。没有KLD级别的钩子意味着"模块文件真的、确实要从内存中永久移除"与普通的`kldunload`不同。 -Two techniques actually achieve cross-unload persistence, and both are used by `md(4)` in production. The first is a **file-backed store**. Instead of allocating a 内核 heap 缓冲区, the 驱动程序 opens a file on an existing 文件系统 using the vnode I/O API (`VOP_READ`, `VOP_WRITE`, and the vnode reference taken via `vn_open`) and services BIOs by reading from and writing to that file. On unload, the 驱动程序 closes the file; on the next load, it re-opens it. The persistence is real because it lives in a 文件系统 whose state is independent of our module. This is exactly what `md -t vnode -f /path/to/image.img` does, and you can study it in `/usr/src/sys/dev/md/md.c`. +两种技术实际实现了跨卸载持久性,两者都被`md(4)`在生产中使用。第一种是**文件后备存储**。驱动程序不是分配内核堆缓冲区,而是使用vnode I/O API(`VOP_READ`、`VOP_WRITE`和通过`vn_open`获取的vnode引用)在现有文件系统上打开一个文件,并通过读取和写入该文件来服务BIO。卸载时,驱动程序关闭文件;下次加载时,它重新打开。持久性是真实的,因为它存在于状态独立于我们模块的文件系统中。这正是`md -t vnode -f /path/to/image.img`所做的,你可以在`/usr/src/sys/dev/md/md.c`中研究它。 -The second technique is a **swap-backed store**. The 驱动程序 allocates a VM object of type `OBJT_SWAP`, as we mentioned earlier, and maps pages from it on demand. The pager lives at a higher level of the 内核 than our module, so the object can outlive any particular `kldunload` as long as something else holds a reference to it. In practice, `md(4)` uses this for swap-backed memory disks, and it ties the object's lifetime to a 内核-wide list rather than to a module instance. +第二种技术是**交换后备存储**。驱动程序分配一个`OBJT_SWAP`类型的VM对象,正如我们之前提到的,并按需从中映射页面。分页器位于比我们模块更高的内核级别,因此只要其他东西持有对它的引用,对象就可以比任何特定的`kldunload`存活更久。在实践中,`md(4)`将此用于交换支持的内存磁盘,它将对象的生命周期绑定到内核范围的列表而不是模块实例。 -For our teaching 驱动程序, we will not implement either technique. The point of showing this discussion is to make sure you understand why the apparent shortcut does not work, so that you do not spend an afternoon debugging a 缓冲区 that keeps disappearing after `kldunload`. If you want to experiment with real cross-unload persistence, read `md.c` carefully, particularly the `MD_VNODE` and `MD_SWAP` branches in `mdstart_vnode` and `mdstart_swap`, and note how the backing objects are 附加ed to the per-unit `struct md_s` rather than to module-scope globals. That structural choice is what makes those backends work across module lifecycles. +对于我们的教学驱动程序,我们不会实现任何一种技术。展示这个讨论的目的是确保你理解为什么明显的快捷方式不起作用,这样你就不会花一下午时间调试在`kldunload`后不断消失的缓冲区。如果你想实验真正的跨卸载持久性,仔细阅读`md.c`,特别是`mdstart_vnode`和`mdstart_swap`中的`MD_VNODE`和`MD_SWAP`分支,并注意后备对象是如何附加到每单元的`struct md_s`而不是模块范围的全局变量。这个结构选择正是让那些后端跨模块生命周期工作的原因。 -### Sketching a Vnode-Backed Strategy Function +### 草拟vnode后备的策略函数 -To make the earlier discussion concrete, let us sketch what a vnode-backed strategy function looks like at the code level. We are not going to drop this into our teaching 驱动程序. We are showing it so that you can see what the "real" solution involves and can recognise the same shape in `md.c` when you read it. +为了让前面的讨论更具体,让我们草拟一个vnode后备的策略函数在代码级别是什么样子的。我们不会将这个放入教学驱动程序中。我们展示它是为了让你能看到"真正的"解决方案涉及什么,并在阅读`md.c`时能认出相同的形状。 -The idea is that the per-unit softc holds a reference to a vnode, acquired at 附加 time from a path provided by the administrator. The strategy function translates each BIO into a `vn_rdwr` call at the right offset and completes the BIO based on the result. +其理念是,每单元的softc持有对vnode的引用,在附加时从管理员提供的路径获取。策略函数将每个BIO转换为正确偏移处的`vn_rdwr`调用,并根据结果完成BIO。 -Attach acquires the vnode: +附加获取vnode: ```c static int @@ -1768,9 +1768,9 @@ myblk_vnode_attach(struct myblk_softc *sc, const char *path) } ``` -`vn_open` looks up the path and returns a locked, referenced vnode. We then drop the lock, because we want to hold a reference without 块ing other operations, and we hang the vnode pointer on our softc. We also keep a reference to the credentials we will use for subsequent I/O. +`vn_open`查找路径并返回一个锁定的、已引用的vnode。然后我们释放锁,因为我们想在不阻塞其他操作的情况下持有引用,并将vnode指针挂在我们的softc上。我们还保留了用于后续I/O的凭据引用。 -The strategy function services BIOs against the vnode: +策略函数对vnode服务BIO: ```c static void @@ -1816,9 +1816,9 @@ myblk_vnode_strategy(struct bio *bp) } ``` -Notice how the shape of the switch is identical to our RAM-backed strategy function. The only difference is what the case arms do: instead of `memcpy` into a 缓冲区, we call `vn_rdwr` against a vnode. The 框架 above us, GEOM and the 缓冲区 cache, does not know or care which backend we chose. +注意switch的形状与我们RAM后备策略函数完全相同。唯一的区别是case分支做什么:不是对缓冲区进行`memcpy`,而是对vnode调用`vn_rdwr`。我们上面的框架,GEOM和缓冲区缓存,不知道也不关心我们选择了哪个后端。 -Detach releases the vnode: +分离释放vnode: ```c static void @@ -1837,86 +1837,86 @@ myblk_vnode_detach(struct myblk_softc *sc) } ``` -`vn_close` releases the vnode reference and, if this was the last reference, allows the vnode to be recycled. The credentials are reference-counted the same way. +`vn_close`释放vnode引用,如果这是最后一个引用,则允许vnode被回收。凭据以相同的方式引用计数。 -Why does this give us cross-unload persistence? Because the state we care about, namely the contents of the backing store, lives in a file on a real 文件系统 whose lifetime is completely independent of our module. When we call `kldunload`, the vnode reference is released and the file closes; its contents on disk are preserved by the 文件系统. When we call `kldload` again and 附加, we open the file again and pick up where we left off. +为什么这给我们跨卸载持久性?因为我们关心的状态(即后备存储的内容)存在于真正文件系统上的文件中,其生命周期完全独立于我们的模块。当我们调用`kldunload`时,vnode引用被释放,文件关闭;其在磁盘上的内容由文件系统保留。当我们再次调用`kldload`并附加时,我们再次打开文件并从上次离开的地方继续。 -The remaining subtleties are substantial. Error paths need to release the vnode if `vn_open` succeeded but subsequent registration steps failed. Calls to `vn_rdwr` can sleep, which means the strategy function must not be called from a context that disallows sleeping; in practice, that is why `md(4)` uses a dedicated worker thread for vnode-backed units. Reading a file can race with the administrator modifying it, so production 驱动程序 usually take measures to detect concurrent external changes. `VOP_FSYNC` is not free, so a fast path that batches writes before flushing is typical. And the vnode lifetime itself is bound by VFS's own reference counting, which interacts with 卸载 of the containing 文件系统. +剩余的微妙之处相当多。如果`vn_open`成功但后续的注册步骤失败,错误路径需要释放vnode。对`vn_rdwr`的调用可能睡眠,这意味着策略函数不能从不允许睡眠的上下文调用;在实践中,这就是为什么`md(4)`为vnode后备单元使用专用工作线程。读取文件可能与管理员修改它竞争,所以生产驱动程序通常采取措施检测并发的外部更改。`VOP_FSYNC`不是免费的,因此在刷新之前批量写入的快速路径是典型的。而且vnode生命周期本身受VFS自己的引用计数约束,这与其所含文件系统的卸载交互。 -We will not add this to our teaching 驱动程序, but when you read `mdstart_vnode` in `/usr/src/sys/dev/md/md.c`, you will recognise every one of these issues handled carefully and explicitly. +我们不会将此添加到教学驱动程序中,但当你阅读`/usr/src/sys/dev/md/md.c`中的`mdstart_vnode`时,你会认出这些问题中每一个都被仔细和明确地处理了。 ### 总结 Section 7 -Persistence is a layered concept. Durability, consistency, and crash safety are all part of what a real storage 设备 must provide, and different backing stores give different subsets of those guarantees. For a teaching 驱动程序, a `malloc`'d in-memory 缓冲区 is a reasonable choice, and we can add "survives module reload" semantics without much code by 分离ing the 缓冲区 from the per-instance softc. +持久性是一个分层概念。持久性、一致性和崩溃安全都是真正的存储设备必须提供的,不同的后备存储提供这些保证的不同子集。对于教学驱动程序,`malloc`分配的内存缓冲区是合理的选择,我们可以通过将缓冲区与每实例的softc分离来添加"存活模块重新加载"的语义,而不需要太多代码。 -For production, the techniques grow more elaborate: page-at-a-time allocation, swap-backed VM objects, vnode-backed files, dedicated worker threads, BIO_FLUSH coordination, and careful handling of every error path. `md(4)` is the canonical example in the FreeBSD tree, and reading it is strongly recommended. +对于生产环境,技术变得更加精细:逐页分配、交换支持的VM对象、vnode支持的文件、专用工作线程、BIO_FLUSH协调和每个错误路径的仔细处理。`md(4)`是FreeBSD源码树中的规范示例,强烈建议阅读。 -In the next section, we will focus on the teardown path in detail. We will look at how GEOM coordinates 卸载, 分离, and cleanup; how access counts gate the module unload path; and how our 驱动程序 should behave when something goes wrong mid-teardown. Storage 卸载 bugs are some of the nastier kinds of 内核 bug, and careful attention here pays off for the rest of your 驱动程序-writing career. +在下一节中,我们将详细关注拆解路径。我们将了解GEOM如何协调卸载、分离和清理;访问计数如何门控模块卸载路径;以及我们的驱动程序在拆解中途出现问题时应该如何表现。存储卸载bug是一些更棘手的内核bug类型,在这里的仔细关注将在你的驱动程序编写生涯的剩余时间里得到回报。 -## Section 8: Safe Un挂载 and Cleanup +## 第8节:安全卸载与清理 -Storage 驱动程序 handle the end of their lives with more care than character 驱动程序 because the stakes are higher. When a character 驱动程序 unloads cleanly, the worst thing that can happen is that an open session is torn down, possibly with some bytes in flight being lost. When a 存储驱动程序 unloads while a 文件系统 is 挂载ed on it, the worst thing that can happen is that the 内核 panics on the next BIO, and the user is left with a 文件系统 image that may or may not have been in a consistent state when the 驱动程序 disappeared. +存储驱动程序比字符驱动程序更加小心地处理其生命终结,因为风险更高。当字符驱动程序干净地卸载时,可能发生的最坏情况是一个打开的会话被拆除,可能有一些飞行中的字节丢失。当存储驱动程序在文件系统挂载在其上时卸载,可能发生的最坏情况是内核在下一次BIO时崩溃,用户留下一个在驱动程序消失时可能或可能未处于一致状态的文件系统镜像。 -The good news is that the 内核's defences make the catastrophic case almost impossible if you use `g_disk` correctly. The refusal of `kldunload` to proceed when the GEOM access count is non-zero, which we saw in Section 6, is the primary safety net. But it is not the only concern. This section walks through the teardown path in detail so that you know what to expect, what to implement, and what to test. +好消息是,如果你正确使用`g_disk`,内核的防御措施使灾难性情况几乎不可能发生。`kldunload`在GEOM访问计数非零时拒绝继续,这是我们在第6节中看到的主要安全网。但这不是唯一的关注点。本节详细遍历拆解路径,以便你知道该期望什么、该实现什么和该测试什么。 -### The Expected Teardown Sequence +### 预期的拆卸序列 -The nominal sequence of events when a user wants to remove a 存储驱动程序 is as follows. +当用户想要移除存储驱动程序时,事件的名义序列如下。 -1. The user 卸载s every 文件系统 that is 挂载ed on the 设备. -2. The user closes any program that has `/dev/myblk0` open for raw access. -3. The user calls `kldunload`. -4. The module unload function calls `disk_destroy`. -5. `disk_destroy` queues the provider for withering, which runs on the GEOM event thread. -6. The withering process waits for any in-flight BIO to complete. -7. The provider is removed from the GEOM topology and the `/dev` node is destroyed. -8. `disk_destroy` returns control to our unload function. -9. Our unload function frees the softc and the backing store. -10. The 内核 unloads the module. +1. 用户卸载挂载在设备上的每个文件系统。 +2. 用户关闭任何以原始访问方式打开`/dev/myblk0`的程序。 +3. 用户调用`kldunload`。 +4. 模块卸载函数调用`disk_destroy`。 +5. `disk_destroy`将提供者排队等待枯萎,枯萎在GEOM事件线程上运行。 +6. 枯萎过程等待任何飞行中的BIO完成。 +7. 提供者从GEOM拓扑中移除,`/dev`节点被销毁。 +8. `disk_destroy`将控制返回给我们的卸载函数。 +9. 我们的卸载函数释放softc和后备存储。 +10. 内核卸载模块。 -Each step has its own failure modes. Let us walk through them. +每个步骤都有自己的故障模式。让我们逐个遍历它们。 ### Step 1: Un挂载 -The user runs `u挂载 /mnt/myblk`. VFS asks UFS to flush the 文件系统, which causes the 缓冲区 cache to issue any pending writes to GEOM, which routes them to our 驱动程序. Our strategy function services the writes and calls `biodone`. The 缓冲区 cache reports success; UFS disposes of its in-memory state; VFS releases the 挂载 point. The consumer that UFS had 附加ed to our provider is 分离ed. The access count drops. +用户运行`umount /mnt/myblk`。VFS请求UFS刷新文件系统,这导致缓冲区缓存向GEOM发出任何待处理的写入,GEOM将它们路由到我们的驱动程序。我们的策略函数服务写入并调用`biodone`。缓冲区缓存报告成功;UFS处置其内存状态;VFS释放挂载点。UFS附加到我们提供者的消费者被分离。访问计数下降。 -Our 驱动程序 does not do anything special during this phase. We keep handling BIOs as they arrive until UFS stops issuing them. +我们的驱动程序在此阶段不做任何特殊处理。我们继续按到达顺序处理BIO,直到UFS停止发出它们。 -### Step 2: Close Raw Access +### 步骤2:关闭原始访问 -The user ensures that no program holds `/dev/myblk0` open. If a `dd` is running, kill it. If a shell has the 设备 open via `exec`, close that. Until every open handle is released, the access count will remain non-zero on at least one of the `r`, `w`, or `e` counters. +用户确保没有程序持有打开的`/dev/myblk0`。如果有`dd`在运行,杀掉它。如果有shell通过`exec`打开了设备,关闭它。在释放每个打开句柄之前,访问计数将在`r`、`w`或`e`计数器中的至少一个上保持非零。 -Again, our 驱动程序 does nothing special. The `close(2)` calls on `/dev/myblk0` propagate through `devfs`, through GEOM's character-设备 integration, and release their access. No BIOs are issued for close. +同样,我们的驱动程序不做任何特殊处理。对`/dev/myblk0`的`close(2)`调用通过`devfs`、通过GEOM的字符设备集成传播,并释放它们的访问权限。关闭不会发出BIO。 -### Step 3: kldunload +### 步骤3:kldunload -The user runs `kldunload myblk`. The 内核's module subsystem calls our unload function with `MOD_UNLOAD`. Our unload function calls `myblk_分离_unit`, which calls `disk_destroy`. +用户运行`kldunload myblk`。内核的模块子系统以`MOD_UNLOAD`调用我们的卸载函数。我们的卸载函数调用`myblk_detach_unit`,后者调用`disk_destroy`。 -At this point, our 驱动程序 is about to stop existing. We must not be holding any lock that could 块, we must not be 块ing on our own worker threads (we do not have any in this design), and we must not be issuing new BIOs. Nothing we do now should cause new work for the 内核. +此时,我们的驱动程序即将停止存在。我们不能持有任何可能阻塞的锁,我们不能在我们自己的工作线程上阻塞(我们在本设计中没有任何工作线程),我们不能发出新的BIO。我们现在做的任何事情都不应该给内核带来新的工作。 -### Step 4: disk_destroy +### 步骤4:disk_destroy -`disk_destroy` is the point of no return. Reading the source in `/usr/src/sys/geom/geom_disk.c` reveals that it does three things: +`disk_destroy`是不可逆的点。阅读`/usr/src/sys/geom/geom_disk.c`中的源码发现它做三件事: -1. It sets a flag on the disk to indicate that destruction is in progress. -2. It queues a GEOM event that will actually dismantle the provider. -3. It waits for the event to complete. +1. 它在磁盘上设置一个标志,表示销毁正在进行。 +2. 它排队一个GEOM事件,该事件将实际拆解提供者。 +3. 它等待事件完成。 -While we are waiting, the GEOM event thread picks up the event and walks our geom. If the access counts are zero, the event proceeds. If they are not zero, the event panics with a message about trying to destroy a disk that still has users. +在我们等待期间,GEOM事件线程拾取事件并遍历我们的geom。如果访问计数为零,事件继续。如果它们不为零,事件会以试图销毁仍有用户的磁盘的消息崩溃。 -This is where the importance of Step 1 and Step 2 shows up. If you skip them and try to unload while the 文件系统 is 挂载ed, the panic happens here. Fortunately, `g_disk` refuses to reach the panic because the module subsystem has already refused the unload earlier, but if you were to bypass the module subsystem and call `disk_destroy` directly from some other context, this is the check that protects the 内核. +这就是步骤1和步骤2的重要性所在。如果你跳过它们并试图在文件系统挂载时卸载,崩溃就在这里发生。幸运的是,`g_disk`拒绝到达崩溃,因为模块子系统已经早些时候拒绝了卸载,但如果你绕过模块子系统并从其他上下文直接调用`disk_destroy`,这就是保护内核的检查。 -### Step 5 to 7: Withering +### 步骤5到7:枯萎 -The GEOM withering process is how providers are removed from the topology. It works by marking the provider as withered, cancelling any BIOs that were queued but not yet delivered, waiting for any in-flight BIOs to complete, removing the provider from the geom's provider list, and then removing the geom from the class. The `/dev` node is removed as part of this. +GEOM枯萎过程是提供者从拓扑中移除的方式。它的工作方式是将提供者标记为枯萎、取消已排队但尚未交付的任何BIO、等待任何飞行中的BIO完成、从geom的提供者列表中移除提供者,然后从类中移除geom。`/dev`节点作为此过程的一部分被移除。 -During withering, the strategy function may still be called for BIOs that were in flight before the withering started. Our strategy function will handle them normally, because our 驱动程序 does not know or care that withering is in progress. The 框架 is responsible for ensuring no new BIOs are issued after the point of no return. +在枯萎期间,对于在枯萎开始之前飞行中的BIO,策略函数仍然可能被调用。我们的策略函数将正常处理它们,因为我们的驱动程序不知道也不关心枯萎正在进行。框架负责确保在不可逆点之后不会发出新的BIO。 -If our 驱动程序 had worker threads, a queue, or other internal state, we would need to coordinate with withering carefully. `md(4)` is a good example of a 驱动程序 that does this: its worker thread watches for a shutdown flag and drains its queue before exiting. Since our 驱动程序 is entirely synchronous and single-threaded, we do not have this complication. +如果我们的驱动程序有工作线程、队列或其他内部状态,我们需要小心地与枯萎协调。`md(4)`是一个这样做的驱动程序的好例子:它的工作线程监视关闭标志并在退出前排干其队列。由于我们的驱动程序完全是同步和单线程的,我们没有这个复杂性。 -### Step 8 to 9: Free Resources +### 步骤8到9:释放资源 -Once `disk_destroy` returns, the disk is gone, the provider is gone, and no more BIOs will arrive. It is safe to free the backing store and destroy the 互斥锁. +`disk_destroy` 返回后,磁盘已消失,提供者已消失,不会再有 BIO 到达。此时可以安全地释放后备存储并销毁互斥锁。 ```c static void @@ -1935,7 +1935,7 @@ myblk_detach_unit(struct myblk_softc *sc) } ``` -Our unload function then destroys the 互斥锁 and frees the softc. +然后我们的卸载函数销毁互斥锁并释放 softc。 ```c case MOD_UNLOAD: @@ -1950,29 +1950,29 @@ case MOD_UNLOAD: return (0); ``` -### Step 10: Module Unload +### 步骤10:模块卸载 -The module subsystem unloads the `.ko` file. At this point, the 驱动程序 is gone. Any attempt to reference the module by name will fail until the user loads it again. +模块子系统卸载 `.ko` 文件。此时驱动程序已经消失。任何通过名称引用该模块的尝试都将失败,直到用户再次加载它。 -### What Can Go Wrong +### 可能出现的问题 -The happy path is smooth. Let us enumerate the unhappy paths and how to recognise them. +正常路径是顺利的。让我们列举异常路径以及如何识别它们。 -**`kldunload` returns `Device 总线y`**. The 文件系统 is still 挂载ed, or a program still has the raw 设备 open. Un挂载 and close, then retry. This is the most common failure, and it is benign. +**`kldunload` 返回 `Device busy`**。文件系统仍然挂载着,或者某个程序仍然打开了原始设备。卸载并关闭,然后重试。这是最常见的失败,而且是良性的。 -**`disk_destroy` never returns**. Something is holding a BIO that will never complete, and the withering process is waiting for it. In practice, this happens if your strategy function fails to call `biodone` on some path. Look at `procstat -kk` of the `g_event` thread; if it is stuck in `g_waitfor_event`, you have a leaked BIO. The fix is in your strategy function: ensure that every path calls `biodone` exactly once. +**`disk_destroy` 永不返回**。某个东西持有一个永远不会完成的 BIO,枯萎过程正在等待它。实际上,如果你的策略函数在某条路径上没有调用 `biodone`,就会发生这种情况。查看 `g_event` 线程的 `procstat -kk` 输出;如果它卡在 `g_waitfor_event` 中,你就有一个泄漏的 BIO。修复方法在策略函数中:确保每条路径恰好调用 `biodone` 一次。 -**The 内核 panics with "g_disk: destroy with open count"**. Your 驱动程序 called `disk_destroy` while the provider still had users. This should not happen if you only call `disk_destroy` from the module unload path, because the module subsystem refuses to unload 总线y modules. But if you call `disk_destroy` in response to some other event, you must check the access count yourself or tolerate the panic. +**内核崩溃并显示 "g_disk: destroy with open count"**。你的驱动程序在提供者仍然有用户时调用了 `disk_destroy`。如果你只从模块卸载路径调用 `disk_destroy`,这不应该发生,因为模块子系统拒绝卸载繁忙的模块。但如果你响应其他事件调用 `disk_destroy`,你必须自己检查访问计数或容忍崩溃。 -**The 内核 panics with "Freeing free memory"**. Your 驱动程序 tried to free the softc or the backing store twice. Check your 分离 path for race conditions or for early exits that free and then fall through to free again. +**内核崩溃并显示 "Freeing free memory"**。你的驱动程序试图释放 softc 或后备存储两次。检查你的分离路径是否存在竞争条件或提前退出后又继续执行到释放代码。 -**The 内核 panics with "Page fault in 内核 mode"**. Something is dereferencing a freed pointer, most often the backing store after it has been freed while a BIO is still in flight. The fix is to ensure `disk_destroy` completes before freeing anything the strategy function touches. +**内核崩溃并显示 "Page fault in kernel mode"**。某个东西正在解引用已释放的指针,最常见的是后备存储释放后仍有 BIO 在飞行中。修复方法是确保 `disk_destroy` 在释放策略函数触及的任何内容之前完成。 -### The d_gone Callback +### d_gone回调 -There is one more piece of the teardown story worth discussing. The `d_gone` 回调 is invoked when something other than our 驱动程序 decides the disk should go away. The canonical example is hotplug removal: a user yanks a USB drive, the USB stack tells the 存储驱动程序 the 设备 is gone, and the 存储驱动程序 wants to tell GEOM to tear down the disk as gracefully as possible even though I/O will start failing. +拆卸故事中还有一部分值得讨论。`d_gone` 回调在我们的驱动程序之外的其他东西决定磁盘应该消失时被调用。典型的例子是热插拔移除:用户拔出 USB 驱动器,USB 栈告诉存储驱动程序设备已消失,存储驱动程序希望尽可能优雅地告诉 GEOM 拆卸磁盘,即使 I/O 将开始失败。 -Our 驱动程序 is a pseudo 设备; it does not have a physical disappearance event. But 注册ing a `d_gone` 回调 costs nothing and makes the 驱动程序 slightly more ro总线t against future extensions. +我们的驱动程序是一个伪设备;它没有物理消失事件。但注册 `d_gone` 回调没有任何代价,并且使驱动程序在将来的扩展中更加健壮。 ```c static void @@ -1983,35 +1983,35 @@ myblk_disk_gone(struct disk *dp) } ``` -Register it with `sc->disk->d_gone = myblk_disk_gone;` before `disk_create`. The function is called by `g_disk` when `disk_gone` is invoked. You can trigger it manually during development by calling `disk_gone(sc->disk)` from a test path; you will not usually call it yourself in a pseudo 驱动程序. +在 `disk_create` 之前用 `sc->disk->d_gone = myblk_disk_gone;` 注册它。该函数在 `disk_gone` 被调用时由 `g_disk` 调用。你可以在开发过程中通过从测试路径调用 `disk_gone(sc->disk)` 来手动触发它;在伪驱动程序中你通常不会自己调用它。 -Note the difference between `disk_gone` and `disk_destroy`. `disk_gone` says "this disk has physically vanished; stop accepting I/O and mark the provider as error-returning". `disk_destroy` says "remove this disk from the topology and free its resources". In a 热拔出 path, `disk_gone` is usually called first (by the 总线 驱动程序, when it notices the 设备 is gone), and `disk_destroy` is called later (by the module unload, or by the 总线 驱动程序's 分离 function). Between the two calls, the disk still exists in the topology but all I/O fails. Our 驱动程序 does not implement this dual-phase teardown; a USB mass 存储驱动程序, for instance, must. +注意 `disk_gone` 和 `disk_destroy` 之间的区别。`disk_gone` 表示"这个磁盘已经物理消失了;停止接受 I/O 并将提供者标记为返回错误"。`disk_destroy` 表示"从拓扑中移除这个磁盘并释放其资源"。在热拔出路径中,`disk_gone` 通常首先被调用(由总线驱动程序调用,当它注意到设备已消失时),`disk_destroy` 稍后被调用(由模块卸载或总线驱动程序的分离函数调用)。在两次调用之间,磁盘仍然存在于拓扑中,但所有 I/O 都会失败。我们的驱动程序不实现这种双阶段拆卸;例如 USB 大容量存储驱动程序则必须实现。 -### Testing the Teardown +### 测试拆卸 -Teardown bugs are often discovered not by careful testing but by accident, months later, when some user finds an unusual sequence that triggers them. It is much cheaper to test teardown deliberately. +拆卸 bug 通常不是通过仔细测试发现的,而是几个月后某个用户找到了触发它们的异常序列时偶然发现的。主动测试拆卸的成本要低得多。 -Here are the tests I recommend running on any new 存储驱动程序. +以下是我建议在任何新存储驱动程序上运行的测试。 -**Basic unload**. Load, format, 挂载, 卸载, unload. Verify `dmesg` shows our load and unload messages and nothing else. Repeat ten times to catch slow leaks. +**基本卸载**。加载、格式化、挂载、卸载文件系统、卸载模块。验证 `dmesg` 显示我们的加载和卸载消息且没有其他内容。重复十次以捕获缓慢的泄漏。 -**Unload without 卸载**. Load, format, 挂载. Attempt to unload. Verify the unload is refused. Un挂载, then unload. Verify no lingering state. +**未卸载文件系统时的卸载**。加载、格式化、挂载。尝试卸载模块。验证卸载被拒绝。卸载文件系统,然后卸载模块。验证没有残留状态。 -**Unload under load**. Load, format, 挂载, start a `dd if=/dev/urandom of=/mnt/myblk/stress bs=1m count=64`. While the `dd` runs, attempt to unload. Verify the unload is refused. Wait for `dd` to finish. Un挂载. Unload. Verify clean. +**负载下的卸载**。加载、格式化、挂载,启动 `dd if=/dev/urandom of=/mnt/myblk/stress bs=1m count=64`。在 `dd` 运行时,尝试卸载模块。验证卸载被拒绝。等待 `dd` 完成。卸载文件系统。卸载模块。验证清理干净。 -**Unload with raw open**. Load. In another terminal, run `cat > /dev/myblk0` to hold the 设备 open. Attempt to unload. Verify the unload is refused. Kill the cat. Unload. Verify clean. +**原始设备打开时的卸载**。加载。在另一个终端中,运行 `cat > /dev/myblk0` 以保持设备打开。尝试卸载模块。验证卸载被拒绝。终止 cat。卸载模块。验证清理干净。 -**Reload stress**. Load, unload, load, unload in a tight loop for a minute. If `vmstat -m` or `zpool list` starts showing leaks, investigate. +**重载压力测试**。在紧凑循环中加载、卸载、加载、卸载一分钟。如果 `vmstat -m` 或 `zpool list` 开始显示泄漏,进行调查。 -**Panic on corruption**. This one is harder: deliberately corrupt the module state via a 内核 debugger hook and verify that the 驱动程序 does not silently return bad data. In practice, few beginners do this, and it is not required for a teaching 驱动程序. +**损坏时的崩溃**。这个比较难:通过内核调试器钩子故意损坏模块状态,并验证驱动程序不会静默返回错误数据。实际上,很少有初学者这样做,教学驱动程序也不需要这样做。 -If all of these pass, you have a reasonably ro总线t teardown. Continue testing every change that touches the unload path. +如果所有这些都通过了,你就有了一个相当健壮的拆卸。每次更改涉及卸载路径的代码时都要继续测试。 -### The Idempotency Principle +### 幂等性原则 -A good teardown path is idempotent: calling it twice is no worse than calling it once. This matters because error paths during 附加 may call the teardown before everything has been set up. +一个好的拆卸路径是幂等的:调用两次不会比调用一次更糟。这很重要,因为附加过程中的错误路径可能在所有内容设置完成之前就调用拆卸。 -Write your teardown to check whether each resource was actually allocated before trying to free it. +编写拆卸函数时,在尝试释放每个资源之前检查它是否确实被分配了。 ```c static void @@ -2033,41 +2033,41 @@ myblk_detach_unit(struct myblk_softc *sc) } ``` -Setting pointers to `NULL` after freeing them is a small discipline that pays off. It makes double-free mistakes obvious at runtime (they become no-ops rather than corruptions), and it makes the teardown function idempotent. +释放指针后将它们设置为 `NULL` 是一个值得坚持的小习惯。它使双重释放错误在运行时变得明显(它们变成空操作而不是内存损坏),并且使拆卸函数幂等。 -### Ordering and Reverse Order +### 顺序与逆序 -A general teardown guideline: free resources in the reverse order of allocation. If 附加 goes `A -> B -> C`, 分离 should go `C -> B -> A`. +一个通用的拆卸准则:按分配的逆序释放资源。如果附加按 `A -> B -> C` 的顺序进行,分离应该按 `C -> B -> A` 的顺序进行。 -In our 驱动程序, 附加 goes `malloc backing -> disk_alloc -> disk_create`. So 分离 goes `disk_destroy -> free backing`. We skip freeing the disk because `disk_destroy` frees it for us. +在我们的驱动程序中,附加按 `malloc backing -> disk_alloc -> disk_create` 的顺序进行。所以分离按 `disk_destroy -> free backing` 的顺序进行。我们跳过释放磁盘,因为 `disk_destroy` 会替我们释放它。 -This pattern is universal. Every well-written teardown function reverses the allocation order. When you see a 分离 that runs in the same order as the 附加, suspect a bug. +这个模式是通用的。每个编写良好的拆卸函数都逆转分配顺序。当你看到一个分离函数按照与附加相同的顺序运行时,要怀疑存在 bug。 -### The MOD_QUIESCE Event +### MOD_QUIESCE事件 -There is a third module event we have not mentioned: `MOD_QUIESCE`. It is delivered before `MOD_UNLOAD` and gives the module a chance to refuse unload if the 驱动程序 is in a state where unloading is unsafe. +还有一个我们没有提到的第三个模块事件:`MOD_QUIESCE`。它在 `MOD_UNLOAD` 之前传递,给模块一个在驱动程序处于不安全卸载状态时拒绝卸载的机会。 -For most 驱动程序, the GEOM access-count check is sufficient, and implementing `MOD_QUIESCE` is not needed. But if your 驱动程序 has internal state that makes unload unsafe independent of GEOM (for example, a cache that must be flushed), `MOD_QUIESCE` is where you decline the unload by returning an error. +对于大多数驱动程序,GEOM 访问计数检查已经足够,不需要实现 `MOD_QUIESCE`。但如果你的驱动程序有独立于 GEOM 的内部状态使卸载不安全(例如,必须刷新的缓存),`MOD_QUIESCE` 就是你通过返回错误来拒绝卸载的地方。 -Our 驱动程序 does not implement `MOD_QUIESCE`. The default behaviour is to accept it silently, which is the right thing for us. +我们的驱动程序不实现 `MOD_QUIESCE`。默认行为是静默接受它,这对我们来说是正确的。 -### Coordinating With Future Worker Threads +### 与未来工作线程的协调 -If you ever add a worker thread to the 驱动程序, the teardown contract changes. You must: +如果你将来给驱动程序添加工作线程,拆卸契约就会改变。你必须: -1. Signal the worker to stop, typically by setting a flag on the softc. -2. Wake the worker if it is sleeping, typically with `wakeup` or `cv_signal`. -3. Wait for the worker to exit, typically with a `kthread_exit`-visible termination flag. -4. Only then call `disk_destroy`. -5. Free the softc and backing store. +1. 通知工作线程停止,通常通过在 softc 上设置一个标志。 +2. 如果工作线程正在睡眠,唤醒它,通常用 `wakeup` 或 `cv_signal`。 +3. 等待工作线程退出,通常通过 `kthread_exit` 可见的终止标志。 +4. 然后才能调用 `disk_destroy`。 +5. 释放 softc 和后备存储。 -Skipping any of these steps is a recipe for a panic. The usual failure mode is that the worker thread is sleeping inside a function that touches softc state after the softc has been freed. `md(4)` handles this carefully, and it is worth reading its worker shutdown code if you plan to add a worker to your own 驱动程序. +跳过这些步骤中的任何一个都会导致崩溃。常见的失败模式是工作线程在 softc 被释放后仍在访问 softc 状态的函数中睡眠。`md(4)` 仔细地处理了这个问题,如果你计划在自己的驱动程序中添加工作线程,值得阅读它的 worker 关闭代码。 -### Cleanup in the Face of Errors +### 错误情况下的清理 -One last concern: what happens if 附加 fails partway through? Suppose `disk_alloc` succeeds, but `disk_create` fails. Or suppose we add code that validates the 扇区 size and rejects invalid configurations before calling `disk_create`. +最后一个关注点:如果附加中途失败怎么办?假设 `disk_alloc` 成功了,但 `disk_create` 失败了。或者假设我们添加了验证扇区大小并在调用 `disk_create` 之前拒绝无效配置的代码。 -The pattern for handling this is "single cleanup path". Write the 附加 function so that any failure jumps to a cleanup label that unwinds everything allocated so far, in reverse order. +处理这种情况的模式是"单一清理路径"。编写附加函数,使任何失败都跳转到一个清理标签,该标签按逆序展开到目前为止分配的所有内容。 ```c static int @@ -2101,25 +2101,25 @@ myblk_attach_unit(struct myblk_softc *sc) } ``` -For our 驱动程序, `disk_alloc` does not fail in practice (it uses `M_WAITOK`), and `disk_create` is a `void` function that queues the real work asynchronously. So the 附加 path cannot really fail. But the pattern of preparing a single cleanup label is worth keeping in mind for 驱动程序 that grow more complex. +对于我们的驱动程序,`disk_alloc` 实际上不会失败(它使用 `M_WAITOK`),`disk_create` 是一个异步排队实际工作的 `void` 函数。所以附加路径实际上不会失败。但准备单一清理标签的模式对于变得更复杂的驱动程序来说是值得记住的。 ### 总结 Section 8 -Safe 卸载 and cleanup for a 存储驱动程序 comes down to a small set of disciplines: handle every BIO through to `biodone`, never hold locks during completion 回调, only call `disk_destroy` when the provider has no users, free resources in the reverse order of allocation, and test the teardown under load. The `g_disk` 框架 handles most of the hard parts; your job is to avoid breaking its invariants. +存储驱动程序的安全卸载和清理归结为一小组准则:确保每个 BIO 都通过 `biodone` 完成、在完成回调期间不持有锁、只在提供者没有用户时才调用 `disk_destroy`、按分配的逆序释放资源、以及在负载下测试拆卸。`g_disk` 框架处理了大部分困难的部分;你的工作是避免破坏其不变量。 -In the next section, we will step back from the teardown specifics and talk about how to let a 存储驱动程序 grow. We will discuss refactoring, versioning, how to support multiple units cleanly, and what to do when the 驱动程序 becomes more than a single source file. These are the habits that turn a teaching 驱动程序 into something you can keep evolving for a long time. +在下一节中,我们将从拆卸细节中退一步,讨论如何让存储驱动程序成长。我们将讨论重构、版本管理、如何干净地支持多个单元,以及当驱动程序变得超过单个源文件时该怎么做。这些是将教学驱动程序变成你可以长期持续演进的东西的习惯。 -## Section 9: Refactoring and Versioning +## 第9节:重构与版本管理 -Our 驱动程序 fits in a single file and solves one problem: it exposes a single pseudo disk of a fixed size, backed by RAM. That is a useful teaching starting point, but it is not where most real 驱动程序 live. A real 存储驱动程序 evolves. It grows ioctl support. It grows multi-unit support. It grows tunable parameters. It splits into multiple source files. Its on-disk representation, if any, goes through format changes. It accumulates a history of compatibility choices. +我们的驱动程序适合放在一个文件中,解决一个问题:它暴露一个由 RAM 支持的固定大小的伪磁盘。这是一个有用的教学起点,但不是大多数真实驱动程序所处的位置。一个真实的存储驱动程序会演进。它增长 ioctl 支持。它增长多单元支持。它增长可调参数。它拆分为多个源文件。它的磁盘上表示(如果有的话)经历格式变更。它积累了兼容性选择的历史。 -This section is about the habits that let a 驱动程序 grow gracefully. We will not add massive new features here; the companion labs and challenges will do that. What we will do is survey the refactoring and versioning questions that arise as any 存储驱动程序 matures, and we will point to the FreeBSD-idiomatic answers for each. +本节是关于让驱动程序优雅成长的习惯。我们不会在这里添加大量新功能;配套的实验和挑战会做这些。我们要做的是调查任何存储驱动程序成熟时出现的重构和版本管理问题,并指出每种情况的 FreeBSD 惯用答案。 -### Multi-Unit Support +### 多单元支持 -Right now our 驱动程序 supports exactly one instance, hardcoded as `myblk0`. If you wanted two or three pseudo disks, the current code would need duplicate softcs and duplicate disk registrations. Real 驱动程序 solve this with a data structure that can hold any number of units. +目前我们的驱动程序只支持一个实例,硬编码为 `myblk0`。如果你想要两个或三个伪磁盘,当前代码需要重复的 softc 和重复的磁盘注册。真实的驱动程序用可以容纳任意数量单元的数据结构来解决这个问题。 -The idiomatic FreeBSD pattern is a global list protected by a lock. The softc is allocated per unit and linked into the list. A loader-time tunable or an ioctl-driven call decides when to create a new unit. The unit number is allocated from a `unrhdr` (unique number range) allocator. +惯用的 FreeBSD 模式是一个由锁保护的全局列表。softc 按单元分配并链接到列表中。加载器时可调参数或 ioctl 驱动的调用决定何时创建新单元。单元号从 `unrhdr`(唯一编号范围)分配器分配。 A sketch: @@ -2179,59 +2179,59 @@ myblk_destroy_unit(struct myblk_softc *sc) } ``` -The loader initialises the unit pool once, and then individual units can be created and destroyed independently. This is very close to the pattern `md(4)` uses. +加载器一次性初始化单元池,然后各个单元可以独立创建和销毁。这与 `md(4)` 使用的模式非常接近。 -We will not refactor our chapter 驱动程序 to multi-unit yet, because the added code distracts from the other teaching goals. But you should know that this is where the 驱动程序 would go. Supporting multiple units is one of the first extensions real 驱动程序 need. +我们还不会将本章的驱动程序重构为多单元,因为添加的代码会分散其他教学目标的注意力。但你应该知道这是驱动程序未来发展的方向。支持多个单元是真实驱动程序首先需要的扩展之一。 -### Ioctl Surface for Runtime Configuration +### 运行时配置的ioctl接口 -With multiple units comes the need to configure them at runtime. You do not want to compile a new module every time you want a second unit or a different size. The answer is an ioctl on a control 设备. +有了多个单元,就需要在运行时配置它们。你不想每次想要第二个单元或不同大小时都编译一个新模块。答案是在控制设备上使用 ioctl。 -`md(4)` follows this pattern. There is a single `/dev/mdctl` 设备, and `mdconfig(8)` talks to it with ioctls. `MDIOCATTACH` creates a new unit with a specified size and backing type. `MDIOCDETACH` destroys a unit. `MDIOCQUERY` reads the state of a unit. `MDIOCRESIZE` changes the size. +`md(4)` 遵循这种模式。有一个单独的 `/dev/mdctl` 设备,`mdconfig(8)` 通过 ioctl 与它通信。`MDIOCATTACH` 创建一个具有指定大小和后备类型的新单元。`MDIOCDETACH` 销毁一个单元。`MDIOCQUERY` 读取单元的状态。`MDIOCRESIZE` 更改大小。 -For a 驱动程序 of any sophistication, this is the right place to invest. Compile-time configuration via macros is fine for a toy. Runtime configuration via ioctls is what real administrators want. +对于任何复杂度的驱动程序,这是值得投入的地方。通过宏进行编译时配置对玩具来说没问题。通过 ioctl 进行运行时配置是真正的管理员想要的。 -If you were to add this to our 驱动程序, you would: +如果你要将其添加到我们的驱动程序中,你会: -1. Create a `cdev` for the control 设备 using `make_dev`. -2. Implement `d_ioctl` on the cdev, switching on a small set of ioctl numbers you define. -3. Write a user-space tool that issues the ioctls. +1. 使用 `make_dev` 为控制设备创建一个 `cdev`。 +2. 在 cdev 上实现 `d_ioctl`,根据你定义的一小组 ioctl 号进行分发。 +3. 编写一个发出 ioctl 的用户空间工具。 -This is a substantial addition, which is why we mention it here without implementing it. 第28章 and later chapters will revisit this pattern. +这是一个相当大的添加,这就是为什么我们在这里提到它但没有实现它。第28章及后续章节将重新讨论这种模式。 -### Splitting the Source File +### 拆分源文件 -At some point, a 驱动程序 outgrows a single file. The usual decomposition for a FreeBSD 存储驱动程序 is roughly: +在某个时候,驱动程序会超出单个文件的范围。FreeBSD 存储驱动程序通常的分解大致如下: -- `驱动程序_name.c`: the public module entry, ioctl dispatch, and 附加/分离 wiring. -- `驱动程序_name_bio.c`: the strategy function and BIO path. -- `驱动程序_name_backing.c`: the backing-store implementation. -- `驱动程序_name_util.c`: small helpers, validation, and debug printing. -- `驱动程序_name.h`: the shared header that declares the softc, enums, and function prototypes. +- `driver_name.c`:公共模块入口、ioctl 分发和附加/分离连接。 +- `driver_name_bio.c`:策略函数和 BIO 路径。 +- `driver_name_backing.c`:后备存储实现。 +- `driver_name_util.c`:小型辅助函数、验证和调试打印。 +- `driver_name.h`:声明 softc、枚举和函数原型的共享头文件。 -The Makefile is updated to list all of them in `SRCS`, and the build system handles the rest. This is the shape of `md(4)`, of `ata(4)`, and of most substantial 驱动程序 in the tree. +Makefile 被更新以在 `SRCS` 中列出所有文件,构建系统处理其余部分。这是 `md(4)`、`ata(4)` 以及源代码树中大多数重要驱动程序的形态。 -We will keep our 驱动程序 in one file for the chapter. But when the challenges or your own extensions push it past, say, 500 lines, a decomposition like the above is the right move. Readers who want a concrete example should look at `/usr/src/sys/dev/ata/`, which splits a complex 驱动程序 across many files along clean lines. +我们将为本章的驱动程序保持一个文件。但当挑战或你自己的扩展将其推过,比如说,500 行时,像上面那样的分解是正确的选择。想要具体示例的读者应该查看 `/usr/src/sys/dev/ata/`,它沿着清晰的界限将复杂的驱动程序拆分到多个文件中。 -### Versioning +### 版本管理 -A 存储驱动程序 has several kinds of versioning to care about. +存储驱动程序有几种版本管理需要关心。 -**Module version**, declared with `MODULE_VERSION(myblk, 1)`. This is a monotonically increasing integer that other modules or userland tools can check. Bump it whenever you change the module's external behaviour in a way that cannot be detected from the code. +**模块版本**,用 `MODULE_VERSION(myblk, 1)` 声明。这是一个单调递增的整数,其他模块或用户空间工具可以检查。每当你以无法从代码检测到的方式更改模块的外部行为时,就递增它。 -**Disk ABI version**, encoded in `DISK_VERSION`. This is the version of the `g_disk` 接口 that your 驱动程序 was compiled against. If the 内核's `g_disk` changes incompatibly, it increments the version, and a 驱动程序 compiled against the old version will fail to 注册. You do not set this directly; you pass the `DISK_VERSION` macro through `disk_create`, and it picks up whatever version the compile found in `geom_disk.h`. You should recompile 驱动程序 against the 内核 you are targeting. +**磁盘 ABI 版本**,编码在 `DISK_VERSION` 中。这是你的驱动程序编译时所针对的 `g_disk` 接口版本。如果内核的 `g_disk` 发生不兼容更改,它会递增版本,针对旧版本编译的驱动程序将注册失败。你不直接设置它;你通过 `disk_create` 传递 `DISK_VERSION` 宏,它会获取编译时在 `geom_disk.h` 中找到的任何版本。你应该针对你目标的内核重新编译驱动程序。 -**On-disk format version**, for 驱动程序 that have any on-disk metadata. If your 驱动程序 stamps a magic number and a version into a reserved 扇区, you must handle upgrades. Our 驱动程序 has no on-disk format, so this does not apply yet, but it would if we added a proper backing-store header. +**磁盘上格式版本**,用于具有任何磁盘上元数据的驱动程序。如果你的驱动程序在保留扇区中写入魔术号和版本,你必须处理升级。我们的驱动程序没有磁盘上格式,所以这暂时不适用,但如果我们添加了适当的后备存储头,就需要了。 -**Ioctl number version**. Once you define ioctls, their numbers are part of the userland ABI. Changing them breaks older userland tools. Use `_IO`, `_IOR`, `_IOW`, `_IOWR` with stable magic letters, and do not repurpose numbers. +**Ioctl 号版本**。一旦你定义了 ioctl,它们的编号就是用户空间 ABI 的一部分。更改它们会破坏旧的用户空间工具。使用带有稳定魔术字母的 `_IO`、`_IOR`、`_IOW`、`_IOWR`,不要重新使用编号。 -For our chapter 驱动程序, the only version we care about right now is the module version. But keeping these four kinds of versioning in mind saves pain later. +对于我们本章的驱动程序,目前我们关心的唯一版本是模块版本。但记住这四种版本管理可以避免以后的麻烦。 -### Debugging and Observability Helpers +### 调试和可观测性辅助工具 -As the 驱动程序 grows, you will want to observe its state more richly than `dmesg` alone allows. Three tools are worth introducing now. +随着驱动程序的增长,你会想比仅使用 `dmesg` 更丰富地观察其状态。有三个工具值得现在介绍。 -**`sysctl` nodes**. FreeBSD's `sysctl(3)` 框架 lets a module publish read-only or read-write variables that user-space tools can query. You create a tree under a chosen name and 附加 values to it. The pattern is standard; in roughly ten lines of code you can expose the number of BIOs serviced, the number of bytes read and written, and the current media size. +**`sysctl` 节点**。FreeBSD 的 `sysctl(3)` 框架允许模块发布用户空间工具可以查询的只读或读写变量。你在选定的名称下创建一棵树并附加值到它。模式是标准的;大约十行代码就可以暴露已服务的 BIO 数量、读写的字节数和当前媒体大小。 ```c SYSCTL_NODE(_dev, OID_AUTO, myblk, CTLFLAG_RD, 0, @@ -2241,9 +2241,9 @@ SYSCTL_ULONG(_dev_myblk, OID_AUTO, reads, CTLFLAG_RD, &myblk_reads, 0, "Number of BIO_READ requests serviced"); ``` -**Devstat**. We are already using this through `g_disk`. It gives `iostat` and `gstat` their data. No further work needed. +**Devstat**。我们已经通过 `g_disk` 使用了这个。它为 `iostat` 和 `gstat` 提供数据。不需要额外工作。 -**DTrace 探测**. The `SDT` 框架 lets a module define static DTrace 探测 that incur zero cost when the 探测 is not being watched. These are especially useful in the BIO path because they let you see live request flow without recompiling. +**DTrace 探针**。`SDT` 框架允许模块定义静态 DTrace 探针,当探针没有被监视时零开销。这些在 BIO 路径中特别有用,因为它们让你无需重新编译就能看到实时请求流。 ```c #include @@ -2256,63 +2256,63 @@ SDT_PROBE3(myblk, , strategy, request, bp->bio_cmd, bp->bio_offset, bp->bio_bcount); ``` -You can then watch with `dtrace -n 'myblk::strategy:request {...}'`. +然后你可以用 `dtrace -n 'myblk::strategy:request {...}'` 来监视。 -For the chapter 驱动程序 we will not add all of this, but these are the patterns you should reach for as the 驱动程序 grows. +对于本章的驱动程序,我们不会添加所有这些,但随着驱动程序的增长,这些是你应该使用的模式。 -### Naming Stability +### 命名稳定性 -One habit that is easy to overlook: do not rename things casually. The name `myblk` is in the 设备 node, in the module version record, in the devstat name, possibly in sysctl nodes, in DTrace 探测, and in documentation. Renaming it cascades through all of those. For a project 驱动程序, pick a name you can live with forever. `md`, `ada`, `nvd`, `zvol`, and other 存储驱动程序 have kept their names for years because renaming is an ABI-affecting change for user-space tooling. +一个容易被忽视的习惯:不要随意重命名东西。名称 `myblk` 出现在设备节点中、模块版本记录中、devstat 名称中,可能还出现在 sysctl 节点、DTrace 探针和文档中。重命名它会级联影响到所有这些。对于项目驱动程序,选择一个你可以永远使用的名称。`md`、`ada`、`nvd`、`zvol` 和其他存储驱动程序多年来一直保持它们的名称,因为重命名是对用户空间工具有 ABI 影响的更改。 -### Keeping the Teaching Driver Simple +### 保持教学驱动程序的简洁 -Everything in this section is a direction your 驱动程序 might grow in. None of it is required for the teaching 驱动程序 in this chapter. We are pointing at the directions so that you can recognise them when you see them in real 驱动程序 source, and so that when you extend your own 驱动程序 you do not have to invent these patterns from scratch. +本节中的所有内容都是你的驱动程序可能成长的方向。这些都不是本章教学驱动程序所必需的。我们指出这些方向,以便你在真实驱动程序源代码中看到它们时能够识别,并且当你扩展自己的驱动程序时不必从头发明这些模式。 -The companion `myfirst_blk.c` remains a single file at the end of this chapter. Its README documents the extension points, and the challenge exercises add some of them. Beyond that, you are free to keep extending it, and every extension you make will use these patterns in some form. +配套的 `myfirst_blk.c` 在本章结束时仍是一个单文件。它的 README 记录了扩展点,挑战练习添加了其中一些。除此之外,你可以自由地继续扩展它,你做的每个扩展都将以某种形式使用这些模式。 -### A Short Design Patterns Recap +### 设计模式简要回顾 -At this point we have accumulated enough patterns that listing them helps. When you start your next 存储驱动程序, these are the patterns to reach for. +到目前为止我们已经积累了足够多的模式,列出它们会有帮助。当你开始下一个存储驱动程序时,这些是你应该使用的模式。 -**The softc pattern.** One per-instance struct to hold everything the 驱动程序 needs. Pointed at by `d_drv1`. Retrieved inside 回调 via `bp->bio_disk->d_drv1`. +**softc 模式。** 每个实例一个结构体来保存驱动程序需要的一切。由 `d_drv1` 指向。在回调内通过 `bp->bio_disk->d_drv1` 获取。 -**The 附加/分离 pair.** Attach allocates, initialises, and 寄存器. Detach reverses the sequence. Both must be idempotent. +**附加/分离对。** 附加负责分配、初始化和注册。分离逆转这个序列。两者都必须是幂等的。 -**The switch-and-biodone pattern.** Every strategy function switches on `bio_cmd`, services each command, sets `bio_resid`, and calls `biodone` exactly once. +**switch-and-biodone 模式。** 每个策略函数根据 `bio_cmd` 进行分发,服务每个命令,设置 `bio_resid`,并恰好调用 `biodone` 一次。 -**The defensive bounds check.** Validate offset and length against media size, using subtraction to avoid overflow. +**防御性边界检查。** 根据媒体大小验证偏移量和长度,使用减法避免溢出。 -**The coarse lock pattern.** A single 互斥锁 around the hot path is often enough for a teaching 驱动程序. Split it only when performance demands. +**粗粒度锁模式。** 热路径周围的一个互斥锁通常对教学驱动程序足够了。只在性能需要时才拆分它。 -**The reverse-order teardown.** Free resources in the opposite order of allocation. +**逆序拆卸。** 按分配相反的顺序释放资源。 -**The null-after-free pattern.** After freeing a pointer, set it to `NULL`. Catches double-frees. +**释放后置空模式。** 释放指针后将其设置为 `NULL`。捕获双重释放。 -**The single cleanup label.** In 附加 functions that can fail, all failures jump to a single cleanup label that unwinds state so far. +**单一清理标签。** 在可能失败的附加函数中,所有失败都跳转到一个清理标签,展开到目前为止的状态。 -**The versioned ABI.** Pass `DISK_VERSION` to `disk_create`. Declare `MODULE_VERSION`. Use `MODULE_DEPEND` on every 内核模块 you rely on. +**版本化 ABI。** 将 `DISK_VERSION` 传递给 `disk_create`。声明 `MODULE_VERSION`。对你依赖的每个内核模块使用 `MODULE_DEPEND`。 -**The deferred-work pattern.** Work that must 块 (like vnode I/O) belongs in a worker thread, not in `d_strategy`. +**延迟工作模式。** 必须阻塞的工作(如 vnode I/O)属于工作线程,而不是 `d_strategy`。 -**The observability-first habit.** Add `printf`, `sysctl`, or DTrace 探测 as you build. Observability retrofitted late is harder than observability designed in. +**可观测性优先习惯。** 在构建时添加 `printf`、`sysctl` 或 DTrace 探针。后期改造的可观测性比设计时就考虑的可观测性更难。 -These are not exhaustive, but they are the patterns you will use most often. Each of them appears somewhere in our 驱动程序, and each of them appears throughout the real FreeBSD storage code. +这些不是详尽无遗的,但它们是你最常使用的模式。每个模式都出现在我们驱动程序的某个地方,每个模式都出现在真实的 FreeBSD 存储代码中。 ### 总结 Section 9 -A maturing 存储驱动程序 grows in predictable directions: multi-unit support, runtime configuration through ioctls, multiple source files, and stable versioning of every 接口 it exposes. None of this has to appear in the first version. Knowing where the growth will happen lets you make early choices that do not need to be undone later. +一个成熟的存储驱动程序以可预测的方向增长:多单元支持、通过 ioctl 进行运行时配置、多个源文件,以及它暴露的每个接口的稳定版本管理。这些都不必出现在第一个版本中。知道增长将发生在哪里可以让你做出以后不需要撤销的早期选择。 -We have now covered every concept the chapter set out to teach. Before the hands-on labs, one more topic deserves a dedicated section, because it will repay you many times over as a 驱动程序 author: observing a running 存储驱动程序. In the next section, we will look at the tools FreeBSD gives you for watching your 驱动程序 in real time and for measuring its behaviour in a disciplined way. +我们已经涵盖了本章要教授的每个概念。在动手实验之前,还有一个主题值得用专门的章节讨论,因为它作为驱动程序作者会回报你很多次:观察运行中的存储驱动程序。在下一节中,我们将看看 FreeBSD 为你提供的实时监视驱动程序和以有条理的方式测量其行为的工具。 -## Section 10: Observability and Measuring Your Driver +## 第10节:可观测性与测量你的驱动程序 -Writing a 存储驱动程序 is mostly a matter of getting the structure right. Once the structure is right, the 驱动程序 just runs. But for the structure to stay right, you must be able to observe what is happening while the 驱动程序 runs. You will want to know how many BIOs per second are hitting the strategy function, how long each one takes, how the latency distribution looks, how much memory the backing store consumes, whether any BIOs are getting retried, and whether any path is leaking completion. +编写存储驱动程序主要是让结构正确的问题。一旦结构正确,驱动程序就会运行。但要保持结构正确,你必须能够在驱动程序运行时观察正在发生的事情。你会想知道每秒有多少BIO到达策略函数、每个花费多长时间、延迟分布如何、后备存储消耗了多少内存、是否有任何BIO正在被重试,以及是否有任何路径泄漏了完成。 -FreeBSD gives you a remarkable set of tools for this, many of which we have already used casually. In this section we will walk through the most important ones in turn, with the goal of making you comfortable enough to reach for the right tool when the next strange symptom appears. +FreeBSD为此提供了一套出色的工具,其中许多我们已经随意使用过。在本节中,我们将依次介绍最重要的工具,目标是让你在下一个奇怪的症状出现时能够轻松地拿起正确的工具。 ### gstat -`gstat` is the first tool to reach for. It updates a per-provider view of I/O activity in real time, and it shows you exactly what is happening at the GEOM layer. +`gstat` 是首选工具。它实时更新每个提供者的 I/O 活动视图,向你展示 GEOM 层正在发生的具体情况。 ```console # gstat -I 1 @@ -2322,26 +2322,26 @@ dT: 1.002s w: 1.000s 0 0 0 0 0.0 0 0 0.0 0.0| myblk0 ``` -The columns, from left to right, are: +各列从左到右依次是: -- `L(q)`: queue length. The number of BIOs currently outstanding on this provider. -- `ops/s`: total operations per second, regardless of direction. -- `r/s`: reads per second. -- `kBps` (for reads): read throughput in kilobytes per second. -- `ms/r`: average read latency, in milliseconds. -- `w/s`: writes per second. -- `kBps` (for writes): write throughput in kilobytes per second. -- `ms/w`: average write latency, in milliseconds. -- `%总线y`: the percentage of time the provider was not idle. -- `Name`: the provider name. +- `L(q)`:队列长度。当前在此提供者上未完成的BIO数量。 +- `ops/s`:每秒总操作数,无论方向。 +- `r/s`:每秒读取数。 +- `kBps`(读取):以每秒千字节为单位的读取吞吐量。 +- `ms/r`:平均读取延迟,以毫秒为单位。 +- `w/s`:每秒写入数。 +- `kBps`(写入):以每秒千字节为单位的写入吞吐量。 +- `ms/w`:平均写入延迟,以毫秒为单位。 +- `%busy`:提供者非空闲的时间百分比。 +- `Name`:提供者名称。 -For a 驱动程序 you have just built, `gstat` tells you at a glance whether the 内核 is sending traffic to your 设备 and how your 驱动程序 is performing relative to real disks. If the numbers look wildly different from what you expect, you have a starting point for investigation. +对于你刚构建的驱动程序,`gstat` 让你一眼就能看出内核是否正在向你的设备发送流量,以及你的驱动程序相对于真实磁盘的表现如何。如果数字与你期望的大不相同,你就有了调查的起点。 -`gstat -p` shows only providers (the default). `gstat -c` shows only consumers, which is less useful for 驱动程序 debugging. `gstat -f ` filters by name. `gstat -b` batches the output one screen at a time instead of refreshing in place. +`gstat -p` 仅显示提供者(默认)。`gstat -c` 仅显示消费者,这对驱动程序调试不太有用。`gstat -f ` 按名称过滤。`gstat -b` 逐屏批处理输出而不是原地刷新。 ### iostat -`iostat` has a more traditional style but provides the same underlying data. It is useful when you want a text log rather than an interactive display. +`iostat` 具有更传统的风格,但提供相同的底层数据。当你想要文本日志而不是交互式显示时,它很有用。 ```console # iostat -x myblk0 1 @@ -2351,11 +2351,11 @@ myblk0 0 128 0 512 0.0 0.1 0.0 0.1 0 2 myblk0 0 128 0 512 0.0 0.1 0.0 0.1 0 2 ``` -`iostat` can watch multiple 设备 at once and can be redirected to a log file for later analysis. For quick live views, `gstat` is usually better. +`iostat` 可以同时监视多个设备,并且可以重定向到日志文件以供后续分析。对于快速实时查看,`gstat` 通常更好。 ### diskinfo -`diskinfo` is less about live traffic and more about static properties. We have already used it to confirm our media size. +`diskinfo` 较少关注实时流量,更多关注静态属性。我们已经用它确认了我们的媒体大小。 ```console # diskinfo -v /dev/myblk0 @@ -2368,7 +2368,7 @@ myblk0 0 128 0 512 0.0 0.1 0.0 0.1 0 2 myblk0 # Disk ident. ``` -`diskinfo -c` runs a timing test, reading a few hundred megabytes and reporting the sustained rate. This is useful for a first-order performance comparison. +`diskinfo -c` 运行计时测试,读取几百兆字节并报告持续速率。这对于一阶性能比较很有用。 ```console # diskinfo -c /dev/myblk0 @@ -2399,35 +2399,35 @@ Transfer rates: inside: 102400 kbytes in 0.017684 sec = 5791 MB/sec ``` -These numbers are unusually fast because the backing store is RAM. On a real disk they would look very different, and comparing the numbers across 设备 is often the first diagnosis step for performance problems. +这些数字异常快,因为后备存储是 RAM。在真实磁盘上它们会看起来非常不同,跨设备比较数字通常是性能问题的第一步诊断。 ### sysctl -`sysctl` is how the 内核 exposes its internal variables to user space. Many subsystems publish data through `sysctl`. You can browse the storage-related sysctls with: +`sysctl` 是内核将其内部变量暴露给用户空间的方式。许多子系统通过 `sysctl` 发布数据。你可以用以下命令浏览与存储相关的 sysctl: ```console # sysctl -a | grep -i kern.geom # sysctl -a | grep -i vfs ``` -Adding your own sysctl tree to your 驱动程序, as we discussed in Section 9, lets you expose whatever metrics your 驱动程序 needs to track, without the ceremony of defining a new tool. +将你自己的 sysctl 树添加到驱动程序中,正如我们在第9节中讨论的,让你可以暴露驱动程序需要跟踪的任何指标,而无需定义新工具的繁文缛节。 ### vmstat -`vmstat -m` shows memory allocation by `MALLOC_DEFINE` tag. Our 驱动程序 uses `M_MYBLK`, so we can see how much memory our 驱动程序 has allocated. +`vmstat -m` 按 `MALLOC_DEFINE` 标签显示内存分配。我们的驱动程序使用 `M_MYBLK`,所以我们可以看到我们的驱动程序分配了多少内存。 ```console # vmstat -m | grep myblk myblk 1 32768K - 12 32K,32M ``` -The columns are type, number of allocations, current size, protection requests, total requests, and possible sizes. For a 驱动程序 that holds a 32 MiB backing store, the current size of 32 MiB is exactly what we expect. If it grew over time without an equivalent decrease on unload, we would have a leak. +各列是类型、分配数量、当前大小、保护请求、总请求和可能的大小。对于持有 32 MiB 后备存储的驱动程序,当前大小 32 MiB 正是我们期望的。如果它随时间增长而在卸载时没有相应的减少,我们就有了泄漏。 -`vmstat -z` shows zone allocator statistics. Much storage-related state lives in zones (GEOM providers, BIOs, disk structures), and `vmstat -z` is where to look if you suspect GEOM-level leaks. +`vmstat -z` 显示区域分配器统计。许多与存储相关的状态存在于区域中(GEOM 提供者、BIO、磁盘结构),如果你怀疑 GEOM 级别的泄漏,`vmstat -z` 是查看的地方。 ### procstat -`procstat` shows per-thread 内核 stacks. It is indispensable when something is stuck. +`procstat` 显示每线程的内核栈。当某些东西卡住时,它是不可或缺的。 ```console # procstat -kk -t $(pgrep -x g_event) @@ -2435,30 +2435,30 @@ The columns are type, number of allocations, current size, protection requests, 4 100038 geom - mi_switch sleepq_switch ... ``` -If the `g_event` thread is sleeping, the GEOM layer is idle. If it is stuck in a function with your 驱动程序's name on its stack, you have a BIO that is not completing. +如果 `g_event` 线程正在睡眠,GEOM 层是空闲的。如果它卡在一个栈上有你的驱动程序名称的函数中,你就有一个没有完成的 BIO。 ```console # procstat -kk $(pgrep -x kldload) ``` -If `kldload` or `kldunload` is stuck, this shows you exactly where. Most often the culprit is a `disk_destroy` waiting for BIOs to drain. +如果 `kldload` 或 `kldunload` 卡住了,这会精确地显示在哪里。最常见的罪魁祸首是等待 BIO 排空的 `disk_destroy`。 -### DTrace for the Block Layer +### 块层的DTrace -We introduced DTrace briefly in Section 6 and in Lab 7. Here let us go a little deeper, because DTrace is the single most effective tool for understanding live storage behaviour. +我们在第6节和实验7中简要介绍了 DTrace。这里让我们深入一点,因为 DTrace 是理解实时存储行为的最有效工具。 -The Function Boundary Tracing (FBT) provider lets you place 探测 on the entry and return of nearly any 内核 function. For our 驱动程序's strategy function, the 探测 name is `fbt::myblk_strategy:entry` for the entry and `fbt::myblk_strategy:return` for the return. +函数边界跟踪(FBT)提供者允许你在几乎所有内核函数的入口和返回处放置探针。对于我们驱动程序的策略函数,探针名称是 `fbt::myblk_strategy:entry` 用于入口,`fbt::myblk_strategy:return` 用于返回。 -A simple one-liner that counts BIOs by command: +一个按命令计数 BIO 的简单单行命令: ```console # dtrace -n 'fbt::myblk_strategy:entry \ { @c[args[0]->bio_cmd] = count(); }' ``` -When you interrupt the script (with `Ctrl-C`), it prints a count per command value. `BIO_READ` is 1, `BIO_WRITE` is 2, `BIO_DELETE` is 3, `BIO_GETATTR` is 4, and `BIO_FLUSH` is 5. (The exact numbers are in `/usr/src/sys/sys/bio.h`.) +当你中断脚本(用 `Ctrl-C`)时,它按命令值打印计数。`BIO_READ` 是 1,`BIO_WRITE` 是 2,`BIO_DELETE` 是 3,`BIO_GETATTR` 是 4,`BIO_FLUSH` 是 5。(具体数字在 `/usr/src/sys/sys/bio.h` 中。) -A latency histogram: +延迟直方图: ```console # dtrace -n ' @@ -2469,49 +2469,49 @@ fbt::myblk_strategy:return /self->t/ { }' ``` -This gives you a log-scale histogram of how long each strategy-function execution took. For our in-memory 驱动程序, most buckets should be in the hundreds-of-nanoseconds range; anything in the millisecond range for an in-memory 驱动程序 is suspicious. +这给你一个每次策略函数执行时间的对数刻度直方图。对于我们的内存驱动程序,大多数桶应该在数百纳秒范围内;对于内存驱动程序来说,毫秒范围内的任何东西都是可疑的。 -A breakdown of I/O size: +I/O 大小的分布: ```console # dtrace -n 'fbt::myblk_strategy:entry \ { @sz = quantize(args[0]->bio_bcount); }' ``` -This shows you the distribution of BIO sizes. For a UFS-backed 文件系统, you should see peaks at 4 KiB, 8 KiB, 16 KiB, and 32 KiB. For a raw `dd` with `bs=1m`, you should see a peak at 1 MiB (or the `MAXPHYS` cap, whichever is smaller). +这显示 BIO 大小的分布。对于 UFS 文件系统,你应该看到在 4 KiB、8 KiB、16 KiB 和 32 KiB 处有峰值。对于使用 `bs=1m` 的原始 `dd`,你应该看到在 1 MiB(或 `MAXPHYS` 上限,以较小者为准)处有峰值。 -DTrace is extraordinarily capable. The one-liners above barely scratch the surface. Two books to pick up, if you want to go deeper, are the original Sun "DTrace Guide" and Brendan Gregg's "DTrace Book". Both are older than FreeBSD 14.3 but the fundamentals still apply. +DTrace 的能力非凡。上面的单行命令只是冰山一角。如果你想深入了解,可以阅读 Sun 原始的 "DTrace Guide" 和 Brendan Gregg 的 "DTrace Book"。两者都比 FreeBSD 14.3 老,但基本原理仍然适用。 -### kgdb and Crash Dumps +### kgdb和崩溃转储 -When your 驱动程序 panics, FreeBSD can capture a crash dump. Configure the dump 设备 in `/etc/rc.conf` (typically `dumpdev="AUTO"`) and verify with `dumpon`. +当你的驱动程序崩溃时,FreeBSD 可以捕获崩溃转储。在 `/etc/rc.conf` 中配置转储设备(通常是 `dumpdev="AUTO"`)并用 `dumpon` 验证。 -After a panic, reboot. `/var/crash/vmcore.last` (a symlink) points to the most recent dump. `kgdb /boot/内核/内核 /var/crash/vmcore.last` opens the dump for inspection. Useful commands inside `kgdb`: +崩溃后,重新启动。`/var/crash/vmcore.last`(一个符号链接)指向最近的转储。`kgdb /boot/kernel/kernel /var/crash/vmcore.last` 打开转储以供检查。`kgdb` 中有用的命令: -- `bt`: backtrace of the thread that panicked. -- `info threads`: list all threads in the crashed system. -- `thread N` then `bt`: backtrace of thread N. -- `print *var`: inspect a variable. -- `list function`: show source around a function. +- `bt`:崩溃线程的回溯。 +- `info threads`:列出崩溃系统中的所有线程。 +- `thread N` 然后 `bt`:线程 N 的回溯。 +- `print *var`:检查变量。 +- `list function`:显示函数周围的源代码。 -If you have compiled your module with debugging symbols (the default for most 内核 configurations), `kgdb` can show you source-level variables in your own code. This is a transformative capability once you get used to it. +如果你编译模块时包含了调试符号(大多数内核配置的默认值),`kgdb` 可以在你自己的代码中显示源代码级别的变量。一旦你习惯了,这是一种变革性的能力。 ### ktrace -`ktrace` is a user-space-oriented tool, but it can be useful for storage debugging when you want to see exactly what system calls a user program is making. If `newfs_ufs` is behaving oddly, you can trace it: +`ktrace` 是一个面向用户空间的工具,但当你想确切看到用户程序正在发出哪些系统调用时,它对存储调试很有用。如果 `newfs_ufs` 行为异常,你可以跟踪它: ```console # ktrace -f /tmp/newfs.ktr newfs_ufs /dev/myblk0 # kdump /tmp/newfs.ktr | head -n 50 ``` -The resulting trace shows the sequence of system calls, their arguments, and their results. For storage tools, this reveals exactly which ioctls are being issued and which file 描述符 are being opened. +生成的跟踪显示系统调用的序列、参数和结果。对于存储工具,这精确地揭示了正在发出哪些 ioctl 以及正在打开哪些文件描述符。 -### dmesg and the Kernel Log +### dmesg和内核日志 -The humble `dmesg` is often the fastest way to diagnose a problem. Our 驱动程序 prints to it on load and unload. The 内核 prints to it on many other events, including GEOM class creation, access-count violations, and panics that the system recovers from. +简单的 `dmesg` 通常是诊断问题最快的方式。我们的驱动程序在加载和卸载时打印到它。内核在许多其他事件中也打印到它,包括 GEOM 类创建、访问计数违规和系统恢复的崩溃。 -Pro tip: redirect `dmesg -a` to a file at the start of each lab session. If something goes wrong you will have a complete log. +专业提示:在每个实验会话开始时将 `dmesg -a` 重定向到文件。如果出了问题,你将有一个完整的日志。 ```console # dmesg -a > /tmp/session.log @@ -2520,26 +2520,26 @@ Pro tip: redirect `dmesg -a` to a file at the start of each lab session. If some # diff /tmp/session.log /tmp/session-final.log ``` -This gives you a precise log of what the 内核 reported during your session. +这给你一个精确的日志,记录内核在你的会话期间报告了什么。 -### A Simple Measurement Recipe +### 简单的测量方法 -Here is a recipe you can use to produce a one-page performance profile of your 驱动程序. +以下是一个可以用来生成驱动程序一页性能概要的方法。 -1. Load the 驱动程序. -2. Run `diskinfo -c /dev/myblk0` and record the three transfer-rate numbers. -3. Format the 设备 and 挂载 it. -4. In one terminal, start `gstat -I 1 -f myblk0 -b` redirected to a file. -5. In another terminal, run `dd if=/dev/zero of=/mnt/myblk/stress bs=1m count=128`. -6. Stop `gstat` after `dd` completes and save the log. -7. Parse the log with `awk` to extract the peak ops/s, the peak throughput, and the average latency. -8. Un挂载 and unload. +1. 加载驱动程序。 +2. 运行 `diskinfo -c /dev/myblk0` 并记录三个传输速率数字。 +3. 格式化设备并挂载它。 +4. 在一个终端中,启动 `gstat -I 1 -f myblk0 -b` 并重定向到文件。 +5. 在另一个终端中,运行 `dd if=/dev/zero of=/mnt/myblk/stress bs=1m count=128`。 +6. `dd` 完成后停止 `gstat` 并保存日志。 +7. 用 `awk` 解析日志以提取峰值 ops/s、峰值吞吐量和平均延迟。 +8. 卸载文件系统并卸载模块。 -This recipe scales. For a real 驱动程序 you would automate it, run it on a matrix of 块 sizes, and plot the results. For a teaching 驱动程序, running it once or twice gives you a feeling for the numbers and a baseline to compare against after future changes. +这个方法可以扩展。对于真实驱动程序,你会自动化它,在块大小的矩阵上运行,并绘制结果。对于教学驱动程序,运行一两次就能让你对数字有感觉,并在未来的更改后有一个比较基准。 -### Comparing Against md(4) +### 与md(4)的比较 -One of the most useful exercises is to load `md(4)` in the same configuration as your 驱动程序 and compare. +最有用的练习之一是以与你的驱动程序相同的配置加载 `md(4)` 并进行比较。 ```console # mdconfig -a -t malloc -s 32m @@ -2547,33 +2547,33 @@ md0 # diskinfo -c /dev/md0 ``` -The numbers will likely be within a small factor of your 驱动程序's. If they are very different, something interesting is going on. The usual differences are: +数字可能在你驱动程序的一个小倍数范围内。如果它们非常不同,就有一些有趣的事情发生。通常的差异是: -- `md(4)` uses a worker thread that receives BIOs from the strategy function and processes them in a separate context. This adds a small 挂载 of latency per BIO but allows higher concurrency. -- `md(4)` uses page-at-a-time backing, which is slightly slower per byte for sequential I/O but scales to much larger sizes. -- `md(4)` supports more BIO commands and attributes than our 驱动程序. +- `md(4)` 使用工作线程接收来自策略函数的 BIO 并在单独的上下文中处理它们。这为每个 BIO 增加了一点延迟,但允许更高的并发性。 +- `md(4)` 使用逐页后备,对于顺序 I/O 每字节稍慢,但可以扩展到更大的大小。 +- `md(4)` 支持比我们的驱动程序更多的 BIO 命令和属性。 -Comparing against `md(4)` is a form of debugging: if your 驱动程序 is much slower or much faster than `md(4)` on the same workload, either you have done something unusual, or you have uncovered a difference worth understanding. +与 `md(4)` 比较是一种调试形式:如果你的驱动程序在相同工作负载上比 `md(4)` 慢得多或快得多,要么你做了一些不寻常的事情,要么你发现了一个值得理解的差异。 ### 总结 Section 10 -Observability is not an afterthought. For a 存储驱动程序, it is how you keep your bearings. `gstat`, `iostat`, `diskinfo`, `sysctl`, `vmstat`, `procstat`, and DTrace are the tools you will reach for most often. `kgdb` and crash dumps are your backstop when things go catastrophically wrong. +可观测性不是事后的想法。对于存储驱动程序,它是你保持方向的方式。`gstat`、`iostat`、`diskinfo`、`sysctl`、`vmstat`、`procstat` 和 DTrace 是你最常使用的工具。`kgdb` 和崩溃转储是当事情灾难性地出错时的后盾。 -Learn these tools now, while the 驱动程序 is simple, because they will be the same tools you use when the 驱动程序 is complex. A developer who can observe a running 驱动程序 is much more effective than one who can only read source. +现在就学习这些工具,当驱动程序还简单的时候,因为当驱动程序变得复杂时,它们将是你使用的相同工具。一个能够观察运行中驱动程序的开发者比只能阅读源代码的开发者要有效得多。 -We have now covered every concept the chapter set out to teach, plus observability and measurement. Before we move on to the hands-on labs, let us spend some time reading real FreeBSD source. The case studies that follow anchor everything we have learned in code from the tree. +我们现在已经涵盖了本章要教授的每个概念,加上可观测性和测量。在我们进入动手实验之前,让我们花一些时间阅读真实的 FreeBSD 源代码。接下来的案例研究将我们从源代码树中学到的一切锚定在实际代码中。 -## Case Studies in Real FreeBSD Storage Code +## 真实FreeBSD存储代码案例研究 -Reading production 驱动程序 source is the fastest way to internalise patterns. In this section we will walk through excerpts from three real 驱动程序 in `/usr/src/sys/`, with commentary that points out what each excerpt is doing and why. The excerpts are short on purpose; we will not read every line of each 驱动程序. We will pick the lines that matter. +阅读生产驱动程序源代码是内化模式最快的方式。在本节中,我们将遍历`/usr/src/sys/`中三个真实驱动程序的摘录,并附有注释指出每个摘录在做什么以及为什么。摘录故意简短;我们不会阅读每个驱动程序的每一行。我们会挑选重要的行。 -Open the files alongside the text and follow along. The point is for you to see the same patterns in our 驱动程序 reappearing in real 驱动程序, under different names and with different constraints. +打开文件并跟着文本一起阅读。关键是要让你看到我们驱动程序中的相同模式在不同的名称和不同的约束下重新出现在真实驱动程序中。 -### Case Study 1: g_zero.c +### 案例研究1:g_zero.c -`g_zero.c` is the simplest GEOM class in the tree. It is a read-always-zero, write-discard provider, with no real backing store and no real work to do. Its purpose is to give you a standard "null disk" you can test against. It is also an excellent teaching reference because it exercises the full `g_class` API in fewer than 150 lines. +`g_zero.c` 是源代码树中最简单的 GEOM 类。它是一个读取始终返回零、写入被丢弃的提供者,没有真正的后备存储,也没有真正的工作要做。它的目的是为你提供一个标准的"空磁盘"用于测试。它也是一个优秀的教学参考,因为它在不到 150 行中使用了完整的 `g_class` API。 -Let us look at its strategy function, called `g_zero_start`. +让我们看看它的策略函数,叫做 `g_zero_start`。 ```c static void @@ -2595,11 +2595,11 @@ g_zero_start(struct bio *bp) } ``` -Three behaviours, with `BIO_GETATTR` intentionally folded into the default case. Reads get zeroed. Writes are silently accepted. Anything else, including attribute queries, gets `EOPNOTSUPP`. The real `/usr/src/sys/geom/zero/g_zero.c` also handles `BIO_DELETE` in the successful-write path; our simplified excerpt above drops that case so you can see the shape clearly. Notice the call to `g_io_deliver` rather than `biodone`. That is because `g_zero` is a class-level GEOM module, not a `g_disk` module. `g_io_deliver` is the class-level completion call; `biodone` is the `g_disk` wrapper. +三种行为,`BIO_GETATTR` 被故意折叠到 default 情况中。读取返回零。写入被静默接受。其他任何操作(包括属性查询)都得到 `EOPNOTSUPP`。真实的 `/usr/src/sys/geom/zero/g_zero.c` 还在成功写入路径中处理 `BIO_DELETE`;我们上面简化的摘录省略了该情况以便你能清楚地看到结构。注意调用的是 `g_io_deliver` 而不是 `biodone`。这是因为 `g_zero` 是一个类级别的 GEOM 模块,而不是 `g_disk` 模块。`g_io_deliver` 是类级别的完成调用;`biodone` 是 `g_disk` 的包装。 -If you re-read our 驱动程序's strategy function side by side with this, you will see the same structure: a switch on `bio_cmd`, a case for each supported operation, a default error path. Our 驱动程序 has more cases and it has a real backing store, but the shape is identical. +如果你并排重新阅读我们驱动程序的策略函数和这个,你会看到相同的结构:对 `bio_cmd` 的 switch、每个支持操作的一个 case、一个默认错误路径。我们的驱动程序有更多的 case 并且有真正的后备存储,但结构是相同的。 -The `init` function that `g_zero` 寄存器 with the class is also small: +`g_zero` 向类注册的 `init` 函数也很小: ```c static void @@ -2615,15 +2615,15 @@ g_zero_init(struct g_class *mp) } ``` -When the `g_zero` module is loaded, this runs. It creates a new geom under the class, points the `start` method at the strategy function, uses the standard access handler, and creates a provider. That is everything it takes to expose `/dev/gzero`. +当 `g_zero` 模块被加载时,这会运行。它在类下创建一个新的 geom,将 `start` 方法指向策略函数,使用标准访问处理器,并创建一个提供者。这就是暴露 `/dev/gzero` 所需的全部。 -In our 驱动程序, `g_disk` does the equivalent of all this when `disk_create` is called. You can see here, once more, what `g_disk` is abstracting away. For most disk 驱动程序 that is a good trade; for `g_zero`, which does not want `g_disk`'s disk-specific features, using the class API directly is the better fit. +在我们的驱动程序中,当调用 `disk_create` 时,`g_disk` 做了所有这些的等价工作。你可以在这里再次看到 `g_disk` 抽象掉了什么。对于大多数磁盘驱动程序来说,这是一个好的交易;对于 `g_zero`,它不想要 `g_disk` 的磁盘特定功能,直接使用类 API 更合适。 -### Case Study 2: md.c, the Malloc Strategy Function +### 案例研究2:md.c的malloc策略函数 -`md(4)` is a memory-disk 驱动程序 with several backing types. The malloc backing type is the closest to our 驱动程序, and its strategy function is worth reading in detail. +`md(4)` 是一个具有多种后备类型的内存磁盘驱动程序。malloc 后备类型与我们的驱动程序最接近,其策略函数值得详细阅读。 -Here is a simplified version of what happens when `md(4)`'s worker thread picks up a BIO for a `MD_MALLOC`-type disk. (In real `md(4)`, this is the function `mdstart_malloc`.) +以下是 `md(4)` 的工作线程为 `MD_MALLOC` 类型磁盘拾取 BIO 时发生情况的简化版本。(在真实的 `md(4)` 中,这是函数 `mdstart_malloc`。) ```c static int @@ -2660,17 +2660,17 @@ mdstart_malloc(struct md_s *sc, struct bio *bp) } ``` -The key difference from our 驱动程序 is the page-at-a-time backing. `md(4)` does not allocate one big 缓冲区. It allocates 4 KiB pages on demand and indexes them through a data structure inside the softc. The benefit is that memory disks can be much larger than a single contiguous `malloc` would allow, and sparse regions (never written) consume no memory. +与我们驱动程序的关键区别是逐页后备。`md(4)` 不分配一个大缓冲区。它按需分配 4 KiB 页面并通过 softc 内部的数据结构索引它们。好处是内存磁盘可以比单个连续 `malloc` 允许的大得多,稀疏区域(从未写入的)不消耗内存。 -The cost is that every BIO may span multiple pages, so the strategy function has to loop. Each iteration copies `len` bytes into the current page, decrements `resid`, advances `offset`, and either exits when `resid` hits zero or moves on to the next page. +代价是每个 BIO 可能跨越多个页面,所以策略函数必须循环。每次迭代将 `len` 字节复制到当前页面,递减 `resid`,推进 `offset`,当 `resid` 达到零时退出或移动到下一个页面。 -Our 驱动程序 avoids this complexity at the cost of supporting only contiguous backing, which is fine up to a few tens of megabytes but not beyond. +我们的驱动程序避免了这种复杂性,代价是只支持连续后备,这在几十兆字节以内没问题,但更远就不行了。 -If you wanted to extend our 驱动程序 to match `md(4)`'s scale, the page-at-a-time pattern is the direction you would go. It is straightforward once you have `md(4)` in front of you as a reference. +如果你想扩展我们的驱动程序以匹配 `md(4)` 的规模,逐页模式是你应该去的方向。一旦你有 `md(4)` 作为参考,这是很直接的。 -### Case Study 3: md.c, the Module Load Path +### 案例研究3:md.c的模块加载路径 -Another piece of `md(4)` worth studying is how it bootstraps its class and sets up the control 设备. +`md(4)` 另一个值得研究的部分是它如何引导其类并设置控制设备。 ```c static void @@ -2692,22 +2692,22 @@ g_md_init(struct g_class *mp __unused) } ``` -The `g_md_init` function runs once per 内核 boot, when the `md(4)` class is first instantiated. It handles any memory disks that the loader preloaded into memory (so that the 内核 can boot from a memory-disk root) and it creates the control 设备 `/dev/mdctl` through which `mdconfig` will later talk to the 驱动程序. +`g_md_init` 函数在每次内核启动时运行一次,当 `md(4)` 类首次被实例化时。它处理加载器预加载到内存中的任何内存磁盘(以便内核可以从内存磁盘根启动),并创建控制设备 `/dev/mdctl`,`mdconfig` 稍后将通过它与驱动程序通信。 -Compare this to our loader, which is a simple `moduledata_t` that calls `disk_create` directly. `md(4)` does not create any memory disks by default. It only creates them in response to preload events or in response to `MDIOCATTACH` ioctls on the control 设备. +与我们的加载器比较,它是一个直接调用 `disk_create` 的简单 `moduledata_t`。`md(4)` 默认不创建任何内存磁盘。它只在响应预加载事件或控制设备上的 `MDIOCATTACH` ioctl 时创建它们。 -The pattern here is generalisable. If you want a 存储驱动程序 that creates units on demand rather than at load time, you: +这里的模式是可泛化的。如果你想要一个按需创建单元而不是在加载时创建的存储驱动程序,你会: -1. Register the class (or, for `g_disk`-based 驱动程序, set up the infrastructure). -2. Create a control 设备 with a cdevsw that supports ioctls. -3. Implement create, destroy, and query ioctls. -4. Write a user-space tool that talks to the control 设备. +1. 注册类(或者对于基于 `g_disk` 的驱动程序,设置基础设施)。 +2. 创建一个支持 ioctl 的带有 cdevsw 的控制设备。 +3. 实现创建、销毁和查询 ioctl。 +4. 编写一个与控制设备通信的用户空间工具。 -`md(4)` is the canonical example. Other 驱动程序, like `geli(4)` and `gmirror(4)`, use a slightly different pattern because they are GEOM transformation classes rather than disk 驱动程序, but the overall shape is similar. +`md(4)` 是典型的例子。其他驱动程序,如 `geli(4)` 和 `gmirror(4)`,使用略有不同的模式,因为它们是 GEOM 转换类而不是磁盘驱动程序,但整体结构相似。 -### Case Study 4: The new总线 Side of a Real Storage Driver +### 案例研究4:真实存储驱动程序的 newbus 侧 -For contrast, let us look briefly at how a real hardware-backed 存储驱动程序 附加. The `ada(4)` 驱动程序, for example, is a CAM-based ATA 驱动程序. Its 附加 path is not directly visible as a single function, because CAM mediates between the 驱动程序 and the hardware, but the end of the chain looks like this (abbreviated from `/usr/src/sys/cam/ata/ata_da.c`): +作为对比,让我们简要看看真实硬件支持的存储驱动程序如何附加。例如 `ada(4)` 驱动程序是一个基于 CAM 的 ATA 驱动程序。它的附加路径不能直接作为单个函数看到,因为 CAM 在驱动程序和硬件之间进行中介,但链的末端看起来像这样(摘自 `/usr/src/sys/cam/ata/ata_da.c`): ```c static void @@ -2737,35 +2737,35 @@ adaregister(struct cam_periph *periph, void *arg) } ``` -The structure is identical to ours: fill in a `struct disk` and call `disk_create`. The differences are: +结构与我们完全相同:填充`struct disk`并调用`disk_create`。区别在于: -- `d_strategy` is `adastrategy`, which translates BIOs into ATA commands and issues them to the controller via CAM. -- `d_dump` is implemented, because `ada(4)` supports 内核 crash dumps. Our 驱动程序 does not implement this. -- The fields like `d_扇区ize` and `d_mediasize` come from hardware probing, not from macros. +- `d_strategy`是`adastrategy`,它将BIO转换为ATA命令并通过CAM发给控制器。 +- `d_dump`已实现,因为`ada(4)`支持内核崩溃转储。我们的驱动程序没有实现它。 +- `d_sectorsize`和`d_mediasize`等字段来自硬件探测,而不是宏定义。 -From `g_disk`'s perspective, however, `ada0` and our `myblk0` are the same kind of thing. Both are disks. Both receive BIOs. Both are completed with `biodone`. The difference is in where the bytes actually go. +但从`g_disk`的角度看,`ada0`和我们的`myblk0`是同一种东西。两者都是磁盘。两者都接收BIO。两者都通过`biodone`完成。区别只在于字节实际去了哪里。 -This is the uniformity that `g_disk` provides. Your 驱动程序 can choose any backing technology, and as long as it fills in `struct disk` correctly, it looks like any other disk to the rest of the 内核. +这就是`g_disk`提供的统一性。你的驱动程序可以选择任何后备技术,只要正确填充`struct disk`,它对内核的其余部分看起来就像任何其他磁盘一样。 -### Takeaways from the Case Studies +### 案例研究要点 -Three patterns become clearer after reading these excerpts. +阅读这些摘录后,三个模式变得更加清晰。 -First, the strategy function is always a switch on `bio_cmd`. The cases vary, but the switch is always there. Memorise this pattern: incoming BIO -> switch -> case per command -> completion. It is the heart of every 存储驱动程序. +第一,策略函数始终是对`bio_cmd`的switch。各个case不同,但switch始终存在。记住这个模式:传入BIO -> switch -> 每个命令一个case -> 完成。它是每个存储驱动程序的核心。 -Second, `g_disk` 驱动程序 are structurally identical at the registration level. Whether the 驱动程序 is a RAM disk or a real SATA drive, the registration code looks the same. The differences are in what happens when the BIO arrives. +第二,`g_disk`驱动程序在注册层面结构完全相同。无论驱动程序是RAM磁盘还是真正的SATA驱动器,注册代码看起来都一样。区别在于BIO到达时发生了什么。 -Third, more sophisticated 驱动程序 enqueue work to a dedicated thread. Our 驱动程序 does not, because it can do its work synchronously in any thread. Drivers that do slow or 块ing work must enqueue, because strategy functions run in the caller's thread context. +第三,更复杂的驱动程序将工作排队到专用线程。我们的驱动程序不会,因为它可以在任何线程中同步完成工作。执行慢速或阻塞工作的驱动程序必须排队,因为策略函数在调用者的线程上下文中运行。 -With these patterns in mind, you can now read almost any 存储驱动程序 in the FreeBSD tree and follow its overall structure, even if specific details about hardware or sub-框架 require further study. +掌握了这些模式,你现在可以阅读FreeBSD源码树中几乎任何存储驱动程序并理解其整体结构,即使有关硬件或子系统的具体细节需要进一步研究。 -We have now covered every concept the chapter set out to teach, plus observability, measurement, and a few real case studies. In the next part of the chapter, we will put this knowledge to work through hands-on labs. The labs build on the 驱动程序 you have been writing and on the skills you have been using, and they take you from the minimum working 驱动程序 through persistence, 挂载, and cleanup scenarios. Let us begin. +我们现在已经涵盖了本章要教授的每个概念,加上可观测性、测量和一些真实案例研究。在下一部分中,我们将通过动手实验将这些知识付诸实践。实验建立在你一直在编写的驱动程序和你一直在使用的技能之上,带你从最小可工作驱动程序经历持久性、挂载和清理场景。让我们开始吧。 ## 动手实验 -Each lab is a self-contained checkpoint. They are designed to be done in order, but you can revisit any lab later if you want to practise a specific skill. Every lab has a companion folder under `examples/part-06/ch27-storage-vfs/`, which contains the reference implementation and the artifacts you would produce if you typed the code by hand. +每个实验都是一个自包含的检查点。它们按顺序设计,但你可以在以后重新访问任何实验来练习特定技能。每个实验在`examples/part-06/ch27-storage-vfs/`下都有配套文件夹,其中包含参考实现和你手动输入代码时会产生的工作产物。 -Before you start, make sure you have the chapter's 驱动程序 building cleanly against your local 内核. From a fresh checkout of the examples tree: +开始之前,确保本章的驱动程序能针对你的本地内核干净地构建。从示例树的全新检出开始: ```console # cd examples/part-06/ch27-storage-vfs @@ -2774,15 +2774,15 @@ Before you start, make sure you have the chapter's 驱动程序 building cleanly myblk.ko ``` -If that works, you are ready. If not, revisit the Makefile and the advice in 第26章, section "Your Build Environment". +如果这成功了,你就准备好了。如果没有,重新检查Makefile和第26章"你的构建环境"一节中的建议。 -### Lab 1: Explore GEOM on a Running System +### 实验1:在运行中的系统上探索GEOM -**Goal.** Build comfort with the GEOM inspection tools before you touch any code. +**目标。**在接触任何代码之前建立对GEOM检查工具的熟悉度。 -**What you do.** +**你做什么。** -On your FreeBSD 14.3 system, run the following commands and take notes in your lab logbook. +在你的FreeBSD 14.3系统上,运行以下命令并在实验日志中做笔记。 ```console # geom disk list @@ -2792,21 +2792,21 @@ On your FreeBSD 14.3 system, run the following commands and take notes in your l # diskinfo -v /dev/ada0 # or whatever your primary disk is called ``` -**What you look for.** +**你观察什么。** -Identify every `DISK` class geom. For each, note its provider name, its media size, its 扇区 size, and its current mode. Notice which geoms have 分区ing layers on top and which do not. If your system has `geli` or `zfs`, notice the chain of classes. +识别每个`DISK`类的geom。对每个,记录其提供者名称、媒体大小、扇区大小和当前模式。注意哪些geom上面有分区层,哪些没有。如果你的系统有`geli`或`zfs`,注意类的链条。 -**Stretch question.** Which of your geoms have non-zero access counts right now? Which ones are free? What would happen if you tried to run `newfs_ufs` on each? +**延伸问题。**你哪些geom目前有非零访问计数?哪些是空闲的?如果你尝试在每个上面运行`newfs_ufs`会发生什么? -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab01-explore-geom/README.md` contains a suggested walkthrough and a sample output transcript from a typical system. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab01-explore-geom/README.md`包含建议的演练和典型系统的示例输出记录。 -### Lab 2: Build the Skeleton Driver +### 实验2:构建骨架驱动程序 -**Goal.** Get the Section 3 skeleton 驱动程序 compiling and loading on your system. +**目标。**让第3节的骨架驱动程序在你的系统上编译和加载。 -**What you do.** +**你做什么。** -Copy `examples/part-06/ch27-storage-vfs/lab02-skeleton/myfirst_blk.c` and its `Makefile` into a working directory. Build it. +将`examples/part-06/ch27-storage-vfs/lab02-skeleton/myfirst_blk.c`及其`Makefile`复制到工作目录。构建它。 ```console # cp -r examples/part-06/ch27-storage-vfs/lab02-skeleton /tmp/myblk @@ -2830,21 +2830,21 @@ Unload it. # ls /dev/myblk0 ``` -**What you look for.** +**你观察什么。** -Confirm that the 内核 printed your `myblk: loaded` message. Confirm that `/dev/myblk0` appeared. Confirm that `geom disk list` reported the expected media size. Confirm that the node disappeared after unload. +确认内核打印了你的`myblk: loaded`消息。确认`/dev/myblk0`出现了。确认`geom disk list`报告了预期的媒体大小。确认卸载后节点消失了。 -**Stretch question.** What happens if you try `newfs_ufs -N /dev/myblk0` with the skeleton 驱动程序? Can you read the output? Why does the dry run succeed even though real writes would fail? +**延伸问题。**如果你在骨架驱动程序上尝试`newfs_ufs -N /dev/myblk0`会发生什么?你能读懂输出吗?为什么干运行会成功,即使真正的写入会失败? -### Lab 3: Implement the BIO Handler +### 实验3:实现BIO处理器 -**Goal.** Add the working strategy function from Section 5 to the skeleton 驱动程序. +**目标。**将第5节的可工作策略函数添加到骨架驱动程序中。 -**What you do.** +**你做什么。** -Starting from the skeleton, implement `myblk_strategy` with support for `BIO_READ`, `BIO_WRITE`, `BIO_DELETE`, and `BIO_FLUSH`. Allocate the backing 缓冲区 in `myblk_附加_unit` and free it in `myblk_分离_unit`. +从骨架开始,实现`myblk_strategy`,支持`BIO_READ`、`BIO_WRITE`、`BIO_DELETE`和`BIO_FLUSH`。在`myblk_attach_unit`中分配后备缓冲区,在`myblk_detach_unit`中释放它。 -Build, load, and test. +构建、加载和测试。 ```console # dd if=/dev/zero of=/dev/myblk0 bs=4096 count=16 @@ -2855,21 +2855,21 @@ Build, load, and test. # cmp /tmp/a /tmp/b ``` -**What you look for.** +**你观察什么。** -The last `cmp` must succeed with no output. If it prints `differ: byte N`, your strategy function is racing or returning stale data. +最后的`cmp`必须成功且没有输出。如果它打印`differ: byte N`,你的策略函数存在竞争或返回陈旧数据。 -**Stretch question.** Put a `printf` in the strategy function that reports `bio_cmd`, `bio_offset`, and `bio_bcount`. Run `dd if=/dev/myblk0 of=/dev/null bs=1m count=1` and look at `dmesg`. What size did `dd` actually issue? Do you see fragmentation? +**延伸问题。**在策略函数中放一个`printf`,报告`bio_cmd`、`bio_offset`和`bio_bcount`。运行`dd if=/dev/myblk0 of=/dev/null bs=1m count=1`并查看`dmesg`。`dd`实际发出了什么大小?你看到分片了吗? -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab03-bio-handler/myfirst_blk.c`. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab03-bio-handler/myfirst_blk.c`。 -### Lab 4: Increase Size and Mount UFS +### 实验4:增加大小并挂载UFS -**Goal.** Increase the backing store to 32 MiB and 挂载 UFS on the 设备. +**目标。**将后备存储增加到32 MiB并在设备上挂载UFS。 -**What you do.** +**你做什么。** -Change `MYBLK_MEDIASIZE` to `(32 * 1024 * 1024)` and rebuild. Load the module. Format and 挂载. +将`MYBLK_MEDIASIZE`改为`(32 * 1024 * 1024)`并重新构建。加载模块。格式化并挂载。 ```console # newfs_ufs /dev/myblk0 @@ -2884,21 +2884,21 @@ Change `MYBLK_MEDIASIZE` to `(32 * 1024 * 1024)` and rebuild. Load the module. F # kldunload myblk ``` -**What you look for.** +**你观察什么。** -Verify that the file survives an 卸载-and-re挂载. Verify that the access counts in `geom disk list` are zero after 卸载. Verify that `kldunload` succeeds cleanly. +验证文件在卸载和重新挂载后仍然存在。验证`geom disk list`中的访问计数在卸载后为零。验证`kldunload`干净地成功。 -**Stretch question.** Watch `gstat -I 1` while running `dd if=/dev/zero of=/mnt/myblk/big bs=1m count=16`. Can you see the writes arrive in bursts? What size are the individual BIOs? Hint: UFS's default 块 size is typically 32 KiB on a 文件系统 this small. +**延伸问题。**在运行`dd if=/dev/zero of=/mnt/myblk/big bs=1m count=16`时观察`gstat -I 1`。你能看到写入以突发方式到达吗?单个BIO的大小是多少?提示:UFS在这个大小的文件系统上默认块大小通常是32 KiB。 -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab04-挂载-ufs/myfirst_blk.c`. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab04-mount-ufs/myfirst_blk.c`。 -### Lab 5: Observing Real Cross-Reload Persistence with md(4) +### 实验5:用md(4)观察真正的跨重载持久性 -**Goal.** Confirm experimentally that cross-reload persistence requires external backing, as Section 7 argued, by using `md(4)`'s vnode mode as a control. +**目标。**通过使用`md(4)`的vnode模式作为对照,实验性地确认跨重载持久性需要外部后备,正如第7节所论证的。 -**What you do.** +**你做什么。** -First, demonstrate that our RAM-backed `myblk` loses its 文件系统 on reload. Load, format, 挂载, write, 卸载, unload, reload, 挂载 again, and observe the empty 文件系统. +首先,演示我们的RAM后备`myblk`在重载时会丢失其文件系统。加载、格式化、挂载、写入、卸载、卸载模块、重新加载、再次挂载,观察空的文件系统。 ```console # kldload ./myblk.ko @@ -2912,9 +2912,9 @@ First, demonstrate that our RAM-backed `myblk` loses its 文件系统 on reload. # ls /mnt/myblk ``` -The `ls` should show an empty or fresh UFS directory; the `token.txt` is gone because the backing 缓冲区 was reclaimed by the 内核 when the module unloaded. +`ls`应该显示一个空的或全新的UFS目录;`token.txt`消失了,因为模块卸载时后备缓冲区被内核回收了。 -Now do the same sequence with `md(4)`'s vnode backend, which uses a real file on disk: +现在用`md(4)`的vnode后端做同样的序列,它使用磁盘上的真实文件: ```console # truncate -s 64m /var/tmp/mdimage.img @@ -2930,51 +2930,51 @@ Now do the same sequence with `md(4)`'s vnode backend, which uses a real file on persistent ``` -**What you look for.** +**你观察什么。** -The first sequence loses the file; the second preserves it. The difference is that `md9` is backed by a real file on disk, whose state survives regardless of what happens inside the 内核. Contrast this with `myblk0`, which is backed by 内核 heap that disappears on `kldunload`. +第一个序列丢失了文件;第二个序列保留了它。区别在于`md9`由磁盘上的真实文件支持,其状态独立于内核内部发生的事情而存在。这与`myblk0`形成对比,后者由`kldunload`时消失的内核堆支持。 -**Stretch question.** Read the `MD_VNODE` branch of `mdstart_vnode` in `/usr/src/sys/dev/md/md.c`. Identify where the vnode reference is stored (hint: it lives on the per-unit `struct md_s`, not a module-scope global). Explain in your own words why that design is what lets the backing survive module lifecycles. +**延伸问题。**阅读`/usr/src/sys/dev/md/md.c`中`mdstart_vnode`的`MD_VNODE`分支。识别vnode引用存储在哪里(提示:它存在于每单元的`struct md_s`上,而不是模块范围的全局变量)。用你自己的话解释为什么那个设计让后备存储能够跨越模块生命周期。 -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab05-persistence/README.md` walks through both sequences and their diagnostic output. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab05-persistence/README.md`走过了两个序列及其诊断输出。 -### Lab 6: Safe Un挂载 Under Load +### 实验6:负载下的安全卸载 -**Goal.** Verify that the teardown path handles an active 文件系统 correctly. +**目标。**验证拆卸路径正确处理活跃的文件系统。 -**What you do.** +**你做什么。** -Load the module, format it, 挂载 it. In one terminal, start a stress loop. +加载模块、格式化、挂载。在一个终端中,启动压力循环。 ```console # while true; do dd if=/dev/urandom of=/mnt/myblk/stress bs=4k \ count=512 2>/dev/null; sync; done ``` -In another terminal, attempt to unload. +在另一个终端中,尝试卸载。 ```console # kldunload myblk kldunload: can't unload file: Device busy ``` -Stop the stress loop. Un挂载. Unload. +停止压力循环。卸载文件系统。卸载模块。 -**What you look for.** +**你观察什么。** -The initial unload must fail gracefully. After 卸载, the final unload must succeed. `dmesg` must not show any 内核 warnings. +初始卸载必须优雅地失败。卸载文件系统后,最终卸载必须成功。`dmesg`不能显示任何内核警告。 -**Stretch question.** Instead of killing the stress loop, try `u挂载 /mnt/myblk` directly. Does UFS let you 卸载 while writes are in flight? What is the error, and what does it mean? +**延伸问题。**与其杀死压力循环,直接尝试`umount /mnt/myblk`。UFS在你写入进行中时允许卸载吗?错误是什么,意味着什么? -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab06-safe-卸载/` includes a test script that performs the sequence above and reports failures. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab06-safe-unload/`包含执行上述序列并报告失败的测试脚本。 -### Lab 7: Observing BIO Traffic with DTrace +### 实验7:用DTrace观察BIO流量 -**Goal.** Use DTrace to see the BIO path as it happens. +**目标。**使用DTrace实时查看BIO路径。 -**What you do.** +**你做什么。** -With the 驱动程序 loaded and a 文件系统 挂载ed, run the following DTrace one-liner in one terminal: +在驱动程序加载且文件系统挂载的情况下,在一个终端中运行以下DTrace单行命令: ```console # dtrace -n 'fbt::myblk_strategy:entry { \ @@ -2985,85 +2985,85 @@ With the 驱动程序 loaded and a 文件系统 挂载ed, run the following DTra }' ``` -In another terminal, create and read files on the 挂载ed 文件系统. +在另一个终端中,在挂载的文件系统上创建和读取文件。 -**What you look for.** +**你观察什么。** -Note which BIO commands you see and in what quantities. Note the typical offsets and lengths. Compare the patterns from `dd` traffic versus `cp` traffic versus `tar` traffic. Note how `cp` or `mv` might produce very different BIO patterns depending on what the 缓冲区 cache decides to flush. +注意你看到哪些BIO命令以及数量。注意典型的偏移量和长度。比较来自`dd`流量、`cp`流量和`tar`流量的模式。注意`cp`或`mv`如何根据缓冲区缓存决定刷新什么而产生非常不同的BIO模式。 -**Stretch question.** Issue `sync` while the DTrace is running. What BIO commands does `sync` cause? What about `newfs_ufs`? +**延伸问题。**在DTrace运行时发出`sync`。`sync`导致哪些BIO命令?`newfs_ufs`呢? -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab07-dtrace/README.md` with sample DTrace output and notes. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab07-dtrace/README.md`包含示例DTrace输出和笔记。 -### Lab 8: Adding a getattr Attribute +### 实验8:添加getattr属性 -**Goal.** Implement a `d_getattr` 回调 that responds to `GEOM::ident`. +**目标。**实现一个响应`GEOM::ident`的`d_getattr`回调。 -**What you do.** +**你做什么。** -Add the `myblk_getattr` function from Section 5 to the 驱动程序, and 注册 it on the disk before `disk_create`. Rebuild, reload, and check `diskinfo -v /dev/myblk0`. +将第5节中的`myblk_getattr`函数添加到驱动程序中,并在`disk_create`之前在磁盘上注册它。重新构建、重新加载并检查`diskinfo -v /dev/myblk0`。 -**What you look for.** +**你观察什么。** -The `ident` field should now show `MYBLK0` instead of `(null)`. +`ident`字段现在应该显示`MYBLK0`而不是`(null)`。 -**Stretch question.** What other attributes might a 文件系统 query? Look at `/usr/src/sys/geom/geom.h` for named attributes like `GEOM::rotation_rate`. Try implementing that too. +**延伸问题。**文件系统还可能查询哪些属性?查看`/usr/src/sys/geom/geom.h`中的命名属性如`GEOM::rotation_rate`。也尝试实现它。 -**Reference implementation.** `examples/part-06/ch27-storage-vfs/lab08-getattr/myfirst_blk.c`. +**参考实现。**`examples/part-06/ch27-storage-vfs/lab08-getattr/myfirst_blk.c`。 -### Lab 9: Exploring md(4) for Comparison +### 实验9:探索md(4)进行比较 -**Goal.** Read a real FreeBSD 存储驱动程序 and identify the patterns we have used. +**目标。**阅读一个真实的FreeBSD存储驱动程序并识别我们使用过的模式。 -**What you do.** +**你做什么。** -Open `/usr/src/sys/dev/md/md.c`. It is a long file. Do not try to read every line. Instead, find and understand these specific things: +打开`/usr/src/sys/dev/md/md.c`。这是一个长文件。不要试图阅读每一行。相反,找到并理解以下具体内容: -1. The `g_md_class` structure at the top of the file. -2. The `struct md_s` softc. -3. The `mdstart_malloc` function that handles BIO_READ and BIO_WRITE for `MD_MALLOC` memory disks. -4. The worker-thread pattern in `md_kthread` (or its equivalent in your version). -5. The `MDIOCATTACH` ioctl handler that creates new units on demand. +1. 文件顶部的`g_md_class`结构。 +2. `struct md_s` softc。 +3. 处理`MD_MALLOC`内存磁盘的BIO_READ和BIO_WRITE的`mdstart_malloc`函数。 +4. `md_kthread`中的工作线程模式(或你版本中的等效实现)。 +5. 按需创建新单元的`MDIOCATTACH` ioctl处理器。 -Compare each of these to the corresponding code in our 驱动程序. +将每项与我们驱动程序中的对应代码进行比较。 -**What you look for.** +**你观察什么。** -Spot the differences. Where does `md(4)` have features we do not? Where does our 驱动程序 have the same mechanism in simpler form? Where would you need to extend our 驱动程序 to add one of `md(4)`'s features? +发现差异。`md(4)`在哪里有我们没有的功能?我们的驱动程序在哪里以更简单的形式拥有相同的机制?你需要在哪里扩展我们的驱动程序以添加`md(4)`的功能之一? -**Reference notes.** `examples/part-06/ch27-storage-vfs/lab09-md-comparison/NOTES.md` contains a mapped walkthrough of the relevant sections of `md.c` for FreeBSD 14.3. +**参考笔记。**`examples/part-06/ch27-storage-vfs/lab09-md-comparison/NOTES.md`包含FreeBSD 14.3的`md.c`相关章节的映射演练。 -### Lab 10: Break It On Purpose +### 实验10:故意破坏它 -**Goal.** Induce known failure modes so that you can recognise them quickly in real work. +**目标。**诱发已知故障模式,以便你在真实工作中能快速识别它们。 -**What you do.** +**你做什么。** -Take a clean copy of the completed 驱动程序 from Lab 8. In separate copies (do not mix the breakages together), introduce the following bugs one at a time, rebuild, load, and observe. +获取实验8中完成的驱动程序的干净副本。在单独的副本中(不要将破坏混在一起),逐一引入以下bug,重新构建、加载并观察。 -**Breakage 1: Forget biodone.** Comment out the `biodone(bp)` call in the `BIO_READ` case. Load, 挂载, and run `cat` on a file. The `cat` will hang forever. Attempt to kill it with `Ctrl-C`; it may not respond. Use `procstat -kk` on the stuck PID to see where the process is waiting. This is the classic leaked-BIO symptom. +**破坏1:忘记biodone。**注释掉`BIO_READ` case中的`biodone(bp)`调用。加载、挂载并对一个文件运行`cat`。`cat`将永远挂起。尝试用`Ctrl-C`杀死它;它可能不响应。对卡住的PID使用`procstat -kk`查看进程在哪里等待。这是经典的泄漏BIO症状。 -**Breakage 2: Free backing before disk_destroy.** In `myblk_分离_unit`, swap the order so that `free(sc->backing, ...)` comes before `disk_destroy(sc->disk)`. Load, format, 挂载, 卸载, and try to unload. If no BIO is in flight during the unload window, you will escape unharmed. If any BIO is in flight (use a running `dd` to ensure this), you will panic with a page fault. +**破坏2:在disk_destroy之前释放后备存储。**在`myblk_detach_unit`中,交换顺序使`free(sc->backing, ...)`在`disk_destroy(sc->disk)`之前。加载、格式化、挂载、卸载并尝试卸载模块。如果在卸载窗口期间没有BIO在飞行中,你会安然无恙。如果有任何BIO在飞行中(用运行中的`dd`确保这一点),你将因页面错误而崩溃。 -**Breakage 3: Skip bio_resid.** Remove the `bp->bio_resid = 0` line from the `BIO_READ` case. Load, format, 挂载, and create a file. Read it back. Depending on what garbage was in `bio_resid` at allocation time, the 文件系统 may report incorrect read sizes and may log errors. Sometimes it works; sometimes it does not. This is the characteristic intermittent failure of a forgotten `bio_resid`. +**破坏3:跳过bio_resid。**从`BIO_READ` case中删除`bp->bio_resid = 0`行。加载、格式化、挂载并创建一个文件。读回它。根据`bio_resid`在分配时的垃圾内容,文件系统可能报告不正确的读取大小并可能记录错误。有时它能工作;有时不行。这是被遗忘的`bio_resid`的特征性间歇性故障。 -**Breakage 4: Off-by-one bounds.** Change the bounds check from `offset > sc->backing_size` to `offset >= sc->backing_size`. This rejects valid reads at the last offset. Load, format, 挂载. Try to write a file that extends to the very last 块. Observe whether UFS notices; whether `dd` notices; what error is reported. +**破坏4:差一的边界检查。**将边界检查从`offset > sc->backing_size`改为`offset >= sc->backing_size`。这拒绝了最后一个偏移量处的有效读取。加载、格式化、挂载。尝试写入一个延伸到最后一个块的文件。观察UFS是否注意到;`dd`是否注意到;报告了什么错误。 -**What you look for.** +**你观察什么。** -In each case, describe in your logbook what you observed, which tool revealed the problem (dmesg, `procstat`, `gstat`, panic trace), and what the fix would be. Then apply the fix and confirm normal operation. +在每种情况下,在你的日志中描述你观察到了什么、哪个工具揭示了问题(dmesg、`procstat`、`gstat`、panic跟踪),以及修复应该是什么。然后应用修复并确认正常操作。 -**Stretch question.** What sequence of commands reliably reproduces each failure? Can you write a shell script that deterministically triggers Breakage 1 or Breakage 2? +**延伸问题。**什么命令序列可以可靠地重现每个故障?你能写一个确定性地触发破坏1或破坏2的shell脚本吗? -**Reference notes.** `examples/part-06/ch27-storage-vfs/lab10-break-on-purpose/BREAKAGES.md` contains short descriptions and a test script for each failure mode. +**参考笔记。**`examples/part-06/ch27-storage-vfs/lab10-break-on-purpose/BREAKAGES.md`包含每个故障模式的简短描述和测试脚本。 -### Lab 11: Measure Under Varying Block Sizes +### 实验11:在不同块大小下测量 -**Goal.** Understand how BIO size affects throughput. +**目标。**理解BIO大小如何影响吞吐量。 -**What you do.** +**你做什么。** -With the 驱动程序 loaded and a 文件系统 挂载ed, run `dd` with progressively larger 块 sizes and time each run. +在驱动程序加载且文件系统挂载的情况下,使用逐渐增大的块大小运行`dd`并计时每次运行。 ```console # for bs in 512 4096 32768 131072 524288 1048576; do @@ -3074,19 +3074,19 @@ done Record the throughput in each case. -**What you look for.** +**你观察什么。** -Throughput should increase as 块 size increases, then plateau at or near `d_maxsize` (typically 128 KiB). Very small 块 sizes will be dominated by per-BIO overhead. +吞吐量应该随着块大小增加而增加,然后在`d_maxsize`(通常为128 KiB)附近达到平台。非常小的块大小将主要受每BIO开销支配。 -**Stretch question.** At what 块 size does the curve visibly plateau? Why? +**延伸问题。**在什么块大小下曲线明显达到平台?为什么? -### Lab 12: Race Test With Two Processes +### 实验12:两个进程的竞争测试 -**Goal.** Observe how the 驱动程序 handles simultaneous access from multiple processes. +**目标。**观察驱动程序如何处理来自多个进程的同时访问。 -**What you do.** +**你做什么。** -With the 驱动程序 loaded and a 文件系统 挂载ed, run two `dd` processes in parallel writing to different files. +在驱动程序加载且文件系统挂载的情况下,并行运行两个`dd`进程写入不同文件。 ```console # dd if=/dev/urandom of=/mnt/myblk/a bs=4k count=1024 & @@ -3096,557 +3096,557 @@ With the 驱动程序 loaded and a 文件系统 挂载ed, run two `dd` processes Record the combined throughput. -**What you look for.** +**你观察什么。** -Both writes should complete without corruption. Verify with `md5` or `sha256` on each file. The combined throughput may be slightly less than twice the single-process throughput because of lock contention in our coarse 互斥锁. +两个写入都应该完成且没有损坏。用每个文件的`md5`或`sha256`验证。合并吞吐量可能略低于两倍的单进程吞吐量,因为我们粗粒度互斥锁的锁竞争。 -**Stretch question.** Does removing the 互斥锁 affect throughput? Does it cause corruption? Why or why not? +**延伸问题。**移除互斥锁是否影响吞吐量?是否导致损坏?为什么是或为什么不是? -### A Word on Lab Discipline +### 关于实验纪律 -Every lab is small, and none of them is an exam. If you get stuck, the reference implementation is there for you to compare against. Do not copy-paste it as your first attempt, though. The copying is not the skill. The skill is in typing, reading, diagnosing, and verifying. +每个实验都很小,没有一个是考试。如果你卡住了,参考实现就在那里供你比较。但不要把复制粘贴作为你的第一次尝试。复制不是技能。技能在于输入、阅读、诊断和验证。 -Keep your logbook open. Record what you ran, what you saw, and what surprised you. Storage bugs often repeat across projects, and your future self will thank your current self for the notes. +保持你的日志打开。记录你运行了什么、看到了什么和什么让你惊讶。存储bug经常跨项目重复,你未来的自己会感谢现在的自己做的笔记。 ## 挑战练习 -The challenge exercises stretch the 驱动程序 a little further. Each one is scoped to something a beginner can accomplish with the material already covered in the chapter, combined with a thoughtful reading of FreeBSD source. They are not timed. Take your time. Open the source tree. Consult manual pages. Compare your solution to `md(4)` when in doubt. +挑战练习将驱动程序推得更远一些。每一个都限定在初学者可以凭借本章已涵盖的材料结合对FreeBSD源码的仔细阅读来完成的范围内。它们不是计时的。慢慢来。打开源码树。查阅手册页。有疑问时与`md(4)`比较。 -Every challenge below has a stub folder under `examples/part-06/ch27-storage-vfs/`, but no reference solution is provided. The point is to work through them yourself. Solutions are left as follow-ups that you can compare with peers or post in your study notes. +下面的每个挑战在`examples/part-06/ch27-storage-vfs/`下都有桩文件夹,但没有提供参考解决方案。重点是自己解决它们。解决方案作为后续留给你与同行比较或发布在你的学习笔记中。 -### Challenge 1: Expose a Read-Only Mode +### 挑战1:暴露只读模式 -Add a module-load tunable that lets the 驱动程序 come up in read-only mode. In read-only mode, `BIO_WRITE` and `BIO_DELETE` should fail with `EROFS`. `newfs_ufs` should refuse to format the 设备, and `挂载` without `-r` should refuse to 挂载 it. +添加一个模块加载时可调参数,让驱动程序以只读模式启动。在只读模式下,`BIO_WRITE`和`BIO_DELETE`应以`EROFS`失败。`newfs_ufs`应拒绝格式化设备,不带`-r`的`mount`应拒绝挂载。 -Hint. The tunable can be a `sysctl_int` bound to a static variable. `TUNABLE_INT` is another way, used at load time only. Your strategy function can check the variable before dispatching writes. Remember that changing the mode at runtime while a 文件系统 is 挂载ed is a recipe for corruption; you can either disallow the change or document that the tunable only takes effect at module load. +提示。可调参数可以是绑定到静态变量的`sysctl_int`。`TUNABLE_INT`是另一种方式,仅在加载时使用。你的策略函数可以在分派写入之前检查该变量。记住,在文件系统挂载时运行时更改模式是数据损坏的根源;你可以禁止更改或记录可调参数仅在模块加载时生效。 -### Challenge 2: Implement a Second Unit +### 挑战2:实现第二个单元 -Add support for exactly two units: `myblk0` and `myblk1`. Each should have its own backing store of its own size. Do not try to implement fully dynamic unit allocation; just hardcode two softcs and two 附加 calls in the module loader. +添加对恰好两个单元的支持:`myblk0`和`myblk1`。每个应该有自己的后备存储和自己的大小。不要尝试实现完全动态的单元分配;只需在模块加载器中硬编码两个softc和两个附加调用。 -Hint. Move the backing allocation, disk allocation, and disk creation into `myblk_附加_unit` parameterised by unit number and size, and call it twice from the loader. Make sure the 分离 path walks both units. +提示。将后备分配、磁盘分配和磁盘创建移入按单元号和大小参数化的`myblk_attach_unit`中,并从加载器中调用两次。确保分离路径遍历两个单元。 -### Challenge 3: Honour BIO_DELETE with a Sysctl Counter +### 挑战3:用Sysctl计数器响应BIO_DELETE -Extend `BIO_DELETE` handling to also bump a `sysctl` counter that reports total bytes deleted. Verify with `sysctl dev.myblk` while running `fstrim /mnt/myblk` or while `dd` writes and overwrites files. +扩展`BIO_DELETE`处理,同时递增一个`sysctl`计数器,报告已删除的总字节数。在运行`fstrim /mnt/myblk`或`dd`写入和覆盖文件时用`sysctl dev.myblk`验证。 -Hint. UFS by default does not issue `BIO_DELETE`. To see delete traffic, 挂载 with `-o trim`. You can verify the trim flow with your DTrace one-liner from Lab 7. +提示。UFS默认不发出`BIO_DELETE`。要看到删除流量,用`-o trim`挂载。你可以用实验7中的DTrace单行命令验证trim流。 -### Challenge 4: Respond to BIO_GETATTR for rotation_rate +### 挑战4:响应BIO_GETATTR查询rotation_rate -Extend `myblk_getattr` to answer `GEOM::rotation_rate` with `DISK_RR_NON_ROTATING` (defined in `/usr/src/sys/geom/geom_disk.h`). Verify with `gpart show` and `diskinfo -v` that the 设备 reports as non-rotating. +扩展`myblk_getattr`以用`DISK_RR_NON_ROTATING`(在`/usr/src/sys/geom/geom_disk.h`中定义)回答`GEOM::rotation_rate`。用`gpart show`和`diskinfo -v`验证设备报告为非旋转。 -Hint. The attribute is returned as a plain `u_int`. Look at how `md(4)` handles `BIO_GETATTR` for comparable attributes. +提示。属性作为普通`u_int`返回。看看`md(4)`如何为类似属性处理`BIO_GETATTR`。 -### Challenge 5: Resizing the Device +### 挑战5:调整设备大小 -Add an ioctl that lets user space resize the backing store while nothing is 挂载ed. If a 文件系统 is 挂载ed, the ioctl must fail with `EBUSY`. If the resize succeeds, update `d_mediasize` and notify GEOM so that `diskinfo` reports the new size. +添加一个ioctl,让用户空间在未挂载任何东西时调整后备存储大小。如果文件系统已挂载,ioctl必须以`EBUSY`失败。如果调整大小成功,更新`d_mediasize`并通知GEOM,以便`diskinfo`报告新大小。 -Hint. Look at `md(4)`'s `MDIOCRESIZE` handling for the pattern. This is a non-trivial challenge; take your time and test with throwaway 文件系统. Do not attempt this on any backing that you would be sad to lose. +提示。查看`md(4)`的`MDIOCRESIZE`处理了解模式。这是一个非平凡的挑战;慢慢来,用一次性的文件系统测试。不要在你舍不得丢失的后备上尝试这个。 -### Challenge 6: A Write Counter and Rate Display +### 挑战6:写入计数器和速率显示 -Add per-second write-byte counters, exposed via `sysctl`, and a small user-space shell script that reads the sysctl every second and prints a human-readable rate. This is useful for testing and it gives you experience wiring metrics through the 内核's observability machinery. +添加每秒写入字节计数器,通过`sysctl`暴露,以及一个小的用户空间shell脚本,每秒读取sysctl并打印人类可读的速率。这对测试有用,也给你提供将指标接入内核可观测性机制的经验。 -Hint. Use `atomic_add_long` on the counters. The shell script is a one-liner in `while true` loops. +提示。在计数器上使用`atomic_add_long`。shell脚本是一个`while true`循环中的单行命令。 -### Challenge 7: A Fixed Pattern Backing Store +### 挑战7:固定模式后备存储 -Implement a backing-store mode where reads always return a fixed byte pattern and writes are silently discarded. This is similar to `g_zero` but with a configurable pattern byte. It is useful for stress-testing the layers above when you do not care about data content. +实现一种后备存储模式,读取总是返回固定的字节模式,写入被静默丢弃。这类似于`g_zero`,但具有可配置的模式字节。当你不关心数据内容时,它对压力测试上面的层很有用。 -Hint. Branch on a mode variable inside the strategy function. Keep the in-memory backing for the normal mode and skip the `memcpy` in pattern mode. +提示。在策略函数内部分支到一个模式变量。正常模式保留内存中的后备,在模式模式下跳过`memcpy`。 -### Challenge 8: Write a mdconfig-Like Control Utility +### 挑战8:编写类似mdconfig的控制工具 -Write a small user-space program that talks to a control 设备 on your 驱动程序 (you will need to add one) and can create, destroy, and query units at runtime. The program should accept command-line flags similar to `mdconfig`. +编写一个小的用户空间程序,与驱动程序上的控制设备(你需要添加一个)通信,并可以在运行时创建、销毁和查询单元。程序应该接受类似`mdconfig`的命令行标志。 -Hint. This is a substantial challenge. Start with a single ioctl that prints "hello" and build up from there. `make_dev` on a cdev for your control 设备, then implement `d_ioctl` on that cdev. +提示。这是一个相当大的挑战。从一个打印"hello"的单个ioctl开始,从那里构建。在你的控制设备上用cdevsw的`make_dev`,然后在该cdev上实现`d_ioctl`。 -### Challenge 9: Survive a Simulated Crash +### 挑战9:在模拟崩溃中存活 -Add a mode where the 驱动程序 drops every Nth write silently (pretending the write succeeded but actually doing nothing). Use this to test UFS's resilience to lost writes. +添加一个模式,驱动程序静默丢弃每第N次写入(假装写入成功但实际上什么也不做)。用这个来测试UFS对丢失写入的弹性。 -Hint. This is a dangerous mode. Only run it on throwaway 文件系统. You should be able to reproduce interesting `fsck_ffs` repair scenarios with it. Be ready to explain to yourself why this mode is only safe on pseudo 设备 you can regenerate from scratch. +提示。这是一个危险的模式。只在一次性的文件系统上运行。你应该能用它重现有趣的`fsck_ffs`修复场景。准备好向自己解释为什么这个模式只在你可以从零重新生成的伪设备上是安全的。 -### Challenge 10: Understand md(4) Well Enough to Teach It +### 挑战10:足够理解md(4)以至于能教授它 -Write a one-page explanation of how `md(4)` creates a new unit in response to `MDIOCATTACH`. Cover the ioctl path, the softc allocation, the backing-type-specific initialisation, the `g_disk` wiring, and the worker thread creation. This is a reading challenge rather than a coding challenge, but it is one of the most useful exercises you can do to deepen your grasp of the storage stack. +写一页关于`md(4)`如何响应`MDIOCATTACH`创建新单元的说明。涵盖ioctl路径、softc分配、特定于后备类型的初始化、`g_disk`连接和工作线程创建。这是一个阅读挑战而不是编码挑战,但它是对加深你对存储栈理解最有用的练习之一。 -Hint. `/usr/src/sys/dev/md/md.c` and `/usr/src/sbin/mdconfig/mdconfig.c` are the two files to read. Pay attention to the `struct md_ioctl` structure in `/usr/src/sys/sys/mdioctl.h`, because that is the ABI between user space and the 内核. +提示。`/usr/src/sys/dev/md/md.c`和`/usr/src/sbin/mdconfig/mdconfig.c`是两个要阅读的文件。注意`/usr/src/sys/sys/mdioctl.h`中的`struct md_ioctl`结构,因为那是用户空间和内核之间的ABI。 -### When to Attempt Challenges +### 何时尝试挑战 -You do not need to do all of them. Pick one or two that speak to something you are curious about or something you can imagine using later. A single carefully-done challenge is worth more than five half-done ones. The reference `md(4)` implementation will be there whenever you want to compare your approach to a production 驱动程序. +你不需要做所有挑战。选择一两个你对其中某个东西感到好奇或你能想象以后会用到的东西。一个仔细完成的挑战比五个半完成的挑战更有价值。参考`md(4)`实现会在你想将自己的方法与生产驱动程序比较时始终在那里。 -## Troubleshooting +## 故障排除 -Storage 驱动程序 have a particular family of failure modes. Some of them are obvious as they happen. Others are silent at first and become obvious only after reboot, sometimes with data corruption in between. This section lists the symptoms you are most likely to see while working through the chapter and the labs, along with the usual causes and fixes. Use it as a reference when things go wrong, and read it through at least once before you start, because it is much easier to recognise a failure mode the second time. +存储驱动程序有一族特定的故障模式。有些在发生时就显而易见。其他则一开始是静默的,只有在重启后才变得明显,有时中间还会出现数据损坏。本节列出了你在学习本章和做实验时最可能看到的症状,以及常见原因和修复方法。当出现问题时将其用作参考,在开始之前至少通读一次,因为第二次识别故障模式要容易得多。 -### `kldload` Succeeds but No /dev Node Appears +### `kldload`成功但没有/dev节点出现 -**Symptom.** `kldload` returns zero. `kldstat` shows the module loaded. But `/dev/myblk0` does not exist. +**症状。**`kldload`返回零。`kldstat`显示模块已加载。但`/dev/myblk0`不存在。 -**Likely causes.** +**可能原因。** -- You forgot to call `disk_create`. The softc is allocated, the disk is allocated, but the disk is not 注册ed with GEOM. -- You called `disk_create` with `d_name` set to a null pointer or an empty string. -- You called `disk_create` with `d_mediasize` set to zero. `g_disk` silently refuses to create a provider with zero size. -- You called `disk_create` before filling in the fields. The 框架 captures the field values at registration time and does not re-read them later. +- 你忘记调用`disk_create`。softc已分配,磁盘已分配,但磁盘未向GEOM注册。 +- 你用`d_name`设置为空指针或空字符串调用了`disk_create`。 +- 你用`d_mediasize`设置为零调用了`disk_create`。`g_disk`静默拒绝创建零大小的提供者。 +- 你在填充字段之前调用了`disk_create`。框架在注册时捕获字段值,之后不会重新读取。 -**Fix.** Check the 内核 message 缓冲区 with `dmesg`. `g_disk` prints a diagnostic when it rejects a registration. Fix the field value and rebuild. +**修复。**用`dmesg`检查内核消息缓冲区。`g_disk`在拒绝注册时打印诊断信息。修复字段值并重新构建。 -### `kldload` Fails with "module version mismatch" +### `kldload`失败并显示"module version mismatch" -**Symptom.** Loading the module reports `kldload: can't load ./myblk.ko: No such file or directory` or a more explicit error about version mismatch. +**症状。**加载模块报告`kldload: can't load ./myblk.ko: No such file or directory`或更明确的版本不匹配错误。 -**Likely causes.** +**可能原因。** -- You compiled against a different 内核 than the one currently running. -- You changed `DISK_VERSION` on your own, which you should never do. -- You forgot `MODULE_VERSION(myblk, 1)`. +- 你针对与当前运行内核不同的内核编译了模块。 +- 你自己修改了`DISK_VERSION`,你不应该这样做。 +- 你忘记添加`MODULE_VERSION(myblk, 1)`。 -**Fix.** Check `uname -a` and the 内核 version your build chose. Recompile against the running 内核. +**修复。**检查`uname -a`和你的构建选择的内核版本。针对运行中的内核重新编译。 -### `diskinfo` Prints the Wrong Size +### `diskinfo`打印错误的大小 -**Symptom.** `diskinfo -v /dev/myblk0` prints a size that does not match `MYBLK_MEDIASIZE`. +**症状。**`diskinfo -v /dev/myblk0`打印的大小与`MYBLK_MEDIASIZE`不匹配。 -**Likely causes.** +**可能原因。** -- You set `d_mediasize` to the wrong expression. A common off-by-one is setting it to the 扇区 count rather than the byte count. -- You have `MYBLK_MEDIASIZE` defined as something other than `(size * 1024 * 1024)` and the macro is being interpreted differently than you intended. Parenthesise aggressively. +- 你将`d_mediasize`设置为错误的表达式。一个常见的差一错误是将其设置为扇区计数而不是字节数。 +- 你的`MYBLK_MEDIASIZE`定义为非`(size * 1024 * 1024)`的值,宏被以不同于你意图的方式解释。积极使用括号。 -**Fix.** Print the size in your load message and sanity-check against `diskinfo -v`. +**修复。**在加载消息中打印大小并与`diskinfo -v`进行合理性检查。 -### `newfs_ufs` Fails with "Device not configured" +### `newfs_ufs`失败并显示"Device not configured" -**Symptom.** `newfs_ufs /dev/myblk0` prints `newfs: /dev/myblk0: Device not configured`. +**症状。**`newfs_ufs /dev/myblk0`打印`newfs: /dev/myblk0: Device not configured`。 -**Likely causes.** +**可能原因。** -- Your strategy function is still the placeholder that returns `ENXIO` for everything. `ENXIO` is mapped to the `Device not configured` message by `errno`. +- 你的策略函数仍然是返回`ENXIO`的占位符。`ENXIO`被`errno`映射为`Device not configured`消息。 -**Fix.** Implement the strategy function from Section 5. +**修复。**实现第5节中的策略函数。 -### `newfs_ufs` Hangs +### `newfs_ufs`挂起 -**Symptom.** `newfs_ufs /dev/myblk0` starts up but never completes. +**症状。**`newfs_ufs /dev/myblk0`启动但从不完成。 -**Likely causes.** +**可能原因。** -- Your strategy function does not call `biodone` on some path. `newfs_ufs` issues a BIO, waits for its completion, and will wait forever if completion never comes. -- Your strategy function calls `biodone` twice on some path. The first call returns success; the second call usually panics, but in some cases the BIO state is corrupted enough to hang. +- 你的策略函数在某条路径上没有调用`biodone`。`newfs_ufs`发出一个BIO,等待其完成,如果完成永远不会到来就会永远等待。 +- 你的策略函数在某条路径上调用了两次`biodone`。第一次调用返回成功;第二次调用通常会导致崩溃,但在某些情况下BIO状态损坏足以导致挂起。 -**Fix.** Audit your strategy function. Every control-flow path must end with exactly one call to `biodone(bp)`. A useful pattern is to use a single exit point at the end of the function. +**修复。**审计你的策略函数。每个控制流路径必须恰好以一次`biodone(bp)`调用结束。一个有用的模式是在函数末尾使用单一退出点。 -### `挂载` Fails with "bad super块" +### `mount`失败并显示"bad super block" -**Symptom.** `挂载 /dev/myblk0 /mnt/myblk` reports `挂载: /dev/myblk0: bad magic`. +**症状。**`mount /dev/myblk0 /mnt/myblk`报告`mount: /dev/myblk0: bad magic`。 -**Likely causes.** +**可能原因。** -- Your strategy function is returning wrong data for some offsets. The super块 is at offset 65536, and UFS validates it carefully. -- Your bounds check is rejecting a legitimate read. -- Your `memcpy` is copying from the wrong address (usually an off-by-one in the offset arithmetic). +- 你的策略函数在某些偏移量返回错误数据。超级块在偏移65536处,UFS仔细验证它。 +- 你的边界检查拒绝了合法的读取。 +- 你的`memcpy`从错误的地址复制(通常是偏移算术中的差一错误)。 -**Fix.** Write a known pattern to the 设备 with `dd`, then read it back with `dd` at various offsets and compare with `cmp`. If the pattern round-trips, the basic I/O is correct. If not, find the first offset where it diverges and inspect the code at the corresponding bounds check or address arithmetic. +**修复。**用`dd`向设备写入已知模式,然后用`dd`在不同偏移量读回并用`cmp`比较。如果模式正确往返,基本I/O是正确的。如果不正确,找到第一个出现偏差的偏移量并检查相应边界检查或地址算术处的代码。 -### `kldunload` Hangs +### `kldunload`挂起 -**Symptom.** `kldunload myblk` does not return. +**症状。**`kldunload myblk`不返回。 -**Likely causes.** +**可能原因。** -- A BIO is in flight and your strategy function never calls `biodone`. `disk_destroy` is waiting for the BIO to complete. -- You added a worker thread and it is sleeping inside a function that will never be awakened. +- 一个BIO在飞行中,你的策略函数从未调用`biodone`。`disk_destroy`正在等待BIO完成。 +- 你添加了工作线程,它在一个永远不会被唤醒的函数中睡眠。 -**Fix.** Run `procstat -kk` in another terminal. Look at the `g_event` thread's stack and at any of your 驱动程序's threads. If they are stuck in a `sleep` or `waitfor` state, you have a leaked BIO or a misbehaving worker. +**修复。**在另一个终端中运行`procstat -kk`。查看`g_event`线程的栈和你驱动程序线程的任何栈。如果它们卡在`sleep`或`waitfor`状态,你有一个泄漏的BIO或行为不当的工作线程。 -### `kldunload` Returns "Device 总线y" +### `kldunload`返回"Device busy" -**Symptom.** `kldunload myblk` reports `Device 总线y` and exits. +**症状。**`kldunload myblk`报告`Device busy`并退出。 -**Likely causes.** +**可能原因。** -- A 文件系统 is still 挂载ed on `/dev/myblk0`. -- A program still has `/dev/myblk0` open for raw access. -- A `dd` from a previous terminal session is still running in the background. +- 文件系统仍然挂载在`/dev/myblk0`上。 +- 一个程序仍然以原始访问方式打开了`/dev/myblk0`。 +- 之前终端会话的`dd`仍然在后台运行。 -**Fix.** Run `挂载 | grep myblk` to check for active 挂载s. Run `fuser /dev/myblk0` to find open handles. Un挂载, close, then unload. +**修复。**运行`mount | grep myblk`检查活跃的挂载。运行`fuser /dev/myblk0`找到打开的句柄。卸载、关闭,然后卸载模块。 -### Kernel Panic with "freeing free memory" +### 内核崩溃并显示"freeing free memory" -**Symptom.** The 内核 panics with a message about freeing already-freed memory, showing a stack trace through your 驱动程序. +**症状。**内核崩溃,显示关于释放已释放内存的消息,栈跟踪经过你的驱动程序。 -**Likely causes.** +**可能原因。** -- The 分离 path is freeing the softc or the backing twice. -- A worker thread survived `disk_destroy` and tried to access freed state. +- 分离路径正在两次释放softc或后备存储。 +- 一个工作线程在`disk_destroy`后仍然存活并试图访问已释放的状态。 -**Fix.** Review the 分离 order. Destroy the disk first (which waits for in-flight BIOs), then free the backing, then destroy the 互斥锁, then free the softc. If you added a worker thread, make sure it has exited before any `free` is called. +**修复。**审查分离顺序。先销毁磁盘(它等待飞行中的BIO),然后释放后备存储,然后销毁互斥锁,然后释放softc。如果你添加了工作线程,确保它在任何`free`被调用之前已经退出。 -### Kernel Panic with "vm_fault: 内核 mode" +### 内核崩溃并显示"vm_fault: kernel mode" -**Symptom.** The 内核 panics with a page fault inside your 驱动程序, typically in the strategy function or in the 分离 path. +**症状。**内核在你的驱动程序内崩溃,出现页面错误,通常在策略函数或分离路径中。 -**Likely causes.** +**可能原因。** -- You dereferenced a null or freed pointer. The most common case is using `sc->backing` after it has been freed. -- You confused `bp->bio_data` with `bp->bio_disk` and read from the wrong pointer. +- 你解引用了一个空指针或已释放的指针。最常见的情况是在`sc->backing`被释放后使用它。 +- 你混淆了`bp->bio_data`和`bp->bio_disk`,从错误的指针读取。 -**Fix.** Audit pointer lifetimes. If the backing store is freed during 分离, ensure no BIOs can still reach the strategy function after that point. The order `disk_destroy` -> `free(backing)` is the correct order. +**修复。**审计指针生命周期。如果后备存储在分离期间被释放,确保之后没有BIO还能到达策略函数。`disk_destroy` -> `free(backing)`是正确的顺序。 -### `gstat` Shows No Activity +### `gstat`显示没有活动 -**Symptom.** You are running `dd` or `newfs_ufs` against the 设备, but `gstat -f myblk0` shows zero ops/s. +**症状。**你正在对设备运行`dd`或`newfs_ufs`,但`gstat -f myblk0`显示零ops/s。 -**Likely causes.** +**可能原因。** -- You are watching the wrong 设备. `gstat -f myblk0` uses a regex; make sure your 设备 name matches. -- Your 驱动程序 uses a custom GEOM class name that `gstat` is filtering out. +- 你在观察错误的设备。`gstat -f myblk0`使用正则表达式;确保你的设备名称匹配。 +- 你的驱动程序使用了`gstat`正在过滤掉的自定义GEOM类名。 -**Fix.** Run `gstat` without the filter and look for your 设备. Check the name field carefully. +**修复。**不带过滤器运行`gstat`并查找你的设备。仔细检查名称字段。 -### "Operation not supported" for DELETE +### DELETE的"Operation not supported" -**Symptom.** Mount-with-trim fails or `fstrim` prints "Operation not supported". +**症状。**带trim挂载失败或`fstrim`打印"Operation not supported"。 -**Likely causes.** +**可能原因。** -- Your strategy function does not handle `BIO_DELETE` and returns `EOPNOTSUPP`. -- The 文件系统 探测d `BIO_DELETE` support during 挂载 and cached the negative result. +- 你的策略函数不处理`BIO_DELETE`并返回`EOPNOTSUPP`。 +- 文件系统在挂载期间探测了`BIO_DELETE`支持并缓存了否定结果。 -**Fix.** Implement `BIO_DELETE` in the strategy function, then 卸载 and re挂载. Most 文件系统 only 探测 at 挂载 time. +**修复。**在策略函数中实现`BIO_DELETE`,然后卸载并重新挂载。大多数文件系统只在挂载时探测。 -### /dev/myblk0 Does Not Appear Until Several Seconds After kldload +### /dev/myblk0在kldload几秒后才出现 -**Symptom.** Immediately after `kldload`, `ls /dev/myblk0` fails. A few moments later, it succeeds. +**症状。**`kldload`后,`ls /dev/myblk0`立即失败。片刻后,它成功。 -**Likely causes.** +**可能原因。** -- GEOM processes events asynchronously. `disk_create` queues an event, and the provider is not published until the event thread picks it up. -- On a system under load, the event queue may be slow. +- GEOM异步处理事件。`disk_create`将事件排队,直到事件线程拾取它才发布提供者。 +- 在负载下的系统上,事件队列可能很慢。 -**Fix.** This is normal behaviour. If your scripts depend on the node existing immediately after `kldload`, add a small sleep or a polling loop. +**修复。**这是正常行为。如果你的脚本依赖于节点在`kldload`后立即可用,添加一个小延迟或轮询循环。 -### Data Written Is Readable but Garbled +### 写入的数据可读但乱码 -**Symptom.** A read after a write returns the right number of bytes but with different content. +**症状。**写入后读取返回正确数量的字节但内容不同。 -**Likely causes.** +**可能原因。** -- Off-by-one in the backing-store offset arithmetic. -- A concurrent BIO is overlapping with the one you expect, and your lock is not held for long enough. -- The strategy function is reading from `bp->bio_data` before the 内核 has finished setting it up (this is extremely unlikely for normal BIOs, but can happen with bugs in how you parse attributes). +- 后备存储偏移算术中的差一错误。 +- 一个并发的BIO与你期望的重叠,你的锁持有时间不够长。 +- 策略函数在内核完成设置`bp->bio_data`之前从中读取(这对普通BIO极其不可能,但可能在解析属性的方式有bug时发生)。 -**Fix.** Add a `printf` to the strategy function that logs the first few bytes before and after the `memcpy`. Repeat the test with a known pattern and look for the mismatch. +**修复。**在策略函数中添加一个`printf`,记录`memcpy`前后前几个字节。用已知模式重复测试并查找不匹配。 -### Backing Store Not Freed, Memory Grows With Every Reload +### 后备存储未释放,每次重新加载内存增长 -**Symptom.** `vmstat -m | grep myblk` shows the allocation bytes growing with each load/unload cycle. +**症状。**`vmstat -m | grep myblk`显示分配字节在每个加载/卸载周期中增长。 -**Likely causes.** +**可能原因。** -- The `MOD_UNLOAD` handler returned without calling `myblk_分离_unit`, so the `free(sc->backing, M_MYBLK)` was skipped. -- An error path in `MOD_UNLOAD` returned early before reaching the free. Every error path needs to free or the allocation leaks. -- A worker thread is holding a reference to the softc and the handler refuses to free while that reference exists. +- `MOD_UNLOAD`处理器返回时没有调用`myblk_detach_unit`,所以`free(sc->backing, M_MYBLK)`被跳过了。 +- `MOD_UNLOAD`中的错误路径在到达释放之前提前返回。每个错误路径都需要释放,否则分配就会泄漏。 +- 一个工作线程持有softc的引用,处理器在该引用存在时拒绝释放。 -**Fix.** Audit the `MOD_UNLOAD` path. `vmstat -m` is a blunt but effective tool. Add a `printf` in the free path to confirm it is being reached. +**修复。**审计`MOD_UNLOAD`路径。`vmstat -m`是一个粗糙但有效的工具。在释放路径中添加`printf`以确认它被执行。 -### `gstat` Shows Very High Queue Length +### `gstat`显示非常高的队列长度 -**Symptom.** `gstat -I 1` shows `L(q)` rising into the tens or hundreds and never returning to zero. +**症状。**`gstat -I 1`显示`L(q)`上升到数十或数百且从不返回零。 -**Likely causes.** +**可能原因。** -- Your strategy function is slow or 块ing, causing BIOs to queue faster than they are serviced. -- You added a worker thread but it is scheduled less often than it should be. -- A synchronisation bottleneck (a heavily contested 互斥锁) is serialising the work. +- 你的策略函数很慢或阻塞,导致BIO排队速度比处理速度快。 +- 你添加了工作线程但它的调度频率比应该的低。 +- 一个同步瓶颈(严重竞争的互斥锁)正在串行化工作。 -**Fix.** Profile with DTrace to find what the strategy function is doing. If the latency per BIO has grown, investigate why. For an in-memory 驱动程序, this should almost never happen; if it does, you have likely introduced a `vn_rdwr` or other 块ing call into the hot path. +**修复。**用DTrace分析策略函数在做什么。如果每个BIO的延迟增加了,调查原因。对于内存驱动程序,这几乎不应该发生;如果发生了,你可能在热路径中引入了`vn_rdwr`或其他阻塞调用。 -### Strategy Function Called With NULL bio_disk +### 策略函数被调用时bio_disk为NULL -**Symptom.** Kernel panic in the strategy function when dereferencing `bp->bio_disk->d_drv1`. +**症状。**解引用`bp->bio_disk->d_drv1`时在策略函数中出现内核崩溃。 -**Likely causes.** +**可能原因。** -- The BIO was synthesised incorrectly by code outside your 驱动程序. -- You are accessing `bp->bio_disk` from the wrong context. In some GEOM paths, `bp->bio_disk` is only valid inside the strategy function of a `g_disk` 驱动程序. +- BIO被驱动程序外部的代码错误合成。 +- 你在错误的上下文中访问`bp->bio_disk`。在某些GEOM路径中,`bp->bio_disk`只在`g_disk`驱动程序的策略函数内部有效。 -**Fix.** If you need to access the softc, do it at the start of the strategy function. Cache the pointer in a local variable. Do not access `bp->bio_disk` from a different thread or from a deferred 回调. +**修复。**如果你需要访问softc,在策略函数开始时进行。将指针缓存在局部变量中。不要从不同线程或延迟回调中访问`bp->bio_disk`。 -### Mysterious I/O Errors After Reload +### 重新加载后出现神秘的I/O错误 -**Symptom.** After `kldunload` and `kldload`, reads return EIO on offsets that worked before the unload. +**症状。**`kldunload`和`kldload`后,读取在卸载之前有效的偏移量上返回EIO。 -**Likely causes.** +**可能原因。** -- You are working with a file-backed or vnode-backed experiment (from Lab 5 or from your own modifications) and the file's size or contents have been changed between loads. -- A type mismatch between the saved and new offsets (for instance, changing `d_扇区ize` between loads). -- `d_mediasize` has changed but the underlying file still reflects the old layout. +- 你正在使用文件后备或vnode后备的实验(来自实验5或你自己的修改),并且文件的大小或内容在两次加载之间被更改了。 +- 保存的偏移量与新偏移量之间存在类型不匹配(例如,在两次加载之间更改了`d_sectorsize`)。 +- `d_mediasize`已更改但底层文件仍反映旧的布局。 -**Fix.** Ensure the backing file and the 驱动程序's geometry agree on both size and 扇区 layout. If you change `d_mediasize` or `d_扇区ize`, regenerate the backing file to match. For a straightforward reload with no changes, the 缓冲区 on a RAM-backed 驱动程序 is always fresh, so mysterious post-reload EIOs usually point to a geometry mismatch rather than data loss. +**修复。**确保后备文件和驱动程序的几何参数在大小和扇区布局上一致。如果你更改了`d_mediasize`或`d_sectorsize`,重新生成后备文件以匹配。对于没有更改的简单重新加载,RAM后备驱动程序上的缓冲区总是全新的,所以神秘的重新加载后EIO通常指向几何参数不匹配而不是数据丢失。 -### Access Count Stuck at Non-Zero After Un挂载 +### 卸载后访问计数卡在非零 -**Symptom.** After `u挂载`, `geom disk list` still shows non-zero access counts. +**症状。**`umount`后,`geom disk list`仍然显示非零访问计数。 -**Likely causes.** +**可能原因。** -- A program still has the raw 设备 open. `fuser /dev/myblk0` will reveal it. -- The 文件系统 did not 卸载 cleanly. Check `挂载 | grep myblk` to see if it is still 挂载ed. -- A lingering NFS client or similar is holding the 文件系统 open. Unlikely for a local memory disk, but possible on shared systems. +- 一个程序仍然打开了原始设备。`fuser /dev/myblk0`会揭示它。 +- 文件系统未干净卸载。检查`mount | grep myblk`看它是否仍然挂载。 +- 一个残留的NFS客户端或类似的东西正在持有文件系统打开。对本地内存磁盘不太可能,但在共享系统上可能。 -**Fix.** Find and close the open handle. If `u挂载` reports success but the access count remains, rebooting is the safest recovery. +**修复。**找到并关闭打开的句柄。如果`umount`报告成功但访问计数保持不变,重启是最安全的恢复方式。 -### Driver Loaded But Not Visible in geom -t +### 驱动程序已加载但在geom -t中不可见 -**Symptom.** `kldstat` shows the module loaded, but `geom -t` does not show any geom of our name. +**症状。**`kldstat`显示模块已加载,但`geom -t`不显示我们名称的任何geom。 -**Likely causes.** +**可能原因。** -- The loader ran but never called `disk_create`. -- `disk_create` was called but the event thread has not run yet. +- 加载器运行了但从未调用`disk_create`。 +- `disk_create`被调用了但事件线程尚未运行。 -**Fix.** Add a `printf` to confirm `disk_create` ran. Wait one or two seconds after `kldload` before checking, to give the event thread a chance. +**修复。**添加`printf`确认`disk_create`运行了。`kldload`后等待一两秒再检查,给事件线程一个机会。 -### Panic on Second Load +### 第二次加载时崩溃 -**Symptom.** Loading the module once works. Unloading works. Loading a second time panics. +**症状。**加载模块一次成功。卸载成功。第二次加载时崩溃。 -**Likely causes.** +**可能原因。** -- A `MOD_UNLOAD` handler did not reset all the state that `MOD_LOAD` assumes is fresh. -- A static pointer holds a reference to a freed structure across the unload boundary; the next load sees a dangling pointer. -- A GEOM class that was 注册ed on first load did not un注册. +- `MOD_UNLOAD`处理器没有重置`MOD_LOAD`假设为新的所有状态。 +- 一个静态指针持有对跨卸载边界已释放结构的引用;下一次加载看到悬空指针。 +- 在第一次加载时注册的GEOM类未注销。 -**Fix.** Audit your load and unload paths as a matched pair. Every allocation on load needs a corresponding free on unload, and every pointer written on load needs to be cleared on unload. For GEOM classes, `DECLARE_GEOM_CLASS` handles the unregistration for you, but if you bypass it you must do the work. +**修复。**将你的加载和卸载路径作为匹配对进行审计。加载时的每个分配都需要卸载时相应的释放,加载时写入的每个指针都需要卸载时清除。对于GEOM类,`DECLARE_GEOM_CLASS`为你处理注销,但如果你绕过它,你必须自己做这个工作。 -### newfs_ufs Aborts with "File system too small" +### newfs_ufs中止并显示"File system too small" -**Symptom.** `newfs_ufs /dev/myblk0` aborts with `newfs: /dev/myblk0: 分区 smaller than minimum UFS size`. +**症状。**`newfs_ufs /dev/myblk0`中止并显示`newfs: /dev/myblk0: partition smaller than minimum UFS size`。 -**Likely causes.** +**可能原因。** -- `MYBLK_MEDIASIZE` is too small for UFS's minimum practical size. -- You forgot to rebuild the module after changing the size. +- `MYBLK_MEDIASIZE`对UFS的最小实际大小来说太小了。 +- 你更改大小后忘记重新构建模块。 -**Fix.** Ensure the media size is at least a few megabytes. UFS's absolute minimum is around 1 MiB, but practical minimums are 4-8 MiB and comfortable minimums are 32 MiB or more. +**修复。**确保媒体大小至少有几兆字节。UFS的绝对最小值大约为1 MiB,但实际最小值为4-8 MiB,舒适的最小值为32 MiB或更多。 -### 挂载 -o trim Does Not Trigger BIO_DELETE +### mount -o trim不触发BIO_DELETE -**Symptom.** Mounting with `-o trim` succeeds, but `gstat` shows no delete operations even during heavy deletion. +**症状。**用`-o trim`挂载成功,但`gstat`在重度删除期间不显示删除操作。 -**Likely causes.** +**可能原因。** -- UFS issues `BIO_DELETE` only on certain patterns; it does not unconditionally trim every freed 块. -- Your 驱动程序 does not advertise `BIO_DELETE` support in its `d_flags`. +- UFS仅在某些模式上发出`BIO_DELETE`;它不会无条件地修剪每个释放的块。 +- 你的驱动程序没有在其`d_flags`中声明`BIO_DELETE`支持。 -**Fix.** Set `sc->disk->d_flags |= DISKFLAG_CANDELETE;` before `disk_create`. This tells GEOM and 文件系统 that your 驱动程序 supports `BIO_DELETE` and is willing to handle them. +**修复。**在`disk_create`之前设置`sc->disk->d_flags |= DISKFLAG_CANDELETE;`。这告诉GEOM和文件系统你的驱动程序支持`BIO_DELETE`并愿意处理它们。 -### UFS Complains About "Fragment out of bounds" +### UFS抱怨"Fragment out of bounds" -**Symptom.** After a 挂载, UFS logs an error about a fragment being out of bounds, and file operations start returning EIO. +**症状。**挂载后,UFS记录关于片段越界的错误,文件操作开始返回EIO。 -**Likely causes.** +**可能原因。** -- Your 驱动程序 is returning wrong data on some offset, and UFS has read a corrupted metadata 块. -- The backing store was partially overwritten during some other test. -- Bounds-check arithmetic is returning incorrect ranges. +- 你的驱动程序在某些偏移量返回错误数据,UFS读取了损坏的元数据块。 +- 后备存储在其他测试期间被部分覆盖。 +- 边界检查算术返回了不正确的范围。 -**Fix.** Un挂载, run `fsck_ffs -y /dev/myblk0` to repair, then re-test. If the error recurs with fresh 文件系统, look for offset-computation bugs in the strategy function. +**修复。**卸载、运行`fsck_ffs -y /dev/myblk0`修复,然后重新测试。如果错误在全新文件系统上重现,在策略函数中寻找偏移计算bug。 -### Kernel Printing "interrupt storm" Messages +### 内核打印"interrupt storm"消息 -**Symptom.** `dmesg` shows messages about interrupt storms, and system responsiveness degrades. +**症状。**`dmesg`显示关于中断风暴的消息,系统响应性下降。 -**Likely causes.** +**可能原因。** -- A real hardware 驱动程序 (not yours) is misbehaving. -- Your 驱动程序 is fine; this is a different subsystem's problem. +- 一个真正的硬件驱动程序(不是你的)行为不当。 +- 你的驱动程序没问题;这是另一个子系统的问题。 -**Fix.** Verify that the storm is not related to your module. If it is, the issue is almost certainly in an 中断处理程序, which our pseudo 驱动程序 does not have. +**修复。**验证风暴与你的模块无关。如果是的话,问题几乎可以肯定在中断处理器中,而我们的伪驱动程序没有中断处理器。 -### Reboot Hangs on Un挂载 During Shutdown +### 关机时重启挂在卸载上 -**Symptom.** On shutdown, the system hangs while 卸载ing, with a message like "Syncing disks, vnodes remaining...". +**症状。**关机时,系统在卸载时挂住,显示类似"Syncing disks, vnodes remaining..."的消息。 -**Likely causes.** +**可能原因。** -- A 文件系统 is still 挂载ed on your 设备, and your 驱动程序 is holding a BIO. -- A syncer thread is stuck waiting for completion. +- 一个文件系统仍然挂载在你的设备上,你的驱动程序持有一个BIO。 +- 一个同步线程卡在等待完成。 -**Fix.** Ensure your 驱动程序 卸载s cleanly before system shutdown. A ro总线t way is to add a `shutdown_post_sync` event handler that 卸载s the 文件系统 and unloads the module. For development, 卸载 and unload manually before issuing `shutdown -r now`. +**修复。**确保你的驱动程序在系统关机前干净地卸载。一个健壮的方法是添加一个`shutdown_post_sync`事件处理器来卸载文件系统并卸载模块。对于开发,在发出`shutdown -r now`之前手动卸载并卸载模块。 -### General Advice +### 一般建议 -Whenever something goes wrong, the first step is to read `dmesg` and look for messages from your own printfs and from 内核 subsystems. The second step is to run `procstat -kk` and look at what threads are doing. The third step is to consult `gstat`, `geom disk list`, and `geom -t` for the storage topology. These three tools will tell you most of what you need in nearly every case. +每当出现问题时,第一步是阅读`dmesg`并查找来自你自己printf和内核子系统的消息。第二步是运行`procstat -kk`并查看线程在做什么。第三步是查阅`gstat`、`geom disk list`和`geom -t`了解存储拓扑。这三个工具在几乎每种情况下都会告诉你大部分你需要的信息。 -If a panic happens, FreeBSD drops you into the debugger. Capture a backtrace with `bt` and a 注册 dump with `show 寄存器`, then reboot with `reboot`. If a crash dump was taken, `kgdb` on `/var/crash/vmcore.last` will let you inspect the state offline. Keeping crash dumps around, at least in a development environment, pays off immediately when you are chasing intermittent bugs. +如果发生崩溃,FreeBSD会把你放进调试器。用`bt`捕获回溯,用`show registers`进行寄存器转储,然后用`reboot`重启。如果获取了崩溃转储,`kgdb`可以让你离线检查`/var/crash/vmcore.last`上的状态。保留崩溃转储,至少在开发环境中,当你追踪间歇性bug时会立即产生回报。 -And above all, when something fails, try to reproduce it. Intermittent bugs in 存储驱动程序 are almost always caused by timing differences in how many BIOs are in flight, how long they take, and when the scheduler decides to run your thread. If you can find a reliable reproduction, you are most of the way to a fix. +最重要的是,当某个东西失败时,尝试重现它。存储驱动程序中的间歇性bug几乎总是由有多少BIO在飞行中、它们花费多长时间以及调度器何时决定运行你的线程等时间差异引起的。如果你能找到可靠的重现方法,你就距离修复已经走了一大半。 ## 总结 -This has been a long chapter. Let us take a moment to step back and see what we have covered. +这是一章很长的内容。让我们花点时间退后一步,看看我们涵盖了什么。 -We started by situating 存储驱动程序 in FreeBSD's layered architecture. The Virtual File System layer sits between system calls and 文件系统, giving every 文件系统 a common shape. `devfs` is itself a 文件系统, providing the `/dev` directory that user-space tools and administrators use to refer to 设备. Storage 驱动程序 do not live inside VFS. They live at the bottom of the stack, below GEOM and below the 缓冲区 cache, and they communicate with the rest of the 内核 through `struct bio`. +我们从将存储驱动程序置于FreeBSD的分层架构中开始。虚拟文件系统层位于系统调用和文件系统之间,给每个文件系统一个共同的形状。`devfs`本身是一个文件系统,提供用户空间工具和管理员用来引用设备的`/dev`目录。存储驱动程序不在VFS内部。它们位于栈的底部,在GEOM之下,在缓冲区缓存之下,通过`struct bio`与内核的其余部分通信。 -We built a working pseudo 块 设备驱动程序 from scratch. In Section 3 we wrote the skeleton that 注册ed a disk with `g_disk` and published a `/dev` node. In Section 4 we explored GEOM's concepts of classes, geoms, providers, and consumers, and we understood how the topology composes and how access counts keep the system safe during teardown. In Section 5 we implemented the strategy function that actually services `BIO_READ`, `BIO_WRITE`, `BIO_DELETE`, and `BIO_FLUSH` against an in-memory backing store. In Section 6 we formatted the 设备 with `newfs_ufs`, 挂载ed a real 文件系统 on it, and saw the two access paths (raw and 文件系统) converge in our strategy function. In Section 7 we surveyed persistence options and added a simple technique for surviving module reloads. In Section 8 we walked through the teardown path in detail and learned how to test it. In Section 9 we looked at the directions a growing 驱动程序 tends to go: multi-unit support, ioctl surfaces, source-file splits, and stable versioning. +我们从零开始构建了一个可工作的伪块设备驱动程序。在第3节中,我们编写了用`g_disk`注册磁盘并发布`/dev`节点的骨架。在第4节中,我们探索了GEOM的类、geom、提供者和消费者的概念,并理解了拓扑如何组合以及访问计数如何在拆卸期间保持系统安全。在第5节中,我们实现了针对内存后备存储实际服务`BIO_READ`、`BIO_WRITE`、`BIO_DELETE`和`BIO_FLUSH`的策略函数。在第6节中,我们用`newfs_ufs`格式化设备,在其上挂载了真正的文件系统,并看到两条访问路径(原始和文件系统)在我们的策略函数中汇合。在第7节中,我们调查了持久性选项并添加了存活模块重载的简单技术。在第8节中,我们详细遍历了拆卸路径并学习了如何测试它。在第9节中,我们看了增长的驱动程序倾向于去的方向:多单元支持、ioctl表面、源文件拆分和稳定版本管理。 -We exercised the 驱动程序 through labs and stretched it with challenges. We collected the common failure modes in a troubleshooting section. And throughout, we kept our eyes on the real FreeBSD source tree, because the goal of this book is not to teach toy 内核 code but to teach the real thing. +我们通过实验练习了驱动程序,通过挑战扩展了它。我们在故障排除部分收集了常见的故障模式。在整个过程中,我们将目光保持在真实的FreeBSD源码树上,因为本书的目标不是教授玩具内核代码,而是教授真正的代码。 -You should now be able to read `md(4)` with real comprehension rather than just staring at it. You should be able to read `g_zero.c` and recognise every function it calls. You should be able to diagnose the common classes of storage-驱动程序 bug by symptom. And you should have a working, if simple, pseudo 块设备 that you wrote yourself. +你现在应该能够真正理解地阅读`md(4)`,而不仅仅是盯着它看。你应该能够阅读`g_zero.c`并识别它调用的每个函数。你应该能够通过症状诊断存储驱动程序bug的常见类别。你应该有一个可工作的、虽然简单的、你自己编写的伪块设备。 -That is a substantial 挂载 of ground covered. Take a moment to notice how far you have come. In 第26章 you knew how to write a character 驱动程序. Now you can also write a 块 驱动程序. The two chapters together give you the foundation for nearly every other kind of 驱动程序 in FreeBSD, because most 驱动程序 are either character-oriented or 块-oriented at the boundary where they meet the rest of the 内核. +这是覆盖的大量内容。花点时间注意你已经走了多远。在第26章中,你知道如何编写字符驱动程序。现在你也可以编写块驱动程序了。这两章一起为你提供了FreeBSD中几乎所有其他类型驱动程序的基础,因为大多数驱动程序在与内核的其余部分相遇的边界上要么是面向字符的,要么是面向块的。 -### A Summary of the Key Moves +### 关键操作总结 -For quick recall, here are the moves that define a minimal 存储驱动程序. +为了快速回忆,以下是定义最小存储驱动程序的操作。 -1. Include the right headers: `sys/bio.h`, `geom/geom.h`, `geom/geom_disk.h`. -2. Allocate a `struct disk` with `disk_alloc`. -3. Fill in `d_name`, `d_unit`, `d_strategy`, `d_扇区ize`, `d_mediasize`, `d_maxsize`, and `d_drv1`. -4. Call `disk_create(sc->disk, DISK_VERSION)`. -5. In `d_strategy`, switch on `bio_cmd` and service the request. Always call `biodone` exactly once. -6. In the unload path, call `disk_destroy` before freeing anything the strategy function touches. -7. Declare `MODULE_DEPEND` on `g_disk`. -8. Use `MAXPHYS` for `d_maxsize` unless you have a specific reason to be smaller. -9. Test the unload path under load. Test it with a 挂载ed 文件系统. Test it with a raw `cat` holding the 设备 open. -10. Read `dmesg`, `gstat`, `geom disk list`, and `procstat -kk` when something goes wrong. +1. 包含正确的头文件:`sys/bio.h`、`geom/geom.h`、`geom/geom_disk.h`。 +2. 用`disk_alloc`分配`struct disk`。 +3. 填充`d_name`、`d_unit`、`d_strategy`、`d_sectorsize`、`d_mediasize`、`d_maxsize`和`d_drv1`。 +4. 调用`disk_create(sc->disk, DISK_VERSION)`。 +5. 在`d_strategy`中,对`bio_cmd`进行switch并服务请求。始终恰好调用`biodone`一次。 +6. 在卸载路径中,在释放策略函数触及的任何内容之前调用`disk_destroy`。 +7. 声明`MODULE_DEPEND`依赖于`g_disk`。 +8. 除非有特定理由使用更小的值,否则对`d_maxsize`使用`MAXPHYS`。 +9. 在负载下测试卸载路径。在文件系统挂载时测试。在原始`cat`持有设备打开时测试。 +10. 出问题时阅读`dmesg`、`gstat`、`geom disk list`和`procstat -kk`。 -These ten moves are the skeleton of every FreeBSD 存储驱动程序 you will ever write. They appear in different clothing in `ada(4)`, in `nvme(4)`, in `mmcsd(4)`, in `zvol(4)`, and in every other 驱动程序 in the tree. Once you see the pattern, the variety across real 驱动程序 becomes much less mysterious. +这十个操作是你将编写的每个FreeBSD存储驱动程序的骨架。它们在`ada(4)`、`nvme(4)`、`mmcsd(4)`、`zvol(4)`和源码树中的每个其他驱动程序中以不同形式出现。一旦你看到这个模式,真实驱动程序之间的变化就不那么神秘了。 -### A Reminder About Raw Access +### 关于原始访问的提醒 -Even with a 文件系统 挂载ed, your 驱动程序 is still reachable as a raw 块设备. `/dev/myblk0` remains a valid handle that tools like `dd`, `diskinfo`, `gstat`, and `dtrace` can use. The two access paths coexist through GEOM's discipline: both paths issue BIOs, both paths respect the access counts, and your strategy function services both without distinguishing between them. That uniformity is the great gift of GEOM to storage-驱动程序 authors. +即使文件系统已挂载,你的驱动程序仍然可以作为原始块设备访问。`/dev/myblk0`仍然是一个有效的句柄,`dd`、`diskinfo`、`gstat`和`dtrace`等工具可以使用它。两条访问路径通过GEOM的纪律共存:两条路径都发出BIO,两条路径都遵守访问计数,你的策略函数服务两者而不区分它们。这种统一性是GEOM给予存储驱动程序作者的巨大礼物。 -### A Reminder About Safety +### 关于安全的提醒 -Working on a shared system while developing a 存储驱动程序 is an invitation for pain. Use a virtual machine, or at the very least a system you can reinstall. Keep a rescue image handy. Keep backups of anything you cannot afford to lose, including code you are in the middle of writing. The chapter's 驱动程序 is well-behaved and should not damage anything, but 驱动程序 you write in the future may not be, and the cost of being prepared is very small compared to the cost of being unprepared. +在共享系统上开发存储驱动程序是自找麻烦。使用虚拟机,或至少使用一个你可以重新安装的系统。保持救援镜像在手。备份你无法承受丢失的任何东西,包括你正在编写中的代码。本章的驱动程序行为良好,不应该损坏任何东西,但你将来编写的驱动程序可能不会,而且准备的成本与未准备的代价相比非常小。 -### Where to Look Next in the FreeBSD Tree +### 在FreeBSD源码树中接下来看什么 -If you want to keep exploring storage before the next chapter, three areas of the tree repay careful reading. +如果你想在下一章之前继续探索存储,源码树中有三个领域值得仔细阅读。 -- `/usr/src/sys/geom/` has the GEOM 框架 itself, including `g_class`, `g_disk`, and many transformation classes like `g_mirror`, `g_stripe`, and `g_eli`. -- `/usr/src/sys/dev/md/md.c` is the full-featured memory-disk 驱动程序, already mentioned many times in this chapter. -- `/usr/src/sys/ufs/` is the UFS 文件系统. Not required reading for 驱动程序 work, but it helps to see the layer immediately above yours. +- `/usr/src/sys/geom/`有GEOM框架本身,包括`g_class`、`g_disk`和许多变换类如`g_mirror`、`g_stripe`和`g_eli`。 +- `/usr/src/sys/dev/md/md.c`是功能齐全的内存磁盘驱动程序,本章已经多次提到。 +- `/usr/src/sys/ufs/`是UFS文件系统。不是驱动程序工作的必读内容,但它有助于了解你上面那层的样子。 -Reading these is not a prerequisite for the next chapter. It is a recommendation for your own growth. +阅读这些不是下一章的先决条件。这是对你自身成长的建议。 -## Bridge to the Next Chapter +## 通向下一章的桥梁 -In this chapter we built a 存储驱动程序 from scratch. The data flowing through it was internal to the system: bytes written to a file, bytes read from a file, super块 and cylinder groups and inodes shuffling around in the 缓冲区 cache. No byte ever left the machine. The 驱动程序's entire world was the 内核's own memory and the processes that consume it. +在本章中,我们从零开始构建了一个存储驱动程序。流经其中的数据是系统内部的:写入文件的字节、从文件读取的字节、在缓冲区缓存中来回移动的超级块、柱面组和inode。没有字节离开过机器。驱动程序的整个世界是内核自己的内存和消费它的进程。 -第28章 takes us into a different world. We will write a 网络接口 驱动程序. Network 驱动程序 are transport 驱动程序 like the USB 串行驱动程序 of 第26章 and the 存储驱动程序 of this chapter, but their conversation partner is not a process and not a 文件系统. It is a network stack, and the unit of work is not a byte range and not a 块 but a 数据包. The 数据包 is a structured object with headers and payload, and the 驱动程序 participates in a stack that includes IP, ARP, ICMP, TCP, UDP, and many other protocols. +第28章将我们带入一个不同的世界。我们将编写一个网络接口驱动程序。网络驱动程序是传输驱动程序,就像第26章的USB串行驱动程序和本章的存储驱动程序一样,但它们的对话伙伴不是进程也不是文件系统。它是一个网络栈,工作单位不是字节范围也不是块,而是数据包。数据包是带有头部和有效载荷的结构化对象,驱动程序参与包括IP、ARP、ICMP、TCP、UDP和许多其他协议在内的栈。 -The patterns you have internalised in this chapter will reappear, with different names. Instead of `struct bio`, you will see `struct mbuf`. Instead of `g_disk`, you will see the `ifnet` 接口. Instead of `disk_strategy`, you will see the `if_transmit` and `if_input` hooks. Instead of GEOM providers and consumers, you will see 网络接口 objects linked into the 内核's network stack. The role is the same: a transport 驱动程序 takes requests from above, delivers them below, accepts responses below, and delivers them above. +你本章内化的模式将以不同的名称重新出现。你将看到`struct mbuf`代替`struct bio`。你将看到`ifnet`接口代替`g_disk`。你将看到`if_transmit`和`if_input`钩子代替`disk_strategy`。你将看到链接到内核网络栈中的网络接口对象代替GEOM提供者和消费者。角色是相同的:传输驱动程序从上面接收请求,向下传递,从下面接受响应,向上传递。 -Many of the concerns will also be the same. Locking. Hot unplug. Resource cleanup on 分离. Observability through 内核 tools. Safety in the face of errors. The fundamentals carry over. What changes is the vocabulary, the structure of the unit of work, and some of the specific tools. +许多关注点也是相同的。锁。热拔出。分离时的资源清理。通过内核工具的可观测性。面对错误时的安全性。基础延续了下来。改变的是词汇、工作单元的结构以及一些特定工具。 -Before you move on, take a short break. Unload your 存储驱动程序. Run `kldstat` and confirm that nothing from this chapter is still loaded. Close your lab logbook. Stand up. Refill your coffee. The next chapter is going to be just as substantive as this one, and you will want a clear head. +在继续之前,短暂休息一下。卸载你的存储驱动程序。运行`kldstat`确认本章的任何东西都不再加载。合上你的实验日志。站起来。续杯咖啡。下一章将与本章一样充实,你需要一个清醒的头脑。 -When you come back, 第28章 will start the same way this one did: with a gentle 引言 and a clear picture of where we are going. See you there. +当你回来时,第28章将以与本章相同的方式开始:一个温和的引言和一幅清晰的路线图。在那里见。 ## 快速参考 -The tables below are intended as a quick lookup when you are writing or debugging a 存储驱动程序 and need to remember a name, a command, or a path. They are not a substitute for the full explanations earlier in the chapter. +下面的表格旨在作为你在编写或调试存储驱动程序时快速查找名称、命令或路径的参考。它们不是本章前面完整解释的替代品。 -### Key Headers +### 关键头文件 -| Header | Defines | -|--------|---------| -| `sys/bio.h` | `struct bio`, `BIO_READ`, `BIO_WRITE`, `BIO_DELETE`, `BIO_FLUSH`, `BIO_GETATTR` | -| `geom/geom.h` | `struct g_class`, `struct g_geom`, `struct g_provider`, `struct g_consumer`, topology primitives | -| `geom/geom_disk.h` | `struct disk`, `DISK_VERSION`, `disk_alloc`, `disk_create`, `disk_destroy`, `disk_gone` | -| `sys/module.h` | `DECLARE_MODULE`, `MODULE_VERSION`, `MODULE_DEPEND` | -| `sys/malloc.h` | `MALLOC_DEFINE`, `malloc`, `free`, `M_WAITOK`, `M_NOWAIT`, `M_ZERO` | -| `sys/lock.h`, `sys/互斥锁.h` | `struct mtx`, `mtx_init`, `mtx_lock`, `mtx_unlock`, `mtx_destroy` | +| 头文件 | 定义 | +|--------|------| +| `sys/bio.h` | `struct bio`、`BIO_READ`、`BIO_WRITE`、`BIO_DELETE`、`BIO_FLUSH`、`BIO_GETATTR` | +| `geom/geom.h` | `struct g_class`、`struct g_geom`、`struct g_provider`、`struct g_consumer`、拓扑原语 | +| `geom/geom_disk.h` | `struct disk`、`DISK_VERSION`、`disk_alloc`、`disk_create`、`disk_destroy`、`disk_gone` | +| `sys/module.h` | `DECLARE_MODULE`、`MODULE_VERSION`、`MODULE_DEPEND` | +| `sys/malloc.h` | `MALLOC_DEFINE`、`malloc`、`free`、`M_WAITOK`、`M_NOWAIT`、`M_ZERO` | +| `sys/lock.h`、`sys/mutex.h` | `struct mtx`、`mtx_init`、`mtx_lock`、`mtx_unlock`、`mtx_destroy` | -### Key Structures +### 关键结构 -| Structure | Role | -|-----------|------| -| `struct disk` | The `g_disk` representation of a disk. Filled in by the 驱动程序, owned by the 框架. | -| `struct bio` | One I/O request, passed between GEOM layers and into the 驱动程序's strategy function. | -| `struct g_provider` | The producer-facing 接口 of a geom. Filesystems and other geoms consume from providers. | -| `struct g_consumer` | The connection from one geom into another geom's provider. | -| `struct g_geom` | An instance of a `g_class`. | -| `struct g_class` | The template from which geoms are created. Defines methods like `init`, `fini`, `start`, `access`. | +| 结构 | 角色 | +|------|------| +| `struct disk` | `g_disk`对磁盘的表示。由驱动程序填充,由框架拥有。 | +| `struct bio` | 一个I/O请求,在GEOM层之间传递并进入驱动程序的策略函数。 | +| `struct g_provider` | geom的面向生产者接口。文件系统和其他geom从提供者消费。 | +| `struct g_consumer` | 从一个geom到另一个geom提供者的连接。 | +| `struct g_geom` | `g_class`的一个实例。 | +| `struct g_class` | 创建geom的模板。定义`init`、`fini`、`start`、`access`等方法。 | -### Common BIO Commands +### 常见BIO命令 -| Command | Meaning | -|---------|---------| -| `BIO_READ` | Read bytes from the 设备 into a 缓冲区. | -| `BIO_WRITE` | Write bytes from a 缓冲区 into the 设备. | -| `BIO_DELETE` | Discard a range of 块. Used for TRIM. | -| `BIO_FLUSH` | Commit outstanding writes to durable storage. | -| `BIO_GETATTR` | Query a named attribute from the provider. | -| `BIO_ZONE` | Zoned-块-设备 operations. Not commonly used. | +| 命令 | 含义 | +|------|------| +| `BIO_READ` | 从设备读取字节到缓冲区。 | +| `BIO_WRITE` | 从缓冲区写入字节到设备。 | +| `BIO_DELETE` | 丢弃一个范围的块。用于TRIM。 | +| `BIO_FLUSH` | 将未完成的写入提交到持久存储。 | +| `BIO_GETATTR` | 从提供者查询命名属性的值。 | +| `BIO_ZONE` | 分区块设备操作。不常用。 | -### Common GEOM Tools +### 常见GEOM工具 -| Tool | Purpose | -|------|---------| -| `geom disk list` | List 注册ed disks and their providers. | -| `geom -t` | Show the entire GEOM topology as a tree. | -| `geom part show` | Show 分区 geoms and their providers. | -| `gstat` | Live per-provider I/O statistics. | -| `diskinfo -v /dev/xxx` | Show disk geometry and attributes. | -| `iostat -x 1` | Live per-设备 throughput and latency. | -| `dd if=... of=...` | Raw 块 I/O for testing. | -| `newfs_ufs /dev/xxx` | Create a UFS 文件系统 on a 设备. | -| `挂载 /dev/xxx /mnt` | Mount a 文件系统. | -| `u挂载 /mnt` | Un挂载 a 文件系统. | -| `mdconfig` | Create or destroy memory disks. | -| `fuser` | Find processes holding a file open. | -| `procstat -kk` | Show 内核 stack traces for all threads. | +| 工具 | 用途 | +|------|------| +| `geom disk list` | 列出已注册的磁盘及其提供者。 | +| `geom -t` | 以树形显示整个GEOM拓扑。 | +| `geom part show` | 显示分区geom及其提供者。 | +| `gstat` | 实时每提供者I/O统计。 | +| `diskinfo -v /dev/xxx` | 显示磁盘几何参数和属性。 | +| `iostat -x 1` | 实时每设备吞吐量和延迟。 | +| `dd if=... of=...` | 用于测试的原始块I/O。 | +| `newfs_ufs /dev/xxx` | 在设备上创建UFS文件系统。 | +| `mount /dev/xxx /mnt` | 挂载文件系统。 | +| `umount /mnt` | 卸载文件系统。 | +| `mdconfig` | 创建或销毁内存磁盘。 | +| `fuser` | 找到持有文件打开的进程。 | +| `procstat -kk` | 显示所有线程的内核栈跟踪。 | -### Key Callback Typedefs +### 关键回调类型定义 -| Typedef | Purpose | -|---------|---------| -| `disk_strategy_t` | Handles BIOs. The core I/O function. Required. | -| `disk_open_t` | Called when a new access is being granted. Optional. | -| `disk_close_t` | Called when an access is being released. Optional. | -| `disk_ioctl_t` | Handles ioctls on the `/dev` node. Optional. | -| `disk_getattr_t` | Answers `BIO_GETATTR` queries. Optional. | -| `disk_gone_t` | Notifies the 驱动程序 when the disk is being forced away. Optional. | +| 类型定义 | 用途 | +|---------|------| +| `disk_strategy_t` | 处理BIO。核心I/O函数。必需。 | +| `disk_open_t` | 当授予新访问时调用。可选。 | +| `disk_close_t` | 当释放访问时调用。可选。 | +| `disk_ioctl_t` | 处理`/dev`节点上的ioctl。可选。 | +| `disk_getattr_t` | 回答`BIO_GETATTR`查询。可选。 | +| `disk_gone_t` | 当磁盘被强制移除时通知驱动程序。可选。 | -### File and Path Reference +### 文件和路径参考 -| Path | What lives there | -|------|------------------| -| `/usr/src/sys/geom/geom_disk.c` | The `g_disk` implementation. | -| `/usr/src/sys/geom/geom_disk.h` | The public `g_disk` 接口. | -| `/usr/src/sys/geom/geom.h` | Core GEOM structures and functions. | -| `/usr/src/sys/sys/bio.h` | The `struct bio` definition. | -| `/usr/src/sys/dev/md/md.c` | The reference memory-disk 驱动程序. | -| `/usr/src/sys/geom/zero/g_zero.c` | A minimal GEOM class, useful as a reading reference. | -| `/usr/src/sys/ufs/ffs/ffs_vfsops.c` | UFS's 挂载 path. Read if you want to see what 挂载 does at the 文件系统 side. | -| `/usr/src/share/man/man9/disk.9` | The `disk(9)` manual page. | -| `/usr/src/share/man/man9/g_bio.9` | The `g_bio(9)` manual page. | +| 路径 | 包含内容 | +|------|----------| +| `/usr/src/sys/geom/geom_disk.c` | `g_disk`实现。 | +| `/usr/src/sys/geom/geom_disk.h` | 公共`g_disk`接口。 | +| `/usr/src/sys/geom/geom.h` | 核心GEOM结构和函数。 | +| `/usr/src/sys/sys/bio.h` | `struct bio`定义。 | +| `/usr/src/sys/dev/md/md.c` | 参考内存磁盘驱动程序。 | +| `/usr/src/sys/geom/zero/g_zero.c` | 最小GEOM类,作为阅读参考很有用。 | +| `/usr/src/sys/ufs/ffs/ffs_vfsops.c` | UFS的挂载路径。如果你想看挂载在文件系统侧做了什么就阅读它。 | +| `/usr/src/share/man/man9/disk.9` | `disk(9)`手册页。 | +| `/usr/src/share/man/man9/g_bio.9` | `g_bio(9)`手册页。 | -### Common Disk Flags +### 常见磁盘标志 -| Flag | Meaning | -|------|---------| -| `DISKFLAG_CANDELETE` | The 驱动程序 handles `BIO_DELETE`. | -| `DISKFLAG_CANFLUSHCACHE` | The 驱动程序 handles `BIO_FLUSH`. | -| `DISKFLAG_UNMAPPED_BIO` | The 驱动程序 accepts unmapped BIOs (advanced). | -| `DISKFLAG_WRITE_PROTECT` | The 设备 is read-only. | -| `DISKFLAG_DIRECT_COMPLETION` | Completion is safe from any context (advanced). | +| 标志 | 含义 | +|------|------| +| `DISKFLAG_CANDELETE` | 驱动程序处理`BIO_DELETE`。 | +| `DISKFLAG_CANFLUSHCACHE` | 驱动程序处理`BIO_FLUSH`。 | +| `DISKFLAG_UNMAPPED_BIO` | 驱动程序接受未映射的BIO(高级)。 | +| `DISKFLAG_WRITE_PROTECT` | 设备是只读的。 | +| `DISKFLAG_DIRECT_COMPLETION` | 完成在任何上下文中都是安全的(高级)。 | -These flags are set on `sc->disk->d_flags` before `disk_create`. They let the 内核 make smarter choices about how to issue BIOs to your 驱动程序. +这些标志在`disk_create`之前设置在`sc->disk->d_flags`上。它们让内核对如何向你的驱动程序发出BIO做出更智能的选择。 -### Patterns for d_strategy +### d_strategy的模式 -Here are the three most common shapes of a strategy function. +以下是策略函数最常见的三种形状。 -**Pattern 1: Synchronous, in-memory.** Our 驱动程序 uses this. The function serves the BIO inline and returns after calling `biodone`. +**模式1:同步、内存中。**我们的驱动程序使用这种方式。函数内联服务BIO并在调用`biodone`后返回。 ```c void strategy(struct bio *bp) { @@ -3660,7 +3660,7 @@ void strategy(struct bio *bp) { } ``` -**Pattern 2: Enqueue to a worker thread.** `md(4)` uses this. The function 附加 the BIO to a queue and signals a worker. +**模式2:排队到工作线程。**`md(4)`使用这种方式。函数将BIO附加到队列并唤醒工作线程。 ```c void strategy(struct bio *bp) { @@ -3671,9 +3671,9 @@ void strategy(struct bio *bp) { } ``` -The worker dequeues BIOs, services them one at a time (perhaps calling `vn_rdwr` or issuing hardware commands), and completes each with `biodone`. +工作线程出队BIO,逐个服务它们(可能调用`vn_rdwr`或发出硬件命令),并用`biodone`完成每个。 -**Pattern 3: Hardware DMA with interrupt completion.** Real hardware 驱动程序 use this. The function programs the hardware, sets up DMA, and returns. A later 中断处理程序 completes the BIO. +**模式3:带中断完成的硬件DMA。**真正的硬件驱动程序使用这种方式。函数编程硬件、设置DMA并返回。稍后的中断处理器完成BIO。 ```c void strategy(struct bio *bp) { @@ -3683,13 +3683,13 @@ void strategy(struct bio *bp) { } ``` -Each pattern has trade-offs. Pattern 1 is simplest but cannot 块. Pattern 2 handles 块ing work but adds latency. Pattern 3 is needed for real hardware but requires interrupt handling, which adds a whole other layer of complexity. +每种模式都有权衡。模式1最简单但不能阻塞。模式2处理阻塞工作但增加延迟。模式3是真正硬件所必需的,但需要中断处理,这增加了整个另一层复杂性。 -Our chapter 驱动程序 uses Pattern 1. `md(4)` uses Pattern 2. `ada(4)`, `nvme(4)`, and friends use Pattern 3. +我们的章节驱动程序使用模式1。`md(4)`使用模式2。`ada(4)`、`nvme(4)`等使用模式3。 -### Minimum Registration Sequence +### 最小注册序列 -For the 驱动程序 writer in a hurry, the minimum sequence to 注册 a 块设备 is: +对于匆忙的驱动程序编写者,注册块设备的最小序列是: ```c sc->disk = disk_alloc(); @@ -3703,7 +3703,7 @@ sc->disk->d_drv1 = sc; disk_create(sc->disk, DISK_VERSION); ``` -And the minimum teardown sequence is: +最小拆卸序列是: ```c disk_destroy(sc->disk); @@ -3714,362 +3714,362 @@ free(sc, M_MYBLK); ## 术语表 -**Access count.** A tuple of three counters on a GEOM provider that tracks how many readers, writers, and exclusive holders currently have access to it. Displayed as `rNwNeN` in `geom disk list`. +**Access count(访问计数)。**GEOM提供者上三个计数器的元组,跟踪当前有多少读取者、写入者和独占持有者正在访问它。在`geom disk list`中显示为`rNwNeN`。 -**Attach.** In the New总线 sense, the step where a 驱动程序 takes responsibility for a 设备. In the storage sense, the step where the 驱动程序 calls `disk_create` to 注册 with `g_disk`. The word overloads; use context. +**Attach(附加)。**在Newbus意义上,驱动程序接管设备的步骤。在存储意义上,驱动程序调用`disk_create`向`g_disk`注册的步骤。这个词有重载;请根据上下文理解。 -**Backing store.** The place where the bytes of a storage 设备 actually live. For our 驱动程序, the backing store is a `malloc`'d 缓冲区 in 内核 memory. For real disks, it is the platter or the flash. For `md(4)` in vnode mode, it is a file in the host 文件系统. +**Backing store(后备存储)。**存储设备字节实际存在的地方。对于我们的驱动程序,后备存储是内核内存中`malloc`分配的缓冲区。对于真正的磁盘,它是盘片或闪存。对于vnode模式的`md(4)`,它是主机文件系统中的文件。 -**BIO.** A `struct bio`. The unit of I/O that flows through GEOM. +**BIO。**一个`struct bio`。流经GEOM的I/O单位。 -**BIO_DELETE.** A BIO command that asks the 驱动程序 to discard a range of 块. Used for TRIM on SSDs. +**BIO_DELETE。**要求驱动程序丢弃一个范围的块的BIO命令。用于SSD上的TRIM。 -**BIO_FLUSH.** A BIO command that asks the 驱动程序 to make all previous writes durable before returning. +**BIO_FLUSH。**要求驱动程序在返回前使所有先前写入持久的BIO命令。 -**BIO_GETATTR.** A BIO command that asks the 驱动程序 to return the value of a named attribute. +**BIO_GETATTR。**要求驱动程序返回命名属性值的BIO命令。 -**BIO_READ.** A BIO command that asks the 驱动程序 to read a range of bytes. +**BIO_READ。**要求驱动程序读取一个范围字节的BIO命令。 -**BIO_WRITE.** A BIO command that asks the 驱动程序 to write a range of bytes. +**BIO_WRITE。**要求驱动程序写入一个范围字节的BIO命令。 -**Block 设备.** A 设备 that is addressed in fixed-size 块, with seekable random access. Historically distinct from 字符设备 in BSD; in modern FreeBSD, 块 and character access converge through GEOM but the mental distinction still matters. +**Block device(块设备)。**以固定大小的块寻址的设备,具有可寻道的随机访问。在BSD中历史上与字符设备不同;在现代FreeBSD中,块和字符访问通过GEOM收敛,但心理上的区分仍然重要。 -**Buffer cache.** The 内核 subsystem that holds recently used 文件系统 块 in RAM. Sits between 文件系统 and GEOM. Not to be confused with the page cache; they are related but distinct in FreeBSD. +**Buffer cache(缓冲区缓存)。**将最近使用的文件系统块保存在RAM中的内核子系统。位于文件系统和GEOM之间。不要与页缓存混淆;它们在FreeBSD中相关但不同。 -**Cache coherency.** The property that reads and writes see each other in a consistent order. The strategy function must not return data that is stale relative to recent writes on the same offset. +**Cache coherency(缓存一致性)。**读写以一致顺序看到彼此的属性。策略函数不能返回相对于同一偏移量上最近写入过时的数据。 -**Cdev.** A 字符设备 node as represented by `struct cdev`. Character 驱动程序 create them with `make_dev`. Block 驱动程序 usually do not. +**Cdev。**由`struct cdev`表示的字符设备节点。字符驱动程序用`make_dev`创建它们。块驱动程序通常不创建。 -**Consumer.** The input-facing side of a geom. A consumer 附加 to a provider and issues BIOs into it. +**Consumer(消费者)。**geom的面向输入的一侧。消费者附加到提供者并向其发出BIO。 -**d_drv1.** A generic pointer in `struct disk` where the 驱动程序 stores its private context, typically the softc. +**d_drv1。**`struct disk`中的通用指针,驱动程序在其中存储其私有上下文,通常是softc。 -**d_mediasize.** The total size of the 设备 in bytes. +**d_mediasize。**设备的总大小(字节)。 -**d_maxsize.** The largest single BIO the 驱动程序 can accept. Usually `MAXPHYS` for pseudo 设备. +**d_maxsize。**驱动程序可以接受的最大单个BIO。对伪设备通常为`MAXPHYS`。 -**d_扇区ize.** The size of a 扇区 in bytes. Typically 512 or 4096. +**d_sectorsize。**扇区大小(字节)。通常为512或4096。 -**d_strategy.** The 驱动程序's BIO-handling function. +**d_strategy。**驱动程序的BIO处理函数。 -**Devfs.** A pseudo-文件系统 挂载ed at `/dev` that synthesises file nodes for 内核 设备. +**Devfs。**挂载在`/dev`的伪文件系统,为内核设备合成文件节点。 -**Devstat.** The 内核's 设备 statistics subsystem, used by `iostat`, `gstat`, and others. Storage 驱动程序 using `g_disk` get devstat integration automatically. +**Devstat。**内核的设备统计子系统,被`iostat`、`gstat`等使用。使用`g_disk`的存储驱动程序自动获得devstat集成。 -**Disk_alloc.** Allocates a `struct disk`. Never fails; uses `M_WAITOK` internally. +**Disk_alloc。**分配`struct disk`。从不失败;内部使用`M_WAITOK`。 -**Disk_create.** Registers a filled-in `struct disk` with `g_disk`. The real work is done asynchronously. +**Disk_create。**向`g_disk`注册填充好的`struct disk`。实际工作异步完成。 -**Disk_destroy.** Un寄存器 and destroys a `struct disk`. Waits for in-flight BIOs to complete. Panics if the provider still has users. +**Disk_destroy。**注销并销毁`struct disk`。等待飞行中的BIO完成。如果提供者仍有用户则崩溃。 -**Disk_gone.** Notifies `g_disk` that the underlying media is gone. Used in 热拔出 scenarios. Distinct from `disk_destroy`. +**Disk_gone。**通知`g_disk`底层介质已消失。用于热拔出场景。与`disk_destroy`不同。 -**DISK_VERSION.** The ABI version of the `struct disk` 接口. Defined in `geom_disk.h` and passed to `disk_create`. +**DISK_VERSION。**`struct disk`接口的ABI版本。在`geom_disk.h`中定义,传递给`disk_create`。 -**DTrace.** FreeBSD's dynamic tracing facility. Especially useful for observing BIO traffic. +**DTrace。**FreeBSD的动态跟踪工具。对观察BIO流量特别有用。 -**Event thread.** The single 内核 thread that GEOM uses to process topology events such as creating and destroying geoms. Usually called `g_event` in `procstat` output. +**Event thread(事件线程)。**GEOM用于处理拓扑事件(如创建和销毁geom)的单一内核线程。在`procstat`输出中通常称为`g_event`。 -**Exclusive access.** A kind of access on a provider that forbids other writers. Filesystems acquire exclusive access on the 设备 they 挂载. +**Exclusive access(独占访问)。**提供者上禁止其他写入者的一种访问类型。文件系统在其挂载的设备上获取独占访问。 -**Filesystem.** A concrete implementation of file storage semantics, such as UFS, ZFS, tmpfs, or NFS. Plugs into VFS. +**Filesystem(文件系统)。**文件存储语义的具体实现,如UFS、ZFS、tmpfs或NFS。插入VFS。 -**GEOM.** The FreeBSD 框架 for composable 块-layer transformations. Classes, geoms, providers, and consumers are its main objects. +**GEOM。**FreeBSD的可组合块层变换框架。类、geom、提供者和消费者是其主要对象。 -**g_disk.** The GEOM subsystem that wraps disk-shaped 驱动程序 with a simpler API. Our 驱动程序 uses it. +**g_disk。**将磁盘形状的驱动程序包装为更简单API的GEOM子系统。我们的驱动程序使用它。 -**g_event.** The GEOM event thread that processes topology changes. +**g_event。**处理拓扑变更的GEOM事件线程。 -**g_io_deliver.** The function used at the class level to complete a BIO. `g_disk` calls it for us; our 驱动程序 calls `biodone`. +**g_io_deliver。**在类级别用于完成BIO的函数。`g_disk`为我们调用它;我们的驱动程序调用`biodone`。 -**g_io_request.** The function used at the class level to issue a BIO downward. Only used in 驱动程序 that implement their own GEOM class. +**g_io_request。**在类级别用于向下发出BIO的函数。仅在实现自己GEOM类的驱动程序中使用。 -**Hotplug.** A 设备 that can appear or disappear without reboot. +**Hotplug(热插拔)。**可以在不重启的情况下出现或消失的设备。 -**Ioctl.** A control operation on a 设备, distinct from read or write. In the storage path, ioctls on `/dev/diskN` go through GEOM and may be handled by `g_disk` or by the 驱动程序's `d_ioctl`. +**Ioctl。**设备上区别于读写的控制操作。在存储路径中,`/dev/diskN`上的ioctl通过GEOM,可能由`g_disk`或驱动程序的`d_ioctl`处理。 -**md(4).** The FreeBSD memory-disk 驱动程序. The canonical pseudo 块设备 in the tree, and a recommended reading reference. +**md(4)。**FreeBSD内存磁盘驱动程序。源码树中规范的伪块设备,推荐的阅读参考。 -**Mount.** The act of 附加ing a 文件系统 to a point in the namespace. Calls VFS, which calls the 文件系统's own 挂载 routine, which typically opens a GEOM provider. +**Mount(挂载)。**将文件系统附加到命名空间中某个点的行为。调用VFS,VFS调用文件系统自己的挂载例程,后者通常打开一个GEOM提供者。 -**New总线.** FreeBSD's 总线 框架. Used for character and hardware 驱动程序. Our 存储驱动程序 does not directly use New总线 because it is a pseudo 设备; real 存储驱动程序 almost always do. +**Newbus。**FreeBSD的总线框架。用于字符和硬件驱动程序。我们的存储驱动程序不直接使用Newbus,因为它是伪设备;真正的存储驱动程序几乎总是使用它。 -**Provider.** The output-facing side of a geom. Other geoms or `/dev` nodes consume providers. +**Provider(提供者)。**geom的面向输出的一侧。其他geom或`/dev`节点消费提供者。 -**Softc.** The per-instance state structure of a 驱动程序. +**Softc。**驱动程序的每实例状态结构。 -**Strategy function.** The 驱动程序's BIO handler. Called `d_strategy` in the `struct disk` API. +**Strategy function(策略函数)。**驱动程序的BIO处理器。在`struct disk` API中称为`d_strategy`。 -**Super块.** A small on-disk structure that describes the layout of a 文件系统. UFS's is at offset 65536. +**Superblock(超级块)。**描述文件系统布局的小型磁盘上结构。UFS的在偏移65536处。 -**Topology.** The tree of GEOM classes, geoms, providers, and consumers. Protected by the topology lock. +**Topology(拓扑)。**GEOM类、geom、提供者和消费者的树。受拓扑锁保护。 -**Topology lock.** The global lock protecting the GEOM topology from concurrent modification. +**Topology lock(拓扑锁)。**保护GEOM拓扑免受并发修改的全局锁。 -**UFS.** The Unix File System, FreeBSD's default 文件系统. Lives under `/usr/src/sys/ufs/`. +**UFS。**Unix文件系统,FreeBSD的默认文件系统。位于`/usr/src/sys/ufs/`下。 -**Unit.** A numbered instance of a 驱动程序. `myblk0` is unit 0 of the `myblk` 驱动程序. +**Unit(单元)。**驱动程序的一个编号实例。`myblk0`是`myblk`驱动程序的单元0。 -**VFS.** The Virtual File System layer. Sits between system calls and concrete 文件系统. +**VFS。**虚拟文件系统层。位于系统调用和具体文件系统之间。 -**Vnode.** The 内核's runtime handle on an open file or directory. Lives inside VFS. +**Vnode。**内核对打开文件或目录的运行时句柄。存在于VFS内部。 -**Withering.** The GEOM process of removing a provider from the topology. Queued on the event thread, waits for in-flight BIOs, and finally destroys the provider. +**Withering(枯萎)。**GEOM从拓扑中移除提供者的过程。在事件线程上排队,等待飞行中的BIO,最终销毁提供者。 -**Zone.** In VM-subsystem vocabulary, a pool of fixed-size objects allocated through the UMA (Universal Memory Allocator). Many 内核 structures, including BIOs and GEOM providers, are allocated from zones. +**Zone(区域)。**在VM子系统词汇中,通过UMA(通用内存分配器)分配的固定大小对象池。许多内核结构,包括BIO和GEOM提供者,从区域分配。 -**BIO_ORDERED.** A BIO flag that asks the 驱动程序 to execute this BIO only after all previously issued BIOs have completed. Used for write barriers. +**BIO_ORDERED。**要求驱动程序仅在所有先前发出的BIO完成后才执行此BIO的BIO标志。用于写屏障。 -**BIO_UNMAPPED.** A BIO flag that indicates `bio_data` is not a mapped 内核 virtual address but rather a list of unmapped pages. Drivers that can handle unmapped data should set `DISKFLAG_UNMAPPED_BIO`. +**BIO_UNMAPPED。**指示`bio_data`不是映射的内核虚拟地址而是未映射页面列表的BIO标志。可以处理未映射数据的驱动程序应设置`DISKFLAG_UNMAPPED_BIO`。 -**Direct completion.** Completing a BIO in the same thread that submitted it, without going through a deferred 回调. Usually faster but not always safe. +**Direct completion(直接完成)。**在提交BIO的同一线程中完成BIO,不经过延迟回调。通常更快但不总是安全的。 -**Drivers in Tree.** Drivers that live inside the FreeBSD source tree and are built as part of the standard 内核 build. Contrast with out-of-tree 驱动程序, which are maintained separately. +**Drivers in Tree(树内驱动程序)。**生活在FreeBSD源码树中并作为标准内核构建一部分构建的驱动程序。与树外驱动程序相对,后者单独维护。 -**Out-of-tree 驱动程序.** A 驱动程序 that is not part of the FreeBSD source tree. These need to be compiled against a matching 内核 and may need updates when the 内核's ABI changes. +**Out-of-tree drivers(树外驱动程序)。**不属于FreeBSD源码树的驱动程序。这些需要针对匹配的内核编译,在内核ABI更改时可能需要更新。 -**ABI.** Application Binary Interface. The set of conventions for function calling, structure layout, and type sizes that allow two pieces of compiled code to interoperate. `DISK_VERSION` is one kind of ABI marker. +**ABI。**应用二进制接口。允许两段编译代码互操作的函数调用、结构布局和类型大小约定的集合。`DISK_VERSION`是一种ABI标记。 -**API.** Application Programming Interface. The set of function signatures and types that code uses at the source level. Distinct from ABI: two 内核s with the same API might have different ABIs if they were compiled differently. +**API。**应用编程接口。代码在源码级别使用的函数签名和类型的集合。与ABI不同:两个具有相同API的内核如果编译方式不同,可能有不同的ABI。 -**KPI.** Kernel Programming Interface. FreeBSD's preferred term for the 内核's API. Guarantees about KPI stability are limited; always recompile against the 内核 you are running. +**KPI。**内核编程接口。FreeBSD对内核API的首选术语。对KPI稳定性的保证是有限的;始终针对你运行的内核重新编译。 -**KLD.** Kernel loadable module. The `.ko` file we produce. The "KLD" stands for Kernel Loadable Driver, though modules are not necessarily 驱动程序. +**KLD。**内核可加载模块。我们产生的`.ko`文件。"KLD"代表Kernel Loadable Driver,虽然模块不一定是驱动程序。 -**Module.** See KLD. +**Module(模块)。**参见KLD。 -**Taste.** In GEOM vocabulary, the process of offering a provider to all classes so that each class can decide whether to 附加 to it. Tasting happens automatically when new providers appear. +**Taste(品尝)。**在GEOM词汇中,将提供者提供给所有类以便每个类决定是否附加到它的过程。新提供者出现时品尝自动发生。 -**Retaste.** Forcing GEOM to taste a provider again, usually after its contents have changed. `geom provider retaste` triggers this for one provider; `geom retaste` triggers it globally. +**Retaste(重新品尝)。**强制GEOM再次品尝提供者,通常在其内容更改后。`geom provider retaste`对单个提供者触发此操作;`geom retaste`全局触发。 -**Orphan.** In GEOM vocabulary, a provider whose underlying storage has gone away. Orphans are cleaned up by the event thread. +**Orphan(孤儿)。**在GEOM词汇中,底层存储已消失的提供者。孤儿由事件线程清理。 -**Spoil.** A GEOM concept related to cache invalidation. If a provider's contents change in a way that could invalidate caches, it is said to have been spoiled. +**Spoil( spoil)。**与缓存失效相关的GEOM概念。如果提供者的内容以可能使缓存失效的方式更改,则称其已被spoiled。 -**Bufobj.** A 内核 object that associates a vnode (or a GEOM consumer) with a 缓冲区 cache. Each 块设备 and each file has one. +**Bufobj。**将vnode(或GEOM消费者)与缓冲区缓存关联的内核对象。每个块设备和每个文件都有一个。 -**bdev_strategy.** A legacy synonym for `d_strategy`. Modern code uses `d_strategy` directly. +**bdev_strategy。**`d_strategy`的遗留同义词。现代代码直接使用`d_strategy`。 -**Schedule.** The act of placing a BIO onto an internal queue for later execution. Distinct from "executing". +**Schedule(调度)。**将BIO放入内部队列以供稍后执行的行为。与"执行"不同。 -**Plug/unplug.** In some 内核s, the plug is a batching mechanism for BIO submission. FreeBSD does not have plug/unplug; it delivers BIOs immediately. +**Plug/unplug。**在某些内核中,plug是BIO提交的批处理机制。FreeBSD没有plug/unplug;它立即交付BIO。 -**Elevator.** A BIO scheduler that sorts BIOs by offset to reduce disk seek time. FreeBSD's GEOM does not implement an elevator at the GEOM layer; it is the 块设备's responsibility, if relevant. +**Elevator(电梯)。**按偏移量排序BIO以减少磁盘寻道时间的BIO调度器。FreeBSD的GEOM不在GEOM层实现电梯;如果相关的话,这是块设备的责任。 -**Super块.** The first metadata 块 of a 文件系统. Describes geometry. At offset 65536 for UFS. +**Superblock(超级块)。**文件系统的第一个元数据块。描述几何参数。对UFS在偏移65536处。 -**Cylinder group.** A UFS concept. The 文件系统 is divided into regions, each with its own inode table and 块 allocation bitmap. Keeps related data physically close on a spinning disk and limits the damage a single bad region can cause. +**Cylinder group(柱面组)。**UFS概念。文件系统被划分为区域,每个区域有自己的inode表和块分配位图。保持相关数据在旋转磁盘上物理接近,并限制单个坏区域可以造成的损害。 -**Inode.** A UFS (and POSIX) structure describing one file: its mode, owner, size, timestamps, and pointers to data 块. Filenames live in directory entries, not in inodes. +**Inode。**UFS(和POSIX)结构,描述一个文件:其模式、所有者、大小、时间戳和指向数据块的指针。文件名存在于目录条目中,不在inode中。 -**Vop_vector.** The dispatch table that a 文件系统 provides to VFS, listing all the operations VFS knows how to ask about (open, close, read, write, lookup, rename, and so on). VFS calls these as indirect function pointers. +**Vop_vector。**文件系统向VFS提供的分发表,列出VFS知道如何询问的所有操作(打开、关闭、读、写、查找、重命名等)。VFS将这些作为间接函数指针调用。 -**Devstat.** A 内核 structure 附加ed to 设备 that records aggregate I/O statistics. `iostat(8)` reads devstat data; `g_disk` allocates and feeds a devstat structure for every disk it creates. +**Devstat。**附加到设备上记录聚合I/O统计的内核结构。`iostat(8)`读取devstat数据;`g_disk`为其创建的每个磁盘分配并填充devstat结构。 -**bp.** Shorthand in 内核 source for a BIO pointer. Used almost universally in strategy functions and completion 回调. When you see `struct bio *bp`, read it as "the current request". +**bp。**内核源码中BIO指针的简写。在策略函数和完成回调中几乎普遍使用。当你看到`struct bio *bp`时,读作"当前请求"。 -**Bread.** Buffer-cache function that reads a 块, consulting the cache first and issuing I/O only on a miss. Used by 文件系统, not by 驱动程序. +**Bread。**缓冲区缓存函数,读取一个块,先查询缓存,仅在未命中时发出I/O。由文件系统使用,不由驱动程序使用。 -**Bwrite.** Buffer-cache function that writes a 块 synchronously. The 文件系统 uses it; your strategy function eventually sees the resulting BIO. +**Bwrite。**缓冲区缓存函数,同步写入一个块。文件系统使用它;你的策略函数最终看到产生的BIO。 -**Getblk.** Buffer-cache function that returns a 缓冲区 for a given 块, allocating it if necessary. Used by 文件系统 as the entry point to both reading and writing. +**Getblk。**缓冲区缓存函数,返回给定块的缓冲区,必要时分配它。由文件系统用作读取和写入的入口点。 -**Bdwrite.** Delayed 缓冲区-cache write. Marks the 缓冲区 dirty but does not issue I/O immediately. Will be written later by the syncer or by 缓冲区 cache pressure. +**Bdwrite。**延迟缓冲区缓存写入。将缓冲区标记为脏但不立即发出I/O。稍后由syncer或缓冲区缓存压力写入。 -**Bawrite.** Asynchronous 缓冲区-cache write. Like `bwrite` but does not wait for completion. +**Bawrite。**异步缓冲区缓存写入。类似于`bwrite`但不等待完成。 -**Syncer.** A 内核 thread that periodically flushes dirty 缓冲区 to their backing 设备. Closing a 文件系统 cleanly requires the syncer to finish. +**Syncer。**定期将脏缓冲区刷新到其后备设备的内核线程。干净地关闭文件系统需要syncer完成。 -**Taskqueue.** A 内核 facility for running 回调 in a separate thread. Useful when your strategy function wants to defer work. Covered in more depth when we discuss 中断处理程序s in later chapters. +**Taskqueue。**在单独线程中运行回调的内核机制。当你的策略函数想延迟工作时很有用。在后面讨论中断处理器时会更深入地介绍。 -**Callout.** A 内核 facility for scheduling a one-shot or periodic 回调 at a given time. Not commonly used in simple 存储驱动程序 but very common in hardware 驱动程序 that implement timeouts. +**Callout。**在给定时间调度一次性或周期性回调的内核机制。在简单的存储驱动程序中不常用,但在实现超时的硬件驱动程序中非常常见。 -**Witness.** A 内核 subsystem that detects lock-order violations and prints warnings. Always enabled in debug 内核s; saves hours of debugging. +**Witness。**检测锁顺序违规并打印警告的内核子系统。在调试内核中始终启用;节省数小时的调试时间。 -**INVARIANTS.** A 内核 compile option that adds runtime assertions. Always enabled in debug 内核s; catches many storage bugs before they become silent corruption. +**INVARIANTS。**添加运行时断言的内核编译选项。在调试内核中始终启用;在许多存储bug变成静默损坏之前捕获它们。 -**Debug 内核.** A 内核 built with `INVARIANTS`, `WITNESS`, and related options. Slower but much safer for 驱动程序 development. Use one during lab work. +**Debug kernel(调试内核)。**用`INVARIANTS`、`WITNESS`和相关选项构建的内核。较慢但对驱动程序开发更安全。在实验工作中使用一个。 -## Frequently Asked Questions +## 常见问题 -### Do I need to support BIO_ORDERED? +### 我需要支持BIO_ORDERED吗? -For a pseudo 设备 that services BIOs synchronously, no. Each BIO completes before the next one is processed, which trivially preserves ordering. For an asynchronous 驱动程序, you must respect `BIO_ORDERED` by deferring subsequent BIOs until the ordered one completes. +对于同步服务BIO的伪设备,不需要。每个BIO在处理下一个之前完成,这自然地保留了顺序。对于异步驱动程序,你必须通过延迟后续BIO直到有序BIO完成来尊重`BIO_ORDERED`。 -### What is the relationship between d_maxsize and MAXPHYS? +### d_maxsize和MAXPHYS之间有什么关系? -`d_maxsize` is the maximum BIO size your 驱动程序 can accept. `MAXPHYS` is the compile-time upper bound on BIO size, defined in `/usr/src/sys/sys/param.h`. On 64-bit systems such as amd64 and arm64, `MAXPHYS` is 1 MiB; on 32-bit systems it is 128 KiB. FreeBSD 14.3 also exposes a runtime tunable, `maxphys`, which some subsystems consult through the `MAXPHYS` macro or the `maxphys` variable. Setting `d_maxsize = MAXPHYS` accepts whatever the 内核 is willing to issue. For most pseudo 驱动程序 this is fine. +`d_maxsize`是你的驱动程序可以接受的最大BIO大小。`MAXPHYS`是BIO大小的编译时上限,在`/usr/src/sys/sys/param.h`中定义。在amd64和arm64等64位系统上,`MAXPHYS`为1 MiB;在32位系统上为128 KiB。FreeBSD 14.3还暴露了一个运行时可调参数`maxphys`,一些子系统通过`MAXPHYS`宏或`maxphys`变量查询它。设置`d_maxsize = MAXPHYS`接受内核愿意发出的任何大小。对大多数伪驱动程序来说这没问题。 -### Can my 驱动程序 issue BIOs to itself? +### 我的驱动程序能向自身发出BIO吗? -Technically yes, but it rarely makes sense. The pattern is used by GEOM transformation classes (they take in BIOs from above and issue new BIOs downward). A `g_disk` 驱动程序 is at the bottom of the stack and has no downward; if you need to split work across multiple backing units, you probably want worker threads rather than nested BIOs. +技术上可以,但很少有道理。这种模式被GEOM变换类使用(它们从上面接收BIO并向下发出新BIO)。`g_disk`驱动程序位于栈的底部,没有向下的方向;如果你需要跨多个后备单元拆分工作,你可能需要工作线程而不是嵌套BIO。 -### Why do some fields in struct disk use u_int and others off_t? +### 为什么struct disk中有些字段使用u_int,有些使用off_t? -`u_int` is used for unsigned integer sizes that fit in 32 bits (扇区 size, number of heads, etc.). `off_t` is a signed 64-bit type used for byte offsets and sizes that can exceed 32 bits (media size, request offsets). The distinction matters for large disks; a media size of 10 TB requires more than 32 bits. +`u_int`用于适合32位的无符号整数大小(扇区大小、磁头数等)。`off_t`是有符号64位类型,用于可以超过32位的字节偏移和大小(媒体大小、请求偏移)。这个区别对大磁盘很重要;10 TB的媒体大小需要超过32位。 -### Is disk_alloc safe to call at any time? +### disk_alloc在任何时候调用都安全吗? -`disk_alloc` uses `M_WAITOK` and will sleep if memory is tight. Do not call it while holding a spin lock or a 互斥锁 you cannot release. Call it at 附加 time, outside any lock. +`disk_alloc`使用`M_WAITOK`,在内存紧张时会睡眠。不要在持有自旋锁或你不能释放的互斥锁时调用它。在附加时、任何锁之外调用它。 -### What happens if I call disk_create twice with the same name? +### 如果我用相同的名称调用disk_create两次会怎样? -`disk_create` will happily create multiple disks with the same name if the unit numbers differ. If both the name and unit number match, GEOM will reject the second registration and the resulting behaviour is implementation-defined. Avoid this case. +如果单元号不同,`disk_create`会愉快地创建多个同名的磁盘。如果名称和单元号都匹配,GEOM将拒绝第二次注册,产生的行为是实现定义的。避免这种情况。 -### Can the strategy function sleep? +### 策略函数可以睡眠吗? -Technically yes, but it should not. The strategy function runs in the caller's thread context, and sleeping there stalls the caller. For work that must 块, use a worker thread. +技术上可以,但不应该。策略函数在调用者的线程上下文中运行,在那里睡眠会阻塞调用者。对于必须阻塞的工作,使用工作线程。 -### How do I know when all BIOs have finished for a given 文件系统? +### 我怎么知道给定文件系统的所有BIO何时完成? -You usually do not need to. `u挂载(2)` does the work: it flushes dirty 缓冲区, drains in-flight BIOs, and returns only after the 文件系统 is fully quiesced. After `u挂载` returns, no BIOs will arrive for that 挂载 point unless something else opens the 设备. +你通常不需要知道。`umount(2)`做这个工作:它刷新脏缓冲区、排干飞行中的BIO,只有在文件系统完全静默后才返回。`umount`返回后,不会有BIO再到达那个挂载点,除非有其他东西打开了设备。 -### Can I pass pointers between threads through bio_caller1 or similar fields? +### 我可以通过bio_caller1或类似字段在线程之间传递指针吗? -Yes. `bio_caller1` and `bio_caller2` are opaque fields meant for the issuer of the BIO to stash context that the completion handler can use. As long as you own the BIO (which you do, because you issued it), the fields are yours. `g_disk` 驱动程序 do not usually need them because the BIO arrives from above and is completed by calling `biodone`, with `g_disk` handling the 回调 routing. +可以。`bio_caller1`和`bio_caller2`是不透明字段,供BIO的发布者存放完成处理器可以使用的上下文。只要你拥有BIO(你确实拥有,因为你发出了它),这些字段就是你的。`g_disk`驱动程序通常不需要它们,因为BIO从上面到达并通过调用`biodone`完成,`g_disk`处理回调路由。 -### My 驱动程序 works on my laptop but not on the server. Why? +### 我的驱动程序在笔记本上工作但在服务器上不行。为什么? -Possibilities: different 内核 ABI (recompile against the server's 内核), different `MAXPHYS` (should be identical on 14.3 systems but check), different GEOM classes loaded (unlikely but possible), different memory size (your allocation might fail on a smaller system), different clock speed (affecting timing). Compare `uname -a` and `sysctl -a | grep kern.maxphys` to start. +可能原因:不同的内核ABI(针对服务器的内核重新编译)、不同的`MAXPHYS`(在14.3系统上应该相同但检查一下)、加载了不同的GEOM类(不太可能但可能)、不同的内存大小(你的分配在较小的系统上可能失败)、不同的时钟速度(影响时序)。从比较`uname -a`和`sysctl -a | grep kern.maxphys`开始。 -### Where does the /dev node's name actually come from? +### /dev节点的名称实际上从哪里来? -From `d_name` and `d_unit` in the `struct disk` you pass to `disk_create`. GEOM concatenates them without a separator: `d_name = "myblk"`, `d_unit = 0` produces `/dev/myblk0`. If you want a different convention, set `d_name` accordingly. There is no separator character between the name and the unit. +来自你传递给`disk_create`的`struct disk`中的`d_name`和`d_unit`。GEOM将它们连接起来不加分隔符:`d_name = "myblk"`、`d_unit = 0`产生`/dev/myblk0`。如果你想要不同的约定,相应地设置`d_name`。名称和单元号之间没有分隔符。 -### What is the maximum number of units I can create? +### 我可以创建的最大单元数是多少? -Limited by `d_unit`, which is `u_int`, so 2^32 - 1 in theory. In practice, per-unit memory consumption and the practical limits of `/dev` name space will stop you long before that. +受`d_unit`限制,它是`u_int`,理论上为2^32 - 1。在实践中,每单元的内存消耗和`/dev`命名空间的实际限制会在你达到那个数字之前很久就阻止你。 -### Can I change d_mediasize after disk_create? +### 我可以在disk_create之后更改d_mediasize吗? -Yes, but carefully. Filesystems 挂载ed on the disk will not pick up the change automatically; most will require 卸载 and re挂载. `md(4)` supports `MDIOCRESIZE` and there is infrastructure for signalling the change to GEOM, but the pattern is non-trivial. +可以,但要小心。挂载在磁盘上的文件系统不会自动拾取更改;大多数需要卸载并重新挂载。`md(4)`支持`MDIOCRESIZE`,有向GEOM发出更改信号的基础设施,但这个模式不简单。 -### What happens if I forget MODULE_DEPEND? +### 如果我忘记MODULE_DEPEND会怎样? -The 内核 may fail to load your module if `g_disk` is not already loaded, or may load it successfully if `g_disk` happens to be built into the 内核. Always declare `MODULE_DEPEND` explicitly to avoid surprise. +如果`g_disk`尚未加载,内核可能无法加载你的模块,或者如果`g_disk`碰巧内建在内核中,可能成功加载。始终显式声明`MODULE_DEPEND`以避免意外。 -### Should I use biodone or g_io_deliver in my 驱动程序? +### 我的驱动程序中应该使用biodone还是g_io_deliver? -Use `biodone`. The `g_disk` wrapper provides a `d_strategy` style 接口 where the correct completion call is `biodone`. If you write your own `g_class`, you will call `g_io_deliver` instead, but that is a different path and a different chapter's worth of complexity. +使用`biodone`。`g_disk`包装器提供了`d_strategy`风格的接口,其中正确的完成调用是`biodone`。如果你编写自己的`g_class`,你将改为调用`g_io_deliver`,但那是不同的路径和不同章节的复杂度。 -### How does BIO_DELETE relate to TRIM and UNMAP? +### BIO_DELETE与TRIM和UNMAP有什么关系? -`BIO_DELETE` is the in-内核 abstraction. For SATA SSDs it maps to the ATA TRIM command, for SCSI/SAS to UNMAP, and for NVMe to Dataset Management with the deallocate bit. Userland triggers it through `fstrim(8)` or the `-o trim` 挂载 option on UFS. Our 驱动程序 is free to treat it as a hint or to honour it by zeroing memory, since backing is in RAM. +`BIO_DELETE`是内核内的抽象。对于SATA SSD,它映射到ATA TRIM命令;对于SCSI/SAS,映射到UNMAP;对于NVMe,映射到带释放位的Dataset Management。用户态通过`fstrim(8)`或UFS上的`-o trim`挂载选项触发它。我们的驱动程序可以自由地将其视为提示或通过清零内存来响应它,因为后备存储在RAM中。 -### Why does my strategy function sometimes receive a BIO with bio_length of zero? +### 为什么我的策略函数有时收到bio_length为零的BIO? -In normal operation you should never see this. If it happens, treat it as a defensive case: call `biodone(bp)` with no error and return. A length-zero BIO is not illegal, but it indicates something odd upstream. Filing a PR against the issuing code is reasonable. +在正常操作中你不应该看到这个。如果发生了,将其视为防御性情况:不带错误调用`biodone(bp)`并返回。长度为零的BIO不是非法的,但表示上游有奇怪的东西。对发出代码提交PR是合理的。 -### What is the difference between d_flags and bio_flags? +### d_flags和bio_flags之间有什么区别? -`d_flags` is static configuration for the whole disk, set once at registration and describing what the 驱动程序 can do (handles DELETE, can FLUSH, accepts unmapped BIOs, and so on). `bio_flags` is dynamic metadata on a single BIO, changing per request (ordered, unmapped, direct completion). Do not confuse them. +`d_flags`是整个磁盘的静态配置,在注册时设置一次,描述驱动程序能做什么(处理DELETE、可以FLUSH、接受未映射BIO等)。`bio_flags`是单个BIO上的动态元数据,每个请求变化(有序、未映射、直接完成)。不要混淆它们。 -### Can my 驱动程序 present itself as removable media? +### 我的驱动程序可以将自己表现为可移动介质吗? -Yes, set `DISKFLAG_CANDELETE` and consider honouring `disk_gone` to simulate ejection. Tools like `camcontrol` and 文件系统 handlers generally treat any GEOM provider uniformly, so "removable" in the user-visible sense is less distinct than in other operating systems. +可以,设置`DISKFLAG_CANDELETE`并考虑响应`disk_gone`来模拟弹出。像`camcontrol`和文件系统处理器这样的工具通常统一对待任何GEOM提供者,所以用户可见意义上的"可移动"在其他操作系统中不那么明显。 -### What thread actually calls my strategy function? +### 什么线程实际调用我的策略函数? -It depends. For synchronous submission from the 缓冲区 cache, it is the thread that called `bwrite` or `bread`. For asynchronous completion paths it is often a GEOM worker or the 缓冲区 cache's flusher thread. Your strategy must be written to tolerate any caller. Do not assume a specific thread identity or a specific priority. +取决于情况。对于来自缓冲区缓存的同步提交,是调用`bwrite`或`bread`的线程。对于异步完成路径,通常是GEOM工作线程或缓冲区缓存的刷新线程。你的策略函数必须编写为容忍任何调用者。不要假设特定的线程标识或特定的优先级。 -### How do I know which process caused a given BIO? +### 我怎么知道哪个进程导致了给定的BIO? -You usually cannot, because BIOs can be reordered, coalesced, merged, and issued from background threads that are not the original requester. `dtrace` with the `io:::start` 探测 plus stack captures can get you close, but it is investigative work, not a routine 驱动程序 responsibility. +你通常无法知道,因为BIO可以被重新排序、合并、归并,并从不是原始请求者的后台线程发出。带有`io:::start`探测加上栈捕获的`dtrace`可以让你接近,但这是调查工作,不是常规的驱动程序责任。 -### Can two different 文件系统 be 挂载ed simultaneously on two unit numbers of my 驱动程序? +### 我的驱动程序的两个不同单元号上可以同时挂载两个不同的文件系统吗? -Yes, if you implemented multi-unit support. Each unit presents its own GEOM provider. Their backing stores are independent. The only shared state is your module's global variables and the 内核 itself, so the two 挂载s do not interact unless you make them. +可以,如果你实现了多单元支持。每个单元呈现自己的GEOM提供者。它们的后备存储是独立的。唯一共享的状态是你模块的全局变量和内核本身,所以两个挂载不会交互,除非你让它们交互。 -### Should my 驱动程序 handle power management events? +### 我的驱动程序应该处理电源管理事件吗? -For a pseudo 设备, no. For a real hardware 驱动程序, yes: suspend and resume events flow through New总线 as method calls, and the 驱动程序 must quiesce I/O on suspend and revalidate 设备 state on resume. Storage 驱动程序 on laptops are a common source of suspend-related bugs, so real 驱动程序 take this seriously. +对于伪设备,不需要。对于真正的硬件驱动程序,需要:挂起和恢复事件通过Newbus作为方法调用传递,驱动程序必须在挂起时停止I/O,在恢复时重新验证设备状态。笔记本电脑上的存储驱动程序是挂起相关bug的常见来源,所以真正的驱动程序对此很认真。 -### What is the practical impact of choosing 512 versus 4096 as d_扇区ize? +### 选择512还是4096作为d_sectorsize有什么实际影响? -On modern 文件系统, very little: UFS, ZFS, and most other FreeBSD 文件系统 work happily with either. On the 驱动程序 side, a larger 扇区 size reduces the number of BIOs for large transfers. On the workload side, applications doing O_DIRECT or aligned I/O may care. When in doubt, pick 4096 for new 驱动程序; it matches modern flash and avoids alignment penalties. +在现代文件系统上,几乎没有:UFS、ZFS和大多数其他FreeBSD文件系统都能愉快地使用两者。在驱动程序侧,较大的扇区大小减少了大传输的BIO数量。在工作负载侧,做O_DIRECT或对齐I/O的应用程序可能在乎。有疑问时,为新驱动程序选择4096;它匹配现代闪存并避免对齐惩罚。 -### If I reload my 驱动程序 many times, does memory leak? +### 如果我多次重新加载驱动程序,内存会泄漏吗? -Only if you have a bug. In our design, `MOD_UNLOAD` calls `myblk_分离_unit`, which frees the backing store and the softc. The persistence variant deliberately retains the backing store across reloads but uses a single global pointer, so there is no leak; the same memory is reused. If `vmstat -m | grep myblk` climbs across reloads, investigate. +只有在你有bug时才会。在我们的设计中,`MOD_UNLOAD`调用`myblk_detach_unit`,它释放后备存储和softc。持久性变体故意在重载间保留后备存储,但使用单一全局指针,所以没有泄漏;相同的内存被重用。如果`vmstat -m | grep myblk`在重载间攀升,请调查。 -### Why does `挂载` sometimes succeed on my raw 设备 but `newfs_ufs` fail? +### 为什么`mount`有时在我的原始设备上成功但`newfs_ufs`失败? -`newfs_ufs` writes structured metadata (super块, cylinder groups, inode tables) and then reads some of it back to verify. If the 设备 is too small, corrupts writes silently, or returns errors only under certain conditions, `newfs_ufs` catches it first. `挂载` is much less strict at the write path; it can read in a broken super块 and produce odd errors later. A successful `newfs` is a stronger correctness signal than a successful `挂载`. +`newfs_ufs`写入结构化元数据(超级块、柱面组、inode表)然后回读其中一些来验证。如果设备太小、静默损坏写入或仅在特定条件下返回错误,`newfs_ufs`会首先捕获它。`mount`在写入路径上不那么严格;它可以读入损坏的超级块并在之后产生奇怪的错误。成功的`newfs`是比成功的`mount`更强的正确性信号。 -### How do I verify that my BIO_FLUSH implementation actually makes data durable? +### 我怎么验证我的BIO_FLUSH实现确实使数据持久? -For our in-memory 驱动程序, durability is bounded by the host's power: flushing does nothing useful because a power cut takes everything with it. For a real 驱动程序 backed by persistent storage, issuing a flush command to the underlying media and confirming completion before calling `biodone` is the contract. Testing requires a power-cycle harness or a simulator; there is no shortcut. +对于我们的内存驱动程序,持久性受主机电源约束:刷新没有实际用途,因为断电会带走一切。对于由持久存储支持的真正驱动程序,向底层介质发出刷新命令并在调用`biodone`之前确认完成就是契约。测试需要断电循环工具或模拟器;没有捷径。 -### What are the correct locking rules inside d_strategy? +### d_strategy内部正确的锁定规则是什么? -Hold the 驱动程序's lock long enough to protect the backing store against concurrent access, and release it before calling `biodone`. Never hold a lock across a call into another subsystem. Never call `malloc(M_WAITOK)` with a lock held. Never sleep. If you need to sleep, schedule the work on a taskqueue and call `biodone` from the worker. +持有驱动程序的锁足够长时间来保护后备存储免受并发访问,并在调用`biodone`之前释放它。永远不要在调用另一个子系统时持有锁。永远不要在持有锁时调用`malloc(M_WAITOK)`。永远不要睡眠。如果你需要睡眠,在工作线程上调度工作并从工作线程调用`biodone`。 -### Why is BIO_FLUSH not a percent-of-capacity barrier like write barriers on Linux? +### 为什么BIO_FLUSH不像Linux上的写屏障那样是百分比容量的屏障? -FreeBSD's BIO_FLUSH is a point-in-time barrier: when it completes, all previously issued writes are durable. It is not associated with a particular range or percentage of the 设备. Drivers can implement it as a strict barrier or as an opportunistic flush, but the minimum contract is the point-in-time guarantee. +FreeBSD的BIO_FLUSH是时间点屏障:当它完成时,所有先前发出的写入都是持久的。它不与特定范围或设备的百分比关联。驱动程序可以将它实现为严格屏障或机会性刷新,但最低契约是时间点保证。 -### Are there any tools that generate BIO traffic to help me test? +### 有生成BIO流量帮助我测试的工具吗? -Yes. `dd(1)` with various `bs=` values, `fio(1)` from ports, `ioping(8)` from ports, plus the usual suspects: `newfs`, `tar`, `rsync`, `cp`. `diskinfo -t` runs a suite of benchmark reads and is useful for rough throughput numbers. The test harnesses under `/usr/src/tools/regression/` can also be adapted. +有。带有各种`bs=`值的`dd(1)`、来自ports的`fio(1)`、来自ports的`ioping(8)`,加上通常的嫌疑人:`newfs`、`tar`、`rsync`、`cp`。`diskinfo -t`运行一套基准读取,对粗略的吞吐量数字有用。`/usr/src/tools/regression/`下的测试工具也可以被适配。 -## What This Chapter Did Not Cover +## 本章未涵盖的内容 -This chapter is long, but there are several related topics we deliberately left for later. Naming them here helps you plan future study and prevents the false impression that 存储驱动程序 end at the BIO handler. +本章很长,但有几个相关主题我们有意留待以后。在这里命名它们有助于你规划未来的学习,并防止产生存储驱动程序止步于BIO处理器的错误印象。 -**Real hardware 存储驱动程序** such as those for SATA, SAS, and NVMe controllers live under CAM and require significant additional machinery: command-块 allocation, tagged queueing, 热插拔 event handling, firmware upload, SMART data, and error-recovery protocols. We introduced the CAM world briefly through the `ada_da.c` excerpt but did not explore it in depth. Chapters 33 through 36 will tackle these 接口, and the md(4) 驱动程序 you read in this chapter is a deliberately small staircase by comparison. +**真正的硬件存储驱动程序**,如SATA、SAS和NVMe控制器的驱动程序,位于CAM之下,需要大量额外的机制:命令块分配、标记队列、热插拔事件处理、固件上传、SMART数据和错误恢复协议。我们通过`ada_da.c`摘录简要介绍了CAM世界,但没有深入探讨。第33到36章将讨论这些接口,你在本章阅读的`md(4)`驱动程序相比之下是一个刻意设置的小台阶。 -**ZFS integration** is its own world. ZFS consumes GEOM providers through its vdev layer but adds copy-on-write semantics, end-to-end checksums, pooled storage, and snapshots that no simple 块 驱动程序 would ever need to know about. If your 驱动程序 works under UFS it almost certainly works under ZFS, but the reverse is not guaranteed: ZFS exercises BIO paths, especially flushing and write ordering, that less demanding 文件系统 skip. +**ZFS集成**是一个独立的世界。ZFS通过其vdev层消费GEOM提供者,但添加了写时复制语义、端到端校验和、池化存储和快照,这些是简单块驱动程序永远不需要知道的。如果你的驱动程序在UFS下工作,它几乎肯定在ZFS下也工作,但反过来不一定:ZFS对BIO路径的要求,特别是刷新和写入顺序,是不那么苛刻的文件系统跳过的。 -**GEOM class authoring** is a larger topic than `g_disk` wrapping. A full class implements taste, start, access, 附加, 分离, dumpconf, destroy_geom, and orphan methods. It can also create and destroy consumers, build multi-level topologies, and respond to configuration via `gctl`. The mirror, stripe, and crypt classes are good starting points once you decide to dig in. +**GEOM类编写**是比`g_disk`包装更大的主题。完整的类实现taste、start、access、attach、detach、dumpconf、destroy_geom和orphan方法。它还可以创建和销毁消费者、构建多层拓扑、通过`gctl`响应配置。一旦你决定深入研究,mirror、stripe和crypt类是好的起点。 -**Quotas, ACLs, and extended attributes** are 文件系统 features that live above the GEOM layer entirely. They matter for userland but do not touch the 存储驱动程序. This is a useful piece of clarity: the 驱动程序's job ends at the BIO boundary. +**配额、ACL和扩展属性**是完全位于GEOM层之上的文件系统功能。它们对用户空间很重要但不涉及存储驱动程序。这是一个有用的澄清:驱动程序的工作止于BIO边界。 -**Tracing and debugging 内核 crashes** deserves its own chapter. Kernel core dumps land on a dump 设备 configured via `dumpon(8)`, analysed with `kgdb(1)` or `crashinfo(8)`. If your 驱动程序 panics the system, being able to load the core file and inspect backtraces is a professional-level skill that this chapter only gestured at. +**跟踪和调试内核崩溃**值得单独一章。内核核心转储通过`dumpon(8)`配置的转储设备落地,用`kgdb(1)`或`crashinfo(8)`分析。如果你的驱动程序导致系统崩溃,能够加载核心文件并检查回溯是一项专业级技能,本章只是提及。 -**High-performance storage paths** use features such as unmapped I/O, direct-dispatch completion, CPU pinning, NUMA-aware allocation, and dedicated queues. These optimisations matter for gigabytes-per-second workloads but are irrelevant to a teaching 驱动程序. When you start chasing microseconds, come back to `/usr/src/sys/dev/nvme/` and study how the real professionals do it. +**高性能存储路径**使用未映射I/O、直接分派完成、CPU固定、NUMA感知分配和专用队列等特性。这些优化对每秒千兆字节的工作负载很重要,但对教学驱动程序无关。当你开始追逐微秒时,回到`/usr/src/sys/dev/nvme/`研究真正的专业人士是怎么做的。 -**Filesystem-specific behaviour** varies widely. UFS asks for one set of BIOs; ZFS asks for a different set; msdosfs and ext2fs ask for something different again. A good 存储驱动程序 is 文件系统-agnostic, but observing different 文件系统 on your 驱动程序 is a fantastic way to build intuition. Try `msdosfs`, `ext2fs`, and `tmpfs` for contrast after you are comfortable with UFS. +**文件系统特定行为**差异很大。UFS请求一组BIO;ZFS请求不同的组;msdosfs和ext2fs又请求不同的东西。一个好的存储驱动程序是文件系统无关的,但在你的驱动程序上观察不同文件系统是建立直觉的绝佳方式。在你对UFS感到舒适后,尝试`msdosfs`、`ext2fs`和`tmpfs`进行对比。 -**iSCSI and network 块设备** present themselves as GEOM providers too, but they are created by userland control daemons and talk to the network stack. 第28章 begins the networking work that makes those providers possible. +**iSCSI和网络块设备**也以GEOM提供者的形式呈现自己,但它们由用户态控制守护程序创建并与网络栈通信。第28章开始使这些提供者成为可能的网络工作。 -Our treatment of the storage path was deliberately focused. We wrote a 驱动程序 that 文件系统 accept as real, we understood why and how it is seen that way, and we traced the data path from `write(2)` to RAM. That foundation is enough to make the unexplored topics above readable rather than bewildering. +我们对存储路径的处理是刻意聚焦的。我们编写了一个文件系统接受为真实的驱动程序,我们理解了为什么以及如何被这样看待,我们跟踪了从`write(2)`到RAM的数据路径。这个基础足以使上述未探索的主题变得可读而非令人困惑。 -## Final Reflection +## 最终反思 -Storage 驱动程序 have a reputation as forbidding territory. This chapter should have replaced some of that reputation with familiarity: the BIO is just a structure, the strategy function is just a dispatcher, GEOM is just a graph, and `disk_create` is just a registration call. What elevates storage work from routine is not the underlying APIs, which are compact, but the operational demands that accumulate around them: performance, durability, error recovery, and correctness under contention. +存储驱动程序有令人生畏的名声。本章应该已经用熟悉感取代了部分这种名声:BIO只是一个结构,策略函数只是一个分派器,GEOM只是一个图,`disk_create`只是一个注册调用。将存储工作从例行公事中提升的不是底层API——它们很紧凑——而是围绕它们积累的运维需求:性能、持久性、错误恢复和竞争下的正确性。 -Those demands do not go away when you leave pseudo 设备 for real hardware. They multiply. But you already have the vocabulary to understand them. You know what a BIO is and where it comes from. You know which thread calls your code and what it expects. You know how to 注册 with GEOM, how to un注册 cleanly, and how to recognise an in-flight request from its shadow in `gstat`. When you sit in front of a real SATA controller 驱动程序 and start reading, you will recognise the shape of the code even though the specifics differ. +当你从伪设备转向真正的硬件时,这些需求不会消失。它们会倍增。但你已经有了理解它们的词汇。你知道BIO是什么,它从哪里来。你知道哪个线程调用你的代码以及它期望什么。你知道如何向GEOM注册、如何干净地注销,以及如何从`gstat`中的影子识别飞行中的请求。当你坐在真正的SATA控制器驱动程序前开始阅读时,你会识别出代码的形状,即使具体细节不同。 -The craft of storage-驱动程序 writing is, ultimately, patient. You learn by writing small 驱动程序, reading the source tree, reproducing simple experiments, and building instincts about when something that looks right is actually right. The chapter you just finished is a single long step along that journey. The next chapters will step again, each time in different directions. +存储驱动程序编写的技艺,归根结底,是耐心的。你通过编写小驱动程序、阅读源码树、重现简单的实验、建立对看起来正确的东西什么时候实际上正确的直觉来学习。你刚完成的章节是这条旅程中的漫长一步。接下来的章节将再次迈步,每次朝着不同的方向。 -## Further Reading +## 延伸阅读 -If this chapter has whetted your appetite for storage internals, here are some places to go next. +如果本章激发了你对存储内部机制的兴趣,以下是一些可以继续深入的地方。 -**Manual pages**. `disk(9)`, `g_bio(9)`, `geom(4)`, `devfs(5)`, `ufs(5)`, `newfs(8)`, `mdconfig(8)`, `gstat(8)`, `diskinfo(8)`, `挂载(2)`, `挂载(8)`. Read them in that order. +**手册页**。`disk(9)`、`g_bio(9)`、`geom(4)`、`devfs(5)`、`ufs(5)`、`newfs(8)`、`mdconfig(8)`、`gstat(8)`、`diskinfo(8)`、`mount(2)`、`mount(8)`。按此顺序阅读。 -**The FreeBSD Architecture Handbook**. The storage chapter is a good complement to this one. +**FreeBSD架构手册**。存储章节是本章的良好补充。 -**Kirk McKusick et al., "The Design and Implementation of the FreeBSD Operating System".** The book's chapters on the 文件系统 are especially relevant. +**Kirk McKusick等人,"The Design and Implementation of the FreeBSD Operating System"。**该书中关于文件系统的章节特别相关。 -**DTrace books.** Brendan Gregg's "DTrace Book" is a practical reference; Sun's "Dynamic Tracing Guide" is the original tutorial. +**DTrace书籍。**Brendan Gregg的"DTrace Book"是实用的参考;Sun的"Dynamic Tracing Guide"是原始教程。 -**The FreeBSD source tree.** `/usr/src/sys/geom/`, `/usr/src/sys/dev/md/`, `/usr/src/sys/ufs/`, and `/usr/src/sys/cam/ata/` (where `ata_da.c` implements the `ada` disk 驱动程序). Every pattern discussed in this chapter is grounded in that code. +**FreeBSD源码树。**`/usr/src/sys/geom/`、`/usr/src/sys/dev/md/`、`/usr/src/sys/ufs/`和`/usr/src/sys/cam/ata/`(`ata_da.c`在其中实现`ada`磁盘驱动程序)。本章讨论的每个模式都根植于该代码。 -**The mailing list archives.** `freebsd-geom@` and `freebsd-fs@` are the two most relevant lists. Reading historic threads is one of the best ways to pick up the institutional knowledge that books do not capture. +**邮件列表档案。**`freebsd-geom@`和`freebsd-fs@`是两个最相关的列表。阅读历史帖子是获取书籍未捕获的制度知识的最佳方式之一。 -**Commit history on GitHub mirrors.** The FreeBSD source tree has a long, well-annotated commit history. For any file you open, running `git log --follow` against its mirror will often reveal the rationale behind design choices, the bugs that shaped the current code, and the people who maintain it. Historical context makes the present code much easier to read. +**GitHub镜像上的提交历史。**FreeBSD源码树有很长、注释良好的提交历史。对于你打开的任何文件,对其镜像运行`git log --follow`通常会揭示设计选择背后的原因、塑造当前代码的bug以及维护它的人。历史背景使现在的代码更容易阅读。 -**The Transactions of the FreeBSD Developer Summit.** Several summits have included storage-focused sessions. Recordings and slides, when available, are excellent for picking up the state of the art and the open design debates. +**FreeBSD开发者峰会论文集。**几次峰会都包含存储相关的会议。录音和幻灯片(如果有)非常适合了解最新技术和公开的设计辩论。 -**Reading other operating systems' storage stacks.** Once you know FreeBSD's storage path, Linux's 块 layer, Illumos's SD 框架, and macOS's IOKit storage classes all become comprehensible in a way they probably were not before. The specific APIs differ, but the fundamental shapes, BIOs or their equivalents, 文件系统 above, hardware below, are universal. +**阅读其他操作系统的存储栈。**一旦你了解了FreeBSD的存储路径,Linux的块层、Illumos的SD框架和macOS的IOKit存储类都变得可以理解了,而以前可能不是这样。具体API不同,但基本的形状——BIO或其等价物、上面是文件系统、下面是硬件——是通用的。 -**Testing 框架 for 内核 code.** The `kyua(1)` harness runs regression tests against real 内核s. The `/usr/tests/sys/geom/` tree has examples of what well-written tests for storage code look like; reading them builds both testing instincts and confidence that your code is right. +**内核代码的测试框架。**`kyua(1)`工具运行针对真实内核的回归测试。`/usr/tests/sys/geom/`树有编写良好的存储代码测试的例子;阅读它们既能建立测试直觉也能增强代码正确的信心。 -**FreeBSD Foundation blog posts.** The Foundation funds several storage-related projects and publishes readable summaries that complement the source tree. +**FreeBSD基金会博客文章。**基金会资助多个存储相关项目,并发布可读的摘要来补充源码树。 --- -End of 第27章. Close your lab logbook, make sure your 驱动程序 is unloaded and your 挂载 points are released, and take a break before 第28章. +第27章结束。合上你的实验日志,确保你的驱动程序已卸载、挂载点已释放,在第28章之前休息一下。 -You have just written a 存储驱动程序, 挂载ed a 文件系统 on it, traced data through the 缓冲区 cache, into GEOM, through your strategy function, and back again. That is a real accomplishment. Rest on it for a moment before you turn the page. +你刚刚编写了一个存储驱动程序,在其上挂载了文件系统,跟踪了数据穿过缓冲区缓存、进入GEOM、通过你的策略函数然后返回。这是一项真正的成就。在翻页之前好好感受一下。 diff --git a/translations/zh_CN/chapters/part6/chapter-28.md b/translations/zh_CN/chapters/part6/chapter-28.md index a4dcfd7..bdf0df7 100644 --- a/translations/zh_CN/chapters/part6/chapter-28.md +++ b/translations/zh_CN/chapters/part6/chapter-28.md @@ -1,6 +1,6 @@ --- title: "编写网络驱动程序" -description: "Developing 网络接口 驱动程序 for FreeBSD" +description: "为 FreeBSD 开发网络接口驱动程序" partNumber: 6 partName: "编写特定传输层驱动程序" chapter: 28 @@ -12,153 +12,152 @@ translator: "AI辅助翻译为简体中文" estimatedReadTime: 240 language: "zh-CN" --- - # 编写网络驱动程序 ## 引言 -In the previous chapter you built a 存储驱动程序. A 文件系统 sat on top of it, a 缓冲区 cache fed it BIO requests, and your code delivered 块 of data to a piece of RAM and back. That was already a step away from the character-设备 world of earlier chapters, because a 存储驱动程序 is not polled by a single process holding a file 描述符. It is driven by many layers above it, all cooperating to turn `write(2)` calls into durable 块, and your 驱动程序 had to sit quietly at the bottom of that chain and honour each request in turn. +在上一章中,你构建了一个存储驱动程序。文件系统位于其上,缓冲区缓存向它提供 BIO 请求,你的代码将数据块传送到一块 RAM 并返回。这已经与前面章节中的字符设备世界有所不同,因为存储驱动程序不是由持有文件描述符的单个进程轮询的。它由上方的许多层驱动,所有层协作将 `write(2)` 调用转化为持久化的块,你的驱动程序必须安静地坐在那条链的底部,依次处理每个请求。 -A 网络驱动程序 is a third kind of animal. It is not a stream of bytes to one process, like a 字符设备. It is not a 块-addressable surface for a 文件系统 to 挂载, like a storage 设备. It is an **接口**. It sits between the machine's network stack on one side and a medium, real or simulated, on the other side. Packets arrive on that medium and the 驱动程序 turns them into mbufs and hands them up to the stack. Packets leave the stack in the form of mbufs and the 驱动程序 turns them into bits on the wire, or into whatever stand-in for a wire you have chosen to use. Link state changes, and the 驱动程序 reports that. Media speed changes, and the 驱动程序 reports that too. The user types `ifconfig mynet0 up`, and the 内核 routes that request through `if_ioctl` into your code. The 内核 is expecting a particular shape of cooperation, not a particular sequence of reads and writes. +网络驱动程序是第三种动物。它不是像字符设备那样面向一个进程的字节流,也不是像存储设备那样供文件系统挂载的块可寻址表面。它是一个**接口**。它位于机器的网络协议栈的一侧和传输介质(真实的或模拟的)的另一侧之间。数据包到达该介质时,驱动程序将它们转换为 mbuf 并向上传递给协议栈。数据包以 mbuf 的形式离开协议栈时,驱动程序将它们转换为线路上的比特,或者转换为你选择使用的任何线路替代物。链路状态变化时驱动程序会报告,媒体速度变化时驱动程序也会报告。用户输入 `ifconfig mynet0 up`,内核通过 `if_ioctl` 将该请求路由到你的代码中。内核期望的是一种特定形式的合作,而不是特定的读写序列。 -This chapter teaches you that shape. You will learn what FreeBSD expects a 网络驱动程序 to be. You will learn the core object that represents an 接口 in the 内核, the struct called `ifnet`, along with the modern `if_t` opaque handle that wraps it. You will learn how to allocate an `ifnet`, how to 注册 it with the stack, how to expose it as a named 接口 that `ifconfig` can see. You will learn how 数据包 enter your 驱动程序 through the transmit 回调 and how you push 数据包 the other way into the stack through `if_input`. You will learn how mbufs carry those 数据包, how link state and media state are reported, how flags like `IFF_UP` and `IFF_DRV_RUNNING` are used, and how a 驱动程序 分离 cleanly when it is unloaded. You will finish the chapter with a working pseudo-以太网 驱动程序 called `mynet` that you can load, configure, exercise with `ping`, `tcpdump`, and `netstat`, and then unload without leaving anything behind. +本章将教你那种合作的形式。你将学习 FreeBSD 期望网络驱动程序是什么样的,学习内核中表示接口的核心对象——名为 `ifnet` 的结构体,以及包装它的现代 `if_t` 不透明句柄。你将学习如何分配 `ifnet`,如何向协议栈注册它,如何将其暴露为 `ifconfig` 可以看到的命名接口。你将学习数据包如何通过发送回调进入你的驱动程序,以及你如何通过 `if_input` 将数据包反向推入协议栈。你将学习 mbuf 如何携带这些数据包,链路状态和媒体状态如何报告,`IFF_UP` 和 `IFF_DRV_RUNNING` 等标志如何使用,以及驱动程序在卸载时如何干净地分离。在本章结束时,你将拥有一个名为 `mynet` 的可用伪以太网驱动程序,你可以加载、配置、用 `ping`、`tcpdump` 和 `netstat` 进行测试,然后卸载而不留下任何痕迹。 -The 驱动程序 you will build is small on purpose. Real 以太网 驱动程序 in modern FreeBSD are usually written against `iflib(9)`, the shared 框架 that takes care of 环形缓冲区, interrupt moderation, and 数据包-steering for most production NICs. That machinery is wonderful when you are shipping a 驱动程序 for a 100-gigabit card, and we will return to it in later chapters. But it is too much scaffolding to hide the core ideas behind. To teach you what a 网络驱动程序 really is, we will write the classical, pre-iflib form: a plain `ifnet` 驱动程序 with its own transmit function and its own receive path. Once you understand that clearly, iflib will feel like a layer of convenience on top of something you already know. +你将要构建的驱动程序故意保持小型。现代 FreeBSD 中真正的以太网驱动程序通常基于 `iflib(9)` 编写,这是一个共享框架,负责处理大多数生产网卡上的环形缓冲区、中断调节和数据包调度。当你为 100Gb 网卡编写驱动程序时,这套机制非常出色,我们将在后续章节中回到这个话题。但它的脚手架太多了,会掩盖核心思想。为了教你网络驱动程序到底是什么,我们将编写经典的、iflib 之前的形式:一个拥有自己的发送函数和接收路径的普通 `ifnet` 驱动程序。一旦你清楚地理解了这一点,iflib 就像是在你已经了解的东西上面增加了一层便利。 -Like 第27章, this chapter is long because the topic is layered. Unlike `/dev` 驱动程序, 网络驱动程序 are wrapped in a vocabulary of their own: 以太网 帧, 接口 cloners, link state, media 描述符, `if_transmit`, `if_input`, `bpf附加`, `ether_if附加`. We will introduce that vocabulary carefully, one concept at a time, and we will ground every concept in code from the real FreeBSD tree. You will see where `epair(4)`, `disc(4)`, and the UFS stack loan patterns that we can adapt for our own 驱动程序. By the end you will recognise the shape of a 网络驱动程序 in any FreeBSD source file you open. +与第27章一样,本章很长,因为主题是分层的。与 `/dev` 驱动程序不同,网络驱动程序被包裹在自己的词汇表中:以太网帧、接口克隆器、链路状态、媒体描述符、`if_transmit`、`if_input`、`bpfattach`、`ether_ifattach`。我们将一次一个概念地仔细介绍这些词汇,并将每个概念建立在真实 FreeBSD 源代码树中的代码基础上。你将看到 `epair(4)`、`disc(4)` 以及 UFS 栈中我们可以为自己驱动程序借鉴的模式。到最后,你将能够在任何 FreeBSD 源文件中识别出网络驱动程序的结构。 -The goal is not a production NIC 驱动程序. The goal is to give you a complete, honest, correct understanding of the layer between a piece of hardware and the FreeBSD network stack, built up through prose, code, and practice. Once that mental model is solid, reading `if_em.c`, `if_bge.c`, or `if_ixl.c` becomes a matter of recognising patterns and looking up the unfamiliar parts. Without that mental model, they look like a storm of macros and bit operations. With it, they look like one more 驱动程序 that does the same things your `mynet` 驱动程序 does, only with hardware underneath. +目标不是一个生产级网卡驱动程序。目标是给你一个完整的、诚实的、正确的理解,关于硬件和 FreeBSD 网络协议栈之间的那层,通过文字、代码和实践逐步建立。一旦这个心智模型稳固了,阅读 `if_em.c`、`if_bge.c` 或 `if_ixl.c` 就变成了识别模式和查找不熟悉部分的事情。没有这个心智模型,它们看起来就像宏和位操作的风暴。有了它,它们看起来就像另一个驱动程序,做着与你的 `mynet` 驱动程序相同的事情,只是底层有硬件而已。 -Take your time. Open a FreeBSD shell while you read. Keep a lab logbook. Think of the network stack not as a black box above your code, but as a peer that expects a clear, contractual handshake with the 驱动程序. Your job is to fulfil that contract cleanly. +慢慢来。阅读时打开一个 FreeBSD shell。保持一本实验日志。不要把网络协议栈想象成你代码上方的一个黑盒,而要把它想象成一个期望与驱动程序进行清晰的、契约式握手的对等方。你的工作是干净地履行那个契约。 -## 读者指南: How to Use This Chapter +## 读者指南:如何使用本章 -This chapter continues the pattern established in 第27章: long, cumulative, deliberately paced. The topic is new and the vocabulary is new, so we will move a little more carefully than usual through the opening sections before we let you type code. +本章延续了第27章中建立的模式:篇幅长、内容累积递进、节奏经过精心设计。这个主题是新的,词汇也是新的,所以在让你输入代码之前,我们会比平时更谨慎地处理开头的几个小节。 -If you choose the **reading-only path**, plan for around two to three focused hours. You will come away with a clear mental model of what a 网络驱动程序 is, how it fits into FreeBSD's network stack, and what the code in real 驱动程序 is doing. This is a legitimate way to use the chapter on a first pass, and it is often the right choice on a day when you do not have time to rebuild a 内核模块. +如果你选择**仅阅读路线**,请计划大约两到三个集中注意力的小时。你将获得一个清晰的心智模型,了解网络驱动程序是什么、它如何融入 FreeBSD 的网络协议栈、以及真实驱动程序中的代码在做什么。这是第一次使用本章时完全合理的方式,在你没有时间重新构建内核模块的日子里,这通常是正确的选择。 -If you choose the **reading-plus-labs path**, plan for about five to eight hours spread across one or two evenings. You will write, build, and load a working pseudo-以太网 驱动程序, bring it up with `ifconfig`, watch its counters move, feed 数据包 into it from `ping`, look at them with `tcpdump`, and then shut everything down and unload the module cleanly. The labs are designed to be safe on any recent FreeBSD 14.3 system, including a virtual machine. +如果你选择**阅读加实验路线**,请计划大约五到八个小时,分布在一个或两个晚上。你将编写、构建和加载一个可用的伪以太网驱动程序,用 `ifconfig` 启动它,观察它的计数器移动,用 `ping` 向它发送数据包,用 `tcpdump` 查看它们,然后关闭一切并干净地卸载模块。这些实验设计为在任何最新的 FreeBSD 14.3 系统上都是安全的,包括虚拟机。 -If you choose the **reading-plus-labs-plus-challenges path**, plan for a weekend or a handful of evenings. The challenges extend the 驱动程序 in directions that matter in practice: adding a real simulated link partner with a shared queue between two 接口, supporting different link states, exposing a sysctl to inject errors, and measuring the behaviour under `iperf3`. Each challenge is self-contained and uses only what the chapter has already covered. +如果你选择**阅读加实验加挑战路线**,请计划一个周末或几个晚上。这些挑战将驱动程序扩展到实际中有意义的方向:添加一个真正的模拟链路伙伴并在两个接口之间共享队列,支持不同的链路状态,暴露一个 sysctl 来注入错误,以及在 `iperf3` 下测量行为。每个挑战都是独立的,只使用本章已经涵盖的内容。 -Regardless of the path you choose, do not skip the troubleshooting section near the end. Network 驱动程序 fail in a handful of characteristic ways, and learning to recognise those patterns is more valuable in the long run than memorising the names of every function in `ifnet`. The troubleshooting material is placed late for readability, but you may find yourself returning to it while running the labs. +无论你选择哪条路线,都不要跳过接近末尾的故障排除部分。网络驱动程序以少数几种特征方式失败,学会识别这些模式从长远来看比记住 `ifnet` 中每个函数的名称更有价值。故障排除材料放在后面是为了可读性,但你可能会在运行实验时发现自己需要回头查阅它。 -A word on prerequisites. You should be comfortable with everything from 第26章 and 第27章: writing a 内核模块, allocating and freeing a softc, reasoning about the load and unload path, and testing your work under `kldload` and `kldunload`. You should also be comfortable enough with FreeBSD's userland to run `ifconfig`, `netstat -in`, `tcpdump`, and `ping` without stopping to check the flags. If any of that feels uncertain, a quick skim of the corresponding earlier chapters will save you time later. +关于先决条件的一点说明。你应该对第26章和第27章的所有内容感到自如:编写内核模块、分配和释放 softc、推理加载和卸载路径、以及在 `kldload` 和 `kldunload` 下测试你的工作。你还应该对 FreeBSD 的用户态足够熟悉,能够在不停下来检查标志的情况下运行 `ifconfig`、`netstat -in`、`tcpdump` 和 `ping`。如果其中任何内容感觉不确定,快速浏览前面相应的章节将在以后节省你的时间。 -You should work on a throwaway FreeBSD 14.3 machine. A dedicated virtual machine is the best option, because 网络驱动程序, by their nature, can interact with the host system's routing tables and 接口 list. A small lab VM lets you experiment without worrying that you are going to confuse your main system. A snapshot before you begin is cheap insurance. +你应该在一台一次性的 FreeBSD 14.3 机器上工作。专用的虚拟机是最好的选择,因为网络驱动程序本质上会与主机系统的路由表和接口列表交互。一个小型实验虚拟机让你可以实验而不用担心会搞乱你的主系统。开始之前的快照是廉价的保险。 -### Work Section by Section +### 按小节顺序学习 -The chapter is organised as a progression. Section 1 explains what a 网络驱动程序 does and how it differs from the character and 存储驱动程序 you have already written. Section 2 introduces the `ifnet` object, the central data structure of the entire networking subsystem. Section 3 walks through allocation, naming, and registration of an 接口, including 接口 cloners. Section 4 handles the transmit path, from `if_transmit` through mbuf processing. Section 5 handles the receive path, including `if_input` and simulated 数据包 generation. Section 6 covers media 描述符, 接口 flags, and link-state notifications. Section 7 shows you how to test the 驱动程序 with FreeBSD's standard networking tools. Section 8 closes with clean 分离, module unload, and refactoring advice. +本章按照渐进的方式组织。第1节解释网络驱动程序做什么以及它与你已经编写的字符驱动程序和存储驱动程序有何不同。第2节介绍 `ifnet` 对象,这是整个网络子系统的核心数据结构。第3节逐步介绍接口的分配、命名和注册,包括接口克隆器。第4节处理发送路径,从 `if_transmit` 到 mbuf 处理。第5节处理接收路径,包括 `if_input` 和模拟数据包生成。第6节涵盖媒体描述符、接口标志和链路状态通知。第7节展示如何使用 FreeBSD 的标准网络工具测试驱动程序。第8节以干净的分离、模块卸载和重构建议结束。 -You are meant to read these sections in order. Each one assumes the previous ones are fresh in your mind, and the labs build on each other. If you jump in the middle, pieces will look strange. +你应该按顺序阅读这些小节。每一节都假设前面的小节在你的脑海中还记忆犹新,实验也是相互构建的。如果你跳到中间,内容会看起来很奇怪。 -### Type the Code +### 动手输入代码 -Typing remains the most effective way to internalise 内核 idioms. The companion files under `examples/part-06/ch28-network-驱动程序/` exist so that you can check your work, not so that you can skip the typing. Reading code is not the same as writing it, and reading a 网络驱动程序 is particularly easy to do passively because the code often looks like a long switch statement. Writing it forces you to think about each branch. +动手输入仍然是内化内核习语最有效的方式。`examples/part-06/ch28-network-driver/` 下的配套文件是为了让你检查你的工作,而不是让你跳过输入。阅读代码和编写代码是不同的,而阅读网络驱动程序特别容易被动地进行,因为代码通常看起来像一个很长的 switch 语句。编写它迫使你思考每个分支。 -### Open the FreeBSD Source Tree +### 打开 FreeBSD 源代码树 -You will be asked several times to open real FreeBSD source files, not only the companion examples. The files of interest for this chapter include `/usr/src/sys/net/if.h`, `/usr/src/sys/net/if_var.h`, `/usr/src/sys/net/if_disc.c`, `/usr/src/sys/net/if_epair.c`, `/usr/src/sys/net/if_ethersubr.c`, `/usr/src/sys/net/if_clone.c`, `/usr/src/sys/net/if_media.h`, and `/usr/src/sys/sys/mbuf.h`. Each of these is a primary reference, and the prose in this chapter refers back to them repeatedly. If you have not already cloned or installed the 14.3 source tree, now is a good moment to do so. +你将被多次要求打开真实的 FreeBSD 源代码文件,而不仅仅是配套示例。本章感兴趣的文件包括 `/usr/src/sys/net/if.h`、`/usr/src/sys/net/if_var.h`、`/usr/src/sys/net/if_disc.c`、`/usr/src/sys/net/if_epair.c`、`/usr/src/sys/net/if_ethersubr.c`、`/usr/src/sys/net/if_clone.c`、`/usr/src/sys/net/if_media.h` 和 `/usr/src/sys/sys/mbuf.h`。这些文件都是主要参考资料,本章的文字会反复引用它们。如果你还没有克隆或安装 14.3 源代码树,现在是一个好时机。 -### Use Your Lab Logbook +### 使用实验日志 -Keep the logbook you started in 第26章 open while you work. You will want to record the `ifconfig` output before and after you load the module, the exact commands you use to send traffic, the counters reported by `netstat -in`, the output of `tcpdump -i mynet0`, and any warnings or panics. Network work is particularly friendly to logbooks because the same command, `ifconfig mynet0`, produces different output at different points in the load-configure-use-unload cycle, and seeing those differences in your own notes makes the concepts stick. +工作时请保持你在第26章中开始的日志打开。你需要记录加载模块前后的 `ifconfig` 输出、你用来发送流量的确切命令、`netstat -in` 报告的计数器、`tcpdump -i mynet0` 的输出以及任何警告或崩溃。网络工作特别适合使用日志,因为同一个命令 `ifconfig mynet0` 在加载-配置-使用-卸载周期的不同点会产生不同的输出,在你自己的笔记中看到这些差异会让概念更加牢固。 -### Pace Yourself +### 把握节奏 -If your understanding blurs during a particular section, stop. Re-read the previous subsection. Try a small experiment, for example `ifconfig lo0` or `netstat -in` to see a real 接口, and think about how it corresponds to what the chapter is teaching. Network programming in the 内核 rewards slow, deliberate exposure. Skimming the chapter for terms to recognise later is much less useful than reading one section well, doing one lab, and moving on. +如果在某个特定小节你的理解变得模糊,停下来。重新阅读前一个小节。尝试一个小实验,例如 `ifconfig lo0` 或 `netstat -in` 来查看一个真实的接口,然后思考它与本章所教内容的对应关系。内核中的网络编程回报缓慢而刻意的接触。为了以后识别术语而浏览本章远不如好好阅读一个小节、做一个实验、然后继续来得有用。 -## How to Get the Most Out of This Chapter +## 如何从本章获得最大收益 -The chapter is structured so that every section adds exactly one new concept on top of what came before. To make the most of that structure, treat the chapter as a workshop rather than as a reference. You are not here to find a quick answer. You are here to build a correct mental model of what an 接口 is, how a 驱动程序 talks to the 内核, and how the network stack talks back. +本章的结构是每一节在前一节的基础上恰好增加一个新概念。为了充分利用这种结构,请把本章当作一个工作坊而不是参考手册。你不是来这里找快速答案的。你是来建立一个正确的心智模型的,了解接口是什么、驱动程序如何与内核对话、以及网络协议栈如何回应。 -### Work in Sections +### 按小节学习 -Do not read the whole chapter end to end without stopping. Read one section, then pause. Try the experiment or lab that goes with it. Look at the related FreeBSD source. Write a few lines in your logbook. Only then move on. Networking in the 内核 is strongly cumulative, and skipping ahead usually means that you will be confused about the next thing for a reason that was explained two sections ago. +不要不停地从头到尾阅读整个章节。读一节,然后暂停。尝试与之配套的实验或练习。查看相关的 FreeBSD 源代码。在你的日志中写几行。然后才继续。内核中的网络编程是强烈累积的,跳过通常意味着你会因为两节之前解释过的原因而对下一个内容感到困惑。 -### Keep the Driver Running +### 保持驱动程序运行 -Once you have loaded the 驱动程序 in Section 3, keep it loaded as much as possible while you read. Modify it, reload, poke it with `ifconfig`, feed it 数据包 with `ping`, watch them with `tcpdump`. Having a live, observable example is far more valuable than any 挂载 of reading, especially for network code, because the feedback loop is fast: the 内核 either accepts your configuration or refuses it, and the counters either move or they do not. +一旦你在第3节中加载了驱动程序,在阅读时尽量保持它处于加载状态。修改它,重新加载,用 `ifconfig` 触碰它,用 `ping` 向它发送数据包,用 `tcpdump` 观察它们。拥有一个活的、可观察的例子远比任何数量的阅读更有价值,特别是对于网络代码,因为反馈循环很快:内核要么接受你的配置,要么拒绝它,计数器要么移动,要么不移动。 -### Consult Manual Pages +### 参阅手册页 -FreeBSD's manual pages are part of the teaching material, not a separate formality. Section 9 of the manual is where the 内核 接口 live. We will refer in this chapter to pages such as `ifnet(9)`, `mbuf(9)`, `ifmedia(9)`, `ether(9)`, and `ng_ether(4)`, and to userland pages such as `ifconfig(8)`, `netstat(1)`, `tcpdump(1)`, `ping(8)`, and `ngctl(8)`. Read them alongside this chapter. They are shorter than they look, and they are written by the same community that wrote the 内核 you are learning about. +FreeBSD 的手册页是教学材料的一部分,不是一种单独的形式。手册的第9节是内核接口所在的地方。本章将引用 `ifnet(9)`、`mbuf(9)`、`ifmedia(9)`、`ether(9)` 和 `ng_ether(4)` 等页面,以及 `ifconfig(8)`、`netstat(1)`、`tcpdump(1)`、`ping(8)` 和 `ngctl(8)` 等用户态页面。请与本章一起阅读它们。它们比你想象的要短,而且它们是由编写你正在学习的内核的同一社区编写的。 -### Type the Code, Then Mutate It +### 输入代码,然后修改它 -When you build the 驱动程序 from the companion examples, type it first. Once it works, start changing things. Rename a method and watch the build fail. Remove an `if` branch in the transmit function and watch what happens under `ping`. Hardcode a smaller MTU and watch `ifconfig` react. Kernel code becomes understandable through deliberate mutation far more than through pure reading, and network code is particularly well-suited to mutation because every change produces an immediately visible effect in `ifconfig` or `netstat`. +当你从配套示例构建驱动程序时,首先输入它。一旦它工作了,开始修改。重命名一个方法,观察构建失败。移除发送函数中的一个 `if` 分支,观察在 `ping` 下会发生什么。硬编码一个更小的 MTU,观察 `ifconfig` 的反应。内核代码通过刻意的变异远比通过纯粹的阅读变得可理解,而网络代码特别适合变异,因为每个更改都会在 `ifconfig` 或 `netstat` 中产生立即可见的效果。 -### Trust the Tooling +### 善用工具 -FreeBSD gives you a wealth of tools for inspecting the network stack: `ifconfig`, `netstat`, `tcpdump`, `ngctl`, `sysctl net.`, `arp`, `ndp`. Use them. When something goes wrong, the first move is almost never to read more source. It is to ask the system what state it is in. A minute with `ifconfig mynet0` and `netstat -in` is often more informative than five minutes of `grep`. +FreeBSD 为你提供了丰富的工具来检查网络协议栈:`ifconfig`、`netstat`、`tcpdump`、`ngctl`、`sysctl net.`、`arp`、`ndp`。使用它们。当出现问题时,第一步几乎绝不是阅读更多源代码。而是询问系统处于什么状态。用 `ifconfig mynet0` 和 `netstat -in` 检查一分钟通常比五分钟的 `grep` 更有信息量。 -### Take Breaks +### 适当休息 -Network code is full of small, precise steps. A missed flag or an unset 回调 will produce behaviour that looks mysterious until you stop, breathe, and trace the data flow again. Two or three focused hours are usually more productive than a seven-hour sprint. If you catch yourself making the same typo three times, or copy-pasting without reading, that is your cue to stand up for ten minutes. +网络代码充满了小的、精确的步骤。一个遗漏的标志或一个未设置的回调会产生看起来神秘的行为,直到你停下来、深呼吸、再次追踪数据流。两到三个集中注意力的小时通常比七小时的冲刺更有效率。如果你发现自己犯了三次同样的打字错误,或者在没有阅读的情况下复制粘贴,那就是你该站起来休息十分钟的信号。 -With those habits in place, let us begin. +有了这些习惯,让我们开始吧。 -## 第1节: What a Network Driver Does +## 第1节:网络驱动程序做什么 -A 网络驱动程序 has one job that sounds simple and turns out to be layered: it moves 数据包 between a transport and the FreeBSD network stack. Everything else follows from that. To understand what that sentence really means, we need to slow down and examine each of its pieces. What is a 数据包? What is a transport? What exactly is "the stack"? And how does a 驱动程序 sit between them without becoming a bottleneck or a source of subtle bugs? +网络驱动程序有一个听起来简单但实际上是分层的任务:它在传输层和 FreeBSD 网络协议栈之间移动数据包。其他一切都由此而来。要理解这句话的真正含义,我们需要放慢速度,检查它的每个部分。什么是数据包?什么是传输层?协议栈到底是什么?驱动程序如何坐在它们之间而不成为瓶颈或微妙错误的来源? -### A Packet, in the Kernel +### 内核中的数据包 -In userland you rarely deal with raw 数据包. You open a 套接字, call `send` or `recv`, and the 内核 takes care of encapsulating your payload in TCP, wrapping that in IP, adding an 以太网 header, and finally handing the whole construct to a 驱动程序. In the 内核, the same 数据包 is represented by a linked list of structures called **mbufs**. An mbuf is a small memory cell, typically 256 bytes, that holds 数据包 data and a small header. If the 数据包 is larger than a single mbuf can hold, the 内核 chains multiple mbufs together through a `m_next` pointer, and the total length of the payload is recorded in `m->m_pkthdr.len`. If the 数据包 does not fit in a single mbuf cluster, the 内核 uses external 缓冲区 referenced by the mbuf, through a mechanism we will revisit in later chapters. +在用户态中,你很少处理原始数据包。你打开一个套接字,调用 `send` 或 `recv`,内核负责将你的有效载荷封装在 TCP 中,将其包装在 IP 中,添加以太网头部,最后将整个构造交给驱动程序。在内核中,相同的数据包由一个名为 **mbuf** 的结构链表表示。mbuf 是一个小的内存单元,通常为256字节,保存数据包数据和一个小的头部。如果数据包大于单个 mbuf 可以容纳的大小,内核通过 `m_next` 指针将多个 mbuf 链接在一起,有效载荷的总长度记录在 `m->m_pkthdr.len` 中。如果数据包不适合单个 mbuf 集群,内核使用由 mbuf 引用的外部缓冲区,这是我们在后面章节中将重新讨论的机制。 -From the 驱动程序's perspective, a 数据包 is almost always presented as an mbuf chain, and the first mbuf carries the 数据包 header. That first mbuf has `M_PKTHDR` set in its flags, which tells you that `m->m_pkthdr` contains valid fields such as the total 数据包 length, the VLAN tag, checksum flags, and the receive 接口. Every 驱动程序 that handles transmitted 数据包 begins by inspecting the mbuf it has been handed, and every 驱动程序 that delivers received 数据包 begins by building a correctly shaped mbuf. +从驱动程序的角度来看,数据包几乎总是以 mbuf 链的形式呈现,第一个 mbuf 携带数据包头部。第一个 mbuf 的标志中设置了 `M_PKTHDR`,这告诉你 `m->m_pkthdr` 包含有效字段,如总数据包长度、VLAN 标签、校验和标志和接收接口。每个处理发送数据包的驱动程序都从检查交给它的 mbuf 开始,每个交付接收数据包的驱动程序都从构建一个正确形状的 mbuf 开始。 -We will cover mbuf construction and teardown in more detail in Sections 4 and 5. For now, the vocabulary is what matters. A mbuf is a 数据包. A mbuf chain is a 数据包 whose payload spans several mbufs. The first mbuf in a chain carries the 数据包 header. The rest of the chain continues the payload, and each mbuf points to the next through `m_next`. +我们将在第4节和第5节中更详细地介绍 mbuf 的构建和拆卸。现在,词汇才是最重要的。一个 mbuf 就是一个数据包。一个 mbuf 链是一个有效载荷跨越多个 mbuf 的数据包。链中的第一个 mbuf 携带数据包头部。链的其余部分继续有效载荷,每个 mbuf 通过 `m_next` 指向下一个。 -### A Transport +### 传输层 -The transport is whatever the 驱动程序 talks to on the hardware side. For a physical 以太网 NIC it is the actual wire, reached through a combination of DMA 缓冲区, hardware rings, and interrupts from the chip. For a USB 以太网 adapter it is the USB 端点 pipeline we introduced in 第26章. For a wireless card it is the radio. For a pseudo-设备, and that is what we will build in this chapter, the transport is simulated: we will pretend that a 数据包 we transmit shows up on some other virtual wire, and we will pretend that incoming 数据包 arrive from it at regular intervals driven by a timer. +传输层是驱动程序在硬件端与之通信的对象。对于物理以太网网卡,它是实际的线路,通过 DMA 缓冲区、硬件环和芯片中断的组合来访问。对于 USB 以太网适配器,它是我们在第26章中介绍的 USB 端点管道。对于无线网卡,它是无线电。对于伪设备——也就是我们将在本章中构建的——传输层是模拟的:我们将假装我们发送的数据包出现在某条其他虚拟线路上,我们将假装传入的数据包以由定时器驱动的规则间隔从中到达。 -The beauty of the `ifnet` abstraction is that the network stack does not care which of these transports you have. The stack sees an 接口. It gives the 接口 mbufs to transmit. It expects the 接口 to hand it mbufs that were received. Whether the 数据包 actually travel across Category 6 cable, radio waves, a USB 总线, or a piece of memory we control, the surface is the same. That uniformity is what lets FreeBSD support dozens of network 设备 without rewriting its network code for each one. +`ifnet` 抽象的美妙之处在于网络协议栈不关心你有哪种传输层。协议栈看到一个接口。它给接口 mbuf 来发送。它期望接口交给它已接收的 mbuf。无论数据包实际是通过六类电缆、无线电波、USB 总线还是我们控制的一块内存传输的,表面都是相同的。这种统一性是让 FreeBSD 支持数十种网络设备而无需为每种设备重写网络代码的原因。 -### The Network Stack +### 网络协议栈 -"The stack" is a shorthand for the collection of code that sits above the 驱动程序 and implements the protocols. Layer by layer, from the lowest to the highest: 以太网 framing, ARP and neighbour discovery, IPv4 and IPv6, TCP and UDP, 套接字 缓冲区, and the system call layer that translates `send` and `recv` into stack operations. In FreeBSD, the code lives in `/usr/src/sys/net/`, `/usr/src/sys/netinet/`, `/usr/src/sys/netinet6/`, and related directories, and it communicates with 驱动程序 through a small, well-defined set of function pointers carried on every `ifnet`. +「协议栈」是位于驱动程序之上并实现协议的代码集合的简称。从最低层到最高层依次为:以太网成帧、ARP 和邻居发现、IPv4 和 IPv6、TCP 和 UDP、套接字缓冲区,以及将 `send` 和 `recv` 转换为协议栈操作的系统调用层。在 FreeBSD 中,代码位于 `/usr/src/sys/net/`、`/usr/src/sys/netinet/`、`/usr/src/sys/netinet6/` 和相关目录中,它通过每个 `ifnet` 上携带的一小组明确定义的函数指针与驱动程序通信。 -For this chapter, you do not need to know the inside of the stack. You need to know its outer 接口 as seen by a 驱动程序. That 接口 is: +对于本章,你不需要了解协议栈的内部。你需要了解驱动程序所看到的外部接口。该接口是: -* The stack calls your transmit function, `if_transmit`, and hands you a mbuf. Your job is to turn that mbuf into something the transport will accept. -* The stack calls your ioctl handler, `if_ioctl`, in response to commands from userland such as `ifconfig mynet0 up` or `ifconfig mynet0 mtu 1400`. Your job is to honour the request or return a reasonable error. -* The stack calls your init function, `if_init`, when the 接口 transitions to an up state. Your job is to prepare the transport for use. -* You call `ifp->if_input(ifp, m)` or, in the modern idiom, `if_input(ifp, m)`, to hand a received 数据包 to the stack. Your job is to ensure the mbuf is well-formed and the 数据包 is complete. +* 协议栈调用你的发送函数 `if_transmit`,并交给你一个 mbuf。你的工作是将该 mbuf 转换为传输层可以接受的内容。 +* 协议栈调用你的 ioctl 处理程序 `if_ioctl`,以响应用户态命令,例如 `ifconfig mynet0 up` 或 `ifconfig mynet0 mtu 1400`。你的工作是履行该请求或返回一个合理的错误。 +* 当接口转换为 up 状态时,协议栈调用你的初始化函数 `if_init`。你的工作是准备传输层以供使用。 +* 你调用 `ifp->if_input(ifp, m)` 或使用现代写法 `if_input(ifp, m)` 将接收到的数据包交给协议栈。你的工作是确保 mbuf 格式正确且数据包完整。 -That is the contract. The rest is detail. +这就是契约。其余的都是细节。 -### How a Network Driver Differs From a Character Driver +### 网络驱动程序与字符驱动程序的区别 -You already built character 驱动程序 in Chapters 14 and 18. A character 驱动程序 sits inside `/dev/`, it is opened by userland through `open(2)`, and it exchanges bytes with one or more processes through `read(2)` and `write(2)`. It has a `cdevsw` table. It is polled and pushed by whoever opens it. +你已经在第14章和第18章中构建了字符驱动程序。字符驱动程序位于 `/dev/` 内部,由用户态通过 `open(2)` 打开,并通过 `read(2)` 和 `write(2)` 与一个或多个进程交换字节。它有一个 `cdevsw` 表。由打开它的任何人轮询和推送。 -A 网络驱动程序 is none of those things. It does not live in `/dev/`. It is not `open(2)`ed by a process. There is no `cdevsw`. The closest thing to a user-visible file handle for a 网络接口 is the 套接字 that is bound to it, and even that is mediated by the stack, not by the 驱动程序. +网络驱动程序不是这些东西中的任何一个。它不在 `/dev/` 中。不是由进程 `open(2)` 的。没有 `cdevsw`。网络接口最接近用户可见文件句柄的东西是绑定到它的套接字,即使那也是由协议栈而不是由驱动程序中介的。 -Instead of a `cdevsw`, a 网络驱动程序 has a `struct ifnet`. Instead of `d_read`, it has `if_input`, but on the other end: the 驱动程序 calls it, rather than having it called by userland. Instead of `d_write`, it has `if_transmit`, called by the stack. Instead of `d_ioctl`, it has `if_ioctl`, called by the stack in response to `ifconfig` and related tools. The top-level structure looks similar, but the relationships between actors are different. In a character 驱动程序 you wait for reads and writes from userland. In a 网络驱动程序 you are embedded in a pipeline where the stack is your main collaborator, and userland is a spectator rather than a direct peer. +网络驱动程序没有 `cdevsw`,而是有一个 `struct ifnet`。它没有 `d_read`,而是有 `if_input`,但在另一端:驱动程序调用它,而不是由用户态调用。它没有 `d_write`,而是有 `if_transmit`,由协议栈调用。它没有 `d_ioctl`,而是有 `if_ioctl`,由协议栈响应 `ifconfig` 和相关工具时调用。顶层结构看起来相似,但参与者之间的关系不同。在字符驱动程序中,你等待来自用户态的读写。在网络驱动程序中,你嵌入在一个管道中,协议栈是你的主要合作者,而用户态是旁观者而不是直接的对等方。 -This shift in perspective is worth internalising before you write any code. When something goes wrong in a character 驱动程序, the question is usually "what did userland do?" When something goes wrong in a 网络驱动程序, the question is usually "what did the stack expect my 驱动程序 to do, and how did I fail to do it?" +这种视角的转变值得在你编写任何代码之前内化。当字符驱动程序出现问题时,问题通常是「用户态做了什么?」当网络驱动程序出现问题时,问题通常是「协议栈期望我的驱动程序做什么,我为什么没有做到?」 -### How a Network Driver Differs From a Storage Driver +### 网络驱动程序与存储驱动程序的区别 -A 存储驱动程序, as you saw in 第27章, is also not a `/dev/` 端点 in the usual sense. It does expose a 块设备 node, but access to it is almost always mediated by a 文件系统 sitting on top. Requests come down as BIOs, the 驱动程序 handles them, and completion is signalled by `biodone(bp)`. +正如你在第27章中看到的,存储驱动程序通常也不是 `/dev/` 端点。它确实暴露了一个块设备节点,但对其的访问几乎总是由位于其上的文件系统来中介。请求以 BIO 的形式下传,驱动程序处理它们,完成通过 `biodone(bp)` 发出信号。 -A 网络驱动程序 shares the "I sit below a subsystem, not next to userland" shape of a 存储驱动程序, but the subsystem above it is very different. The storage subsystem is deeply synchronous at the BIO level, in the sense that every request has a well-defined completion event. Network traffic is not like that. A 驱动程序 transmits a 数据包, but there is no per-数据包 completion 回调 bubbling up from the 驱动程序 to any specific requester. The stack trusts the 驱动程序 to succeed or fail cleanly, increments counters, and moves on. Likewise, received 数据包 are not replies to specific earlier transmissions: they just arrive, and the 驱动程序 must funnel them into `if_input` whenever they show up. +网络驱动程序共享存储驱动程序的「我坐在子系统下面,而不是用户态旁边」的形式,但它上方的子系统非常不同。存储子系统在 BIO 层面是深度同步的,因为每个请求都有一个明确定义的完成事件。网络流量不是这样的。驱动程序发送一个数据包,但没有从驱动程序冒泡到任何特定请求者的逐包完成回调。协议栈信任驱动程序能够干净地成功或失败,递增计数器,然后继续。同样,接收到的数据包不是对特定早期发送的回复:它们只是到达,驱动程序必须随时将它们导入 `if_input`。 -Another difference is concurrency. A 存储驱动程序 usually has a single BIO path and handles each BIO in turn. A 网络驱动程序 is frequently called from multiple CPU contexts at once, because the stack serves many 套接字s in parallel, and modern hardware delivers receive events on multiple queues. We will not cover that complexity in this chapter, but you should already be aware that locking conventions for 网络驱动程序 are strict. The `mynet` 驱动程序 we will build is small enough that a single 互斥锁 suffices, but even then the discipline around when to take it, and when to drop it before calling up, matters. +另一个区别是并发性。存储驱动程序通常有单个 BIO 路径并依次处理每个 BIO。网络驱动程序经常同时从多个 CPU 上下文被调用,因为协议栈并行服务许多套接字,而现代硬件在多个队列上交付接收事件。我们不会在本章中涵盖这种复杂性,但你已经应该意识到网络驱动程序的锁定约定是严格的。我们将构建的 `mynet` 驱动程序足够小,单个互斥锁就足够了,但即使如此,何时获取它、何时在向上调用之前释放它的纪律也很重要。 -### The Role of `ifconfig`, `netstat`, and `tcpdump` +### `ifconfig`、`netstat` 和 `tcpdump` 的角色 -Every FreeBSD user knows `ifconfig`. From the 网络驱动程序 author's perspective, `ifconfig` is the primary way the 内核 expects user commands to reach your 驱动程序. When the user runs `ifconfig mynet0 up`, the 内核 translates that into a `SIOCSIFFLAGS` ioctl on the 接口 whose name is `mynet0`. The call arrives in your `if_ioctl` 回调, and you decide what to do with it. The symmetry between the userland command and the 内核-side 回调 is almost one-to-one. +每个 FreeBSD 用户都知道 `ifconfig`。从网络驱动程序作者的角度来看,`ifconfig` 是内核期望用户命令到达你的驱动程序的主要方式。当用户运行 `ifconfig mynet0 up` 时,内核将其转换为名为 `mynet0` 的接口上的 `SIOCSIFFLAGS` ioctl。调用到达你的 `if_ioctl` 回调,你决定如何处理它。用户态命令和内核端回调之间的对称性几乎是一对一的。 -`netstat -in` asks the 内核 for the 接口 statistics carried on every `ifnet`. Your 驱动程序 updates those counters by calling `if_inc_counter(ifp, IFCOUNTER_*, n)` at the appropriate moments in the transmit and receive paths. The set of counters is defined in `/usr/src/sys/net/if.h` and includes `IFCOUNTER_IPACKETS`, `IFCOUNTER_OPACKETS`, `IFCOUNTER_IBYTES`, `IFCOUNTER_OBYTES`, `IFCOUNTER_IERRORS`, `IFCOUNTER_OERRORS`, `IFCOUNTER_IMCASTS`, `IFCOUNTER_OMCASTS`, and `IFCOUNTER_OQDROPS`, among others. These counters are what users see in `netstat` and `systat`. +`netstat -in` 向内核请求每个 `ifnet` 上携带的接口统计信息。你的驱动程序通过在发送和接收路径的适当时刻调用 `if_inc_counter(ifp, IFCOUNTER_*, n)` 来更新这些计数器。计数器集在 `/usr/src/sys/net/if.h` 中定义,包括 `IFCOUNTER_IPACKETS`、`IFCOUNTER_OPACKETS`、`IFCOUNTER_IBYTES`、`IFCOUNTER_OBYTES`、`IFCOUNTER_IERRORS`、`IFCOUNTER_OERRORS`、`IFCOUNTER_IMCASTS`、`IFCOUNTER_OMCASTS` 和 `IFCOUNTER_OQDROPS` 等。这些计数器是用户在 `netstat` 和 `systat` 中看到的。 -`tcpdump` relies on a separate subsystem called the Berkeley Packet Filter, or BPF. Every 接口 that wants to be visible to `tcpdump` must 注册 with BPF through `bpf附加()`, and every 数据包 that the 驱动程序 transmits or receives must be presented to BPF through `BPF_MTAP()` or `bpf_mtap2()` before being either sent out or handed up. We will do this in our 驱动程序. It is one of the small courtesies you pay to the rest of the system so that the tools work. +`tcpdump` 依赖于一个名为 Berkeley Packet Filter(BPF)的独立子系统。每个想要对 `tcpdump` 可见的接口都必须通过 `bpfattach()` 向 BPF 注册,驱动程序发送或接收的每个数据包都必须通过 `BPF_MTAP()` 或 `bpf_mtap2()` 在发送出去或向上传递之前呈现给 BPF。我们将在我们的驱动程序中这样做。这是你向系统其余部分支付的小礼貌,以便工具能够工作。 -### A Useful Picture +### 一张有用的图 -It is worth closing the section with a diagram. The picture below shows how the pieces we have described fit together. Do not memorise it yet. Just get used to the shape. We will come back to every box in later sections. +值得用一张图来结束这一节。下面的图片显示了我们描述的各个部分如何组合在一起。暂时不要记住它。只要习惯这个形状。我们将在后面的章节中回到每个框。 ```text +-------------------+ @@ -196,79 +195,79 @@ It is worth closing the section with a diagram. The picture below shows how the +-------------------+ ``` -The boxes above the 驱动程序 are the stack and userland. The box below is the transport. Your 驱动程序, on that middle line, is the only place in the system where a `struct ifnet` meets a `struct mbuf` meets a wire. That is your territory. +驱动程序上方的框是协议栈和用户态。下方的框是传输层。你的驱动程序,在那条中间线上,是系统中 `struct ifnet` 遇到 `struct mbuf` 遇到线路的唯一地方。那是你的领地。 -### Tracing a Packet Through the Stack +### 追踪数据包穿越协议栈的过程 -It is useful to follow one specific 数据包 from birth to death, because that fixes the relationships in the diagram above to real code. Let us trace an outbound ICMP echo request generated by `ping 192.0.2.99` on an 接口 named `mynet0` that has been assigned the address `192.0.2.1/24`. +追踪一个特定数据包从诞生到消亡是很有用的,因为这将上图中的关系与真实代码固定下来。让我们追踪一个由 `ping 192.0.2.99` 在名为 `mynet0` 的接口上生成的出站 ICMP 回显请求,该接口已被分配地址 `192.0.2.1/24`。 -The `ping(8)` program opens a raw ICMP 套接字 and writes an echo request payload through `sendto(2)`. Inside the 内核, the 套接字 layer in `/usr/src/sys/kern/uipc_套接字.c` copies the payload into a fresh mbuf chain. The 套接字 is unconnected, so each write carries a destination address that the 套接字 layer forwards to the protocol layer. The protocol layer, in `/usr/src/sys/netinet/raw_ip.c`, 附加 an IP header and calls `ip_output` in `/usr/src/sys/netinet/ip_output.c`. `ip_output` performs the route lookup and finds a routing entry that points at `mynet0`. It also notices that the destination is not the broadcast address and not an on-link neighbour whose MAC it already knows, so it must trigger ARP. +`ping(8)` 程序打开一个原始 ICMP 套接字,通过 `sendto(2)` 写入一个回显请求有效载荷。在内核内部,`/usr/src/sys/kern/uipc_socket.c` 中的套接字层将有效载荷复制到一个新的 mbuf 链中。套接字是未连接的,因此每次写入都携带一个目标地址,套接字层将其转发给协议层。协议层位于 `/usr/src/sys/netinet/raw_ip.c`,它附加一个 IP 头部并调用 `/usr/src/sys/netinet/ip_output.c` 中的 `ip_output`。`ip_output` 执行路由查找,找到一个指向 `mynet0` 的路由条目。它还注意到目标不是广播地址,也不是它已经知道 MAC 地址的链路本地邻居,因此必须触发 ARP。 -At this point the IP layer calls `ether_output`, defined in `/usr/src/sys/net/if_ethersubr.c`. `ether_output` notices that the next-hop address is unresolved and issues an ARP request first. The ARP machinery, in `/usr/src/sys/netinet/if_ether.c`, constructs a broadcast ARP 帧, wraps it in a new mbuf, and calls `ether_output_帧`, which in turn calls `ifp->if_transmit`. That is our `mynet_transmit` function. The mbuf we receive in the transmit 回调 already contains a complete 以太网 帧: destination MAC `ff:ff:ff:ff:ff:ff`, source MAC our fabricated address, EtherType `0x0806` (ARP), and the ARP payload. +此时 IP 层调用 `/usr/src/sys/net/if_ethersubr.c` 中定义的 `ether_output`。`ether_output` 注意到下一跳地址未解析,首先发出一个 ARP 请求。ARP 机制位于 `/usr/src/sys/netinet/if_ether.c`,它构造一个广播 ARP 帧,将其包装在一个新的 mbuf 中,然后调用 `ether_output_frame`,后者又调用 `ifp->if_transmit`。这就是我们的 `mynet_transmit` 函数。我们在发送回调中收到的 mbuf 已经包含一个完整的以太网帧:目标 MAC `ff:ff:ff:ff:ff:ff`,源 MAC 为我们编造的地址,EtherType `0x0806`(ARP),以及 ARP 有效载荷。 -We do what every 驱动程序 does at that point: validate, count, tap BPF, and release. Because we are a pseudo-驱动程序, we free the 帧 rather than handing it to hardware. In a real NIC 驱动程序 we would hand the mbuf to DMA and free it later when the completion interrupt fires. Either way, the mbuf has reached the end of its life from the 驱动程序's perspective. +我们在那个点做每个驱动程序所做的事情:验证、计数、BPF 捕获和释放。因为我们是伪驱动程序,我们释放帧而不是将其交给硬件。在真实的网卡驱动程序中,我们会将 mbuf 交给 DMA 并在完成中断触发时稍后释放它。无论哪种方式,从驱动程序的角度来看,mbuf 已经到达了其生命的终点。 -While the ARP request hangs unanswered, the stack queues the original ICMP payload in the ARP pending queue. When the ARP reply does not arrive within a configurable timeout, the stack gives up on that 数据包 and increments `IFCOUNTER_OQDROPS`. In our pseudo-驱动程序, of course, no reply will ever come because there is nothing on the other end of the simulated wire. That is why `ping` eventually prints "100.0% 数据包 loss" and exits without success. The absence of a reply is not a bug in our 驱动程序; it is a property of the transport we have chosen to simulate. +当 ARP 请求悬而未决时,协议栈将原始 ICMP 有效载荷排队在 ARP 等待队列中。当 ARP 回复在可配置的超时时间内没有到达时,协议栈放弃该数据包并递增 `IFCOUNTER_OQDROPS`。当然,在我们的伪驱动程序中,永远不会收到回复,因为模拟线路的另一端没有任何东西。这就是为什么 `ping` 最终打印「100.0% 数据包丢失」并无成功退出的原因。没有回复不是我们驱动程序中的错误;这是我们所选择模拟的传输层的属性。 -Now trace the reverse path. The synthetic ARP request we generate every second in `mynet_rx_timer` starts life as memory we allocate with `MGETHDR` inside our 驱动程序. We fill in the 以太网 header, the ARP header, and the ARP payload. We tap BPF. We call `if_input`, which dereferences `ifp->if_input` and lands in `ether_input`. `ether_input` looks at the EtherType and dispatches the payload to `arpintr` (or its modern equivalent, a direct call from within `ether_demux`). The ARP code inspects the sender and target IPs, notices that the target is not us, and silently drops the 帧. Done. +现在追踪反向路径。我们在 `mynet_rx_timer` 中每秒生成的合成 ARP 请求,最初是在驱动程序内部用 `MGETHDR` 分配的内存。我们填入以太网头部、ARP 头部和 ARP 有效载荷。我们捕获 BPF。我们调用 `if_input`,它解引用 `ifp->if_input` 并进入 `ether_input`。`ether_input` 查看 EtherType 并将有效载荷分派到 `arpintr`(或其现代等价物,即 `ether_demux` 内部的直接调用)。ARP 代码检查发送方和目标 IP,注意到目标不是我们,静默丢弃该帧。完成。 -In both directions the 驱动程序 is a brief pass-through: a mbuf arrives, a mbuf departs, counters move, and BPF sees everything in between. That simplicity is deceptive, because every step has a contract that must not be broken, but the pattern is genuinely this short. +在两个方向上,驱动程序都是一个简短的直通:一个 mbuf 到达,一个 mbuf 离开,计数器移动,BPF 看到其间的一切。这种简单性具有欺骗性,因为每一步都有一个不可违反的契约,但模式确实是这么短。 -### The Queue Disciplines Above You +### 你上方的队列调度 -You do not see them from the 驱动程序, but the stack has queue disciplines that govern how 数据包 are delivered to `if_transmit`. Historically, 驱动程序 had an `if_start` 回调 and the stack would place 数据包 on an internal queue (`if_snd`) for later dispatch. Modern 驱动程序 use `if_transmit` and receive the mbuf directly, letting the 驱动程序 or the `drbr(9)` helper library manage any per-CPU queues internally. +你从驱动程序中看不到它们,但协议栈有队列调度规则来控制数据包如何传递给 `if_transmit`。历史上,驱动程序有一个 `if_start` 回调,协议栈会将数据包放在内部队列(`if_snd`)上以便稍后分发。现代驱动程序使用 `if_transmit` 并直接接收 mbuf,让驱动程序或 `drbr(9)` 辅助库在内部管理任何每 CPU 队列。 -In practice, almost all modern 驱动程序 use `if_transmit` and let the stack hand them 数据包 one at a time. Because `if_transmit` is called on the thread that produced the 数据包 (typically a TCP retransmit timer or the thread that wrote to the 套接字), the transmit path is usually on a regular 内核 thread with preemption enabled. This matters because it means you generally cannot assume that transmit runs at elevated priority, and you must not hold a 互斥锁 across a long operation. +实际上,几乎所有现代驱动程序都使用 `if_transmit`,让协议栈一次交给它们一个数据包。因为 `if_transmit` 在产生数据包的线程上被调用(通常是 TCP 重传定时器或写入套接字的线程),发送路径通常在启用了抢占的常规内核线程上。这很重要,因为这意味着你通常不能假设发送以提升的优先级运行,你不得在长时间操作中持有互斥锁。 -A small number of 驱动程序 still use the classic `if_start` model, where the stack fills a queue and calls `if_start` to drain it. That model is simpler for 驱动程序 with simple hardware queueing, but less flexible under load. `epair(4)` uses `if_transmit` directly. `disc(4)` implements its own tiny `discoutput` that is called from `ether_output`'s pre-transmit path. Most real NIC 驱动程序 use `if_transmit` with internal per-CPU queues powered by `drbr`. +少数驱动程序仍然使用经典的 `if_start` 模型,其中协议栈填充一个队列并调用 `if_start` 来排空它。该模型对于具有简单硬件排队的驱动程序来说更简单,但在负载下灵活性较差。`epair(4)` 直接使用 `if_transmit`。`disc(4)` 实现了自己微小的 `discoutput`,从 `ether_output` 的预发送路径中调用。大多数真正的网卡驱动程序使用 `if_transmit`,配合由 `drbr` 驱动的内部每 CPU 队列。 -For `mynet`, we use `if_transmit` and no internal queue. This is the simplest possible design and it matches what a minimal real 驱动程序 would do for low-bandwidth links. +对于 `mynet`,我们使用 `if_transmit` 且没有内部队列。这是最简单的设计,它匹配最小真实驱动程序在低带宽链路上的做法。 -### A Note on Packet-Tap Visibility +### 关于数据包捕获可见性的说明 -Packet taps, discussed in the next few sections, are one of the key reasons a 网络驱动程序 feels different from a character 驱动程序. A character 驱动程序's traffic is invisible to external observers, because there is no analogue of `tcpdump` for arbitrary `/dev/` traffic. A 网络驱动程序's traffic, by contrast, is observable at multiple levels simultaneously: BPF captures at the 驱动程序 level, pflog at the 数据包-filter level, 接口 counters at the 内核 level, and 套接字 缓冲区 at the userland level. All of that observability is free for the 驱动程序 author, provided the 驱动程序 taps BPF and updates counters at the correct points. +数据包捕获是网络驱动程序与字符驱动程序感觉不同的关键原因之一。字符驱动程序的流量对外部观察者是不可见的,因为对于任意 `/dev/` 流量没有类似 `tcpdump` 的工具。相比之下,网络驱动程序的流量可以在多个级别同时观察:BPF 在驱动程序级别捕获,pflog 在包过滤级别,接口计数器在内核级别,套接字缓冲区在用户态级别。所有这些可观测性对驱动程序作者来说是免费的,只要驱动程序在正确的点捕获 BPF 并更新计数器。 -This unusual level of external visibility is a blessing for debugging. When you cannot tell why a 数据包 did or did not flow, you can almost always answer the question with a combination of `tcpdump`, `netstat`, `arp`, and `route monitor`. That is a capable toolset, and we will put it to work throughout the labs. +这种不寻常的外部可见性水平是调试的福音。当你无法判断一个数据包为什么流动或没有流动时,你几乎总是可以通过 `tcpdump`、`netstat`、`arp` 和 `route monitor` 的组合来回答问题。那是一套有能力的工具集,我们将在整个实验中使用它。 -### 总结 Section 1 +### 第1节小结 -We have set the scene. A 网络驱动程序 moves mbufs between the stack and a transport. It presents a standardised 接口 called `ifnet`. It is driven by calls from the stack into fixed 回调. It pushes received traffic up through `if_input`. It is visible to `ifconfig`, to `netstat`, and to `tcpdump` through a handful of 内核 conventions. +我们已经布好了场景。网络驱动程序在协议栈和传输层之间移动 mbuf。它呈现一个名为 `ifnet` 的标准化接口。它由协议栈通过固定回调驱动。它通过 `if_input` 向上推送接收到的流量。它通过少量内核约定对 `ifconfig`、`netstat` 和 `tcpdump` 可见。 -With that rough shape in mind, we can look at the `ifnet` object itself. That is the subject of Section 2. +有了那个粗略的形状,我们可以看看 `ifnet` 对象本身。那是第2节的主题。 -## 第2节: Introducing `ifnet` +## 第2节:认识 `ifnet` -Every 网络接口 on a running FreeBSD system is represented in the 内核 by a `struct ifnet`. That structure is the central object of the networking subsystem. When `ifconfig` lists 接口, it is essentially iterating over a list of `ifnet` objects. When the stack picks a route, it eventually lands on an `ifnet` and calls its transmit function. When a 驱动程序 reports link state, it updates fields inside an `ifnet`. Learning `ifnet` is not optional. Everything else in this chapter is built on it. +每个运行中的 FreeBSD 系统上的网络接口在内核中由一个 `struct ifnet` 表示。该结构是网络子系统的核心对象。当 `ifconfig` 列出接口时,它本质上是在遍历一个 `ifnet` 对象列表。当协议栈选择路由时,它最终落在一个 `ifnet` 上并调用其发送函数。当驱动程序报告链路状态时,它更新 `ifnet` 内部的字段。学习 `ifnet` 不是可选的。本章中的其他一切都建立在它之上。 -### Where `ifnet` Lives +### `ifnet` 的位置 -The declaration of `struct ifnet` is in `/usr/src/sys/net/if_var.h`. Over the years FreeBSD has moved toward treating it as opaque, and the recommended way to refer to it in new 驱动程序 code is through the typedef `if_t`, which is a pointer to the underlying structure: +`struct ifnet` 的声明在 `/usr/src/sys/net/if_var.h` 中。多年来,FreeBSD 一直趋向于将其视为不透明的,在新驱动程序代码中引用它的推荐方式是通过 typedef `if_t`,它是指向底层结构的指针: ```c typedef struct ifnet *if_t; ``` -Old 驱动程序 code reaches directly into `ifp->if_softc`, `ifp->if_flags`, `ifp->if_mtu`, and similar fields. New 驱动程序 code prefers accessor functions such as `if_setsoftc(ifp, sc)`, `if_getflags(ifp)`, `if_setflags(ifp, flags)`, and `if_setmtu(ifp, mtu)`. Both styles still exist in the tree, and existing 驱动程序 such as `/usr/src/sys/net/if_disc.c` still use direct field access. The opaque style is the direction the 内核 is moving, but you will see both for years to come. +旧的驱动程序代码直接访问 `ifp->if_softc`、`ifp->if_flags`、`ifp->if_mtu` 和类似字段。新的驱动程序代码倾向于使用访问器函数,如 `if_setsoftc(ifp, sc)`、`if_getflags(ifp)`、`if_setflags(ifp, flags)` 和 `if_setmtu(ifp, mtu)`。两种风格仍然存在于源代码树中,现有驱动程序如 `/usr/src/sys/net/if_disc.c` 仍然使用直接字段访问。不透明风格是内核发展的方向,但你在未来几年内仍会看到两种风格。 -Throughout this chapter we will use whatever is clearest in the given context. When the direct-field style makes the code smaller and easier to read, we will use it. When an accessor makes the intent clearer, we will use that. You should be able to read either form. +在本章中,我们将使用在给定上下文中最清晰的方式。当直接字段风格使代码更小、更易读时,我们将使用它。当访问器使意图更清晰时,我们将使用它。你应该能够阅读两种形式。 -### The Minimum Fields You Care About +### 你需要关心的最少字段 -A `struct ifnet` has dozens of fields. The good news is that a 驱动程序 only touches a handful of them directly. The fields you will set or inspect in the 驱动程序 we build are, broadly: +`struct ifnet` 有几十个字段。好消息是驱动程序只直接接触其中的一小部分。你将在我们构建的驱动程序中设置或检查的字段大致如下: -* **Identity.** `if_softc` points back at your 驱动程序's private structure, `if_xname` is the 接口 name (for example `mynet0`), `if_dname` is the family name (`"mynet"`), and `if_dunit` is the unit number. -* **Capabilities and counts.** `if_mtu` is the maximum transmission unit, `if_baudrate` is a reported line rate in bits per second, `if_capabilities` and `if_capenable` describe offload capabilities like VLAN tagging and checksum offload. -* **Flags.** `if_flags` holds the 接口-level flags set by userland: `IFF_UP`, `IFF_BROADCAST`, `IFF_SIMPLEX`, `IFF_MULTICAST`, `IFF_POINTOPOINT`, `IFF_LOOPBACK`. `if_drv_flags` holds 驱动程序-private flags; the most important is `IFF_DRV_RUNNING`, which means the 驱动程序 has allocated its per-接口 resources and is ready to move traffic. -* **Callbacks.** `if_init`, `if_ioctl`, `if_transmit`, `if_qflush`, and `if_input` are the function pointers the stack invokes. Some of these have long-standing direct fields; the accessor equivalents are `if_setinitfn`, `if_setioctlfn`, `if_settransmitfn`, `if_setqflushfn`, and `if_setinputfn`. -* **Statistics.** The per-counter accessors `if_inc_counter(ifp, IFCOUNTER_*, n)` increment the counters that `netstat -in` displays. -* **BPF hook.** `if_bpf` is an opaque pointer used by BPF. Your 驱动程序 does not normally read it directly, but when you call `bpf附加(ifp, ...)` and `BPF_MTAP(ifp, m)`, the system will manage it. -* **Media and link state.** `ifmedia` lives in your softc, not in the `ifnet`, but the 接口 reports link state by calling `if_link_state_change(ifp, LINK_STATE_*)`. +* **身份。** `if_softc` 指回你驱动程序的私有结构体,`if_xname` 是接口名称(例如 `mynet0`),`if_dname` 是家族名称(`"mynet"`),`if_dunit` 是单元编号。 +* **能力和计数。** `if_mtu` 是最大传输单元,`if_baudrate` 是以比特每秒为单位的报告线路速率,`if_capabilities` 和 `if_capenable` 描述卸载能力,如 VLAN 标记和校验和卸载。 +* **标志。** `if_flags` 保存由用户态设置的接口级标志:`IFF_UP`、`IFF_BROADCAST`、`IFF_SIMPLEX`、`IFF_MULTICAST`、`IFF_POINTOPOINT`、`IFF_LOOPBACK`。`if_drv_flags` 保存驱动程序私有标志;最重要的是 `IFF_DRV_RUNNING`,表示驱动程序已分配其每接口资源并准备好移动流量。 +* **回调。** `if_init`、`if_ioctl`、`if_transmit`、`if_qflush` 和 `if_input` 是协议栈调用的函数指针。其中一些有长期存在的直接字段;访问器等价物是 `if_setinitfn`、`if_setioctlfn`、`if_settransmitfn`、`if_setqflushfn` 和 `if_setinputfn`。 +* **统计。** 每计数器访问器 `if_inc_counter(ifp, IFCOUNTER_*, n)` 递增 `netstat -in` 显示的计数器。 +* **BPF 钩子。** `if_bpf` 是 BPF 使用的不透明指针。你的驱动程序通常不会直接读取它,但当你调用 `bpfattach(ifp, ...)` 和 `BPF_MTAP(ifp, m)` 时,系统会管理它。 +* **媒体和链路状态。** `ifmedia` 位于你的 softc 中,而不是 `ifnet` 中,但接口通过调用 `if_link_state_change(ifp, LINK_STATE_*)` 报告链路状态。 -If the list looks long, remember that most 驱动程序 set each field once and then leave it alone. The work of a 驱动程序 is in the 回调, not in the ifnet fields themselves. +如果列表看起来很长,请记住大多数驱动程序设置每个字段一次然后就不管了。驱动程序的工作在回调中,不在 ifnet 字段本身中。 -### The `ifnet` Life Cycle +### `ifnet` 的生命周期 -A `struct ifnet` goes through the same high-level stages as a `设备_t` or a softc: allocation, configuration, registration, active life, and teardown. The call graph is: +`struct ifnet` 经历与 `device_t` 或 softc 相同的高层阶段:分配、配置、注册、活跃生命周期和拆卸。调用图为: ```text if_alloc(type) -> returns a fresh ifnet, not yet attached @@ -298,23 +297,23 @@ A `struct ifnet` goes through the same high-level stages as a `设备_t` or a so if_free(ifp) ``` -There are two common variants of the 附加 and 分离 calls. A plain pseudo-接口 that does not need 以太网 wiring uses `if_附加` and `if_分离`. A pseudo or real 以太网 接口 uses `ether_if附加` and `ether_if分离` instead. The 以太网 variants wrap the plain ones and add the extra setup needed for a layer-2 以太网 接口, including `bpf附加`, address registration, and wiring up `ifp->if_input` and `ifp->if_output` to `ether_input` and `ether_output`. We will use the 以太网 variant in our 驱动程序 because it gives us a familiar MAC-addressed 接口 that `ifconfig`, `ping`, and `tcpdump` all understand without special treatment. +附加和分离调用有两种常见的变体。不需要以太网布线的普通伪接口使用 `if_attach` 和 `if_detach`。伪或真实以太网接口使用 `ether_ifattach` 和 `ether_ifdetach`。以太网变体包装了普通变体,并添加了二层以太网接口所需的额外设置,包括 `bpfattach`、地址注册,以及将 `ifp->if_input` 和 `ifp->if_output` 连接到 `ether_input` 和 `ether_output`。我们将在驱动程序中使用以太网变体,因为它为我们提供了一个熟悉的 MAC 地址接口,`ifconfig`、`ping` 和 `tcpdump` 都可以直接理解而无需特殊处理。 -If you open `/usr/src/sys/net/if_ethersubr.c` and look at `ether_if附加`, you will see precisely this logic: set `if_addrlen` to `ETHER_ADDR_LEN`, set `if_hdrlen` to `ETHER_HDR_LEN`, set `if_mtu` to `ETHERMTU`, call `if_附加`, then install the common 以太网 input and output routines and finally call `bpf附加`. It is worth reading that function in full. It is short and it shows you exactly what a 驱动程序 gets for free by using `ether_if附加` instead of the bare `if_附加`. +如果你打开 `/usr/src/sys/net/if_ethersubr.c` 查看 `ether_ifattach`,你会看到正是这个逻辑:将 `if_addrlen` 设置为 `ETHER_ADDR_LEN`,将 `if_hdrlen` 设置为 `ETHER_HDR_LEN`,将 `if_mtu` 设置为 `ETHERMTU`,调用 `if_attach`,然后安装通用以太网输入和输出例程,最后调用 `bpfattach`。值得完整阅读那个函数。它很短,它向你展示了驱动程序通过使用 `ether_ifattach` 而不是裸 `if_attach` 免费获得了什么。 -### Why `ifnet` Is Not a `cdevsw` +### 为什么 `ifnet` 不是 `cdevsw` -It is tempting to see `ifnet` as just "a cdevsw for networking". It is not. A `cdevsw` is an entry table used by `devfs` to dispatch `read`, `write`, `ioctl`, `open`, and `close` from userland to a 驱动程序. An `ifnet` is the first-class object the network stack itself maintains for every 接口. Even if no userland process has ever touched the 接口, the stack still cares about its `ifnet`, because routing tables, ARP, and 数据包 forwarding all depend on it. +很容易将 `ifnet` 看作只是「网络的 cdevsw」。不是这样的。`cdevsw` 是 `devfs` 用来将用户态的 `read`、`write`、`ioctl`、`open` 和 `close` 分派到驱动程序的入口表。`ifnet` 是网络协议栈自身为每个接口维护的一等对象。即使用户态进程从未接触过该接口,协议栈仍然关心它的 `ifnet`,因为路由表、ARP 和数据包转发都依赖于它。 -You can see this if you think about how `ifconfig` talks to the 内核. It does not open `/dev/mynet0`. It opens a 套接字 and issues ioctls on that 套接字, passing the 接口 name as an argument. The 内核 then looks up the `ifnet` by name and invokes `if_ioctl` on it. There is no file 描述符 pointing at your 接口 on the userland side. The 接口 is a stack-level entity, not a `/dev/` entity. +如果你思考 `ifconfig` 如何与内核对话,你可以看到这一点。它不打开 `/dev/mynet0`。它打开一个套接字并在该套接字上发出 ioctl,将接口名称作为参数传递。内核然后按名称查找 `ifnet` 并对其调用 `if_ioctl`。用户态端没有指向你接口的文件描述符。接口是协议栈级别的实体,不是 `/dev/` 实体。 -That is why we need a whole new object: because networking requires a persistent, 内核-internal handle that exists regardless of which process is doing what. `ifnet` is that handle. +这就是为什么我们需要一个全新的对象:因为网络需要一个持久的、内核内部的句柄,无论哪个进程在做什么都存在。`ifnet` 就是那个句柄。 -### Pseudo-Interfaces vs Real NIC Interfaces +### 伪接口与真实网卡接口 -Every 接口 in the 内核, pseudo or real, has an `ifnet`. The loopback 接口 `lo0` has one. The `disc` 接口 we will study has one. Every `emX` 以太网 adapter has one. Every `wlanX` wireless 接口 has one. The `ifnet` is the universal currency. +内核中的每个接口,无论是伪的还是真实的,都有一个 `ifnet`。环回接口 `lo0` 有一个。我们将研究的 `disc` 接口有一个。每个 `emX` 以太网适配器都有一个。每个 `wlanX` 无线接口都有一个。`ifnet` 是通用货币。 -Pseudo-接口 differ from real NICs in how they are instantiated. A real NIC 接口 is created by the 驱动程序's `附加` method during 总线 探测, the same way the USB and PCI 驱动程序 in 第26章 附加 their 设备. A pseudo-接口 is created at module load time, or on demand through `ifconfig mynet0 create`, via a mechanism called the **接口 cloner**. We will use an 接口 cloner for `mynet`, which means users will be able to create 接口 dynamically, just as they can create epair 接口 today: +伪接口与真实网卡在实例化方式上不同。真实网卡接口在总线探测期间由驱动程序的 `attach` 方法创建,就像第26章中的 USB 和 PCI 驱动程序附加它们的设备一样。伪接口在模块加载时创建,或者通过 `ifconfig mynet0 create` 按需创建,通过一种称为**接口克隆器**的机制。我们将为 `mynet` 使用接口克隆器,这意味着用户将能够动态创建接口,就像他们今天可以创建 epair 接口一样: ```console # ifconfig mynet create @@ -324,64 +323,64 @@ mynet0 mynet0: flags=8843 metric 0 mtu 1500 ``` -We will describe cloners in Section 3. For now, it is enough to know that cloning is how a module contributes one or more `ifnet` objects to the running system at the user's request. +我们将在第3节中描述克隆器。现在,只需要知道克隆是模块根据用户请求向运行中的系统贡献一个或多个 `ifnet` 对象的方式就够了。 -### A Closer Look at Key `ifnet` Fields +### 深入了解关键 `ifnet` 字段 -Because the `ifnet` is the structure your 驱动程序 writes to most often, it helps to survey a few of its fields in slightly more depth before we open the code. You do not need to memorise the complete declaration. What you need is enough familiarity with the layout to read 驱动程序 code without constantly flipping back to `if_var.h`. +因为 `ifnet` 是你的驱动程序最常写入的结构,在打开代码之前,稍微深入地了解它的一些字段会有帮助。你不需要记住完整的声明。你需要的是对布局足够熟悉,以便在不不断翻回 `if_var.h` 的情况下阅读驱动程序代码。 -`if_xname` is a character array holding the 接口's user-visible name, such as `mynet0`. It is set by `if_initname` and from that moment is treated by the stack as read-only. When you read `ifconfig -a` output, every line that begins with an 接口 name is printing a copy of `if_xname`. +`if_xname` 是一个字符数组,保存接口的用户可见名称,例如 `mynet0`。它由 `if_initname` 设置,从那一刻起被协议栈视为只读。当你阅读 `ifconfig -a` 输出时,每一行以接口名称开头的行都在打印 `if_xname` 的副本。 -`if_dname` and `if_dunit` record the 驱动程序 family name and the unit number separately. `if_dname` is `"mynet"` for every instance of our 驱动程序, and `if_dunit` is `0` for `mynet0`, `1` for `mynet1`, and so on. The network stack uses these fields to index the 接口 into various hashes, and `ifconfig` uses them when matching an 接口 name to a 驱动程序 family. +`if_dname` 和 `if_dunit` 分别记录驱动程序家族名称和单元编号。对于我们驱动程序的每个实例,`if_dname` 都是 `"mynet"`,而 `if_dunit` 对于 `mynet0` 是 `0`,对于 `mynet1` 是 `1`,依此类推。网络协议栈使用这些字段将接口索引到各种哈希中,`ifconfig` 在将接口名称匹配到驱动程序家族时也使用它们。 -`if_softc` is the back-pointer to your 驱动程序's private per-接口 structure. Every 回调 the stack invokes will pass an `ifp` argument, and the first thing most 回调 do is pull the softc out of `ifp->if_softc` (or `if_getsoftc(ifp)`). If you forget to set `if_softc` during creation, your 回调 will dereference a NULL pointer and the 内核 will panic. +`if_softc` 是指回你驱动程序私有每接口结构体的反向指针。协议栈调用的每个回调都会传递一个 `ifp` 参数,大多数回调做的第一件事就是从 `ifp->if_softc`(或 `if_getsoftc(ifp)`)中取出 softc。如果你在创建期间忘记设置 `if_softc`,你的回调将解引用一个 NULL 指针,内核将会崩溃。 -`if_type` is the type constant from `/usr/src/sys/net/if_types.h`. `IFT_ETHER` for an 以太网-like 接口, `IFT_LOOP` for loopback, `IFT_IEEE80211` for wireless, `IFT_TUNNEL` for a generic tunnel, and dozens of others. The stack occasionally specialises behaviour based on `if_type`, for example in deciding how to format a link-layer address for display. +`if_type` 是来自 `/usr/src/sys/net/if_types.h` 的类型常量。`IFT_ETHER` 用于类似以太网的接口,`IFT_LOOP` 用于环回,`IFT_IEEE80211` 用于无线,`IFT_TUNNEL` 用于通用隧道,还有几十个其他类型。协议栈偶尔会根据 `if_type` 专门化行为,例如在决定如何格式化链路层地址以供显示时。 -`if_addrlen` and `if_hdrlen` describe the link-layer address length (six bytes for 以太网, eight bytes for InfiniBand, zero for a pure L3 tunnel) and the link-layer header length (14 bytes for plain 以太网, 22 for tagged 以太网). `ether_if附加` sets both of these for you with the 以太网 defaults. Other link-layer helpers set them with their own values. +`if_addrlen` 和 `if_hdrlen` 描述链路层地址长度(以太网为 6 字节,InfiniBand 为 8 字节,纯三层隧道为 0)和链路层头部长度(普通以太网为 14 字节,带标签的以太网为 22 字节)。`ether_ifattach` 会用以太网默认值为你设置这两个字段。其他链路层辅助函数会用它们自己的值来设置。 -`if_flags` is a bitmask of user-visible flags like `IFF_UP` and `IFF_BROADCAST`. `if_drv_flags` is a bitmask of 驱动程序-private flags like `IFF_DRV_RUNNING`. They are separate because they have different access rules. The user can write `if_flags`; only the 驱动程序 writes `if_drv_flags`. Mixing them is a classic bug. +`if_flags` 是用户可见标志的位掩码,如 `IFF_UP` 和 `IFF_BROADCAST`。`if_drv_flags` 是驱动程序私有标志的位掩码,如 `IFF_DRV_RUNNING`。它们是分开的,因为它们有不同的访问规则。用户可以写入 `if_flags`;只有驱动程序写入 `if_drv_flags`。将它们混淆是一个典型的错误。 -`if_capabilities` and `if_capenable` describe offload features. `if_capabilities` is what the hardware claims it can do. `if_capenable` is what is currently turned on. The split allows userland to toggle offloads at runtime through `ifconfig mynet0 -rxcsum` or `ifconfig mynet0 +tso`, and the 驱动程序 to honour that choice. We will see this interact with `SIOCSIFCAP` in Section 6. +`if_capabilities` 和 `if_capenable` 描述卸载特性。`if_capabilities` 是硬件声称它能做的事情。`if_capenable` 是当前已启用的功能。这种分离允许用户态在运行时通过 `ifconfig mynet0 -rxcsum` 或 `ifconfig mynet0 +tso` 切换卸载,驱动程序则遵守该选择。我们将在第 6 节中看到它与 `SIOCSIFCAP` 的交互。 -`if_mtu` is the maximum transmission unit in bytes. It is the largest L3 payload the 接口 can carry, not counting the link-layer header. 以太网 defaults to 1500. Jumbo-帧 以太网 typically supports 9000 or 9216. `if_baudrate` is an informational line-rate field in bits per second; it is advisory only. +`if_mtu` 是以字节为单位的最大传输单元。它是接口可以承载的最大三层有效载荷,不包括链路层头部。以太网默认值为 1500。巨型帧以太网通常支持 9000 或 9216。`if_baudrate` 是以比特每秒为单位的信息性线路速率字段;仅供参考。 -`if_init` is a function pointer invoked when the 接口 transitions to the up state. Its signature is `void (*)(void *softc)`. `if_ioctl` is invoked for 套接字 ioctls destined at this 接口; signature `int (*)(struct ifnet *, u_long, caddr_t)`. `if_transmit` is invoked to send a 数据包; signature `int (*)(struct ifnet *, struct mbuf *)`. `if_qflush` is invoked to flush 驱动程序-private queues; signature `void (*)(struct ifnet *)`. `if_input` is a function pointer in the other direction: the 驱动程序 calls it (usually through the `if_input(ifp, m)` helper) to hand a received mbuf to the stack. +`if_init` 是一个函数指针,在接口转换为 up 状态时被调用。其签名为 `void (*)(void *softc)`。`if_ioctl` 在目标为此接口的套接字 ioctl 时被调用;签名为 `int (*)(struct ifnet *, u_long, caddr_t)`。`if_transmit` 在发送数据包时被调用;签名为 `int (*)(struct ifnet *, struct mbuf *)`。`if_qflush` 在刷新驱动程序私有队列时被调用;签名为 `void (*)(struct ifnet *)`。`if_input` 是另一个方向的函数指针:驱动程序调用它(通常通过 `if_input(ifp, m)` 辅助函数)将接收到的 mbuf 交给协议栈。 -`if_snd` is the legacy send queue, used by 驱动程序 that still have an `if_start` 回调 rather than an `if_transmit`. For modern 驱动程序 with `if_transmit`, `if_snd` is unused. Most textbook examples you will read in the tree (including our `if_disc.c` reference) do not touch `if_snd` any more. +`if_snd` 是遗留的发送队列,由仍然使用 `if_start` 回调而不是 `if_transmit` 的驱动程序使用。对于使用 `if_transmit` 的现代驱动程序,`if_snd` 不再使用。你在源代码树中读到的大多数教科书示例(包括我们的 `if_disc.c` 参考)不再接触 `if_snd`。 -`if_bpf` is the BPF 附加ment pointer. BPF itself manages the value; 驱动程序 treat it as opaque. `BPF_MTAP` and related macros use it internally. +`if_bpf` 是 BPF 附加指针。BPF 本身管理该值;驱动程序将其视为不透明的。`BPF_MTAP` 和相关宏在内部使用它。 -`if_data` is a large structure carrying per-接口 statistics, media 描述符, and miscellaneous fields. Modern 驱动程序 avoid touching `if_data` directly and instead go through `if_inc_counter` and friends. The `if_data` structure is still there for backward compatibility and for userland-visible stats. +`if_data` 是一个大型结构体,承载每接口统计信息、媒体描述符和各种杂项字段。现代驱动程序避免直接接触 `if_data`,而是通过 `if_inc_counter` 及相关函数来操作。`if_data` 结构体仍然存在是为了向后兼容和供用户态可见的统计信息。 -This is far from an exhaustive list; `struct ifnet` has more than fifty fields in total. But the ones above are the ones your 驱动程序 is most likely to touch, and being comfortable naming them will make every later code listing easier to read. +这远非一个详尽的列表;`struct ifnet` 总共有五十多个字段。但上面列出的那些是你的驱动程序最可能接触到的字段,熟悉它们的名称将使后续每个代码清单更容易阅读。 -### The Accessor API in More Detail +### 访问器 API 详解 -The `if_t` opaque handle has been growing a family of accessor functions since FreeBSD 12. The pattern is consistent: where you would have written `ifp->if_flags |= IFF_UP`, you now write `if_setflagbits(ifp, IFF_UP, 0)`. Where you would have written `ifp->if_softc = sc`, you now write `if_setsoftc(ifp, sc)`. The motivation is to let the 内核 evolve the internal layout of `struct ifnet` without breaking 驱动程序. +`if_t` 不透明句柄自 FreeBSD 12 以来一直在发展一系列访问器函数。模式是一致的:以前你会写 `ifp->if_flags |= IFF_UP`,现在你写 `if_setflagbits(ifp, IFF_UP, 0)`。以前你会写 `ifp->if_softc = sc`,现在你写 `if_setsoftc(ifp, sc)`。其动机是让内核能够演化 `struct ifnet` 的内部布局而不破坏驱动程序。 -The accessor functions include: +访问器函数包括: -* `if_setsoftc(ifp, sc)` and `if_getsoftc(ifp)` for the softc pointer. -* `if_setflagbits(ifp, set, clear)` and `if_getflags(ifp)` for `if_flags`. -* `if_setdrvflagbits(ifp, set, clear)` and `if_getdrvflags(ifp)` for `if_drv_flags`. -* `if_setmtu(ifp, mtu)` and `if_getmtu(ifp)` for the MTU. -* `if_setbaudrate(ifp, rate)` and `if_getbaudrate(ifp)` for the advertised line rate. -* `if_sethwassist(ifp, assist)` and `if_gethwassist(ifp)` for checksum-offload hints. -* `if_settransmitfn(ifp, fn)` for `if_transmit`. -* `if_setioctlfn(ifp, fn)` for `if_ioctl`. -* `if_setinitfn(ifp, fn)` for `if_init`. -* `if_setqflushfn(ifp, fn)` for `if_qflush`. -* `if_setinputfn(ifp, fn)` for `if_input`. -* `if_inc_counter(ifp, ctr, n)` for the statistics counters. +* `if_setsoftc(ifp, sc)` 和 `if_getsoftc(ifp)` 用于 softc 指针。 +* `if_setflagbits(ifp, set, clear)` 和 `if_getflags(ifp)` 用于 `if_flags`。 +* `if_setdrvflagbits(ifp, set, clear)` 和 `if_getdrvflags(ifp)` 用于 `if_drv_flags`。 +* `if_setmtu(ifp, mtu)` 和 `if_getmtu(ifp)` 用于 MTU。 +* `if_setbaudrate(ifp, rate)` 和 `if_getbaudrate(ifp)` 用于报告的线路速率。 +* `if_sethwassist(ifp, assist)` 和 `if_gethwassist(ifp)` 用于校验和卸载提示。 +* `if_settransmitfn(ifp, fn)` 用于 `if_transmit`。 +* `if_setioctlfn(ifp, fn)` 用于 `if_ioctl`。 +* `if_setinitfn(ifp, fn)` 用于 `if_init`。 +* `if_setqflushfn(ifp, fn)` 用于 `if_qflush`。 +* `if_setinputfn(ifp, fn)` 用于 `if_input`。 +* `if_inc_counter(ifp, ctr, n)` 用于统计计数器。 -Some of these are inlines that still reach through to a direct field access behind the scenes; others are wrappers that may in the future refer to a subtly different field layout. Using the accessors now costs nothing and protects your 驱动程序 against future churn. +其中一些是内联函数,在幕后仍然直接访问字段;其他的是包装器,将来可能引用微妙不同的字段布局。现在使用访问器不花任何代价,并能保护你的驱动程序免受未来的变动影响。 -For `mynet` we mostly use the direct-field style, because that is what the existing reference 驱动程序 like `if_disc.c` and `if_epair.c` still use, and consistency with the rest of the tree is valuable for readers. When you graduate to writing your own new 驱动程序, feel free to prefer the accessors. Both styles are correct. +对于 `mynet`,我们主要使用直接字段风格,因为现有的参考驱动程序如 `if_disc.c` 和 `if_epair.c` 仍在使用它,与源代码树其余部分的一致性对读者来说是有价值的。当你毕业编写自己的新驱动程序时,可以随意选择访问器。两种风格都是正确的。 -### A First Glimpse of the Code +### 代码初览 -Before we move on, let us look at a tiny code fragment that summarises the shape of a 驱动程序's relationship with `ifnet`. This is the pattern you will type more fully in Section 3, but it is already useful to see the skeleton: +在我们继续之前,让我们看一个微小的代码片段,它总结了驱动程序与 `ifnet` 关系的形状。这是你在第 3 节中会更完整地输入的模式,但看到骨架已经很有用了: ```c struct mynet_softc { @@ -430,49 +429,49 @@ mynet_create(void) } ``` -Do not type this yet. It is only a sketch, and several pieces are missing. We will fill them in during Section 3. What matters now is the shape: allocate, configure, 附加. Every 驱动程序 in the tree does this, with variations for the 总线 it lives on and the transport it talks to. +先不要输入这段代码。它只是一个草图,还有几个部分缺失。我们将在第 3 节中填充它们。现在重要的是形状:分配、配置、附加。源代码树中的每个驱动程序都这样做,只是根据它所在的总线和它对话的传输层有所不同。 -### 总结 Section 2 +### 第2节小结 -The `ifnet` object is the 内核's representation of a 网络接口. It has identity fields, capability fields, flags, 回调, counters, and media state. It is created with `if_alloc`, configured by the 驱动程序, and installed in the system with `if_附加` or `ether_if附加`. A pseudo-接口 驱动程序 creates `ifnet`s on demand through an 接口 cloner. A real NIC 驱动程序 creates its `ifnet` during 探测 and 附加. +`ifnet` 对象是内核对网络接口的表示。它有身份字段、能力字段、标志、回调、计数器和媒体状态。它由 `if_alloc` 创建,由驱动程序配置,并通过 `if_attach` 或 `ether_ifattach` 安装到系统中。伪接口驱动程序通过接口克隆器按需创建 `ifnet`。真正的网卡驱动程序在探测和附加期间创建其 `ifnet`。 -You now have the vocabulary. In Section 3 we will put it to use by creating and 注册ing a real working 网络接口. Before we do, though, it is worth spending a little time reading a real 驱动程序 that uses the same patterns we are about to write. The next subsection guides you through `if_disc.c`, the canonical "simplest pseudo-以太网" 驱动程序 in the FreeBSD source tree. +你现在掌握了词汇。在第 3 节中,我们将通过创建和注册一个真正可用的网络接口来运用它。但在那之前,值得花一点时间阅读一个使用我们即将编写的相同模式的真实驱动程序。下一个小节将引导你阅读 `if_disc.c`,它是 FreeBSD 源代码树中经典的「最简伪以太网」驱动程序。 -### A Guided Tour of `if_disc.c` +### `if_disc.c` 导读 -Open `/usr/src/sys/net/if_disc.c` in your editor. It is about two hundred lines of code, and every line is instructive. The `disc(4)` 驱动程序 creates an 接口 whose only job is to silently drop every 数据包 it receives for transmission. It is the moral equivalent of `/dev/null` for 数据包. Because it is so small, it shows the shape of a pseudo-驱动程序 without any distraction. +在你的编辑器中打开 `/usr/src/sys/net/if_disc.c`。它大约有两百行代码,每一行都很有教益。`disc(4)` 驱动程序创建一个接口,其唯一工作是静默丢弃它收到的每个待发送数据包。它相当于数据包世界的 `/dev/null`。因为它如此之小,它展示了伪驱动程序的形状而没有任何干扰。 -The file begins with the standard license header, then a cluster of `#include` directives that should now look familiar. `net/if.h` and `net/if_var.h` for the 接口 structure, `net/ethernet.h` for 以太网-specific helpers, `net/if_clone.h` for the cloner API, `net/bpf.h` for 数据包 taps, and `net/vnet.h` for VNET awareness. That is almost exactly the include set we will use in `mynet.c`. +该文件以标准许可证头部开始,然后是一组现在应该看起来很熟悉的 `#include` 指令。`net/if.h` 和 `net/if_var.h` 用于接口结构体,`net/ethernet.h` 用于以太网特定的辅助函数,`net/if_clone.h` 用于克隆器 API,`net/bpf.h` 用于数据包捕获,`net/vnet.h` 用于 VNET 感知。这几乎正是我们将在 `mynet.c` 中使用的包含集。 -Next come a handful of module-level declarations. The string `discname = "disc"` is the family name the cloner will expose. `M_DISC` is the memory-type tag for `vmstat -m` accounting. `VNET_DEFINE_STATIC(struct if_clone *, disc_cloner)` declares a per-VNET cloner variable, and the `V_disc_cloner` macro provides the access shim. These are all pieces you will recognise when we write the same three lines in our own 驱动程序 a few pages from now. +接下来是一些模块级声明。字符串 `discname = "disc"` 是克隆器将暴露的家族名称。`M_DISC` 是 `vmstat -m` 记账的内存类型标签。`VNET_DEFINE_STATIC(struct if_clone *, disc_cloner)` 声明一个每 VNET 的克隆器变量,`V_disc_cloner` 宏提供访问垫片。这些片段在你几页后在我们自己的驱动程序中写入相同的三行时都会被识别出来。 -The softc declaration is particularly short. `struct disc_softc` holds only an `ifnet` pointer. That is all the state a discard 驱动程序 needs: one 接口 per softc, no counters, no queues, no timers. Our `mynet` softc will be longer because we have a simulated receive path, a media 描述符, and a 互斥锁, but the pattern of "one softc per 接口" is the same. +softc 声明特别短。`struct disc_softc` 只保存一个 `ifnet` 指针。这就是一个丢弃驱动程序所需的全部状态:每个 softc 一个接口,没有计数器,没有队列,没有定时器。我们的 `mynet` softc 会更长,因为我们有模拟的接收路径、媒体描述符和互斥锁,但「每个接口一个 softc」的模式是相同的。 -Move down the file to `disc_clone_create`. It begins by allocating the softc with `M_WAITOK | M_ZERO`, because the cloner is called from user context and can afford to sleep. Then it allocates the `ifnet` with `if_alloc(IFT_LOOP)`. Note that `disc` uses `IFT_LOOP` rather than `IFT_ETHER`, because its link-layer semantics are more loopback-like than 以太网-like. The choice of `IFT_*` constant matters because the stack queries `if_type` to decide which link-layer helper to invoke. Our 驱动程序 will use `IFT_ETHER` because we want to use `ether_if附加`. +向下浏览文件到 `disc_clone_create`。它首先用 `M_WAITOK | M_ZERO` 分配 softc,因为克隆器是从用户上下文调用的,可以承受睡眠。然后它用 `if_alloc(IFT_LOOP)` 分配 `ifnet`。注意 `disc` 使用 `IFT_LOOP` 而不是 `IFT_ETHER`,因为它的链路层语义更像环回而不是以太网。`IFT_*` 常量的选择很重要,因为协议栈查询 `if_type` 来决定调用哪个链路层辅助函数。我们的驱动程序将使用 `IFT_ETHER`,因为我们想使用 `ether_ifattach`。 -Then `disc_clone_create` calls `if_initname(ifp, discname, unit)`, sets the softc pointer, sets the `if_mtu` to `DSMTU` (a locally-defined value), and sets `if_flags` to `IFF_LOOPBACK | IFF_MULTICAST`. The 回调 `if_ioctl`, `if_output`, and `if_init` are set. Notice that `disc` sets `if_output` rather than `if_transmit`, because loopback-style 驱动程序 are still wired to the classical output path. Our 以太网 驱动程序 will use `if_transmit` through `ether_if附加`. +然后 `disc_clone_create` 调用 `if_initname(ifp, discname, unit)`,设置 softc 指针,将 `if_mtu` 设置为 `DSMTU`(一个本地定义的值),并将 `if_flags` 设置为 `IFF_LOOPBACK | IFF_MULTICAST`。回调 `if_ioctl`、`if_output` 和 `if_init` 被设置。注意 `disc` 设置的是 `if_output` 而不是 `if_transmit`,因为环回风格的驱动程序仍然连接到经典的输出路径。我们的以太网驱动程序将通过 `ether_ifattach` 使用 `if_transmit`。 -Then comes `if_附加(ifp)`, which 寄存器 the 接口 with the stack without 以太网-specific setup. `bpf附加(ifp, DLT_NULL, sizeof(u_int32_t))` follows, 注册ing with BPF using the null link-type (which tells `tcpdump` to expect a four-byte header carrying the address family of the payload). Our 驱动程序 will use `DLT_EN10MB`, automatically, via `ether_if附加`. +然后是 `if_attach(ifp)`,它在没有以太网特定设置的情况下将接口注册到协议栈。接着是 `bpfattach(ifp, DLT_NULL, sizeof(u_int32_t))`,使用空链路类型向 BPF 注册(告诉 `tcpdump` 期望一个携带有效载荷地址族的四字节头部)。我们的驱动程序将通过 `ether_ifattach` 自动使用 `DLT_EN10MB`。 -The destroy path, `disc_clone_destroy`, is symmetric: it calls `bpf分离`, `if_分离`, `if_free`, and finally `free(sc, M_DISC)`. Our 驱动程序 will be slightly more involved because we have callouts and a media 描述符 to tear down, but the skeleton is identical. +销毁路径 `disc_clone_destroy` 是对称的:它调用 `bpfdetach`、`if_detach`、`if_free`,最后调用 `free(sc, M_DISC)`。我们的驱动程序会稍微复杂一些,因为我们有 callout 和媒体描述符需要拆卸,但骨架是相同的。 -The transmit path, `discoutput`, is three lines of code. It inspects the 数据包 family, fills in the four-byte BPF header, taps BPF, updates counters, and frees the mbuf. That is all a "discard everything" 驱动程序 needs to do. Our `mynet_transmit` will be longer, but structurally it does exactly the same things with slightly more discipline: validate, tap, count, release. +发送路径 `discoutput` 只有三行代码。它检查数据包族,填入四字节的 BPF 头部,捕获 BPF,更新计数器,并释放 mbuf。这就是一个「丢弃一切」驱动程序需要做的全部。我们的 `mynet_transmit` 会更长,但在结构上它做的事情完全相同,只是稍微更有纪律:验证、捕获、计数、释放。 -The ioctl handler, `discioctl`, handles `SIOCSIFADDR`, `SIOCSIFFLAGS`, and `SIOCSIFMTU`, and returns `EINVAL` for everything else. For a minimal pseudo-驱动程序 this is plenty. Our 驱动程序 will be more elaborate because we add media 描述符 and delegate unknown ioctls to `ether_ioctl`, but the switch-statement shape is the same. +ioctl 处理程序 `discioctl` 处理 `SIOCSIFADDR`、`SIOCSIFFLAGS` 和 `SIOCSIFMTU`,对所有其他请求返回 `EINVAL`。对于一个最小的伪驱动程序来说这已经足够了。我们的驱动程序会更精细,因为我们添加了媒体描述符并将未知 ioctl 委托给 `ether_ioctl`,但 switch 语句的形状是相同的。 -Finally, the cloner registration is done in `vnet_disc_init` through `if_clone_simple(discname, disc_clone_create, disc_clone_destroy, 0)`, wrapped in `VNET_SYSINIT` and matched by a `VNET_SYSUNINIT` that calls `if_clone_分离`. Again, this is exactly the pattern we will use. +最后,克隆器注册在 `vnet_disc_init` 中通过 `if_clone_simple(discname, disc_clone_create, disc_clone_destroy, 0)` 完成,包装在 `VNET_SYSINIT` 中,并由调用 `if_clone_detach` 的 `VNET_SYSUNINIT` 匹配。同样,这正是我们将使用的模式。 -The take-away from reading `disc` is that a working pseudo-驱动程序 in the FreeBSD tree is about two hundred lines of code. Most of those lines are boilerplate that you set once and forget. The interesting parts are the softc, the cloner, and the handful of 回调. Everything else is rhythm. +阅读 `disc` 的收获是,FreeBSD 源代码树中一个可工作的伪驱动程序大约是两百行代码。其中大部分行是样板代码,你设置一次然后就不必管了。有趣的部分是 softc、克隆器和少数回调。其余的都是节奏。 -Do not feel obligated to memorise `disc`. Just read it once, slowly, now. When we start writing `mynet`, return to this section and you will see that most of what we type is the same pattern with a few additions for 以太网-like behaviour, 数据包 reception, and media 描述符. The pattern is worth seeing once in its purest form before we elaborate it. +不要觉得必须记住 `disc`。现在只需慢慢读一次。当我们开始编写 `mynet` 时,回到这一节,你会发现我们输入的大部分内容都是相同的模式,只是为类似以太网的行为、数据包接收和媒体描述符添加了一些内容。在我们详细阐述之前,以最纯粹的形式看到一次这个模式是值得的。 -## 第3节: Creating and Registering a Network Interface +## 第3节:创建和注册网络接口 -Time to write code. In this section we will build the skeleton of `mynet`, a pseudo-以太网 驱动程序. It will appear as a normal 以太网 接口 to the rest of the system. Userland will be able to create an instance with `ifconfig mynet create`, assign an IPv4 address, bring it up, take it down, and destroy it, just like `epair` and `disc`. We will not yet handle real 数据包 movement. Section 4 and Section 5 will handle the transmit and receive paths. Here we focus on the creation, registration, and basic metadata. +是时候写代码了。在本节中,我们将构建 `mynet` 的骨架,一个伪以太网驱动程序。它对系统其余部分将表现为一个普通的以太网接口。用户态将能够通过 `ifconfig mynet create` 创建一个实例,分配 IPv4 地址,启动它、关闭它、销毁它,就像 `epair` 和 `disc` 一样。我们暂时不处理真正的数据包移动。第 4 节和第 5 节将处理发送和接收路径。这里我们专注于创建、注册和基本元数据。 -### Project Layout +### 项目布局 -All companion files for this chapter live under `examples/part-06/ch28-network-驱动程序/`. The skeleton in this section is in `examples/part-06/ch28-network-驱动程序/lab01-skeleton/`. Create the directory if you are typing along manually, or look at the files if you prefer to read first and experiment later. The top-level layout we will use for the chapter is: +本章的所有配套文件位于 `examples/part-06/ch28-network-driver/` 下。本节的骨架在 `examples/part-06/ch28-network-driver/lab01-skeleton/` 中。如果你是手动输入的,请创建目录;如果你喜欢先阅读再实验,可以查看文件。我们将用于本章的顶层布局是: ```text examples/part-06/ch28-network-driver/ @@ -495,11 +494,11 @@ examples/part-06/ch28-network-driver/ challenge06-netgraph/ ``` -The top-level `mynet.c` is the reference 驱动程序 for the whole chapter and evolves from the skeleton in Section 3 through the final cleanup code in Section 8. The `lab0x` directories contain README files that walk you through the corresponding lab step. The challenges each add a small feature on top of the finished 驱动程序, and `shared/` holds helper scripts and notes referenced by more than one lab. +顶层 `mynet.c` 是整个章节的参考驱动程序,从第 3 节的骨架到第 8 节的最终清理代码不断演进。`lab0x` 目录包含引导你完成相应实验步骤的 README 文件。每个挑战在完成的驱动程序之上添加一个小功能,`shared/` 包含多个实验引用的辅助脚本和笔记。 -### The Makefile +### Makefile -Let us start with the build file. A 内核模块 for a pseudo-以太网 驱动程序 is one of the simplest Makefiles in the entire tree. Ours will look like this: +让我们从构建文件开始。伪以太网驱动程序的内核模块是整个源代码树中最简单的 Makefile 之一。我们的将如下所示: ```console # Makefile for mynet - Chapter 28 (Writing a Network Driver). @@ -517,11 +516,11 @@ SYSDIR?= /usr/src/sys .include ``` -This is very close to the Makefile used by `/usr/src/sys/modules/if_disc/Makefile`, which is exactly what you want for a clone-based pseudo-接口 驱动程序. Two small differences: we do not set `.PATH`, because our source file is in the current directory rather than in `/usr/src/sys/net/`, and we set `SYSDIR` explicitly so that the build works on machines that may not ship a system configuration for it. Otherwise, it is the standard `bsd.kmod.mk` pattern you have seen since Chapter 10. +这与 `/usr/src/sys/modules/if_disc/Makefile` 使用的 Makefile 非常接近,这正是你想要的基于克隆的伪接口驱动程序。两个小区别:我们不设置 `.PATH`,因为我们的源文件在当前目录而不是 `/usr/src/sys/net/`;我们显式设置 `SYSDIR`,以便在没有为其提供系统配置的机器上构建也能正常工作。除此之外,这是你自第 10 章以来看到的标准 `bsd.kmod.mk` 模式。 -### Preliminary Includes and Module Glue +### 头文件包含与模块胶水代码 -Open your editor and start `mynet.c` with the following preamble. Each include has a specific role, so we will annotate them as we go: +打开你的编辑器,用以下前言开始 `mynet.c`。每个 include 都有特定的作用,所以我们将在进行过程中逐一注释: ```c #include @@ -547,9 +546,9 @@ Open your editor and start `mynet.c` with the following preamble. Each include h #include ``` -The first 块 pulls in the core 内核 headers you already know from earlier chapters: parameters, system calls, module machinery, memory allocator, locking, mbufs, 套接字 IO constants, and the callout subsystem. The second 块 pulls in the networking-specific headers: `if.h` for the `ifnet` structure and flags, `if_var.h` for the inline helpers, `if_arp.h` for address resolution constants, `ethernet.h` for 以太网 framing, `if_types.h` for 接口-type constants like `IFT_ETHER`, `if_clone.h` for the cloner API, `if_media.h` for media 描述符, `bpf.h` for `tcpdump` support, and `vnet.h` for VNET-awareness, which we use in the same way that `/usr/src/sys/net/if_disc.c` uses it. +第一个块引入了你已经从前几章中了解的核心内核头文件:参数、系统调用、模块机制、内存分配器、锁定、mbuf、套接字 IO 常量和 callout 子系统。第二个块引入了网络特定的头文件:`if.h` 用于 `ifnet` 结构体和标志,`if_var.h` 用于内联辅助函数,`if_arp.h` 用于地址解析常量,`ethernet.h` 用于以太网成帧,`if_types.h` 用于接口类型常量如 `IFT_ETHER`,`if_clone.h` 用于克隆器 API,`if_media.h` 用于媒体描述符,`bpf.h` 用于 `tcpdump` 支持,`vnet.h` 用于 VNET 感知,我们的使用方式与 `/usr/src/sys/net/if_disc.c` 相同。 -Next, a module-wide memory type and the 接口 family name: +接下来,是模块范围的内存类型和接口家族名称: ```c static const char mynet_name[] = "mynet"; @@ -559,13 +558,13 @@ VNET_DEFINE_STATIC(struct if_clone *, mynet_cloner); #define V_mynet_cloner VNET(mynet_cloner) ``` -`mynet_name` is the string we will pass to `if_initname` so that 接口 are named `mynet0`, `mynet1`, and so on. `M_MYNET` is the memory type tag so that `vmstat -m` shows you how much memory the 驱动程序 is using. `VNET_DEFINE_STATIC` is VNET-aware: it gives each virtual network stack its own cloner variable. This mirrors the `VNET_DEFINE_STATIC(disc_cloner)` declaration in `/usr/src/sys/net/if_disc.c`. We will return to VNET briefly in Section 8. +`mynet_name` 是我们将传递给 `if_initname` 的字符串,以便接口命名为 `mynet0`、`mynet1` 等。`M_MYNET` 是内存类型标签,以便 `vmstat -m` 显示驱动程序正在使用多少内存。`VNET_DEFINE_STATIC` 是 VNET 感知的:它给每个虚拟网络栈自己的克隆器变量。这镜像了 `/usr/src/sys/net/if_disc.c` 中的 `VNET_DEFINE_STATIC(disc_cloner)` 声明。我们将在第 8 节中简要回到 VNET。 -Function, macro, and structure names are the durable reference into the FreeBSD tree. Line numbers drift release to release. For FreeBSD 14.3 orientation only: in `/usr/src/sys/net/if_disc.c`, the `VNET_DEFINE_STATIC(disc_cloner)` declaration sits near line 79 and the `if_clone_simple` call inside `vnet_disc_init` near line 134; in `/usr/src/sys/net/if_epair.c`, `epair_transmit` begins near line 324 and `epair_ioctl` near line 429; in `/usr/src/sys/sys/mbuf.h`, the `MGETHDR` compatibility macro sits near line 1125. Open the file and jump to the symbol. +函数、宏和结构体名称是进入 FreeBSD 源代码树的持久参考。行号会随版本变化。仅作为 FreeBSD 14.3 定位参考:在 `/usr/src/sys/net/if_disc.c` 中,`VNET_DEFINE_STATIC(disc_cloner)` 声明位于第 79 行附近,`vnet_disc_init` 中的 `if_clone_simple` 调用位于第 134 行附近;在 `/usr/src/sys/net/if_epair.c` 中,`epair_transmit` 从第 324 行附近开始,`epair_ioctl` 从第 429 行附近开始;在 `/usr/src/sys/sys/mbuf.h` 中,`MGETHDR` 兼容宏位于第 1125 行附近。打开文件并跳转到符号。 -### The Softc +### softc 结构 -A softc, as you know from earlier chapters, is the private per-instance structure your 驱动程序 allocates to track the state of one 设备. For a 网络驱动程序, the softc is per-接口. Here is what ours looks like at this stage: +正如你从前几章中所知,softc 是你的驱动程序分配的私有每实例结构体,用于跟踪一个设备的状态。对于网络驱动程序,softc 是每接口的。以下是我们在这一阶段的 softc 结构: ```c struct mynet_softc { @@ -583,15 +582,15 @@ struct mynet_softc { #define MYNET_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) ``` -The fields are straightforward. `ifp` is the 接口 object we create. `mtx` is a 互斥锁 to protect the softc during concurrent transmit, ioctl, and teardown. `hwaddr` is the six-byte 以太网 address we fabricate. `media` is the media 描述符 we expose through `SIOCGIFMEDIA`. `rx_callout` and `rx_interval_hz` are used by the simulated receive path we build in Section 5. `running` reflects the 驱动程序's sense of whether the 接口 is currently active. +字段很直观。`ifp` 是我们创建的接口对象。`mtx` 是一个互斥锁,用于在并发发送、ioctl 和拆卸期间保护 softc。`hwaddr` 是我们编造的六字节以太网地址。`media` 是我们通过 `SIOCGIFMEDIA` 暴露的媒体描述符。`rx_callout` 和 `rx_interval_hz` 用于我们在第 5 节中构建的模拟接收路径。`running` 反映驱动程序对接口当前是否活动的感知。 -The macros at the bottom give us short, readable locking primitives. They are a stylistic convention used in many FreeBSD 驱动程序, including `/usr/src/sys/dev/e1000/if_em.c` and `/usr/src/sys/net/if_epair.c`. +底部的宏为我们提供了简短、可读的锁定原语。它们是许多 FreeBSD 驱动程序中使用的风格约定,包括 `/usr/src/sys/dev/e1000/if_em.c` 和 `/usr/src/sys/net/if_epair.c`。 -### The Skeleton of `mynet_create` +### `mynet_create` 的骨架 -Now the main action of this section. We will write a function that is called from the cloner to create and 注册 a new 接口. This function is the heart of the initialisation code. Let us build it step by step, then assemble the pieces. +现在是本节的主要部分。我们将编写一个从克隆器调用的函数,用于创建和注册新接口。这个函数是初始化代码的核心。让我们逐步构建它,然后组装各个部分。 -First, allocate the softc and the `ifnet`: +首先,分配 softc 和 `ifnet`: ```c struct mynet_softc *sc; @@ -607,18 +606,18 @@ sc->ifp = ifp; mtx_init(&sc->mtx, "mynet", NULL, MTX_DEF); ``` -We use `M_WAITOK | M_ZERO` because this is called from a user-context path (the cloner) and we want zero-initialised memory. `IFT_ETHER` is from `/usr/src/sys/net/if_types.h`: it declares our 接口 as an 以太网 接口 for the 内核's bookkeeping purposes, which is important because the stack uses `if_type` to decide what link-layer semantics to apply. +我们使用 `M_WAITOK | M_ZERO`,因为这是从用户上下文路径(克隆器)调用的,我们需要零初始化的内存。`IFT_ETHER` 来自 `/usr/src/sys/net/if_types.h`:它将我们的接口声明为以太网接口用于内核的簿记目的,这很重要,因为协议栈使用 `if_type` 来决定应用什么链路层语义。 -Next, fabricate a MAC address. In real NIC 驱动程序, the hardware has an EEPROM with a unique factory-assigned MAC. We do not have that luxury, so we invent one. A locally-administered unicast address starts with a byte whose second-lowest bit is set and whose lowest bit is clear. The classic way is `02:xx:xx:xx:xx:xx`. We will do something similar to what `epair(4)` does in its `epair_generate_mac` function: +接下来,编造一个 MAC 地址。在真正的网卡驱动程序中,硬件有一个带有唯一出厂分配 MAC 的 EEPROM。我们没有这种奢侈,所以我们要发明一个。本地管理的单播地址以一个字节开始,该字节的第二低位被设置,最低位被清除。经典方式是 `02:xx:xx:xx:xx:xx`。我们将做类似 `epair(4)` 在其 `epair_generate_mac` 函数中做的事情: ```c arc4rand(sc->hwaddr, ETHER_ADDR_LEN, 0); sc->hwaddr[0] = 0x02; /* locally administered, unicast */ ``` -`arc4rand` is a 内核-internal entropy-backed random function, defined in `/usr/src/sys/libkern/arc4random.c`. It is fine for MAC-address fabrication. We then force the first byte to `0x02` so that the address is both locally-administered and unicast, which is what the IEEE reserves for addresses that are not factory-assigned. +`arc4rand` 是一个内核内部的熵支持随机函数,定义在 `/usr/src/sys/libkern/arc4random.c` 中。它适合用于 MAC 地址编造。然后我们将第一个字节强制为 `0x02`,使地址既是本地管理的又是单播的,这正是 IEEE 为非出厂分配的地址保留的。 -Next, configure the 接口 fields: +接下来,配置接口字段: ```c if_initname(ifp, mynet_name, unit); @@ -633,9 +632,9 @@ ifp->if_init = mynet_init; ifp->if_baudrate = IF_Gbps(1); ``` -`if_initname` sets both `if_xname`, the unique name of the 接口, and the 驱动程序's family name and unit number. `if_softc` ties the 接口 back to our private structure so that 回调 can find it. The flags mark the 接口 as broadcast-capable, simplex (meaning it cannot hear its own transmissions, which is true of an 以太网 NIC), and multicast-capable. `IFCAP_VLAN_MTU` says we can forward VLAN-tagged 帧 whose total payload exceeds the baseline 以太网 MTU by four bytes. The 回调 are the functions we will implement shortly. `if_baudrate` is informational; `IF_Gbps(1)` reports one gigabit per second, roughly matching what an average simulated link might claim. +`if_initname` 设置 `if_xname`(接口的唯一名称)以及驱动程序的家族名称和单元编号。`if_softc` 将接口与我们的私有结构体关联起来,以便回调可以找到它。这些标志将接口标记为支持广播、单工(意味着它不能听到自己的传输,这对以太网网卡来说是正确的)和支持多播。`IFCAP_VLAN_MTU` 表示我们可以转发 VLAN 标记的帧,其总有效载荷超过基线以太网 MTU 四个字节。回调是我们稍后将实现的函数。`if_baudrate` 是信息性的;`IF_Gbps(1)` 报告每秒一千兆比特,大致匹配平均模拟链路可能声称的速率。 -Next, set up the media 描述符. This is what `SIOCGIFMEDIA` will return, and it is what `ifconfig mynet0` uses to print the media line: +接下来,设置媒体描述符。这是 `SIOCGIFMEDIA` 将返回的内容,也是 `ifconfig mynet0` 用来打印媒体行的内容: ```c ifmedia_init(&sc->media, 0, mynet_media_change, mynet_media_status); @@ -644,28 +643,28 @@ ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL); ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO); ``` -`ifmedia_init` 寄存器 two 回调: one the stack calls when the user changes the media, and one it calls to learn the current media state. `ifmedia_add` declares a specific media type the 接口 supports. `IFM_ETHER | IFM_1000_T | IFM_FDX` means "以太网, 1000BaseT, full duplex"; `IFM_ETHER | IFM_AUTO` means "以太网, auto-negotiate". `ifmedia_set` chooses the default. `ifconfig mynet0` will reflect this choice. +`ifmedia_init` 注册两个回调:一个是协议栈在用户更改媒体时调用的,另一个是它调用以了解当前媒体状态的。`ifmedia_add` 声明接口支持的特定媒体类型。`IFM_ETHER | IFM_1000_T | IFM_FDX` 表示「以太网,1000BaseT,全双工」;`IFM_ETHER | IFM_AUTO` 表示「以太网,自动协商」。`ifmedia_set` 选择默认值。`ifconfig mynet0` 将反映此选择。 -Next, initialise the simulated receive callout. We will implement it in Section 5, but we prepare the field now so that `mynet_create` leaves the softc fully usable: +接下来,初始化模拟接收 callout。我们将在第 5 节中实现它,但现在我们准备该字段,以便 `mynet_create` 使 softc 完全可用: ```c callout_init_mtx(&sc->rx_callout, &sc->mtx, 0); sc->rx_interval_hz = hz; /* one simulated packet per second */ ``` -`callout_init_mtx` 寄存器 our callout with the softc's 互斥锁 so that the callout system acquires and releases the lock for us when it invokes the handler. This is a widely-used pattern in the 内核 and it avoids a whole class of lock-ordering bugs. +`callout_init_mtx` 用 softc 的互斥锁注册我们的 callout,以便 callout 系统在调用处理程序时为我们获取和释放锁。这是内核中广泛使用的模式,它避免了一整类锁排序错误。 -Finally, 附加 the 接口 to the 以太网 layer: +最后,将接口附加到以太网层: ```c ether_ifattach(ifp, sc->hwaddr); ``` -This single call does a lot of work. It sets `if_addrlen` and `if_hdrlen` and `if_mtu` to 以太网 defaults, it calls `if_附加` to 注册 the 接口, it installs `ether_input` and `ether_output` as the link-layer input and output handlers, and it calls `bpf附加(ifp, DLT_EN10MB, ETHER_HDR_LEN)` so that `tcpdump -i mynet0` works immediately. After this call, the 接口 is live: userland can see it, assign addresses to it, and begin issuing ioctls on it. +这个单一调用做了大量的工作。它将 `if_addrlen`、`if_hdrlen` 和 `if_mtu` 设置为以太网默认值,它调用 `if_attach` 注册接口,它安装 `ether_input` 和 `ether_output` 作为链路层输入和输出处理程序,它调用 `bpfattach(ifp, DLT_EN10MB, ETHER_HDR_LEN)` 使 `tcpdump -i mynet0` 立即工作。此调用之后,接口是活动的:用户态可以看到它、为其分配地址,并开始对其发出 ioctl。 -### The Skeleton of `mynet_destroy` +### `mynet_destroy` 的骨架 -Destruction mirrors creation but in reverse order. Here is the skeleton: +销毁是创建的逆序操作。以下是骨架: ```c static void @@ -688,11 +687,11 @@ mynet_destroy(struct mynet_softc *sc) } ``` -We mark the softc as no longer running, drain the callout so no scheduled receive event can fire, call `ether_if分离` to un注册 the 接口, free the ifnet, remove any allocated media entries, destroy the 互斥锁, and free the softc. The order matters: you must not free the `ifnet` while the callout might still run against it, and you must not destroy the 互斥锁 while the callout might still acquire it. `callout_drain` is what gives us the synchronous guarantee that no more 回调 will fire after it returns. +我们将 softc 标记为不再运行,排空 callout 使没有计划的接收事件可以触发,调用 `ether_ifdetach` 注销接口,释放 ifnet,移除所有已分配的媒体条目,销毁互斥锁,并释放 softc。顺序很重要:你不能在 callout 可能仍在其上运行时释放 `ifnet`,也不能在 callout 可能仍会获取互斥锁时销毁它。`callout_drain` 为我们提供了同步保证,即它返回后不再有回调会触发。 -### Registering the Cloner +### 注册克隆器 -Two pieces tie `mynet_create` and `mynet_destroy` to the 内核: the cloner registration and the module handler. Here is the cloner code: +两个部分将 `mynet_create` 和 `mynet_destroy` 连接到内核:克隆器注册和模块处理函数。以下是克隆器代码: ```c static int @@ -725,13 +724,13 @@ VNET_SYSUNINIT(vnet_mynet_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY, vnet_mynet_uninit, NULL); ``` -`if_clone_simple` 寄存器 a simple cloner, meaning a cloner whose name matching is by exact prefix (`mynet` followed by an optional unit number). `/usr/src/sys/net/if_disc.c` uses this same call inside `vnet_disc_init`, the VNET init routine for the `disc` 驱动程序. The create function receives a unit number and is responsible for producing a new 接口. The destroy function receives an `ifnet` and is responsible for taking it away. The `SYSINIT` and `SYSUNINIT` macros ensure that the cloner is 注册ed when the module loads and un注册ed when it unloads. +`if_clone_simple` 注册一个简单克隆器,即名称匹配通过精确前缀进行的克隆器(`mynet` 后跟可选的单元编号)。`/usr/src/sys/net/if_disc.c` 在 `vnet_disc_init`(`disc` 驱动程序的 VNET 初始化例程)内部使用相同的调用。创建函数接收一个单元编号并负责生成一个新接口。销毁函数接收一个 `ifnet` 并负责将其移除。`SYSINIT` 和 `SYSUNINIT` 宏确保克隆器在模块加载时注册,在模块卸载时注销。 -The `mynet_create_unit` helper glues the two halves together. It takes a unit number, does the allocation we described above, calls `ether_if附加`, and returns zero on success or an error on failure. The full listing is in the companion file under `lab01-skeleton/`. +`mynet_create_unit` 辅助函数将两半粘合在一起。它接收一个单元编号,执行我们上面描述的分配,调用 `ether_ifattach`,成功时返回零,失败时返回错误。完整清单在 `lab01-skeleton/` 下的配套文件中。 -### The Module Handler +### 模块处理函数 -Finally, the standard module boilerplate: +最后,是标准的模块样板代码: ```c static int @@ -757,51 +756,51 @@ MODULE_DEPEND(mynet, ether, 1, 1, 1); MODULE_VERSION(mynet, 1); ``` -The module handler itself does nothing interesting. The real initialisation happens in `vnet_mynet_init`, which `VNET_SYSINIT` arranges to be called at `SI_SUB_PSEUDO`. This split is not strictly necessary for a non-VNET 驱动程序, but following the pattern from `disc(4)` and `epair(4)` keeps our 驱动程序 ready for VNET use and matches the convention used by the rest of the tree. +模块处理函数本身没有做任何有趣的事情。真正的初始化发生在 `vnet_mynet_init` 中,`VNET_SYSINIT` 安排在 `SI_SUB_PSEUDO` 时调用它。这种分割对于非 VNET 驱动程序来说并非绝对必要,但遵循 `disc(4)` 和 `epair(4)` 的模式使我们的驱动程序为 VNET 使用做好准备,并与源代码树其余部分使用的约定匹配。 -`MODULE_DEPEND(mynet, ether, 1, 1, 1)` declares a dependency on the `ether` module so that 以太网 support is loaded before we try to use `ether_if附加`. `MODULE_VERSION(mynet, 1)` declares our own version number so that other modules can depend on us if they ever want to. +`MODULE_DEPEND(mynet, ether, 1, 1, 1)` 声明对 `ether` 模块的依赖,以便在我们尝试使用 `ether_ifattach` 之前加载以太网支持。`MODULE_VERSION(mynet, 1)` 声明我们自己的版本号,以便其他模块在需要时可以依赖我们。 -### A Closer Look at Interface Cloners +### 深入了解接口克隆器 -Interface cloners are worth a short detour because they drive much of the lifecycle of a pseudo-驱动程序, and because the API is slightly richer than the `if_clone_simple` call we have used so far. +接口克隆器值得稍微绕道一下,因为它们驱动了伪驱动程序的大部分生命周期,而且 API 比我们目前使用的 `if_clone_simple` 调用略微丰富。 -A cloner is a named factory 注册ed with the network stack. It carries a name prefix, a create 回调, a destroy 回调, and optionally a match 回调. When userland runs `ifconfig mynet create`, the stack walks its list of cloners looking for one whose prefix matches the string `mynet`. If it finds one, it picks a unit number, calls the create 回调, and returns the resulting 接口's name. +克隆器是注册到网络协议栈的命名工厂。它携带一个名称前缀、一个创建回调、一个销毁回调,以及可选的匹配回调。当用户态运行 `ifconfig mynet create` 时,协议栈遍历其克隆器列表,寻找前缀与字符串 `mynet` 匹配的克隆器。如果找到,它选取一个单元编号,调用创建回调,并返回结果接口的名称。 -The API has two flavours. `if_clone_simple` 寄存器 a cloner with the default matching rule: the name must begin with the cloner's prefix and may be followed by a unit number. `if_clone_advanced` 寄存器 a cloner with a caller-provided match function, which allows more flexible naming. `epair(4)` uses `if_clone_advanced` because its 接口 come in pairs named `epairXa` and `epairXb`. We use `if_clone_simple` because `mynet0`, `mynet1`, and so on are good enough. +API 有两种风格。`if_clone_simple` 使用默认匹配规则注册克隆器:名称必须以克隆器的前缀开头,后面可以跟一个单元编号。`if_clone_advanced` 使用调用者提供的匹配函数注册克隆器,允许更灵活的命名。`epair(4)` 使用 `if_clone_advanced`,因为它的接口以成对形式出现,命名为 `epairXa` 和 `epairXb`。我们使用 `if_clone_simple`,因为 `mynet0`、`mynet1` 等已经足够好了。 -Within the create 回调 you have two pieces of information: the cloner itself (through which you can look up sibling 接口) and the requested unit number (which may be `IF_MAXUNIT` if the user did not specify one, in which case you pick a free unit). In our 驱动程序 we accept whatever unit the cloner tells us and pass it straight to `if_initname`. +在创建回调中,你有两条信息:克隆器本身(通过它可以查找兄弟接口)和请求的单元编号(如果用户没有指定,可能是 `IF_MAXUNIT`,在这种情况下你选择一个空闲单元)。在我们的驱动程序中,我们接受克隆器告诉我们的任何单元编号,并将其直接传递给 `if_initname`。 -The destroy 回调 is simpler: it receives the `ifnet` pointer of the 接口 to destroy and must tear everything down. The cloner 框架 handles the list of 接口 for us; we do not need to maintain one ourselves. +销毁回调更简单:它接收要销毁的接口的 `ifnet` 指针,必须拆卸一切。克隆器框架为我们处理接口列表;我们不需要自己维护一个。 -When the module unloads, `if_clone_分离` walks the list of 接口 the cloner created and calls the destroy 回调 for each. After that, the cloner itself is un注册ed. This two-step teardown is what makes `kldunload` clean: even if the user forgot to `ifconfig mynet0 destroy` before unloading, the cloner takes care of it. +当模块卸载时,`if_clone_detach` 遍历克隆器创建的接口列表,并为每个接口调用销毁回调。之后,克隆器本身被注销。这种两步拆卸就是使 `kldunload` 干净的原因:即使用户在卸载前忘记 `ifconfig mynet0 destroy`,克隆器也会处理它。 -If your 驱动程序 ever needs to expose additional arguments to the create path (for example, the partner 接口 name in an `epair`-style 驱动程序), the cloner 框架 supports a `caddr_t params` argument to the create 回调, which carries bytes the user supplied through `ifconfig mynet create foo bar`. We do not use that mechanism here, but it is present and worth knowing about. +如果你的驱动程序需要向创建路径暴露额外的参数(例如,`epair` 风格驱动程序中的伙伴接口名称),克隆器框架支持创建回调的 `caddr_t params` 参数,它携带用户通过 `ifconfig mynet create foo bar` 提供的字节。我们在这里不使用该机制,但它存在且值得了解。 -### What Happens Inside `ether_if附加` +### `ether_ifattach` 内部发生了什么 -We called `ether_if附加(ifp, sc->hwaddr)` at the end of `mynet_create_unit` and said only that it "does a lot of work". Let us open `/usr/src/sys/net/if_ethersubr.c` and look at what that work really is, because understanding it makes the rest of our 驱动程序's behaviour predictable rather than mysterious. +我们在 `mynet_create_unit` 的末尾调用了 `ether_ifattach(ifp, sc->hwaddr)`,只说了它「做了大量的工作」。让我们打开 `/usr/src/sys/net/if_ethersubr.c` 看看那些工作到底是什么,因为理解它可以使我们驱动程序其余部分的行为变得可预测而不是神秘。 -`ether_if附加` begins by setting `ifp->if_addrlen = ETHER_ADDR_LEN` and `ifp->if_hdrlen = ETHER_HDR_LEN`. These fields tell the stack how many bytes of link-layer addressing and header prepend a 帧. For 以太网 both values are constants: six bytes of MAC and fourteen bytes of header. +`ether_ifattach` 首先设置 `ifp->if_addrlen = ETHER_ADDR_LEN` 和 `ifp->if_hdrlen = ETHER_HDR_LEN`。这些字段告诉协议栈一个帧前面有多少字节的链路层寻址和头部。对于以太网,这两个值都是常量:6 字节的 MAC 和 14 字节的头部。 -Next it sets `ifp->if_mtu = ETHERMTU` (1500 bytes, the IEEE 以太网 default) if the 驱动程序 has not already set a larger value. Our 驱动程序 left `if_mtu` at zero after `if_alloc`, so `ether_if附加` gives us the default. We could override it afterwards; a jumbo-capable 驱动程序 might set `if_mtu` to 9000 before `ether_if附加`. +接下来,如果驱动程序尚未设置更大的值,它设置 `ifp->if_mtu = ETHERMTU`(1500 字节,IEEE 以太网默认值)。我们的驱动程序在 `if_alloc` 之后将 `if_mtu` 保留为零,所以 `ether_ifattach` 给我们默认值。我们之后可以覆盖它;支持巨型帧的驱动程序可能会在 `ether_ifattach` 之前将 `if_mtu` 设置为 9000。 -Then it sets the link-layer output function, `if_output`, to `ether_output`. `ether_output` is the generic L3-to-L2 handler: it receives a 数据包 with an IP header and a destination address, resolves ARP or neighbour discovery if needed, constructs the 以太网 header, and calls `if_transmit`. This chain of indirection is what allows an IP 数据包 from a 套接字 to travel transparently through the stack and reach our 驱动程序. +然后它将链路层输出函数 `if_output` 设置为 `ether_output`。`ether_output` 是通用的三层到二层处理程序:它接收一个带有 IP 头部和目标地址的数据包,在需要时解析 ARP 或邻居发现,构造以太网头部,并调用 `if_transmit`。这个间接链就是允许来自套接字的 IP 数据包透明地通过协议栈并到达我们驱动程序的原因。 -It sets `if_input` to `ether_input`. `ether_input` is the inverse: it receives a complete 以太网 帧, strips the 以太网 header, dispatches on the EtherType, and hands the payload up to the appropriate protocol (IPv4, IPv6, ARP, LLC, and so on). When our 驱动程序 calls `if_input(ifp, m)`, it is effectively calling `ether_input(ifp, m)`. +它将 `if_input` 设置为 `ether_input`。`ether_input` 是反向的:它接收一个完整的以太网帧,剥离以太网头部,根据 EtherType 进行分派,并将有效载荷上交给相应的协议(IPv4、IPv6、ARP、LLC 等)。当我们的驱动程序调用 `if_input(ifp, m)` 时,它实际上是在调用 `ether_input(ifp, m)`。 -Then it stores the MAC address in the 接口's address list, making it visible to userland through `getifaddrs(3)` and through `ifconfig`. This is how `ifconfig mynet0` prints an `ether` line. +然后它将 MAC 地址存储在接口的地址列表中,使其通过 `getifaddrs(3)` 和 `ifconfig` 对用户态可见。这就是 `ifconfig mynet0` 打印 `ether` 行的方式。 -Then it calls `if_附加(ifp)`, which 寄存器 the 接口 with the global list, allocates any stack-side state needed, and makes the 接口 visible to userland. +然后它调用 `if_attach(ifp)`,将接口注册到全局列表,分配所需的协议栈端状态,并使接口对用户态可见。 -Finally it calls `bpf附加(ifp, DLT_EN10MB, ETHER_HDR_LEN)`, which 寄存器 the 接口 with BPF using the 以太网 link type. From that moment `tcpdump -i mynet0` will find the 接口 and will expect 帧 with 14-byte 以太网 headers. +最后它调用 `bpfattach(ifp, DLT_EN10MB, ETHER_HDR_LEN)`,使用以太网链路类型将接口注册到 BPF。从那一刻起,`tcpdump -i mynet0` 将找到该接口,并期望带有 14 字节以太网头部的帧。 -It is a lot of work for one function call. Doing it all by hand is legal (and many older 驱动程序 do) but error-prone. `ether_if附加` is one of those helpers whose existence makes writing a 驱动程序 genuinely easier, and reading its body is rewarding because it demystifies what happens between "I allocated an ifnet" and "the stack is fully aware of my 接口". +一次函数调用做了大量的工作。手动完成所有这些是合法的(许多旧驱动程序这样做),但容易出错。`ether_ifattach` 是那些真正使编写驱动程序变得更容易的辅助函数之一,阅读其函数体是有回报的,因为它揭开了从「我分配了一个 ifnet」到「协议栈完全了解我的接口」之间发生的事情的神秘面纱。 -The complementary function `ether_if分离` performs the inverse operations in the correct reverse order. It is the right function to call during teardown, and it is what we call in `mynet_destroy`. +互补函数 `ether_ifdetach` 以正确的逆序执行反向操作。它是在拆卸期间调用的正确函数,也是我们在 `mynet_destroy` 中调用的函数。 -### Build, Load, and Verify +### 编译、加载和验证 -At this point, even without transmit and receive logic, the skeleton should build and load. Here is what the verification flow looks like: +此时,即使没有发送和接收逻辑,骨架也应该能够构建和加载。以下是验证流程: ```console # cd examples/part-06/ch28-network-driver @@ -818,70 +817,70 @@ mynet0: flags=8802 metric 0 mtu 1500 groups: mynet ``` -The exact MAC address will differ because `arc4rand` gives you a different random address each time. The rest of the output should closely match. If it does, you have succeeded: you have a live, 注册ed, named, MAC-addressed 网络接口, visible to all the standard tools, without yet handling any real 数据包. That is already a significant accomplishment. +确切的 MAC 地址会有所不同,因为 `arc4rand` 每次给你一个不同的随机地址。输出的其余部分应该非常接近。如果是这样,你就成功了:你拥有一个活跃的、已注册的、命名的、有 MAC 地址的网络接口,对所有标准工具可见,而无需处理任何真正的数据包。这已经是一个重要的成就。 -Destroy the 接口 and unload the module to close the lifecycle: +销毁接口并卸载模块以完成生命周期: ```console # ifconfig mynet0 destroy # kldunload mynet ``` -`kldstat` should show that the module is gone. `ifconfig -a` should no longer list `mynet0`. If anything is left behind, we will cover how to diagnose it in Section 8. +`kldstat` 应该显示模块已消失。`ifconfig -a` 不应再列出 `mynet0`。如果留下了任何东西,我们将在第 8 节中介绍如何诊断它。 -### What the Stack Now Knows About Us +### 协议栈现在了解我们的哪些信息 -After `ether_if附加` returns, the stack knows several important facts about our 接口: +`ether_ifattach` 返回后,协议栈了解我们接口的几个重要事实: -* It is of type `IFT_ETHER`. -* It supports broadcast, simplex, and multicast. -* It has a specific MAC address. -* It has a default MTU of 1500 bytes. -* It has a transmit 回调, an ioctl 回调, an init 回调, and a media handler. -* It is 附加ed to BPF with `DLT_EN10MB` encapsulation. -* Its state-of-the-link is currently undefined (we have not called `if_link_state_change` yet). +* 它是 `IFT_ETHER` 类型。 +* 它支持广播、单工和多播。 +* 它有一个特定的 MAC 地址。 +* 它有一个 1500 字节的默认 MTU。 +* 它有一个发送回调、一个 ioctl 回调、一个初始化回调和一个媒体处理程序。 +* 它已通过 `DLT_EN10MB` 封装附加到 BPF。 +* 其链路状态当前未定义(我们尚未调用 `if_link_state_change`)。 -Everything else, 数据包 movement, counter updates, link state, will come alive in the following sections. The skeleton is intentionally small. It is the first time you can point at something on your system and say, honestly, "that is my 网络接口." Pause on that sentence. It marks a real milestone in the book. +其他一切——数据包移动、计数器更新、链路状态——将在后续小节中活跃起来。骨架故意保持小型。这是你第一次可以指向你系统上的某个东西,诚实地说出「那是我的网络接口」。在这个句子上停下来想一想。它标志着本书中一个真正的里程碑。 ### 常见错误 -Two mistakes are easy to make in this section, and both of them produce confusing symptoms. +在本节中容易犯两个错误,它们都会产生令人困惑的症状。 -The first is forgetting to call `ether_if附加` and calling `if_附加` directly. That is perfectly legal, and it results in a non-以太网 pseudo-接口, but your 驱动程序 then has to install its own `if_input` and `if_output` handlers, and `tcpdump` does not work until you `bpf附加` yourself. If you see an 接口 that looks like it should work but `tcpdump -i mynet0` complains about the link type, check whether you used `ether_if附加`. +第一个是忘记调用 `ether_ifattach` 而直接调用 `if_attach`。这完全合法,但会产生一个非以太网伪接口,你的驱动程序必须安装自己的 `if_input` 和 `if_output` 处理程序,而且在你自己调用 `bpfattach` 之前 `tcpdump` 无法工作。如果你看到一个看起来应该能工作的接口但 `tcpdump -i mynet0` 抱怨链路类型,检查你是否使用了 `ether_ifattach`。 -The second mistake is to allocate the softc with `M_NOWAIT` instead of `M_WAITOK`. `M_NOWAIT` is correct in interrupt context, but `mynet_clone_create` runs in a regular user context through the `ifconfig create` path, and `M_WAITOK` is the right choice. Using `M_NOWAIT` here introduces a rare allocation-failure path for no benefit. +第二个错误是用 `M_NOWAIT` 而不是 `M_WAITOK` 分配 softc。`M_NOWAIT` 在中断上下文中是正确的,但 `mynet_clone_create` 通过 `ifconfig create` 路径在常规用户上下文中运行,`M_WAITOK` 是正确的选择。在这里使用 `M_NOWAIT` 会引入一个罕见但无益的分配失败路径。 -### 总结 Section 3 +### 第3节小结 -You now have a working skeleton. The 接口 exists, is 注册ed, has an 以太网 address, and can be created and destroyed on demand. The stack is ready to call into our 驱动程序 through `if_transmit`, `if_ioctl`, and `if_init`, but we have not yet implemented the bodies of those 回调. Section 4 tackles the transmit path. That is the one you will feel most viscerally, because once it works, `ping` starts to push real bytes through your code. +你现在有了一个可工作的骨架。接口已存在、已注册、拥有以太网地址,并且可以按需创建和销毁。协议栈准备好通过 `if_transmit`、`if_ioctl` 和 `if_init` 调用我们的驱动程序,但我们尚未实现这些回调的主体。第 4 节处理发送路径。这是你感受最深切的部分,因为一旦它工作,`ping` 就开始通过你的代码推送真正的字节。 -## 第4节: Handling Packet Transmission +## 第4节:处理数据包发送 -Transmission is the outbound half of 数据包 flow. When the 内核's network stack decides that a 数据包 needs to leave through `mynet0`, it packages the 数据包 in an mbuf chain and invokes our `if_transmit` 回调. Our job is to accept the mbuf, do whatever is appropriate with it, and free it. In this section we will build a complete transmit path that validates the mbuf, updates counters, taps BPF so that `tcpdump` sees the 数据包, and disposes of the 帧. Because `mynet` is a pseudo-设备 without a real wire, we will initially drop the 数据包 after counting it. That is similar to what `disc(4)` does in `/usr/src/sys/net/if_disc.c`, and it is enough to demonstrate the full transmit flow end-to-end. +发送是数据包流的出站半部分。当内核的网络协议栈决定一个数据包需要通过 `mynet0` 离开时,它将数据包打包在一个 mbuf 链中并调用我们的 `if_transmit` 回调。我们的工作是接受 mbuf,对它做适当的事情,然后释放它。在本节中,我们将构建一个完整的发送路径,验证 mbuf,更新计数器,捕获 BPF 以便 `tcpdump` 看到数据包,并处理该帧。因为 `mynet` 是一个没有真正线路的伪设备,我们最初在计数后丢弃数据包。这与 `disc(4)` 在 `/usr/src/sys/net/if_disc.c` 中所做的类似,足以端到端地演示完整的发送流程。 -### How the Stack Reaches Us +### 协议栈如何到达我们的驱动 -Before we open our editor, let us trace how a 数据包 gets from a process to our 驱动程序. When a process calls `send(2)` on a TCP 套接字 that is bound to an IP address assigned to `mynet0`, the following sequence happens, in broad strokes. Do not worry about memorising every step; the point is to see where our code sits in the bigger picture. +在我们打开编辑器之前,让我们追踪一个数据包如何从进程到达我们的驱动程序。当一个进程在一个绑定到分配给 `mynet0` 的 IP 地址的 TCP 套接字上调用 `send(2)` 时,以下序列大致如下发生。不必担心记住每一步;重点是看到我们的代码在更大的图景中处于什么位置。 -1. The 套接字 layer copies the user payload into mbufs and passes it to TCP. -2. TCP segments the payload, adds TCP headers, and passes the segments to IP. -3. IP adds IP headers, looks up the route, and passes the result to the 以太网 layer through `ether_output`. -4. `ether_output` resolves the next-hop MAC address (through ARP if required), prepends an 以太网 header, and calls `if_transmit` on the output 接口. -5. Our `if_transmit` function is invoked with `ifp` pointing at `mynet0` and the mbuf pointing at the complete 以太网 帧 ready to be transmitted. +1. 套接字层将用户有效载荷复制到 mbuf 中并传递给 TCP。 +2. TCP 对有效载荷进行分段,添加 TCP 头部,并将段传递给 IP。 +3. IP 添加 IP 头部,查找路由,并通过 `ether_output` 将结果传递给以太网层。 +4. `ether_output` 解析下一跳 MAC 地址(如果需要则通过 ARP),前置以太网头部,并在输出接口上调用 `if_transmit`。 +5. 我们的 `if_transmit` 函数被调用,`ifp` 指向 `mynet0`,mbuf 指向准备好传输的完整以太网帧。 -From that moment the 帧 is ours. We must either send it out, drop it cleanly, or queue it for later delivery. Whichever we choose, we must free the mbuf exactly once. Double-free leads to 内核 corruption, use-after-free leads to mystery panics, and forgetting to free leaks mbufs until the machine runs out. +从那一刻起,帧就属于我们了。我们必须将其发送出去、干净地丢弃,或者排队等待稍后交付。无论选择哪种方式,我们必须恰好释放 mbuf 一次。双重释放会导致内核损坏,释放后使用会导致神秘崩溃,忘记释放会泄漏 mbuf 直到机器耗尽。 -### The Transmit Callback Signature +### 发送回调函数签名 -The prototype of an `if_transmit` 回调 is: +`if_transmit` 回调的原型是: ```c int mynet_transmit(struct ifnet *ifp, struct mbuf *m); ``` -It is declared in `/usr/src/sys/net/if_var.h` as the typedef `if_transmit_fn_t`. The return value is an errno: zero on success, or an error such as `ENOBUFS` if the 数据包 could not be queued. Real NIC 驱动程序 rarely return non-zero, because they prefer to silently drop and increment `IFCOUNTER_OERRORS`. Pseudo-驱动程序 that mimic real behaviour usually do the same. +它在 `/usr/src/sys/net/if_var.h` 中声明为 typedef `if_transmit_fn_t`。返回值是一个 errno:成功时为零,或错误(例如 `ENOBUFS`)如果数据包无法排队。真正的网卡驱动程序很少返回非零值,因为它们更倾向于静默丢弃并递增 `IFCOUNTER_OERRORS`。模仿真实行为的伪驱动程序通常也这样做。 -Here is the full 回调 we will implement: +以下是我们将实现的完整回调: ```c static int @@ -925,59 +924,59 @@ mynet_transmit(struct ifnet *ifp, struct mbuf *m) } ``` -Let us walk through it. This is where the shape of a transmit routine becomes clear, so it is worth reading the code slowly. +让我们逐一讲解。这是发送例程的形状变得清晰的地方,所以值得慢慢阅读代码。 -### The NULL Check +### NULL 检查 -The first two lines handle the defensive case where the stack calls us with a NULL pointer. This is not supposed to happen in normal operation, but the 内核 is a place where defensive programming earns its keep. Returning `0` on a NULL input is the standard idiom; `if_epair.c` does the same at the top of `epair_transmit`. +前两行处理协议栈用 NULL 指针调用我们的防御性情况。在正常操作中这不应该发生,但内核是防御性编程值得的地方。在 NULL 输入上返回 `0` 是标准习惯;`if_epair.c` 在 `epair_transmit` 的顶部也做了同样的事情。 ### `M_ASSERTPKTHDR` -The next line is a macro from `/usr/src/sys/sys/mbuf.h` that asserts the mbuf has `M_PKTHDR` set. Every mbuf that reaches a 驱动程序's transmit 回调 must be the head of a 数据包, and must therefore carry a valid 数据包 header. Asserting this catches bugs caused by mbuf surgery elsewhere in the system. In production 内核s the assertion is compiled out, but having it in the source tree documents the contract, and in `INVARIANTS` 内核s it catches bad usage during development. +下一行是来自 `/usr/src/sys/sys/mbuf.h` 的宏,它断言 mbuf 已设置 `M_PKTHDR`。到达驱动程序发送回调的每个 mbuf 必须是数据包的头部,因此必须携带有效的数据包头部。断言这一点可以捕获系统中其他地方 mbuf 操作引起的错误。在生产内核中,断言被编译掉,但在源代码树中存在它记录了契约,在 `INVARIANTS` 内核中它在开发期间捕获不良使用。 -### MTU Validation +### MTU 验证 -The 块 under the comment `/* Reject oversize 帧. */` rejects 数据包 that are larger than the 接口 MTU plus a small slack for a VLAN header. `epair_transmit` in `/usr/src/sys/net/if_epair.c` does exactly the same check; look for the `if (m->m_pkthdr.len > (ifp->if_mtu + sizeof(struct ether_vlan_header)))` guard that `m_freem`s the 帧 and bumps `IFCOUNTER_OERRORS`. We leave slack for `ether_vlan_header` because VLAN-tagged 帧 carry four extra bytes beyond the base 以太网 header, and we advertised `IFCAP_VLAN_MTU` in Section 3, so we should honour that capability. +注释 `/* Reject oversize frames. */` 下面的代码块拒绝大于接口 MTU 加上 VLAN 头部少量余量的数据包。`/usr/src/sys/net/if_epair.c` 中的 `epair_transmit` 做了完全相同的检查;寻找 `if (m->m_pkthdr.len > (ifp->if_mtu + sizeof(struct ether_vlan_header)))` 守卫,它 `m_freem` 帧并递增 `IFCOUNTER_OERRORS`。我们为 `ether_vlan_header` 留出余量,因为 VLAN 标记帧在基本以太网头部之外还携带四个额外字节,而且我们在第 3 节中声明了 `IFCAP_VLAN_MTU`,所以我们应该兑现该能力。 -On rejection, we free the mbuf with `m_freem(m)` and increment `IFCOUNTER_OERRORS`. We also return `E2BIG` as a hint to the caller, though in practice the stack rarely looks at the return value other than to decide whether to drop locally. +拒绝时,我们用 `m_freem(m)` 释放 mbuf 并递增 `IFCOUNTER_OERRORS`。我们还返回 `E2BIG` 作为给调用者的提示,尽管在实践中协议栈很少查看返回值,除非是决定是否在本地丢弃。 -### State Validation +### 状态验证 -The `if` 块 under the comment `/* If the 接口 is administratively down, drop. */` checks two conditions. `IFF_UP` is set by `ifconfig mynet0 up` and cleared by `ifconfig mynet0 down`, and it is the userland's way of saying that the 接口 should or should not be carrying traffic. `IFF_DRV_RUNNING` is the 驱动程序's internal "I have allocated my resources and I am ready to move traffic" flag. If either is clear, we have no 总线iness sending the 数据包, so we drop it and increment the error counter. +注释 `/* If the interface is administratively down, drop. */` 下面的 `if` 代码块检查两个条件。`IFF_UP` 由 `ifconfig mynet0 up` 设置,由 `ifconfig mynet0 down` 清除,它是用户态表示接口应该或不应该承载流量的方式。`IFF_DRV_RUNNING` 是驱动程序内部的「我已分配好资源并准备好传输流量」标志。如果其中任何一个被清除,我们就没有理由发送数据包,所以我们丢弃它并递增错误计数器。 -This check is not strictly necessary for correctness in all cases, because the stack usually avoids routing traffic through a down 接口. But defensive 驱动程序 check anyway, because races between the stack's view of state and the 驱动程序's view of state do happen, especially during 接口 teardown. +这个检查在所有情况下对正确性来说并非严格必要,因为协议栈通常避免通过 down 的接口路由流量。但防御性驱动程序仍然会检查,因为协议栈的状态视图和驱动程序的状态视图之间的竞争确实会发生,特别是在接口拆卸期间。 -### BPF Tap +### BPF 捕获 -`BPF_MTAP(ifp, m)` is a macro that conditionally calls into BPF if any 数据包 capture session is active on the 接口. It expands to `bpf_mtap_if((_ifp), (_m))` in the current tree. The macro is defined in `/usr/src/sys/net/bpf.h`. When `tcpdump -i mynet0` is running, BPF has 附加ed to the 接口's `if_bpf` pointer, and the macro hands it a copy of the outgoing 数据包. When no one is listening, the macro quickly returns and has negligible cost. +`BPF_MTAP(ifp, m)` 是一个宏,如果接口上有活动的数据包捕获会话,它有条件地调用 BPF。在当前源代码树中它展开为 `bpf_mtap_if((_ifp), (_m))`。该宏定义在 `/usr/src/sys/net/bpf.h` 中。当 `tcpdump -i mynet0` 正在运行时,BPF 已附加到接口的 `if_bpf` 指针上,宏将传出数据包的副本交给它。当没有人监听时,宏快速返回,开销可忽略不计。 -Placement matters. We tap before we drop, because we want `tcpdump` to see the 数据包 even if we are simulating a down 接口. Real NIC 驱动程序 tap slightly earlier, right before they hand the 帧 to hardware DMA, but the idea is the same. +放置位置很重要。我们在丢弃之前捕获,因为我们希望 `tcpdump` 能看到数据包,即使我们正在模拟一个 down 的接口。真正的网卡驱动程序捕获得稍早一些,就在将帧交给硬件 DMA 之前,但思想是相同的。 -### Counter Updates +### 计数器更新 -Four counters are relevant on every transmit: +每次发送相关有四个计数器: -* `IFCOUNTER_OPACKETS`: the number of 数据包 transmitted. -* `IFCOUNTER_OBYTES`: the total bytes transmitted. -* `IFCOUNTER_OMCASTS`: the number of multicast or broadcast 帧 transmitted. -* `IFCOUNTER_OERRORS`: the number of errors observed during transmit. +* `IFCOUNTER_OPACKETS`:已发送的数据包数。 +* `IFCOUNTER_OBYTES`:已发送的总字节数。 +* `IFCOUNTER_OMCASTS`:已发送的多播或广播帧数。 +* `IFCOUNTER_OERRORS`:发送期间观察到的错误数。 -`if_inc_counter(ifp, IFCOUNTER_*, n)` is the correct way to update these. It is defined in `/usr/src/sys/net/if.c` and uses per-CPU counters internally so that concurrent calls from multiple CPUs do not contend. Do not reach into the `if_data` fields directly: the internals have changed over the years, and the accessor is the stable 接口. +`if_inc_counter(ifp, IFCOUNTER_*, n)` 是更新这些计数器的正确方式。它定义在 `/usr/src/sys/net/if.c` 中,内部使用每 CPU 计数器,使来自多个 CPU 的并发调用不会竞争。不要直接访问 `if_data` 字段:内部结构多年来已经改变,访问器是稳定的接口。 -Because the stack has already computed 数据包 length and populated `m->m_pkthdr.len`, we cache that into a local `len` variable before we free the mbuf. Reading `m->m_pkthdr.len` after `m_freem(m)` would be use-after-free, so the local variable is not a stylistic choice. It is a correctness choice. +因为协议栈已经计算了数据包长度并填充了 `m->m_pkthdr.len`,我们在释放 mbuf 之前将其缓存到本地 `len` 变量中。在 `m_freem(m)` 之后读取 `m->m_pkthdr.len` 将是释放后使用,所以本地变量不是风格选择,而是正确性选择。 -### The Final Drop +### 最终丢弃 -`m_freem(m)` frees an entire mbuf chain. It walks the chain through the `m_next` pointers and frees every mbuf in it. You do not need to free each one by hand. If you had only `m_free(m)` you would free the first mbuf and leak the rest. Confusing `m_freem` and `m_free` is one of the most common beginner mistakes. The conventional names are: +`m_freem(m)` 释放整个 mbuf 链。它通过 `m_next` 指针遍历链并释放其中的每个 mbuf。你不需要手动释放每一个。如果你只用 `m_free(m)`,你会释放第一个 mbuf 并泄漏其余的。混淆 `m_freem` 和 `m_free` 是最常见的初学者错误之一。惯用名称是: -* `m_free(m)`: free a single mbuf. Rarely called in 驱动程序. -* `m_freem(m)`: free a whole chain. This is what you almost always want. +* `m_free(m)`:释放单个 mbuf。在驱动程序中很少调用。 +* `m_freem(m)`:释放整个链。这几乎总是你想要的。 -In a real NIC 驱动程序, instead of `m_freem(m)`, we would hand the 帧 to hardware DMA and free the mbuf later, in the transmit-completion interrupt. For our pseudo-驱动程序, we drop it. This is the behaviour of `if_disc.c` in the tree: simulate the transmit, free the mbuf, and return. +在真正的网卡驱动程序中,我们不会使用 `m_freem(m)`,而是将帧交给硬件 DMA,稍后在发送完成中断中释放 mbuf。对于我们的伪驱动程序,我们丢弃它。这是源代码树中 `if_disc.c` 的行为:模拟发送,释放 mbuf,然后返回。 -### The Queue-Flush Callback +### 队列刷新回调 -Alongside `if_transmit`, the stack expects a trivial 回调 called `if_qflush`. It is invoked when the stack wants to flush any 数据包 the 驱动程序 has queued internally. Because our 驱动程序 does not queue, the 回调 has no work to do: +除了 `if_transmit` 之外,协议栈期望一个名为 `if_qflush` 的简单回调。它在协议栈想要刷新驱动程序内部排队的任何数据包时被调用。因为我们的驱动程序不排队,回调没有工作要做: ```c static void @@ -986,11 +985,11 @@ mynet_qflush(struct ifnet *ifp __unused) } ``` -That is identical to `epair_qflush` in `/usr/src/sys/net/if_epair.c`. Drivers that maintain their own 数据包 queues, which is less common now than it was, have more work to do here. We do not. +这与 `/usr/src/sys/net/if_epair.c` 中的 `epair_qflush` 相同。维护自己数据包队列的驱动程序(现在比以前少见了)在这里有更多工作要做。我们没有。 -### The `mynet_init` Callback +### `mynet_init` 回调 -The third 回调 assigned in Section 3 was `mynet_init`, the function the stack calls when the 接口 transitions to the up state. It is a simple one for us: +在第 3 节中分配的第三个回调是 `mynet_init`,即协议栈在接口转换为 up 状态时调用的函数。对我们来说很简单: ```c static void @@ -1010,29 +1009,29 @@ mynet_init(void *arg) } ``` -On init we mark ourselves running, clear `IFF_DRV_OACTIVE` (a flag meaning "transmit queue is full, do not call me again until I clear it"), start the receive-simulation callout we will describe in Section 5, and announce that the link is up. The `if_link_state_change` call at the end causes `ifconfig` to report `status: active` on this 接口. Keep the placement in mind: we set `IFF_DRV_RUNNING` first, then announce the link, in that order. Reversing the order would tell the stack that the link is up on an 接口 whose 驱动程序 is still initialising, and the stack might start pushing traffic at us before we are ready. +在初始化时,我们标记自己正在运行,清除 `IFF_DRV_OACTIVE`(一个表示「发送队列已满,在我清除之前不要再调用我」的标志),启动我们将在第 5 节中描述的接收模拟 callout,并宣布链路已连接。末尾的 `if_link_state_change` 调用使 `ifconfig` 在此接口上报告 `status: active`。记住放置顺序:我们先设置 `IFF_DRV_RUNNING`,然后宣布链路,按此顺序。反转顺序会告诉协议栈在一个驱动程序仍在初始化的接口上链路已连接,协议栈可能在我们准备好之前就开始向我们推送流量。 -### A Close Look at Ordering and Locking +### 仔细审视顺序和锁 -The code above is simple enough that locking feels like overkill. Why do we need a 互斥锁 at all? There are two reasons. +上面的代码足够简单,让人感觉锁定是多余的。为什么我们需要一个互斥锁?有两个原因。 -The first reason is that `if_transmit` and `if_ioctl` run concurrently. The stack can call `if_transmit` on one CPU while userland issues `ifconfig mynet0 down` on another, which translates into `if_ioctl(SIOCSIFFLAGS)` running on that other CPU. Without a 互斥锁, these two 回调 can both read and write softc state simultaneously. The 互斥锁 is what lets us reason about state transitions. +第一个原因是 `if_transmit` 和 `if_ioctl` 并发运行。协议栈可以在一个 CPU 上调用 `if_transmit`,而用户态在另一个 CPU 上发出 `ifconfig mynet0 down`,这转化为 `if_ioctl(SIOCSIFFLAGS)` 在那个 CPU 上运行。没有互斥锁,这两个回调可以同时读写 softc 状态。互斥锁让我们能够推理状态转换。 -The second reason is that the callout-based receive simulation in Section 5 touches the softc when it fires. Without a 互斥锁, the callout and `if_ioctl` can collide, and you get the classic "the list I was walking just changed out from under me" style of bug. Again, a single per-softc 互斥锁 is enough to make these interactions safe. +第二个原因是第 5 节中基于 callout 的接收模拟在触发时接触 softc。没有互斥锁,callout 和 `if_ioctl` 可能冲突,你会得到经典的「我正在遍历的列表刚刚在我脚下改变了」风格的错误。同样,每个 softc 一个互斥锁足以使这些交互安全。 -We have chosen a simple locking rule: the softc 互斥锁 is the big lock. Every softc access outside the transmit fast path takes it. The transmit fast path in `mynet_transmit` does not take the 互斥锁, because `if_transmit` is designed for concurrent callers and we only touch ifnet counters and BPF, both of which are thread-safe on their own. If we were to add 驱动程序-specific shared state that transmit updates, we would add a finer-grained lock for that state. +我们选择了一个简单的锁定规则:softc 互斥锁是大锁。发送快速路径之外的每个 softc 访问都获取它。`mynet_transmit` 中的发送快速路径不获取互斥锁,因为 `if_transmit` 为并发调用者设计,我们只接触 ifnet 计数器和 BPF,它们本身都是线程安全的。如果我们要添加由发送更新的驱动程序特定共享状态,我们会为该状态添加更细粒度的锁。 -This is a simplification. Real high-performance NIC 驱动程序 use far more complex locking, often with per-queue locks, per-CPU state, and per-数据包 sanity checks. The single-互斥锁 design is absolutely fine for a pseudo-驱动程序 and for any low-rate 接口; for a production 100-gigabit 驱动程序 it would become a bottleneck, which is one reason why the modern iflib 框架 exists. We will touch on iflib in later chapters. +这是一个简化。真正的高性能网卡驱动程序使用更复杂的锁定,通常有每队列锁、每 CPU 状态和每数据包健全性检查。单互斥锁设计对于伪驱动程序和任何低速率接口来说绝对没问题;对于生产环境的 100Gb 驱动程序它会成为瓶颈,这也是现代 iflib 框架存在的原因之一。我们将在后面的章节中涉及 iflib。 -### Packet Surgery with `m_pullup` +### 使用 `m_pullup` 进行数据包处理 -Real 网络驱动程序 frequently need to read fields from deep inside a 数据包 before deciding what to do with it. A VLAN 驱动程序 needs to read the 802.1Q tag. A bridging 驱动程序 needs to read the source MAC to update a forwarding table. A hardware-offloading 驱动程序 needs to read the IP and TCP headers to decide whether a checksum can be computed in hardware. +真正的网络驱动程序经常需要在决定如何处理数据包之前读取数据包深处的字段。VLAN 驱动程序需要读取 802.1Q 标签。桥接驱动程序需要读取源 MAC 以更新转发表。硬件卸载驱动程序需要读取 IP 和 TCP 头部以决定是否可以在硬件中计算校验和。 -The trouble is that a received mbuf chain does not guarantee that any particular byte lives in any particular mbuf. The first mbuf might hold only the first fourteen bytes (the 以太网 header) while the next mbuf holds the rest. A 驱动程序 that casts `mtod(m, struct ip *)` and reaches past the 以太网 header will read nonsense unless it first ensures that the bytes it needs are contiguous. +问题在于接收到的 mbuf 链不保证任何特定字节位于任何特定 mbuf 中。第一个 mbuf 可能只保存前十四个字节(以太网头部),而下一个 mbuf 保存其余部分。一个将 `mtod(m, struct ip *)` 转换并越过以太网头部的驱动程序将读取到无意义的数据,除非它首先确保所需的字节是连续的。 -The 内核 provides `m_pullup(m, len)` for exactly this purpose. `m_pullup` guarantees that the first `len` bytes of the mbuf chain live in the first mbuf. If they already do, it is a no-op. If they do not, it reshapes the chain by moving bytes into the first mbuf, possibly allocating a new mbuf if the first one is too small. It returns a (possibly different) mbuf pointer, or NULL on allocation failure, in which case the mbuf chain has been freed for you. +内核正是为此目的提供了 `m_pullup(m, len)`。`m_pullup` 保证 mbuf 链的前 `len` 个字节位于第一个 mbuf 中。如果已经是这样,它就是无操作。如果不是,它通过将字节移入第一个 mbuf 来重塑链,如果第一个 mbuf 太小则可能分配一个新的 mbuf。它返回一个(可能不同的)mbuf 指针,或分配失败时返回 NULL,在这种情况下 mbuf 链已被为你释放。 -The idiom for a 驱动程序 that needs to inspect headers is: +需要检查头部的驱动程序的习惯写法是: ```c m = m_pullup(m, sizeof(struct ether_header) + sizeof(struct ip)); @@ -1044,19 +1043,19 @@ eh = mtod(m, struct ether_header *); ip = (struct ip *)(eh + 1); ``` -`mynet` does not need to do this, because we do not inspect 数据包 contents in the transmit path. But you will see `m_pullup` sprinkled throughout real 驱动程序, especially on the receive side and in L2 helpers. +`mynet` 不需要这样做,因为我们在发送路径中不检查数据包内容。但你会在真正的驱动程序中到处看到 `m_pullup`,特别是在接收端和二层辅助函数中。 -A related function, `m_copydata(m, offset, len, buf)`, copies bytes out of a mbuf chain into a caller-provided 缓冲区. It is the right tool when you want to read some bytes without modifying the chain. `m_copyback` goes the other way: write bytes into a chain at a given offset, extending the chain if needed. +一个相关的函数 `m_copydata(m, offset, len, buf)` 将字节从 mbuf 链复制到调用者提供的缓冲区中。当你想读取一些字节而不修改链时,这是正确的工具。`m_copyback` 是另一个方向:在给定偏移量处向链写入字节,如果需要则扩展链。 -Another frequently-used helper is `m_defrag(m, how)`, which flattens a chain into a single (large) mbuf. This is used by 驱动程序 whose hardware has a maximum scatter-gather count. If a transmit 帧 spans more mbufs than the hardware can handle, the 驱动程序 falls back to `m_defrag`, which copies the payload into a contiguous single cluster. +另一个常用的辅助函数是 `m_defrag(m, how)`,它将链扁平化为单个(大型)mbuf。这被硬件具有最大散点-收集计数的驱动程序使用。如果发送帧跨越的 mbuf 数量超过硬件能处理的数量,驱动程序会退回到 `m_defrag`,将有效载荷复制到一个连续的单个集群中。 -You will meet all of these functions in the course of reading real 驱动程序. For now, knowing that they exist, and that mbuf layout is something a real 驱动程序 must take seriously, is enough. +在阅读真正驱动程序的过程中你会遇到所有这些函数。现在,知道它们存在,并且知道 mbuf 布局是真正的驱动程序必须认真对待的事情,就足够了。 -### A Deeper Look at mbuf Structure +### 深入了解 mbuf 结构 -Because mbufs are the currency of the network stack, spending a few more pages on their structure is time well spent. The decisions a 驱动程序 makes about mbufs are the decisions that determine whether the 驱动程序 is fast, correct, and maintainable. +因为 mbuf 是网络协议栈的通用货币,在它们的结构上多花几页时间是值得的。驱动程序对 mbuf 所做的决策决定了驱动程序是否快速、正确和可维护。 -The mbuf structure itself lives in `/usr/src/sys/sys/mbuf.h`. The on-disk layout, as of FreeBSD 14.3, is something like this (simplified for teaching): +mbuf 结构体本身位于 `/usr/src/sys/sys/mbuf.h` 中。在 FreeBSD 14.3 中,其磁盘布局大致如下(为教学简化): ```c struct mbuf { @@ -1074,62 +1073,62 @@ struct mbuf { }; ``` -Two union variants inside two unions. The layout captures the fact that an mbuf can be in one of several modes: +两个联合体内部有两个联合体变体。该布局捕获了 mbuf 可以处于几种模式之一的事实: -* A plain mbuf with its data stored inline (about 200 bytes available). -* A 数据包-header mbuf with its data stored inline (slightly less available because of the header). -* A 数据包-header mbuf with its data stored in an external cluster (`m_ext`). -* A non-header mbuf with its data stored in an external cluster. +* 数据内联存储的普通 mbuf(约 200 字节可用)。 +* 数据内联存储的数据包头部 mbuf(由于头部占空间,可用空间略少)。 +* 数据存储在外部集群(`m_ext`)中的数据包头部 mbuf。 +* 数据存储在外部集群中的非头部 mbuf。 -The `m_flags` field indicates which variant is in effect through the bits `M_PKTHDR` and `M_EXT`. +`m_flags` 字段通过 `M_PKTHDR` 和 `M_EXT` 位指示哪个变体生效。 -A cluster is a larger pre-allocated 缓冲区, typically 2048 bytes on modern FreeBSD. The mbuf holds a pointer to the cluster in `m_ext.ext_buf`, and the cluster is reference-counted through `m_ext.ext_count`. Clusters exist because many 数据包 are larger than a plain mbuf can hold, and allocating a fresh 缓冲区 for every large 数据包 would be costly. +集群是一个更大的预分配缓冲区,在现代 FreeBSD 上通常为 2048 字节。mbuf 在 `m_ext.ext_buf` 中保存指向集群的指针,集群通过 `m_ext.ext_count` 进行引用计数。集群存在是因为许多数据包大于普通 mbuf 可以容纳的大小,而为每个大数据包分配新缓冲区是昂贵的。 -When you call `MGETHDR(m, M_NOWAIT, MT_DATA)`, you get a 数据包-header mbuf with inline data. When you call `m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR)`, you get a 数据包-header mbuf with an external cluster 附加ed. The second form can hold about 2000 bytes without chaining, which is convenient for 以太网-sized 数据包. +当你调用 `MGETHDR(m, M_NOWAIT, MT_DATA)` 时,你会得到一个带有内联数据的数据包头部 mbuf。当你调用 `m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR)` 时,你会得到一个附加了外部集群的数据包头部 mbuf。第二种形式可以在不链接的情况下保存约 2000 字节,这对以太网大小的数据包很方便。 -### mbuf Chains and Scatter-Gather +### mbuf 链与分散-聚集 -Because a single mbuf can hold only limited bytes, many 数据包 span several mbufs chained through `m_next`. The `m_pkthdr.len` field on the head mbuf holds the total 数据包 length; the `m_len` on each mbuf in the chain holds that mbuf's contribution. Their relationship is `m_pkthdr.len == sum(m_len across chain)`, and any mismatch is a bug. +因为单个 mbuf 只能容纳有限的字节,许多数据包跨越通过 `m_next` 链接的多个 mbuf。头部 mbuf 上的 `m_pkthdr.len` 字段保存总数据包长度;链中每个 mbuf 上的 `m_len` 保存该 mbuf 的贡献。它们的关系是 `m_pkthdr.len == sum(链中所有 m_len)`,任何不匹配都是错误。 -This chaining has several advantages. It lets the stack prepend headers cheaply: to add an 以太网 header, the stack can allocate a new mbuf, fill in the header, and link it as the new head. It lets the stack split 数据包 cheaply: TCP can segment a large payload by walking a chain rather than copying data. It lets the hardware use scatter-gather DMA: a NIC can transmit a chain by issuing multiple DMA 描述符, one per mbuf. +这种链接有几个优点。它让协议栈可以廉价地前置头部:要添加以太网头部,协议栈可以分配一个新的 mbuf,填入头部,并将其链接为新的头部。它让协议栈可以廉价地分割数据包:TCP 可以通过遍历链而不是复制数据来对大有效载荷进行分段。它让硬件使用分散-收集 DMA:网卡可以通过发出多个 DMA 描述符(每个 mbuf 一个)来传输链。 -The cost is that 驱动程序 must walk chains carefully. If you cast `mtod(m, struct ip *)` and the IP header is split across the first and second mbufs, you read garbage. `m_pullup` is the defence against that mistake, and every serious 驱动程序 uses it when it needs to inspect headers. +代价是驱动程序必须小心地遍历链。如果你进行 `mtod(m, struct ip *)` 转换,而 IP 头部分布在第一个和第二个 mbuf 之间,你会读到垃圾数据。`m_pullup` 是针对该错误的防御,每个严肃的驱动程序在需要检查头部时都使用它。 -### mbuf Types and What They Mean +### mbuf 类型及其含义 -The `m_type` field on every mbuf classifies its purpose: +每个 mbuf 上的 `m_type` 字段分类其用途: -* `MT_DATA`: ordinary 数据包 data. This is what you use for network 数据包. -* `MT_HEADER`: a mbuf dedicated to holding protocol headers. -* `MT_SONAME`: a 套接字 address structure. Used by 套接字-layer code. -* `MT_CONTROL`: ancillary 套接字 control data. -* `MT_NOINIT`: an uninitialised mbuf. Never seen by 驱动程序. +* `MT_DATA`:普通数据包数据。这是你用于网络数据包的类型。 +* `MT_HEADER`:专门用于保存协议头部的 mbuf。 +* `MT_SONAME`:套接字地址结构。由套接字层代码使用。 +* `MT_CONTROL`:辅助套接字控制数据。 +* `MT_NOINIT`:未初始化的 mbuf。驱动程序永远不会看到。 -For 驱动程序 code, `MT_DATA` is almost always correct. The stack handles the others internally. +对于驱动程序代码,`MT_DATA` 几乎总是正确的。协议栈在内部处理其他类型。 -### Packet Header Fields +### 数据包头字段 -The `m_pkthdr` structure on a header mbuf carries fields that travel with the 数据包 through the stack. Some of the most relevant for 驱动程序 authors: +头部 mbuf 上的 `m_pkthdr` 结构体携带随数据包通过协议栈的字段。对驱动程序作者最相关的一些: -* `len`: total length of the mbuf chain. -* `rcvif`: the 接口 on which the 数据包 was received. Drivers set this when constructing a received mbuf. -* `flowid` and `rsstype`: hash of the 数据包's flow, used for multi-queue dispatch. -* `csum_flags` and `csum_data`: hardware checksum state. Drivers with TX checksum offload read these; 驱动程序 with RX checksum offload write them. -* `ether_vtag` and `M_VLANTAG` flag in `m_flags`: hardware-extracted VLAN tag, if VLAN hardware tagging is in use. -* `vt_nrecs` and other VLAN fields: for more elaborate VLAN configurations. -* `tso_segsz`: segment size for TSO 帧. +* `len`:mbuf 链的总长度。 +* `rcvif`:接收数据包的接口。驱动程序在构建接收到的 mbuf 时设置此项。 +* `flowid` 和 `rsstype`:数据包流的哈希,用于多队列分发。 +* `csum_flags` 和 `csum_data`:硬件校验和状态。具有 TX 校验和卸载的驱动程序读取这些;具有 RX 校验和卸载的驱动程序写入这些。 +* `ether_vtag` 和 `m_flags` 中的 `M_VLANTAG` 标志:硬件提取的 VLAN 标签,如果正在使用 VLAN 硬件标记。 +* `vt_nrecs` 和其他 VLAN 字段:用于更复杂的 VLAN 配置。 +* `tso_segsz`:TSO 帧的段大小。 -Most of these fields are set by higher layers before the 数据包 reaches the 驱动程序. For our purposes, setting `rcvif` during receive and reading `len` during transmit is enough. The other fields are hooks that iflib and its predecessors use for offload coordination; a pseudo-驱动程序 can safely ignore them. +这些字段中的大多数在数据包到达驱动程序之前由更高层设置。就我们的目的而言,在接收期间设置 `rcvif`,在发送期间读取 `len` 就够了。其他字段是 iflib 及其前身用于卸载协调的钩子;伪驱动程序可以安全地忽略它们。 -### Reference-Counted External Buffers +### 引用计数的外部缓冲区 -When a cluster is 附加ed to a mbuf, the cluster is reference-counted. This allows 数据包 duplication (via `m_copy数据包`) without copying the payload: two mbufs can share the same cluster, and the cluster is freed only when both mbufs release their reference. BPF uses this mechanism to tap a 数据包 without forcing a copy. +当集群附加到 mbuf 时,集群是引用计数的。这允许数据包复制(通过 `m_copypacket`)而不复制有效载荷:两个 mbuf 可以共享同一个集群,集群只有在两个 mbuf 都释放其引用时才被释放。BPF 使用这种机制在不强制复制的情况下捕获数据包。 -For 驱动程序 code this is mostly transparent. You call `m_freem` on your mbuf, and if the mbuf has an external cluster, the cluster's reference count is decremented; if it reaches zero, the cluster is freed. You do not have to think about the reference counts explicitly. But you should know that they exist, because they explain why `BPF_MTAP` can be cheap: it does not copy the 数据包, it merely grabs an additional reference. +对于驱动程序代码来说,这主要是透明的。你对 mbuf 调用 `m_freem`,如果 mbuf 有外部集群,集群的引用计数递减;如果达到零,集群被释放。你不必显式地考虑引用计数。但你应该知道它们存在,因为它们解释了为什么 `BPF_MTAP` 可以很便宜:它不复制数据包,只是获取一个额外的引用。 -### The Receive Allocation Pattern +### 接收分配模式 -A real NIC 驱动程序 usually allocates mbufs and 附加 clusters to them at initialisation time, fills the receive ring with those mbufs, and lets the hardware DMA into them. The pattern is: +真正的网卡驱动程序通常在初始化时分配 mbuf 并附加集群,用这些 mbuf 填充接收环,并让硬件 DMA 写入它们。模式是: ```c for (i = 0; i < RX_RING_SIZE; i++) { @@ -1141,44 +1140,44 @@ for (i = 0; i < RX_RING_SIZE; i++) { } ``` -When the hardware receives a 数据包, it writes the 数据包 data into the cluster pointed at by one of the 描述符, sets the status to indicate completion, and raises an interrupt. The 驱动程序's receive routine looks at the status, grabs the mbuf, sets `m->m_pkthdr.len` and `m->m_len` from the 描述符's length field, taps BPF, calls `if_input`, and then allocates a replacement mbuf for the 描述符. +当硬件接收到数据包时,它将数据包数据写入由某个描述符指向的集群中,设置状态以指示完成,并引发中断。驱动程序的接收例程查看状态,获取 mbuf,从描述符的长度字段设置 `m->m_pkthdr.len` 和 `m->m_len`,捕获 BPF,调用 `if_input`,然后为描述符分配替换的 mbuf。 -Our pseudo-驱动程序 uses a much simpler pattern: allocate a fresh mbuf every time the receive timer fires. This is perfectly fine for a teaching 驱动程序 because the allocation rate is low. At higher rates you would want the pre-allocation pattern, because allocating mbufs in bulk at init time and recycling them is much cheaper than allocating one per 数据包. +我们的伪驱动程序使用一个更简单的模式:每次接收定时器触发时分配一个新的 mbuf。这对于教学驱动程序来说完全没问题,因为分配率很低。在更高速率下你会想要预分配模式,因为在初始化时批量分配 mbuf 并回收它们比每个数据包分配一个要便宜得多。 -### Common mbuf-Related Mistakes +### 与 mbuf 相关的常见错误 -Even with knowledge of the above, a few mistakes keep occurring in 驱动程序 code: +即使了解了上述内容,驱动程序代码中仍然有一些反复出现的错误: -* Using `m_free` instead of `m_freem` on a chain head. You free the first mbuf and leak the rest. -* Forgetting to set `m_pkthdr.len` correctly when building a 数据包. The stack reads `m_pkthdr.len` rather than walking the chain, so if the two disagree, decoding silently fails. -* Reading `m_pkthdr.len` after `m_freem`. Always cache the length into a local before freeing. -* Confusing `m->m_len` (length of this mbuf) with `m->m_pkthdr.len` (total length of the chain). For a single-mbuf 数据包 they are equal; for chains they differ. -* Reading past `m_len` without walking the chain. If you need bytes beyond the first mbuf, use `m_pullup` or `m_copydata`. -* Modifying a mbuf that you do not own. Once you have handed a mbuf to `if_input`, it is not yours any more. -* Allocating without checking for NULL. `m_gethdr(M_NOWAIT, ...)` can return NULL under memory pressure, and the 驱动程序 must handle that gracefully. +* 在链头部使用 `m_free` 而不是 `m_freem`。你释放了第一个 mbuf 并泄漏了其余的。 +* 在构建数据包时忘记正确设置 `m_pkthdr.len`。协议栈读取 `m_pkthdr.len` 而不是遍历链,所以如果两者不一致,解码会静默失败。 +* 在 `m_freem` 之后读取 `m_pkthdr.len`。总是在释放之前将长度缓存到本地变量中。 +* 混淆 `m->m_len`(此 mbuf 的长度)与 `m->m_pkthdr.len`(链的总长度)。对于单个 mbuf 数据包它们相等;对于链它们不同。 +* 不遍历链就读取超过 `m_len` 的内容。如果你需要第一个 mbuf 之外的字节,使用 `m_pullup` 或 `m_copydata`。 +* 修改不属于你的 mbuf。一旦你将 mbuf 交给 `if_input`,它就不再是你的了。 +* 分配时不检查 NULL。`m_gethdr(M_NOWAIT, ...)` 在内存压力下可能返回 NULL,驱动程序必须优雅地处理这种情况。 -These mistakes are easy to avoid if you know the rules, and reading other 驱动程序 is the best way to internalise them. +如果你了解规则,这些错误很容易避免,阅读其他驱动程序是内化它们的最佳方式。 -### Multi-Queue Transmit in Real Drivers +### 真实驱动程序中的多队列发送 -Modern hardware NICs can transmit on many queues in parallel. A 10-gigabit NIC commonly has eight or sixteen transmit queues, each with its own hardware 环形缓冲区, its own DMA 描述符, and its own completion interrupt. The 驱动程序 distributes outgoing 数据包 among these queues based on a hash of the 数据包's source and destination addresses, so that traffic from different flows goes to different queues and can be processed concurrently on different CPU cores. +现代硬件网卡可以在多个队列上并行发送。一个 10Gb 网卡通常有八个或十六个发送队列,每个都有自己的硬件环形缓冲区、自己的 DMA 描述符和自己的完成中断。驱动程序根据数据包源地址和目标地址的哈希在队列之间分配出站数据包,使来自不同流的流量去往不同队列,并可以在不同的 CPU 核心上并发处理。 -This is far beyond what our pseudo-驱动程序 needs. But the pattern is worth recognising, because it shows up prominently in production 驱动程序. The key pieces are: +这远远超出了我们伪驱动程序的需求。但该模式值得认识,因为它在生产驱动程序中显著出现。关键部分是: -* A queue-selection function that takes a mbuf and returns an index into the 驱动程序's queue array. `mynet` has only one queue (or zero, depending on how you count), so this step is trivial. Real 驱动程序 often use `m->m_pkthdr.flowid` as a precomputed hash. -* A per-queue lock and a per-queue software queue (typically managed by `drbr(9)`) that allows concurrent producers to enqueue 数据包 without contention. -* A transmit kick that drains the software queue into hardware when a producer has enqueued and the hardware is idle. -* A completion 回调, usually from a hardware interrupt, that frees the mbufs whose transmission has completed. +* 一个队列选择函数,接受 mbuf 并返回驱动程序队列数组的索引。`mynet` 只有一个队列(或零个,取决于你怎么计数),所以这一步是微不足道的。真正的驱动程序通常使用 `m->m_pkthdr.flowid` 作为预计算的哈希。 +* 每队列锁和每队列软件队列(通常由 `drbr(9)` 管理),允许并发生产者无竞争地入队数据包。 +* 发送触发,在生产者入队且硬件空闲时将软件队列排入硬件。 +* 完成回调,通常来自硬件中断,释放已完成传输的 mbuf。 -The `if_transmit` prototype is designed to fit this pattern naturally. The caller produces a mbuf and hands it to `if_transmit`. The 驱动程序 either queues it immediately (in a simple case like ours) or dispatches it to the appropriate hardware queue (in a multi-queue case). Either way, the caller sees a single function call and does not need to know how many queues live underneath. +`if_transmit` 原型被设计为自然地适应这种模式。调用者产生一个 mbuf 并将其交给 `if_transmit`。驱动程序要么立即排队(在我们这样的简单情况下),要么将其分派到适当的硬件队列(在多队列情况下)。无论哪种方式,调用者看到的都是一个单一的函数调用,不需要知道下面有多少个队列。 -We will return to multi-queue design when we discuss iflib in a later chapter. For now, it is enough to know that the single-queue model we are building here is a simplification that real 驱动程序 elaborate. +我们将在后面的章节讨论 iflib 时回到多队列设计。现在,知道我们在这里构建的单队列模型是真正的驱动程序所扩展的简化就足够了。 -### A Digression on the `drbr(9)` Helper +### 关于 `drbr(9)` 辅助库的补充说明 -`drbr` stands for "驱动程序 环形缓冲区" and it is a helper library for 驱动程序 that want to maintain their own per-queue software queue. The API is defined and implemented as `static __inline` functions in `/usr/src/sys/net/ifq.h`; there is no separate `drbr.c` or `drbr.h` file. The helpers wrap the underlying `buf_ring(9)` 环形缓冲区 with explicit enqueue and dequeue operations, plus helpers for tapping BPF, counting 数据包, and synchronising with the transmit thread. The shape `drbr` is built for is multi-producer, single-consumer, which is the typical shape of a transmit queue where many threads enqueue but a single dequeue thread drains the ring into hardware. +`drbr` 代表「驱动程序环形缓冲区」,它是一个辅助库,用于想要维护自己的每队列软件队列的驱动程序。API 定义并实现为 `/usr/src/sys/net/ifq.h` 中的 `static __inline` 函数;没有单独的 `drbr.c` 或 `drbr.h` 文件。辅助函数包装了底层的 `buf_ring(9)` 环形缓冲区,提供显式的入队和出队操作,以及捕获 BPF、计数数据包和与发送线程同步的辅助函数。`drbr` 构建的多生产者、单消费者形状,这是发送队列的典型形状,其中许多线程入队但单个出队线程将环形缓冲区排入硬件。 -A 驱动程序 that uses `drbr` typically has a transmit function that looks like this sketch: +使用 `drbr` 的驱动程序通常有一个类似以下草图的发送函数: ```c int @@ -1196,13 +1195,13 @@ my_transmit(struct ifnet *ifp, struct mbuf *m) } ``` -The producer enqueues into a 环形缓冲区 and kicks a taskqueue. The taskqueue consumer then dequeues from the 环形缓冲区 and hands 帧 to hardware. This decouples the producer (which can be any CPU) from the consumer (which runs on a dedicated worker thread per queue), which is exactly the structure that works well on multi-core systems. +生产者入队到环形缓冲区并触发 taskqueue。taskqueue 消费者然后从环形缓冲区出队并将帧交给硬件。这解耦了生产者(可以是任何 CPU)和消费者(在每个队列的专用工作线程上运行),这正是多核系统上效果良好的结构。 -`mynet` does not use `drbr`, because we have neither multiple queues nor hardware to kick. But the pattern is worth seeing once, because it shows up in every performance-conscious 驱动程序 in the tree. +`mynet` 不使用 `drbr`,因为我们既没有多个队列也没有硬件可以触发。但该模式值得看一次,因为它出现在源代码树中每个注重性能的驱动程序中。 -### Testing the Transmit Path +### 测试发送路径 -Build, load, and create the 接口 as in Section 3, then send traffic at it: +像第 3 节那样构建、加载并创建接口,然后向其发送流量: ```console # kldload ./mynet.ko @@ -1219,47 +1218,47 @@ mynet0 1500 02:a3:f1:22:bc:0d 0 0 1 0 mynet0 - 192.0.2.0/24 192.0.2.1 0 - 0 - ``` -The key line is `Opkts 1`. Even though the ping received no reply, we can see that one 数据包 was transmitted through our 驱动程序. The reason there was no reply is that `mynet0` is a pseudo-接口 with nothing on the other side. We will give it a simulated arrival path in Section 5. +关键行是 `Opkts 1`。即使 ping 没有收到回复,我们可以看到一个数据包已经通过我们的驱动程序发送。没有回复的原因是 `mynet0` 是一个伪接口,另一端什么也没有。我们将在第 5 节中为它提供模拟到达路径。 -Leave `tcpdump -i mynet0 -n` running in another terminal, repeat the `ping`, and you will see the outgoing ARP request and IPv4 数据包 being captured. That confirms `BPF_MTAP` is wired up correctly. +在另一个终端保持 `tcpdump -i mynet0 -n` 运行,重复 `ping`,你会看到传出的 ARP 请求和 IPv4 数据包被捕获。这确认 `BPF_MTAP` 已正确连接。 -### Pitfalls +### 陷阱 -A handful of mistakes appear repeatedly in student code and even in experienced 驱动程序. Let us walk through them so you learn to recognise them. +一些错误在学生代码甚至经验丰富的驱动程序中反复出现。让我们逐一讲解,以便你学会识别它们。 -**Freeing the mbuf twice.** If your transmit function has multiple exit paths and one of them forgets to skip `m_freem`, the same mbuf ends up freed twice. The 内核 usually panics with a message about a corrupted free list. The fix is to structure the function with a single exit that owns the free, or to null out `m` after you free it and check before freeing again. +**两次释放 mbuf。** 如果你的发送函数有多个退出路径,其中之一忘记跳过 `m_freem`,同一个 mbuf 会被释放两次。内核通常会因损坏的空闲列表消息而崩溃。修复方法是构造函数使用拥有释放操作的单个退出,或在释放后将 `m` 置为 null 并在再次释放之前检查。 -**Not freeing the mbuf at all.** The other side of the same mistake. If you return from `if_transmit` without freeing or queuing the mbuf, you leak it. In a low-rate 驱动程序 this might take hours to notice; in a high-rate 驱动程序 the machine runs out of mbuf memory quickly. `vmstat -z | grep mbuf` is your best friend for spotting this. +**完全未释放 mbuf。** 同一错误的另一面。如果你从 `if_transmit` 返回而未释放或排队 mbuf,你就会泄漏它。在低速驱动程序中,这可能需要数小时才能注意到;在高速驱动程序中,机器很快就会耗尽 mbuf 内存。`vmstat -z | grep mbuf` 是发现此问题的最佳工具。 -**Assuming the mbuf fits in a single memory 块.** Even a simple 以太网 帧 can be spread across multiple mbufs in a chain, especially after IP fragmentation or TCP segmentation. If you need to examine the headers, either use `m_pullup` to pull the headers into the first mbuf, or walk the chain carefully. +**假设 mbuf 适合单个内存块。** 即使是一个简单的以太网帧也可以分布在链中的多个 mbuf 中,特别是在 IP 分片或 TCP 分段之后。如果你需要检查头部,要么使用 `m_pullup` 将头部拉入第一个 mbuf,要么小心地遍历链。 -**Forgetting to tap BPF.** `tcpdump -i mynet0` will still work for received 数据包 but will miss transmitted ones, and your debugging will be harder because the two halves of the conversation will appear asymmetric. +**忘记捕获 BPF。** `tcpdump -i mynet0` 对接收到的数据包仍然有效,但会遗漏发送的数据包,你的调试会更加困难,因为对话的两半会出现不对称。 -**Updating counters after `m_freem`.** We already mentioned this. Always read `m->m_pkthdr.len` into a local before freeing, or do all your counter updates before freeing. +**在 `m_freem` 之后更新计数器。** 我们已经提到过这一点。总是在释放之前将 `m->m_pkthdr.len` 读入本地变量,或在释放之前完成所有计数器更新。 -**Calling `if_link_state_change` with the wrong argument.** `LINK_STATE_UP`, `LINK_STATE_DOWN`, and `LINK_STATE_UNKNOWN` are the three values defined in `/usr/src/sys/net/if.h`. Passing a random integer like `1` might coincidentally match `LINK_STATE_DOWN` but make the code unreadable and fragile. +**用错误参数调用 `if_link_state_change`。** `LINK_STATE_UP`、`LINK_STATE_DOWN` 和 `LINK_STATE_UNKNOWN` 是 `/usr/src/sys/net/if.h` 中定义的三个值。传递随机整数如 `1` 可能碰巧匹配 `LINK_STATE_DOWN`,但会使代码不可读且脆弱。 -### 总结 Section 4 +### 第4节小结 -The transmit path is the clearest demonstration of how the network stack and the 驱动程序 cooperate. We accept a mbuf, validate it, count it, let BPF see it, and free it. Real hardware 驱动程序 add DMA and hardware rings at the bottom; the skeleton remains the same. +发送路径是网络协议栈和驱动程序如何合作的最清晰演示。我们接受 mbuf,验证它,计数它,让 BPF 看到它,然后释放它。真正的硬件驱动程序在底部添加 DMA 和硬件环;骨架保持不变。 -We have one large piece missing: the receive path. Without it, our 接口 talks but never listens. Section 5 builds that half. +我们还缺少一个大的部分:接收路径。没有它,我们的接口只说但从不听。第 5 节构建那一半。 -## 第5节: Handling Packet Reception +## 第5节:处理数据包接收 -Reception is the inbound half of 数据包 flow. Packets arrive from the transport, and the 驱动程序 is responsible for turning them into mbufs, giving them to BPF, and handing them up to the stack through `if_input`. In a real NIC 驱动程序 the arrival is an interrupt or a 描述符-ring completion. In our pseudo-驱动程序, we will simulate arrival with a callout that fires every second and constructs a synthetic 数据包. The mechanism is artificial, but the code path is identical to what real 驱动程序 do after the initial 描述符-ring dequeue. +接收是数据包流入站的半部分。数据包从传输层到达,驱动程序负责将它们转换为 mbuf,交给 BPF,并通过 `if_input` 向上传递给协议栈。在真正的网卡驱动程序中,到达是一个中断或描述符环完成。在我们的伪驱动程序中,我们将用每秒触发一次的 callout 来模拟到达并构造合成数据包。机制是人工的,但代码路径与真正的驱动程序在初始描述符环出队之后所做的相同。 -### The Callback Direction +### 回调方向 -Transmit flows down: stack calls 驱动程序. Reception flows up: 驱动程序 calls stack. You do not 注册 a receive 回调 for the stack to invoke. Instead, whenever a 数据包 arrives, you call `if_input(ifp, m)` (or equivalently `(*ifp->if_input)(ifp, m)`) and the stack takes over. `ether_if附加` arranged for `ifp->if_input` to point at `ether_input`, so when we call `if_input` the 以太网 layer receives the 帧, strips the 以太网 header, dispatches on the EtherType, and hands the payload up to IPv4, IPv6, ARP, or wherever it belongs. +发送向下流动:协议栈调用驱动程序。接收向上流动:驱动程序调用协议栈。你不注册一个供协议栈调用的接收回调。相反,每当数据包到达时,你调用 `if_input(ifp, m)`(或等价的 `(*ifp->if_input)(ifp, m)`),协议栈接管。`ether_ifattach` 安排 `ifp->if_input` 指向 `ether_input`,所以当我们调用 `if_input` 时,以太网层接收帧,剥离以太网头部,根据 EtherType 进行分派,并将有效载荷上交给 IPv4、IPv6、ARP 或其所属的位置。 -This is an important mental shift from `if_transmit`. The stack does not poll your 驱动程序. It waits to be called. Your 驱动程序 is the active party for reception. Whenever you have a 帧 ready, you make the call. The stack does the rest. +这是从 `if_transmit` 的一个重要思维转变。协议栈不轮询你的驱动程序。它等待被调用。你的驱动程序是接收的主动方。每当你有准备好的帧,你就发起调用。协议栈做其余的事情。 -### The Simulated Arrival +### 模拟到达 -Let us build a simulated arrival path. The idea: once a second, wake up, build a small mbuf containing a valid 以太网 帧, and feed it to the stack. The 帧 will be a broadcast ARP request targeting a nonexistent IP address. That is easy to construct, useful for testing because `tcpdump` will clearly display it, and harmless to the rest of the system. +让我们构建一个模拟到达路径。思路是:每秒唤醒一次,构建一个包含有效以太网帧的小型 mbuf,并将其送入协议栈。该帧将是一个针对不存在 IP 地址的广播 ARP 请求。这很容易构建,对测试很有用,因为 `tcpdump` 会清晰地显示它,而且对系统的其余部分无害。 -First, the callout handler: +首先,callout 处理程序: ```c static void @@ -1282,9 +1281,9 @@ mynet_rx_timer(void *arg) } ``` -The callout is initialised with `callout_init_mtx` and the softc 互斥锁, so the system acquires our 互斥锁 before calling us. That gives us `MYNET_ASSERT` for free: the lock is already held. We check if we are still running, reschedule the timer for the next tick, drop the lock, do the actual work, and reacquire the lock on the way back. Dropping the lock is important, because `if_input` can take its time and may acquire other locks. Calling up into the stack while holding a 驱动程序 互斥锁 is a recipe for lock-order reversals. +callout 使用 `callout_init_mtx` 和 softc 互斥锁初始化,因此系统在调用我们之前会获取我们的互斥锁。这使我们可以免费使用 `MYNET_ASSERT`:锁已经被持有。我们检查是否仍在运行,重新调度定时器以等待下一个节拍,释放锁,执行实际工作,然后在返回时重新获取锁。释放锁很重要,因为 `if_input` 可能需要一些时间并可能获取其他锁。在持有驱动程序互斥锁的情况下向上调用协议栈是锁序反转的经典配方。 -Next, the 数据包 construction itself: +接下来,数据包构造本身: ```c static void @@ -1337,53 +1336,53 @@ mynet_rx_fake_arp(struct mynet_softc *sc) } ``` -There is a lot to unpack, but most of it is simple. Let us walk through. +这里有很多内容需要消化,但大部分都很简单。让我们逐步讲解。 -### `MGETHDR`: Allocating the Head of the Chain +### `MGETHDR`:分配链的头部 -`MGETHDR(m, M_NOWAIT, MT_DATA)` allocates a new mbuf and prepares it as the head of a 数据包 chain. It expands to `m_gethdr(M_NOWAIT, MT_DATA)` through the compatibility macro 块 in `/usr/src/sys/sys/mbuf.h` (the `#define MGETHDR(m, how, type) ((m) = m_gethdr((how), (type)))` entry, right next to `MGET` and `MCLGET`). `M_NOWAIT` tells the allocator to fail rather than sleep, which is appropriate because we may run in contexts where sleeping is forbidden (this particular 回调 is a callout, which cannot sleep). `MT_DATA` is the mbuf type for generic data. +`MGETHDR(m, M_NOWAIT, MT_DATA)` 分配一个新的 mbuf 并将其准备为数据包链的头部。它通过 `/usr/src/sys/sys/mbuf.h` 中的兼容宏块展开为 `m_gethdr(M_NOWAIT, MT_DATA)`(`#define MGETHDR(m, how, type) ((m) = m_gethdr((how), (type)))` 条目,紧挨着 `MGET` 和 `MCLGET`)。`M_NOWAIT` 告诉分配器失败而不是睡眠,这是合适的,因为我们可能在不允许睡眠的上下文中运行(这个特定的回调是一个 callout,不能睡眠)。`MT_DATA` 是通用数据的 mbuf 类型。 -On allocation failure we increment `IFCOUNTER_IQDROPS` (input queue drops) and return. Drops caused by mbuf starvation are counted this way in most 驱动程序. +分配失败时,我们递增 `IFCOUNTER_IQDROPS`(输入队列丢弃)并返回。大多数驱动程序以这种方式统计由 mbuf 耗尽导致的丢弃。 -### Setting Packet Header Fields +### 设置数据包头字段 -Once we have the mbuf, we set three fields in the 数据包 header: +一旦我们有了 mbuf,我们在数据包头部中设置三个字段: -* `m->m_pkthdr.len`: the total length of the 数据包. This is the sum of `m_len` across the chain. For a single-mbuf 数据包 like ours, `m_pkthdr.len` equals `m_len`. -* `m->m_len`: the length of data in this mbuf. We are storing the whole 帧 in the first (and only) mbuf. -* `m->m_pkthdr.rcvif`: the 接口 on which the 数据包 arrived. The stack uses this for routing decisions and for reporting. +* `m->m_pkthdr.len`:数据包的总长度。这是链中所有 `m_len` 的总和。对于像我们这样的单 mbuf 数据包,`m_pkthdr.len` 等于 `m_len`。 +* `m->m_len`:此 mbuf 中数据的长度。我们将整个帧存储在第一个(也是唯一的)mbuf 中。 +* `m->m_pkthdr.rcvif`:数据包到达的接口。协议栈使用此字段进行路由决策和报告。 -A small mbuf (about 256 bytes) holds our 42-byte 以太网 ARP 帧 comfortably. If we were building a larger 帧, we would use `MGET` and external 缓冲区, or `m_getcl` for a cluster-backed mbuf, or chain several mbufs together. We will revisit those patterns in later chapters. +一个小的 mbuf(约 256 字节)可以舒适地容纳我们 42 字节的以太网 ARP 帧。如果我们构建一个更大的帧,我们会使用 `MGET` 和外部缓冲区,或使用 `m_getcl` 获取集群支持的 mbuf,或将多个 mbuf 链接在一起。我们将在后面的章节中重新讨论这些模式。 -### Writing the 以太网 Header +### 写入以太网头部 -`mtod(m, struct ether_header *)` is a macro from `/usr/src/sys/sys/mbuf.h` that casts `m_data` to a pointer to the requested type. It stands for "mbuf to data". We use it to get a writeable `struct ether_header` pointer at the start of the 数据包 and fill in the destination MAC (broadcast `ff:ff:ff:ff:ff:ff`), the source MAC (our 接口's MAC), and the EtherType (`ETHERTYPE_ARP`, in network byte order). +`mtod(m, struct ether_header *)` 是 `/usr/src/sys/sys/mbuf.h` 中的一个宏,它将 `m_data` 转换为所请求类型的指针。它代表"mbuf to data"。我们使用它在数据包起始处获取一个可写的 `struct ether_header` 指针,并填入目标 MAC(广播 `ff:ff:ff:ff:ff:ff`)、源 MAC(我们接口的 MAC)和 EtherType(`ETHERTYPE_ARP`,网络字节序)。 -The 以太网 header is the minimum layer-2 encapsulation the stack expects on our 接口, because we 附加ed with `ether_if附加`. `ether_input` will strip this header and dispatch on the EtherType. +以太网头部是协议栈期望我们接口提供的最小二层封装,因为我们使用 `ether_ifattach` 附加。`ether_input` 将剥离此头部并根据 EtherType 进行分派。 -### Writing the ARP Body +### 写入 ARP 报文体 -Past the 以太网 header comes the ARP header proper, then the ARP payload (sender MAC, sender IP, target MAC, target IP). The field names and constants come from `/usr/src/sys/net/if_arp.h`. We put a real sender MAC (ours), a sender IP of `0.0.0.0`, a zero target MAC, and a target IP of `192.0.2.99`. That last address is in the TEST-NET-1 range reserved by RFC 5737 for documentation and examples, which is a polite choice for a synthetic 数据包 that will never leave our system. +在以太网头部之后是 ARP 头部本身,然后是 ARP 有效载荷(发送方 MAC、发送方 IP、目标 MAC、目标 IP)。字段名称和常量来自 `/usr/src/sys/net/if_arp.h`。我们放入一个真实的发送方 MAC(我们的),发送方 IP 为 `0.0.0.0`,目标 MAC 为零,目标 IP 为 `192.0.2.99`。最后一个地址位于 RFC 5737 为文档和示例保留的 TEST-NET-1 范围内,对于永远不会离开我们系统的合成数据包来说,这是一个礼貌的选择。 -None of this is production-grade ARP code. We are not trying to resolve anything. We are generating a well-formed 帧 that the 以太网 input layer will recognise, parse, log in counters, and drop (because the target IP is not ours). It is exactly the right level of realism for a teaching 驱动程序. +这些都不是生产级的 ARP 代码。我们不是试图解析任何东西。我们正在生成一个格式良好的帧,以太网输入层会识别它、解析它、在计数器中记录它,然后丢弃它(因为目标 IP 不是我们的)。这正是教学驱动程序所需的真实度级别。 -### Handing It to BPF +### 交给 BPF -`BPF_MTAP(ifp, m)` gives `tcpdump` a chance to see the incoming 帧. We tap before we call `if_input`, because `if_input` may mutate the mbuf in ways that would make the tap show confusing data. Real 驱动程序 always tap before consuming. +`BPF_MTAP(ifp, m)` 给 `tcpdump` 一个查看传入帧的机会。我们在调用 `if_input` 之前捕获,因为 `if_input` 可能以使捕获显示令人困惑数据的方式修改 mbuf。真正的驱动程序总是在消费之前捕获。 -### Incrementing Input Counters +### 递增输入计数器 -`IFCOUNTER_IPACKETS` and `IFCOUNTER_IBYTES` count received 数据包 and bytes respectively. If the 帧 is a broadcast or multicast, we would also increment `IFCOUNTER_IMCASTS`. We omit that here for brevity but the full companion file includes it. +`IFCOUNTER_IPACKETS` 和 `IFCOUNTER_IBYTES` 分别统计接收到的数据包数和字节数。如果帧是广播或多播,我们还需要递增 `IFCOUNTER_IMCASTS`。这里为简洁起见省略了,但完整的配套文件包含它。 -### Calling `if_input` +### 调用 `if_input` -`if_input(ifp, m)` is the final step. It is an inline helper in `/usr/src/sys/net/if_var.h` that dereferences `ifp->if_input` (which `ether_if附加` set to `ether_input`) and invokes it. From that moment, the mbuf is the stack's responsibility. If the stack accepts the 数据包, it uses it and eventually frees it. If the stack rejects the 数据包, it frees it and increments `IFCOUNTER_IERRORS`. Either way, we must not touch `m` again. +`if_input(ifp, m)` 是最后一步。它是 `/usr/src/sys/net/if_var.h` 中的一个内联辅助函数,解引用 `ifp->if_input`(`ether_ifattach` 将其设置为 `ether_input`)并调用它。从那一刻起,mbuf 就是协议栈的责任了。如果协议栈接受数据包,它会使用它并最终释放它。如果协议栈拒绝数据包,它会释放它并递增 `IFCOUNTER_IERRORS`。无论哪种方式,我们都不得再次触碰 `m`。 -This is the complementary rule to transmit: in transmit, the 驱动程序 owns the mbuf until it is freed or handed to hardware; in receive, the stack takes ownership the moment you call `if_input`. Getting these ownership rules right is the single most important discipline in writing 网络驱动程序. +这是与发送互补的规则:在发送中,驱动程序拥有 mbuf 直到它被释放或交给硬件;在接收中,协议栈在你调用 `if_input` 的那一刻就取得了所有权。正确处理这些所有权规则是编写网络驱动程序中最重要的纪律。 -### Verifying the Receive Path +### 验证接收路径 -Build and load the updated 驱动程序, bring up the 接口, and watch `tcpdump`: +构建并加载更新后的驱动程序,启动接口,然后观察 `tcpdump`: ```console # kldload ./mynet.ko @@ -1398,11 +1397,11 @@ listening on mynet0, link-type EN10MB (Ethernet), capture size 262144 bytes ... ``` -Every second, you should see one synthesised ARP request fly by. If you then check `netstat -in -I mynet0`, the `Ipkts` counter should be climbing. The stack accepts the 数据包, inspects the ARP, decides it is not a question addressed to it (because `192.0.2.99` is not assigned to the 接口), and silently drops it. That is exactly what we want, and it demonstrates that the full receive path works. +每秒你应该看到一个合成的 ARP 请求飞过。如果你随后检查 `netstat -in -I mynet0`,`Ipkts` 计数器应该在不断攀升。协议栈接受数据包,检查 ARP,判断它不是一个发给自己的查询(因为 `192.0.2.99` 未分配给该接口),然后静默丢弃它。这正是我们想要的结果,它证明完整的接收路径工作正常。 -### Ownership: A Diagram +### 所有权:一张图 -Because the ownership rules are so important, it helps to draw them. The following diagram summarises who owns the mbuf at each stage: +因为所有权规则如此重要,用一张图来总结它们会很有帮助。下图总结了在每个阶段谁拥有 mbuf: ```text Transmit: @@ -1420,46 +1419,46 @@ Receive: driver MUST NOT touch m again ``` -If you keep these two diagrams in your head, you will not get mbuf ownership wrong in your own 驱动程序. +如果你把这两张图记在脑海中,你就不会在自己的驱动程序中搞错 mbuf 所有权。 -### Keeping Receive Safe Under Contention +### 在竞争条件下保持接收安全 -A production 驱动程序's receive path is usually called from an 中断处理程序 or a hardware queue completion routine, running on one CPU while another CPU may be transmitting or handling ioctls. The pattern we have shown here is safe because: +生产驱动程序的接收路径通常从中断处理程序或硬件队列完成例程中调用,运行在一个 CPU 上,而另一个 CPU 可能正在发送或处理 ioctl。我们这里展示的模式是安全的,因为: -* We hold our 互斥锁 around the "am I running?" check. -* We drop the 互斥锁 before the heavy work of mbuf allocation and 数据包 construction. -* We drop the 互斥锁 before calling `if_input`, which may in turn call into the stack and acquire other locks. -* We reacquire our 互斥锁 after `if_input` returns, so that the callout 框架 can see a consistent state. +* 我们在「我是否在运行?」检查周围持有互斥锁。 +* 我们在 mbuf 分配和数据包构造的繁重工作之前释放互斥锁。 +* 我们在调用 `if_input` 之前释放互斥锁,`if_input` 可能反过来调用协议栈并获取其他锁。 +* 我们在 `if_input` 返回后重新获取互斥锁,以便 callout 框架能看到一致的状态。 -Real 驱动程序 often add per-CPU receive queues, deferred processing via taskqueues, and lock-free counters. All of that is a refinement of the same pattern. The core invariants remain the same: do not call up with a 驱动程序 lock held, and do not touch an mbuf after it has been handed up. +真正的驱动程序通常添加每 CPU 接收队列、通过 taskqueue 的延迟处理和无锁计数器。所有这些都只是同一模式的改进。核心不变量保持不变:不要在持有驱动锁的情况下向上调用,不要在 mbuf 已向上提交后触碰它。 -### Alternative: Using `if_epoch` +### 替代方案:使用 `if_epoch` -FreeBSD 12 introduced a network epoch mechanism, `net_epoch`, for accessing certain data structures without long-lived locks. Modern 驱动程序 often enter the net epoch around receive code to make their access to the routing table, ARP tables, and some parts of the `ifnet` list safe and fast. You will see `NET_EPOCH_ENTER(et)` and `NET_EPOCH_EXIT(et)` in many 驱动程序. For our simple pseudo-驱动程序, entering net_epoch would add complexity we do not need. We mention it here so that you recognise it when you read `if_em.c` or `if_bge.c`, and we will return to it in later chapters. +FreeBSD 12 引入了网络 epoch 机制 `net_epoch`,用于在不使用长生命周期锁的情况下访问某些数据结构。现代驱动程序通常在接收代码周围进入 net epoch,使其对路由表、ARP 表和 `ifnet` 列表某些部分的访问既安全又快速。你会看到许多驱动程序中使用 `NET_EPOCH_ENTER(et)` 和 `NET_EPOCH_EXIT(et)`。对于我们简单的伪驱动程序,进入 net epoch 会增加我们不需要的复杂性。我们在这里提及它,是为了让你在阅读 `if_em.c` 或 `if_bge.c` 时能认出它,我们将在后面的章节中回到这个话题。 -### Receive Paths in Real NIC Drivers +### 真实网卡驱动程序中的接收路径 -Our simulated receive path is artificial, but the surrounding structure is exactly what real 驱动程序 use. The differences are in where the mbuf comes from and who calls the receive routine, not in what the receive routine does afterwards. This subsection walks through the typical real-驱动程序 receive path so that you recognise it the next time you open an 以太网 驱动程序 in the tree. +我们的模拟接收路径是人工的,但其周围的结构与真正的驱动程序所使用的完全相同。区别在于 mbuf 的来源和谁调用接收例程,而不在于接收例程之后做什么。本小节将带你了解典型的真实驱动程序接收路径,以便你下次在源代码树中打开以太网驱动程序时能认出它。 -On a real NIC, 数据包 arrive as DMA writes to receive 描述符 in 环形缓冲区. The hardware populates each 描述符 with a pointer to a pre-allocated mbuf (provided by the 驱动程序 during initialisation), a length, and a status field indicating whether the 描述符 is ready for the 驱动程序 to process. When a 描述符 is ready, the hardware either raises an interrupt or sets a bit that the 驱动程序 will notice through polling, or both. +在真正的网卡上,数据包以 DMA 写入环形缓冲区中接收描述符的方式到达。硬件用驱动程序在初始化期间提供的预分配 mbuf 指针、长度和指示描述符是否准备好供驱动程序处理的状态字段来填充每个描述符。当描述符就绪时,硬件要么引发中断,要么设置一个驱动程序通过轮询注意到的位,或者两者兼有。 -The 驱动程序's receive routine walks the ring starting at the last-processed index. For each ready 描述符, it reads the length and status, fixes up the corresponding mbuf to have the correct `m_len` and `m_pkthdr.len`, sets `m->m_pkthdr.rcvif = ifp`, taps BPF, updates counters, and calls `if_input`. It then allocates a replacement mbuf to put back into the 描述符, so that future 数据包 have somewhere to land, and advances the head pointer. +驱动程序的接收例程从最后处理的索引开始遍历环形缓冲区。对于每个就绪描述符,它读取长度和状态,修复相应的 mbuf 使其具有正确的 `m_len` 和 `m_pkthdr.len`,设置 `m->m_pkthdr.rcvif = ifp`,捕获 BPF,更新计数器,并调用 `if_input`。然后它分配一个替换 mbuf放回描述符,以便未来的数据包有地方着陆,并推进头指针。 -This loop continues until either the ring is empty or the 驱动程序 has processed its per-invocation budget. Processing too many 数据包 in one interrupt starves other interrupts and hurts latency for other 设备; processing too few wastes context switches. A budget of 32 or 64 数据包 is typical. +此循环持续进行,直到环形缓冲区为空或驱动程序已处理完其每次调用的预算。在一次中断中处理太多数据包会饿死其他中断并损害其他设备的延迟;处理太少则浪费上下文切换。32 或 64 个数据包的预算是典型的。 -After the receive loop, the 驱动程序 updates the hardware's tail pointer to reflect the newly-replenished 描述符. If any 描述符 are still ready, the 驱动程序 either re-arms the interrupt or schedules itself to run again through a taskqueue. +接收循环之后,驱动程序更新硬件的尾指针以反映新补充的描述符。如果任何描述符仍然就绪,驱动程序要么重新启用中断,要么通过 taskqueue 调度自己再次运行。 -The completion routine for transmit is the mirror image: it walks the transmit ring looking for 描述符 whose status indicates the hardware has finished with them, frees the corresponding mbufs, and updates the 驱动程序's sense of available transmit slots. +发送的完成例程是镜像:它遍历发送环,寻找状态指示硬件已完成的描述符,释放相应的 mbuf,并更新驱动程序对可用发送槽位的感知。 -You will see all of this in `/usr/src/sys/dev/e1000/em_txrx.c` and its equivalents for other 以太网 hardware. The ring-缓冲区 machinery looks intimidating at first, but its purpose is always the same: produce mbufs from hardware DMA and hand them up through `if_input`. Our pseudo-驱动程序 produces mbufs from `malloc` and hands them up through `if_input`. The hand-up is identical; only the source of mbufs differs. +你会在 `/usr/src/sys/dev/e1000/em_txrx.c` 及其他以太网硬件的等价文件中看到所有这些。环形缓冲区机制乍一看令人生畏,但其目的始终相同:从硬件 DMA 产生 mbuf 并通过 `if_input` 向上传递。我们的伪驱动程序从 `malloc` 产生 mbuf 并通过 `if_input` 向上传递。向上传递是相同的;只有 mbuf 的来源不同。 -### Deferred Receive Processing with Taskqueues +### 使用任务队列的延迟接收处理 -A common refinement in high-rate 驱动程序 is to defer the actual receive processing out of the interrupt context and into a taskqueue. The 中断处理程序 does the minimum 挂载 of work (typically acknowledging the interrupt to hardware and scheduling the task), and the taskqueue worker thread does the ring walk and the `if_input` calls. +高速率驱动程序中一个常见的改进是将实际接收处理从中断上下文延迟到 taskqueue。中断处理程序做最少量的工作(通常是向硬件确认中断并调度任务),taskqueue 工作线程做环形遍历和 `if_input` 调用。 -Why defer? Because `if_input` can do significant work inside the stack, including TCP processing, 套接字-缓冲区 deposition, and sleep operations. Holding a CPU in an 中断处理程序 for that long is bad for interrupt latency on other 设备. Moving receive processing to a taskqueue lets the scheduler interleave it with other work. +为什么要延迟?因为 `if_input` 在协议栈内部可能做大量工作,包括 TCP 处理、套接字缓冲区填充和睡眠操作。在那么长时间内持有一个 CPU 在中断处理程序中对其他设备的中断延迟是有害的。将接收处理移到 taskqueue 让调度器将其与其他工作交错进行。 -FreeBSD's taskqueue subsystem, `/usr/src/sys/kern/subr_taskqueue.c`, provides per-CPU worker threads that can be targeted by 驱动程序. A receive 中断处理程序 looks like: +FreeBSD 的 taskqueue 子系统 `/usr/src/sys/kern/subr_taskqueue.c` 提供了驱动程序可以定位的每 CPU 工作线程。接收中断处理程序看起来像这样: ```c static void @@ -1483,17 +1482,17 @@ my_rx_task(void *arg, int pending __unused) } ``` -Again, `mynet` is a pseudo-驱动程序 and does not need this complexity. But seeing the pattern means that when you read `if_em.c` or `if_ixl.c` and see `taskqueue_enqueue`, you know what is being deferred and why. +同样,`mynet` 是一个伪驱动程序,不需要这种复杂性。但看到这个模式意味着当你阅读 `if_em.c` 或 `if_ixl.c` 并看到 `taskqueue_enqueue` 时,你就知道什么正在被延迟以及为什么。 -### Understanding `net_epoch` +### 理解 `net_epoch` -The `net_epoch` 框架 in FreeBSD is an implementation of epoch-based reclamation adapted for the networking subsystem. Its purpose is to let readers of networking data structures (routing tables, ARP tables, 接口 lists, and so on) read those structures without acquiring locks, while ensuring that writers do not free a structure while a reader might still be looking at it. +FreeBSD 中的 `net_epoch` 框架是为网络子系统适配的基于 epoch 的回收机制的实现。其目的是让网络数据结构(路由表、ARP 表、接口列表等)的读者在不获取锁的情况下读取这些结构,同时确保写入者不会在读者可能仍在查看某个结构时释放它。 -The API is simple. A reader enters the epoch with `NET_EPOCH_ENTER(et)` and exits with `NET_EPOCH_EXIT(et)`, where `et` is a per-call tracker variable. Between enter and exit, the reader can safely dereference pointers into the protected data structures. Writers that want to free a protected object call `epoch_call` to defer the free until all current readers have exited. +API 很简单。读者使用 `NET_EPOCH_ENTER(et)` 进入 epoch,使用 `NET_EPOCH_EXIT(et)` 退出,其中 `et` 是一个每次调用的跟踪器变量。在进入和退出之间,读者可以安全地解引用指向受保护数据结构的指针。想要释放受保护对象的写入者调用 `epoch_call` 来延迟释放,直到所有当前读者都退出。 -For 驱动程序 code, the relevance is this: the stack routines you call from your receive path, including `ether_input` and its downstream callers, expect to be invoked while the caller is inside the net epoch. Some 驱动程序 therefore wrap their `if_input` calls in `NET_EPOCH_ENTER`/`NET_EPOCH_EXIT`. Others (and this includes most callout-based pseudo-驱动程序) rely on the fact that `if_input` itself enters the epoch on entry if not already inside it. +对于驱动程序代码,其相关性在于:你从接收路径调用的协议栈例程,包括 `ether_input` 及其下游调用者,期望在调用者位于 net epoch 内部时被调用。因此,一些驱动程序将 `if_input` 调用包裹在 `NET_EPOCH_ENTER`/`NET_EPOCH_EXIT` 中。其他驱动程序(包括大多数基于 callout 的伪驱动程序)则依赖 `if_input` 本身在进入时如果不在 epoch 内则自动进入 epoch 这一事实。 -For `mynet`, we do not enter the epoch explicitly. `if_input` handles that for us. If you want to be extra careful or are operating in a context where the epoch is known not to be entered, you can wrap your call like this: +对于 `mynet`,我们不显式进入 epoch。`if_input` 会为我们处理。如果你想格外小心,或者操作在一个已知未进入 epoch 的上下文中,你可以像这样包裹你的调用: ```c struct epoch_tracker et; @@ -1503,68 +1502,68 @@ if_input(ifp, m); NET_EPOCH_EXIT(et); ``` -This is the idiom you will see in more recent 驱动程序. We have omitted it in the main chapter text because it adds noise without changing behaviour for our pseudo-驱动程序. In a 驱动程序 that may fire `if_input` from unusual contexts (for example, a workqueue or a timer tick scheduled on a non-network CPU), you would want to wrap explicitly. +这是你在更新的驱动程序中会看到的惯用法。我们在正文中省略了它,因为它为我们的伪驱动程序增加了噪音而不改变行为。在可能从不寻常的上下文(例如工作队列或调度在非网络 CPU 上的定时器节拍)触发 `if_input` 的驱动程序中,你会想要显式包裹。 -### Receive Backpressure +### 接收背压 -A 驱动程序 that receives 数据包 faster than the stack can process them will eventually overrun its 环形缓冲区. Real 驱动程序 handle this in one of two ways: they drop the oldest pending 数据包 and update `IFCOUNTER_IQDROPS`, or they stop taking new 描述符 and let the hardware itself drop. +一个接收数据包速度超过协议栈处理能力的驱动程序最终会耗尽其环形缓冲区。真正的驱动程序以两种方式之一处理:丢弃最旧的待处理数据包并更新 `IFCOUNTER_IQDROPS`,或者停止接收新描述符让硬件自己丢弃。 -In software pseudo-驱动程序 there is no hardware to run out of 描述符, but you should still think about backpressure. If your simulated receive path is generating 数据包 faster than the stack can consume them, you will eventually see mbuf allocation failures, or the system will start queueing 数据包 in 套接字 缓冲区 without ever emptying them. The practical defence is to rate-limit yourself through the callout interval and to watch `vmstat -z | grep mbuf` during long-running tests. +在软件伪驱动程序中没有会耗尽描述符的硬件,但你仍然应该考虑背压。如果你的模拟接收路径生成数据包的速度超过协议栈消费的速度,你最终会看到 mbuf 分配失败,或者系统开始在不排空的情况下将数据包排队到套接字缓冲区中。实际的防御是通过 callout 间隔限制自己的速率,并在长时间测试中观察 `vmstat -z | grep mbuf`。 -For `mynet`, we generate one synthetic ARP per second. That is several orders of magnitude below any reasonable backpressure threshold. But if you increase `sc->rx_interval_hz` to something aggressive like `hz / 1000` (one 数据包 per millisecond), you are asking the 内核 to absorb a thousand ARPs per second from a single 驱动程序, and you will see the costs. +对于 `mynet`,我们每秒生成一个合成 ARP。这比任何合理的背压阈值低几个数量级。但如果你将 `sc->rx_interval_hz` 增加到像 `hz / 1000`(每毫秒一个数据包)这样激进的值,你就是要求内核从单个驱动程序吸收每秒一千个 ARP,你会看到代价。 ### 常见错误 -The most common receive-path mistakes are the following. +最常见的接收路径错误如下。 -**Forgetting `M_PKTHDR` discipline.** If you construct the mbuf without `MGETHDR`, you do not get a 数据包 header, and the stack will assert or misbehave. Always use `MGETHDR` (or `m_gethdr`) for the head mbuf, and `MGET` (or `m_get`) for subsequent ones. +**忘记 `M_PKTHDR` 纪律。** 如果你不用 `MGETHDR` 构造 mbuf,你就不会得到数据包头部,协议栈会断言失败或行为异常。始终对头部 mbuf 使用 `MGETHDR`(或 `m_gethdr`),对后续的 mbuf 使用 `MGET`(或 `m_get`)。 -**Forgetting to set `m_len` and `m_pkthdr.len`.** The stack uses `m_pkthdr.len` to decide how big the 数据包 is, and it uses `m_len` to walk the chain. If these are wrong, decoding fails silently. +**忘记设置 `m_len` 和 `m_pkthdr.len`。** 协议栈使用 `m_pkthdr.len` 来决定数据包有多大,使用 `m_len` 来遍历链。如果这些值错误,解码会静默失败。 -**Holding the 驱动程序 互斥锁 across `if_input`.** The stack can take a long time inside `if_input`, and it may attempt to acquire other locks. Releasing the 驱动程序 lock before calling up is a discipline that avoids deadlocks. +**在 `if_input` 期间持有驱动互斥锁。** 协议栈在 `if_input` 内部可能花费很长时间,并可能尝试获取其他锁。在向上调用之前释放驱动锁是避免死锁的纪律。 -**Touching `m` after `if_input`.** The stack may have already freed or re-queued the mbuf. Treat `if_input` as a one-way door. +**在 `if_input` 之后触碰 `m`。** 协议栈可能已经释放或重新排队了 mbuf。将 `if_input` 视为一扇单向门。 -**Feeding raw data without a link-layer header.** Because we used `ether_if附加`, `ether_input` expects a full 以太网 帧. If you feed it a bare IPv4 数据包, it will reject the 帧 and increment `IFCOUNTER_IERRORS`. +**在没有链路层头部的情况下送入原始数据。** 因为我们使用了 `ether_ifattach`,`ether_input` 期望一个完整的以太网帧。如果你送入一个裸 IPv4 数据包,它会拒绝该帧并递增 `IFCOUNTER_IERRORS`。 -### 总结 Section 5 +### 第5节小结 -We now have two-way traffic through our 驱动程序. Transmit consumes mbufs from the stack; receive produces mbufs for the stack. In between we have BPF hooks, counter updates, and 互斥锁 discipline. What we do not yet have is a careful story for link state, media 描述符, and 接口 flags. That is Section 6. +我们现在有了通过驱动程序的双向流量。发送消费来自协议栈的 mbuf;接收为协议栈产生 mbuf。在此之间我们有 BPF 钩子、计数器更新和互斥锁纪律。我们还没有的是关于链路状态、媒体描述符和接口标志的完整叙述。那是第 6 节的内容。 -## Section 6: Media State, Flags, and Link Events +## 第6节:媒体状态、标志和链路事件 -Up to this point we have focused on 数据包. But a 网络接口 is more than a 数据包 mover. It is a stateful participant in the network stack. It goes up and it goes down. It has a media type, and that media can change. Its link can come and go. The stack cares about all of those transitions, and userland tools present them to the administrator. In this section we add the state-management layer to `mynet`. +到目前为止我们专注于数据包。但网络接口不仅仅是一个数据包搬运工。它是网络协议栈中有状态的参与者。它会上线也会下线。它有一个媒体类型,媒体可以改变。它的链路可以出现和消失。协议栈关心所有这些转换,用户态工具将它们呈现给管理员。在本节中,我们向 `mynet` 添加状态管理层。 -### Interface Flags: `IFF_` and `IFF_DRV_` +### 接口标志:`IFF_` 和 `IFF_DRV_` -You have already met `IFF_UP` and `IFF_DRV_RUNNING`. There are many more, and they divide into two families that work in distinct ways. +你已经见过 `IFF_UP` 和 `IFF_DRV_RUNNING`。还有更多,它们分为两个以不同方式工作的家族。 -The `IFF_` flags, defined in `/usr/src/sys/net/if.h`, are the user-visible flags. They are what `ifconfig` reads and writes. Common ones include: +`IFF_` 标志定义在 `/usr/src/sys/net/if.h` 中,是用户可见的标志。它们是 `ifconfig` 读取和写入的。常见的包括: -* `IFF_UP` (`0x1`): the 接口 is administratively up. -* `IFF_BROADCAST` (`0x2`): the 接口 supports broadcast. -* `IFF_POINTOPOINT` (`0x10`): the 接口 is point-to-point. -* `IFF_LOOPBACK` (`0x8`): the 接口 is a loopback. -* `IFF_SIMPLEX` (`0x800`): the 接口 cannot hear its own transmissions. -* `IFF_MULTICAST` (`0x8000`): the 接口 supports multicast. -* `IFF_PROMISC` (`0x100`): the 接口 is in promiscuous mode. -* `IFF_ALLMULTI` (`0x200`): the 接口 is receiving all multicast. -* `IFF_DEBUG` (`0x4`): debug tracing is requested by the user. +* `IFF_UP` (`0x1`):接口在管理上处于 up 状态。 +* `IFF_BROADCAST` (`0x2`):接口支持广播。 +* `IFF_POINTOPOINT` (`0x10`):接口是点对点的。 +* `IFF_LOOPBACK` (`0x8`):接口是环回接口。 +* `IFF_SIMPLEX` (`0x800`):接口无法听到自己的发送。 +* `IFF_MULTICAST` (`0x8000`):接口支持多播。 +* `IFF_PROMISC` (`0x100`):接口处于混杂模式。 +* `IFF_ALLMULTI` (`0x200`):接口正在接收所有多播。 +* `IFF_DEBUG` (`0x4`):用户请求了调试追踪。 -These flags are set and cleared primarily by userland through `SIOCSIFFLAGS`. Your 驱动程序 should react to changes in them: when `IFF_UP` goes from clear to set, initialise; when it goes from set to clear, quiesce. +这些标志主要通过用户态通过 `SIOCSIFFLAGS` 设置和清除。你的驱动程序应该对它们的变化做出反应:当 `IFF_UP` 从清除变为设置时,初始化;当从设置变为清除时,停止。 -The `IFF_DRV_` flags, also in `if.h`, are 驱动程序-private. They live in `ifp->if_drv_flags` (not `if_flags`). Userland cannot see or modify them. The two most important are: +`IFF_DRV_` 标志也位于 `if.h` 中,是驱动程序私有的。它们存储在 `ifp->if_drv_flags` 中(不是 `if_flags`)。用户态无法看到或修改它们。最重要的两个是: -* `IFF_DRV_RUNNING` (`0x40`): the 驱动程序 has allocated its per-接口 resources and can move traffic. Identical to the older `IFF_RUNNING` alias. -* `IFF_DRV_OACTIVE` (`0x400`): the 驱动程序's output queue is full. The stack should not call `if_start` or `if_transmit` again until this flag clears. +* `IFF_DRV_RUNNING` (`0x40`):驱动程序已分配其每接口资源并可以移动流量。与较老的 `IFF_RUNNING` 别名相同。 +* `IFF_DRV_OACTIVE` (`0x400`):驱动程序的输出队列已满。协议栈不应再调用 `if_start` 或 `if_transmit`,直到此标志清除。 -Think of `IFF_UP` as the user's intent and `IFF_DRV_RUNNING` as the 驱动程序's readiness. Both need to be true for traffic to flow. +把 `IFF_UP` 想象成用户的意图,把 `IFF_DRV_RUNNING` 想象成驱动程序的准备状态。两者都需要为真才能传输流量。 -### The `SIOCSIFFLAGS` Ioctl +### `SIOCSIFFLAGS` ioctl -When userland runs `ifconfig mynet0 up`, it sets `IFF_UP` in the 接口's flag field and issues `SIOCSIFFLAGS`. The stack dispatches this ioctl through our `if_ioctl` 回调. Our job is to notice the flag change and react. +当用户态运行 `ifconfig mynet0 up` 时,它在接口的标志字段中设置 `IFF_UP` 并发出 `SIOCSIFFLAGS`。协议栈通过我们的 `if_ioctl` 回调分派此 ioctl。我们的工作是注意到标志变化并做出反应。 -Here is the canonical pattern for handling `SIOCSIFFLAGS` in a 网络驱动程序: +以下是在网络驱动程序中处理 `SIOCSIFFLAGS` 的经典模式: ```c case SIOCSIFFLAGS: @@ -1586,17 +1585,17 @@ case SIOCSIFFLAGS: break; ``` -Let us parse this. +让我们解析这段代码。 -If `IFF_UP` is set, we check whether the 驱动程序 is already running. If not, we invoke `mynet_init` to initialise. If the 驱动程序 is already running, we do nothing: the user setting the flag again is a no-op. +如果 `IFF_UP` 被设置,我们检查驱动程序是否已经在运行。如果不是,我们调用 `mynet_init` 进行初始化。如果驱动程序已经在运行,我们什么都不做:用户再次设置该标志是无操作。 -If `IFF_UP` is not set, we check whether we were running. If so, we call `mynet_stop` to quiesce. If not, again a no-op. +如果 `IFF_UP` 未设置,我们检查是否曾在运行。如果是,我们调用 `mynet_stop` 来停止。如果不是,同样是空操作。 -We drop the lock before calling `mynet_init` or `mynet_stop`, because those functions may take time and may internally reacquire the lock. The pattern of "unlock, call, relock" is a standard idiom for ioctl handlers. +我们在调用 `mynet_init` 或 `mynet_stop` 之前释放锁,因为这些函数可能需要时间并可能在内部重新获取锁。「解锁、调用、重新加锁」的模式是 ioctl 处理程序的标准惯用法。 -### Writing `mynet_stop` +### 编写 `mynet_stop` -`mynet_init` we wrote in Section 4. Its counterpart `mynet_stop` is similar but in reverse: +`mynet_init` 我们在第 4 节中已经写过。它的对应物 `mynet_stop` 类似但是反向的: ```c static void @@ -1614,34 +1613,34 @@ mynet_stop(struct mynet_softc *sc) } ``` -We clear our running flag, drop the `IFF_DRV_RUNNING` bit so the stack knows we are not carrying traffic, stop the receive callout, and announce link-down to the stack. This is the symmetric partner to the init function. +我们清除运行标志,丢弃 `IFF_DRV_RUNNING` 位以便协议栈知道我们不再承载流量,停止接收 callout,并向协议栈宣布链路断开。这是初始化函数的对称伙伴。 -### Link State: `if_link_state_change` +### 链路状态:`if_link_state_change` -`if_link_state_change(ifp, state)` is the canonical way for a 驱动程序 to report link transitions. The values come from `/usr/src/sys/net/if.h`: +`if_link_state_change(ifp, state)` 是驱动程序报告链路转换的经典方式。值来自 `/usr/src/sys/net/if.h`: -* `LINK_STATE_UNKNOWN` (0): the 驱动程序 does not know the link state. This is the initial value. -* `LINK_STATE_DOWN` (1): no carrier, no link partner reachable. -* `LINK_STATE_UP` (2): link is up, link partner is reachable, carrier is present. +* `LINK_STATE_UNKNOWN` (0):驱动程序不知道链路状态。这是初始值。 +* `LINK_STATE_DOWN` (1):无载波,无法到达链路伙伴。 +* `LINK_STATE_UP` (2):链路已连接,可以到达链路伙伴,存在载波。 -The stack records the new state, sends a routing 套接字 notification, wakes up any sleepers on the 接口 state, and lets userland know through `ifconfig`'s `status:` line. Real NIC 驱动程序 call `if_link_state_change` from the link-state-change 中断处理程序, typically in response to PHY autonegotiation completion or loss. For pseudo-驱动程序, we choose when to call it based on the 驱动程序's own logic. +协议栈记录新状态,发送路由套接字通知,唤醒在该接口状态上睡眠的线程,并通过 `ifconfig` 的 `status:` 行通知用户态。真正的网卡驱动程序从链路状态变化中断处理程序中调用 `if_link_state_change`,通常是在 PHY 自动协商完成或丢失时。对于伪驱动程序,我们根据驱动程序自己的逻辑选择何时调用它。 -It is worth being deliberate about when you call this function. In `mynet_init` we call it with `LINK_STATE_UP` after we have set `IFF_DRV_RUNNING`. In `mynet_stop` we call it with `LINK_STATE_DOWN` after we have cleared `IFF_DRV_RUNNING`. If you reverse the order, you will briefly be reporting a link up on an 接口 that is not running, or a link down on an 接口 that still claims to be running. The stack can cope, but the symptoms of the reversal are confusing. +值得认真考虑何时调用此函数。在 `mynet_init` 中,我们在设置 `IFF_DRV_RUNNING` 之后用 `LINK_STATE_UP` 调用它。在 `mynet_stop` 中,我们在清除 `IFF_DRV_RUNNING` 之后用 `LINK_STATE_DOWN` 调用它。如果你反转顺序,你会短暂地报告一个未运行的接口链路已连接,或者一个仍然声称正在运行的接口链路已断开。协议栈可以应对,但反转的症状会令人困惑。 -### Media Descriptors +### 媒体描述符 -Above link state sits media. Media is the description of what kind of connection is in use: 10BaseT, 100BaseT, 1000BaseT, 10GBaseSR, and so on. It is not the same as link state: a connection can have a known media type even when the link is down. +在链路状态之上是媒体。媒体是对正在使用的连接类型的描述:10BaseT、100BaseT、1000BaseT、10GBaseSR 等等。它与链路状态不同:连接即使在链路断开时也可以有已知的媒体类型。 -FreeBSD's media subsystem lives in `/usr/src/sys/net/if_media.c` and its header `/usr/src/sys/net/if_media.h`. Drivers use it through a small API: +FreeBSD 的媒体子系统位于 `/usr/src/sys/net/if_media.c` 及其头文件 `/usr/src/sys/net/if_media.h`。驱动程序通过一个小型 API 使用它: -* `ifmedia_init(ifm, dontcare_mask, change_fn, status_fn)`: initialise the 描述符. +* `ifmedia_init(ifm, dontcare_mask, change_fn, status_fn)`:初始化描述符。 * `ifmedia_add(ifm, word, data, aux)`: add a media entry. * `ifmedia_set(ifm, word)`: choose the default entry. -* `ifmedia_ioctl(ifp, ifr, ifm, cmd)`: handle `SIOCGIFMEDIA` and `SIOCSIFMEDIA`. +* `ifmedia_ioctl(ifp, ifr, ifm, cmd)`:处理 `SIOCGIFMEDIA` 和 `SIOCSIFMEDIA`。 -The "word" is a bitfield combining the media subtype and flags. For 以太网 驱动程序 you combine `IFM_ETHER` with a subtype like `IFM_1000_T` (1000BaseT), `IFM_10G_T` (10GBaseT), or `IFM_AUTO` (autonegotiate). The full set of subtypes is enumerated in `if_media.h`. +「字」是一个组合了媒体子类型和标志的位字段。对于以太网驱动程序,你将 `IFM_ETHER` 与 `IFM_1000_T`(1000BaseT)、`IFM_10G_T`(10GBaseT)或 `IFM_AUTO`(自动协商)等子类型组合。完整的子类型集合在 `if_media.h` 中列举。 -We set up the 描述符 in 第3节: +我们在第 3 节中设置了描述符: ```c ifmedia_init(&sc->media, 0, mynet_media_change, mynet_media_status); @@ -1650,7 +1649,7 @@ ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL); ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO); ``` -The 回调 are what the stack invokes when userland queries or sets the media: +回调是协议栈在用户态查询或设置媒体时调用的函数: ```c static int @@ -1672,9 +1671,9 @@ mynet_media_status(struct ifnet *ifp, struct ifmediareq *imr) } ``` -`mynet_media_change` is the stub: there is no PHY to reprogram in a pseudo-驱动程序. `mynet_media_status` is what `ifconfig` reports through `SIOCGIFMEDIA`: `ifm_status` gets `IFM_AVALID` (the status fields are valid) and `IFM_ACTIVE` (the link is currently active) when we are running, and `ifm_active` tells the caller which media we are actually using. +`mynet_media_change` 是一个桩:伪驱动程序没有 PHY 可以重新编程。`mynet_media_status` 是 `ifconfig` 通过 `SIOCGIFMEDIA` 报告的内容:`ifm_status` 在我们运行时获得 `IFM_AVALID`(状态字段有效)和 `IFM_ACTIVE`(链路当前活动),`ifm_active` 告诉调用者我们实际使用的媒体。 -The ioctl handler routes media requests to `ifmedia_ioctl`: +ioctl 处理程序将媒体请求路由到 `ifmedia_ioctl`: ```c case SIOCGIFMEDIA: @@ -1683,9 +1682,9 @@ case SIOCSIFMEDIA: break; ``` -This is exactly the pattern used by the `SIOCSIFMEDIA` / `SIOCGIFMEDIA` case inside `epair_ioctl` in `/usr/src/sys/net/if_epair.c`. +这正是 `/usr/src/sys/net/if_epair.c` 中 `epair_ioctl` 内部 `SIOCSIFMEDIA` / `SIOCGIFMEDIA` case 所使用的模式。 -With this in place, `ifconfig mynet0` will report something like: +有了这些,`ifconfig mynet0` 将报告类似以下内容: ```text mynet0: flags=8843 metric 0 mtu 1500 @@ -1695,9 +1694,9 @@ mynet0: flags=8843 metric 0 mtu 1500 status: active ``` -### Handling MTU Changes +### 处理 MTU 变更 -`SIOCSIFMTU` is the ioctl the user issues when running `ifconfig mynet0 mtu 1400`. A well-behaved 驱动程序 checks that the requested value is within its supported range and then updates `if_mtu`. Our code: +`SIOCSIFMTU` 是用户运行 `ifconfig mynet0 mtu 1400` 时发出的 ioctl。一个行为良好的驱动程序检查请求的值是否在其支持的范围内,然后更新 `if_mtu`。我们的代码: ```c case SIOCSIFMTU: @@ -1709,11 +1708,11 @@ case SIOCSIFMTU: break; ``` -The lower limit of 68 bytes matches the smallest IPv4 payload plus headers. The upper limit of 9216 is a generous jumbo-帧 bound. Real 驱动程序 have narrower ranges that match what their hardware can fragment. We keep the range permissive because this is a pseudo-驱动程序. +68 字节的下限匹配最小的 IPv4 有效载荷加头部。9216 的上限是一个慷慨的巨型帧边界。真正的驱动程序有更窄的范围,匹配其硬件能处理的大小。我们保持范围宽松,因为这是一个伪驱动程序。 -### Handling Multicast Group Changes +### 处理多播组变更 -`SIOCADDMULTI` and `SIOCDELMULTI` signal that the user has added or removed a multicast group on the 接口. For a real NIC that implements hardware multicast filtering, the 驱动程序 would reprogram the filter each time. Our pseudo-驱动程序 has no filter, so we simply acknowledge the request: +`SIOCADDMULTI` 和 `SIOCDELMULTI` 表示用户已在接口上添加或删除了多播组。对于实现硬件多播过滤的真正网卡,驱动程序每次都会重新编程过滤器。我们的伪驱动程序没有过滤器,所以我们只是确认请求: ```c case SIOCADDMULTI: @@ -1722,11 +1721,11 @@ case SIOCDELMULTI: break; ``` -This is good enough for correct operation. The stack will deliver multicast traffic to the 接口 based on its internal group list, and we do not need to do anything special. +这足以保证正确操作。协议栈将根据其内部组列表向接口传递多播流量,我们不需要做任何特殊的事情。 -### Putting the Ioctl Handler Together +### 组装 ioctl 处理函数 -With all of the above, the full `mynet_ioctl` looks like this: +有了以上所有内容,完整的 `mynet_ioctl` 如下所示: ```c static int @@ -1782,45 +1781,45 @@ mynet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) } ``` -The `default` case delegates to `ether_ioctl`, which handles the ioctls that every 以太网 驱动程序 handles the same way (for example `SIOCSIFADDR`, `SIOCSIFCAP` in the common cases). That saves us writing fifteen lines of boilerplate. `/usr/src/sys/net/if_epair.c` does the same in the `default` arm of the switch in `epair_ioctl`. +`default` case 委托给 `ether_ioctl`,它处理每个以太网驱动程序以相同方式处理的 ioctl(例如常见情况下的 `SIOCSIFADDR`、`SIOCSIFCAP`)。这为我们节省了编写十五行样板代码。`/usr/src/sys/net/if_epair.c` 在 `epair_ioctl` 中 switch 的 `default` 分支中做了同样的事情。 -### Flag Coherence Rules +### 标志一致性规则 -There are a few coherence rules you should keep in mind as you write 驱动程序 state transitions: +在编写驱动程序状态转换时,你应该记住一些一致性规则: -1. `IFF_DRV_RUNNING` follows `IFF_UP`, not the other way around. The user sets `IFF_UP`, and the 驱动程序 sets or clears `IFF_DRV_RUNNING` in response. -2. Link state changes should happen after `IFF_DRV_RUNNING` transitions, not before. -3. Callouts and taskqueues that were started when you set `IFF_DRV_RUNNING` should be stopped or drained when you clear it. -4. `if_input` calls should only happen when `IFF_DRV_RUNNING` is set. Otherwise, you are delivering 数据包 on an 接口 that the stack has not finished bringing up. -5. `if_transmit` may be called even when `IFF_UP` is clear, because of a race between userland and the stack. Your transmit path should check the flags and drop gracefully if either is clear. +1. `IFF_DRV_RUNNING` 跟随 `IFF_UP`,而不是反过来。用户设置 `IFF_UP`,驱动程序响应设置或清除 `IFF_DRV_RUNNING`。 +2. 链路状态变化应该在 `IFF_DRV_RUNNING` 转换之后发生,而不是之前。 +3. 在设置 `IFF_DRV_RUNNING` 时启动的 callout 和 taskqueue 应该在清除它时停止或排空。 +4. `if_input` 调用应该只在 `IFF_DRV_RUNNING` 被设置时发生。否则,你正在协议栈尚未完成启动的接口上传递数据包。 +5. `if_transmit` 可能在 `IFF_UP` 被清除时仍然被调用,因为用户态和协议栈之间存在竞争。你的发送路径应该检查标志并在任一标志被清除时优雅地丢弃。 -These rules are implicit in the code of every well-written 驱动程序. Making them explicit is useful when you are first learning. +这些规则在每个编写良好的驱动程序代码中都是隐含的。将它们明确化在你初学时是有用的。 -### Interface Capabilities in Depth +### 接口能力详解 -We touched on capabilities in Section 3 when we set `IFCAP_VLAN_MTU`. Capabilities deserve a fuller treatment here, because they are how a 驱动程序 tells the stack which offloads it can perform, and they are increasingly central to how fast 驱动程序 stay fast. +我们在第 3 节中设置 `IFCAP_VLAN_MTU` 时简要提到了能力。能力值得在此更全面地讨论,因为它们是驱动程序告诉协议栈自己能执行哪些卸载的方式,而且它们对于快速驱动程序保持快速越来越核心。 -The `if_capabilities` field, defined in `/usr/src/sys/net/if.h`, is a bitmask of capabilities the hardware can perform. The `if_capenable` field is a bitmask of capabilities currently enabled. They are separated because userland can toggle individual offloads at runtime through `ifconfig mynet0 -rxcsum` or `ifconfig mynet0 +tso`, and the 驱动程序 must honour that choice. +`if_capabilities` 字段定义在 `/usr/src/sys/net/if.h` 中,是硬件能执行的能力的位掩码。`if_capenable` 字段是当前已启用能力的位掩码。它们是分开的,因为用户态可以在运行时通过 `ifconfig mynet0 -rxcsum` 或 `ifconfig mynet0 +tso` 切换单个卸载,驱动程序必须遵守该选择。 -The common capabilities are: +常见的能力包括: -* `IFCAP_RXCSUM` and `IFCAP_RXCSUM_IPV6`: the 驱动程序 will verify IPv4 and IPv6 checksums in hardware and mark correctly-summed 数据包 with `CSUM_DATA_VALID` in the mbuf's `m_pkthdr.csum_flags`. -* `IFCAP_TXCSUM` and `IFCAP_TXCSUM_IPV6`: the 驱动程序 will compute TCP, UDP, and IP checksums in hardware for outbound 数据包 whose `m_pkthdr.csum_flags` requests it. -* `IFCAP_TSO4` and `IFCAP_TSO6`: the 驱动程序 accepts large TCP segments and the hardware splits them into MTU-sized 帧 on the wire. This dramatically reduces CPU load for TCP-heavy workloads. -* `IFCAP_LRO`: the 驱动程序 aggregates multiple received TCP segments into a single large mbuf before handing up. Symmetric to TSO on the receive side. -* `IFCAP_VLAN_HWTAGGING`: the 驱动程序 will add and strip 802.1Q VLAN tags in hardware rather than in software. This saves a mbuf copy per VLAN 帧. -* `IFCAP_VLAN_MTU`: the 驱动程序 can carry VLAN-tagged 帧 whose total length slightly exceeds the standard 以太网 MTU because of the extra 4-byte tag. -* `IFCAP_JUMBO_MTU`: the 驱动程序 supports 帧 larger than 1500 bytes of payload. -* `IFCAP_WOL_MAGIC`: wake-on-LAN using the magic 数据包. -* `IFCAP_POLLING`: classic 设备 polling, now rarely used. -* `IFCAP_NETMAP`: the 驱动程序 supports `netmap(4)` 内核-bypass 数据包 I/O. -* `IFCAP_TOE`: TCP offload engine. Rare, but exists on some high-end NICs. +* `IFCAP_RXCSUM` 和 `IFCAP_RXCSUM_IPV6`:驱动程序将在硬件中验证 IPv4 和 IPv6 校验和,并在 mbuf 的 `m_pkthdr.csum_flags` 中用 `CSUM_DATA_VALID` 标记正确校验的数据包。 +* `IFCAP_TXCSUM` 和 `IFCAP_TXCSUM_IPV6`:驱动程序将在硬件中为 `m_pkthdr.csum_flags` 请求的出站数据包计算 TCP、UDP 和 IP 校验和。 +* `IFCAP_TSO4` 和 `IFCAP_TSO6`:驱动程序接受大型 TCP 段,硬件将它们在线路上拆分为 MTU 大小的帧。这显著减少了 TCP 密集型工作负载的 CPU 负载。 +* `IFCAP_LRO`:驱动程序将多个接收到的 TCP 段聚合为单个大型 mbuf 后再向上传递。接收端 TSO 的对称操作。 +* `IFCAP_VLAN_HWTAGGING`:驱动程序将在硬件而不是软件中添加和剥离 802.1Q VLAN 标签。这为每个 VLAN 帧节省了一次 mbuf 复制。 +* `IFCAP_VLAN_MTU`:驱动程序可以承载总长度因额外 4 字节标签而略微超过标准以太网 MTU 的 VLAN 标记帧。 +* `IFCAP_JUMBO_MTU`:驱动程序支持有效载荷大于 1500 字节的帧。 +* `IFCAP_WOL_MAGIC`:使用魔术包的局域网唤醒。 +* `IFCAP_POLLING`:经典设备轮询,现在很少使用。 +* `IFCAP_NETMAP`:驱动程序支持 `netmap(4)` 内核旁路数据包 I/O。 +* `IFCAP_TOE`:TCP 卸载引擎。罕见,但存在于一些高端网卡上。 -Advertising a capability makes a promise to the stack that you will honour it. If you claim `IFCAP_TXCSUM` but do not actually compute the TCP checksum for outbound 帧, the 内核 will happily hand you 数据包 with an uncomputed checksum and expect you to finish the job. The receiver will get corrupt 帧 and discard them. The symptom is silent data loss, which is painful to debug. +声明一个能力就是向协议栈做出你会兑现它的承诺。如果你声称 `IFCAP_TXCSUM` 但实际上并没有为出站帧计算 TCP 校验和,内核会愉快地交给你带有未计算校验和的数据包并期望你完成工作。接收方会得到损坏的帧并丢弃它们。症状是静默的数据丢失,这调试起来很痛苦。 -For `mynet`, we honestly advertise only what we can deliver. `IFCAP_VLAN_MTU` is the only capability we claim, and we honour it by accepting 帧 up to `ifp->if_mtu + sizeof(struct ether_vlan_header)` in our transmit path. +对于 `mynet`,我们诚实地只声明我们能兑现的内容。`IFCAP_VLAN_MTU` 是我们声称的唯一能力,我们通过在发送路径中接受最大到 `ifp->if_mtu + sizeof(struct ether_vlan_header)` 的帧来兑现它。 -A well-behaved 驱动程序 also handles `SIOCSIFCAP` in its ioctl handler so that the user can toggle specific offloads: +一个行为良好的驱动程序还在其 ioctl 处理程序中处理 `SIOCSIFCAP`,以便用户可以切换特定的卸载: ```c case SIOCSIFCAP: @@ -1831,29 +1830,29 @@ case SIOCSIFCAP: break; ``` -For a pseudo-驱动程序 there is no hardware to reprogram, but the user-visible toggle still works because the ioctl updates `if_capenable` and every subsequent transmit decision reads that field. +对于伪驱动程序没有硬件可以重新编程,但用户可见的切换仍然有效,因为 ioctl 更新了 `if_capenable`,每个后续的发送决策都会读取该字段。 -### The `ether_ioctl` Common Handler +### `ether_ioctl` 通用处理函数 -We saw earlier that `mynet_ioctl` delegates unknown ioctls to `ether_ioctl`. It is worth peeking at what that function does, because it explains why most 驱动程序 can get away with handling only a handful of ioctls explicitly. +我们之前看到 `mynet_ioctl` 将未知 ioctl 委托给 `ether_ioctl`。值得看看那个函数做了什么,因为它解释了为什么大多数驱动程序只需显式处理少量 ioctl。 -`ether_ioctl`, defined in `/usr/src/sys/net/if_ethersubr.c`, is a generic handler for the ioctls that every 以太网 接口 treats the same way. Its responsibilities include: +`ether_ioctl` 定义在 `/usr/src/sys/net/if_ethersubr.c` 中,是每个以太网接口以相同方式处理的 ioctl 的通用处理程序。其职责包括: -* `SIOCSIFADDR`: the user is assigning an IP address to the 接口. `ether_ioctl` handles the ARP 探测 and the address registration. It invokes the 驱动程序's `if_init` 回调 if the 接口 is down and should be brought up. -* `SIOCGIFADDR`: return the link-layer address of the 接口. -* `SIOCSIFMTU`: if the 驱动程序 does not provide its own handler, `ether_ioctl` performs the generic MTU change by updating `if_mtu`. -* `SIOCADDMULTI` and `SIOCDELMULTI`: update the 驱动程序's multicast filter, if one exists. -* Various capability-related ioctls. +* `SIOCSIFADDR`:用户正在为接口分配 IP 地址。`ether_ioctl` 处理 ARP 探测和地址注册。如果接口已关闭且应该启动,它会调用驱动程序的 `if_init` 回调。 +* `SIOCGIFADDR`:返回接口的链路层地址。 +* `SIOCSIFMTU`:如果驱动程序不提供自己的处理程序,`ether_ioctl` 通过更新 `if_mtu` 执行通用 MTU 更改。 +* `SIOCADDMULTI` 和 `SIOCDELMULTI`:更新驱动程序的多播过滤器(如果存在)。 +* 各种与能力相关的 ioctl。 -Because the default handler handles so much, 驱动程序 typically only need to handle ioctls that require 驱动程序-specific logic: `SIOCSIFFLAGS` for the up/down transition, `SIOCSIFMEDIA` to reprogram media, and `SIOCSIFCAP` to toggle capabilities. Everything else falls through to `ether_ioctl`. +因为默认处理程序处理了这么多,驱动程序通常只需要处理需要驱动程序特定逻辑的 ioctl:用于上/下转换的 `SIOCSIFFLAGS`、用于重新编程媒体的 `SIOCSIFMEDIA`,以及用于切换能力的 `SIOCSIFCAP`。其余的都落到 `ether_ioctl`。 -This delegation model is one of the things that makes writing a small 以太网 驱动程序 pleasant: you write the code that is specific to your 驱动程序, and the common code takes care of the rest. +这种委托模型是让编写小型以太网驱动程序变得愉快的原因之一:你编写特定于你驱动程序的代码,通用代码处理其余的事情。 -### Hardware Multicast Filtering +### 硬件多播过滤 -For a real NIC, multicast filtering is often done in hardware. The 驱动程序 programs a set of MAC addresses into a hardware filter table, and the NIC only delivers 帧 whose destination matches an address in the table. When the user runs `ifconfig mynet0 addm 01:00:5e:00:00:01` to join a multicast group, the stack issues `SIOCADDMULTI`, and the 驱动程序 must update the filter table. +对于真正的网卡,多播过滤通常在硬件中完成。驱动程序将一组 MAC 地址编程到硬件过滤表中,网卡只传递目标地址与表中地址匹配的帧。当用户运行 `ifconfig mynet0 addm 01:00:5e:00:00:01` 加入多播组时,协议栈发出 `SIOCADDMULTI`,驱动程序必须更新过滤表。 -The typical pattern in a real 驱动程序 is: +真正的驱动程序中的典型模式是: ```c case SIOCADDMULTI: @@ -1866,25 +1865,25 @@ case SIOCDELMULTI: break; ``` -`mydrv_setup_multicast` walks the 接口's multicast list (accessed through `if_maddr_rlock` and friends) and programs each address into the hardware filter. The code is boring but important; getting it wrong means multicast applications like mDNS (Bonjour, Avahi), IGMP-based routing, and IPv6 neighbour discovery quietly misbehave. +`mydrv_setup_multicast` 遍历接口的多播列表(通过 `if_maddr_rlock` 及相关函数访问)并将每个地址编程到硬件过滤器中。这段代码枯燥但重要;搞错它意味着像 mDNS(Bonjour、Avahi)、基于 IGMP 的路由和 IPv6 邻居发现等多播应用会静默出错。 -For `mynet` we have no hardware filter, so we simply accept `SIOCADDMULTI` and `SIOCDELMULTI` without doing anything. The stack still tracks the list of multicast groups for us, and our receive path does not filter, so everything works. +对于 `mynet` 我们没有硬件过滤器,所以我们只是接受 `SIOCADDMULTI` 和 `SIOCDELMULTI` 而不做任何事情。协议栈仍然为我们跟踪多播组列表,我们的接收路径不过滤,所以一切正常。 -If you ever write a 驱动程序 with hardware multicast filtering, read `/usr/src/sys/dev/e1000/if_em.c`'s `em_multi_set` function for a clear example of the pattern. +如果你将来编写带有硬件多播过滤的驱动程序,阅读 `/usr/src/sys/dev/e1000/if_em.c` 中的 `em_multi_set` 函数可以找到该模式的清晰示例。 -### 总结 Section 6 +### 第6节小结 -We have covered the state half of a 网络驱动程序. Flags, link state, media 描述符, and the ioctls that tie them all together. Combined with the transmit and receive paths from Sections 4 and 5, we now have a 驱动程序 that is indistinguishable from a simple real 以太网 驱动程序 at the `ifnet` boundary. +我们已经涵盖了网络驱动的状态半部分。标志、链路状态、媒体描述符以及将它们联系在一起的 ioctl。结合第 4 节和第 5 节的发送和接收路径,我们现在有了一个在 `ifnet` 边界上与简单的真实以太网驱动程序无法区分的驱动程序。 -Before we can call the 驱动程序 finished, we need to make sure we can test it thoroughly with the tools the FreeBSD ecosystem provides. That is Section 7. +在我们可以称驱动程序完成之前,我们需要确保能够使用 FreeBSD 生态系统提供的工具对其进行彻底测试。那是第 7 节的内容。 -## Section 7: Testing the Driver With Standard Networking Tools +## 第7节:使用标准网络工具测试驱动程序 -A 驱动程序 is only as good as your confidence that it works. Confidence does not come from staring at code. It comes from running the 驱动程序, interacting with it from the outside, and observing the results. This section walks through the standard FreeBSD networking tools and shows how to use each one to exercise a specific aspect of `mynet`. +一个驱动程序的好坏取决于你对它能正常工作的信心。信心不是来自盯着代码看。它来自运行驱动程序、从外部与之交互并观察结果。本节将带你了解标准的 FreeBSD 网络工具,并展示如何使用每个工具来测试 `mynet` 的特定方面。 -### Load, Create, Configure +### 加载、创建、配置 -Start with a clean slate. If the module is loaded, unload it, then load the fresh build and create the first 接口: +从干净状态开始。如果模块已加载,卸载它,然后加载新构建并创建第一个接口: ```console # kldstat | grep mynet @@ -1893,7 +1892,7 @@ Start with a clean slate. If the module is loaded, unload it, then load the fres mynet0 ``` -`ifconfig mynet0` should show the 接口 with a MAC address, no IP, no flags beyond the default set, and a media 描述符 saying "autoselect". Assign an address and bring it up: +`ifconfig mynet0` 应该显示带有 MAC 地址、无 IP、除默认集之外无标志、以及显示"autoselect"的媒体描述符的接口。分配地址并启动它: ```console # ifconfig mynet0 inet 192.0.2.1/24 up @@ -1906,11 +1905,11 @@ mynet0: flags=8843 metric 0 mtu 1500 groups: mynet ``` -The `UP` and `RUNNING` flags confirm that the user's intent and the 驱动程序's readiness are both present. The `status: active` line comes from our media 回调. The media description includes `1000baseT` because that is what `mynet_media_status` returned. +`UP` 和 `RUNNING` 标志确认用户的意图和驱动程序的准备状态都已就位。`status: active` 行来自我们的媒体回调。媒体描述包括 `1000baseT`,因为那是 `mynet_media_status` 返回的。 -### Inspecting With `netstat` +### 使用 `netstat` 检查 -`netstat -in -I mynet0` shows per-接口 counters. Initially, everything is zero; wait a few seconds for the receive simulation to kick in and the counter should climb: +`netstat -in -I mynet0` 显示每接口计数器。最初,一切都是零;等待几秒让接收模拟启动,计数器应该攀升: ```console # netstat -in -I mynet0 @@ -1919,11 +1918,11 @@ mynet0 1500 02:a3:f1:22:bc:0d 3 0 0 0 mynet0 - 192.0.2.0/24 192.0.2.1 0 - 0 - ``` -The first line's `Ipkts` counts the synthetic ARP requests our receive timer produces. It should rise by about one every second. If it does not, the `rx_interval_hz` setting is wrong, or the callout is not being started in `mynet_init`, or `running` is false. +第一行的 `Ipkts` 统计我们的接收定时器产生的合成 ARP 请求数量。它应该大约每秒增加一。如果不是,说明 `rx_interval_hz` 设置错误,或者 callout 在 `mynet_init` 中没有被启动,或者 `running` 为 false。 -### Capturing With `tcpdump` +### 使用 `tcpdump` 捕获 -`tcpdump -i mynet0 -n` captures all traffic on our 接口. You should see the synthetic ARP requests being generated every second, along with any traffic caused by your own `ping` attempts: +`tcpdump -i mynet0 -n` 捕获我们接口上的所有流量。你应该看到每秒生成的合成 ARP 请求,以及你自己的 `ping` 尝试导致的任何流量: ```console # tcpdump -i mynet0 -n @@ -1934,11 +1933,11 @@ listening on mynet0, link-type EN10MB (Ethernet), capture size 262144 bytes ... ``` -The "link-type EN10MB (以太网)" confirms that BPF saw us as an 以太网 接口, which is the consequence of `ether_if附加` having called `bpf附加(ifp, DLT_EN10MB, ETHER_HDR_LEN)` for us. Switch to `-v` or `-vv` to see fuller protocol decoding. +"link-type EN10MB (Ethernet)" 确认 BPF 将我们视为以太网接口,这是 `ether_ifattach` 为我们调用 `bpfattach(ifp, DLT_EN10MB, ETHER_HDR_LEN)` 的结果。切换到 `-v` 或 `-vv` 可以看到更完整的协议解码。 -### Generating Traffic With `ping` +### 使用 `ping` 生成流量 -Trigger outbound traffic by pinging an IP in the subnet we assigned: +通过 ping 我们分配的子网中的某个 IP 来触发出站流量: ```console # ping -c 3 192.0.2.99 @@ -1947,7 +1946,7 @@ PING 192.0.2.99 (192.0.2.99): 56 data bytes 3 packets transmitted, 0 packets received, 100.0% packet loss ``` -All three pings are lost, because our pseudo-驱动程序 simulates a wire with nothing at the other end. But the transmit counter moves: +所有三个 ping 都丢失了,因为我们的伪驱动程序模拟的线缆另一端什么也没有。但发送计数器在移动: ```console # netstat -in -I mynet0 @@ -1955,27 +1954,27 @@ Name Mtu Network Address Ipkts Ierrs ... Opkts Oerrs mynet0 1500 02:a3:f1:22:bc:0d 30 0 6 0 ``` -The 6 transmitted 数据包 are three pings plus three ARP broadcast requests the stack issued trying to resolve `192.0.2.99`. You can verify this with `tcpdump`. +6 个已发送的数据包是三个 ping 加上协议栈为解析 `192.0.2.99` 而发出的三个 ARP 广播请求。你可以用 `tcpdump` 验证这一点。 ### `arp -an` -`arp -an` shows the system's ARP cache. Entries for `192.0.2.99` should appear as incomplete while the stack waits for an ARP reply that will never come. After a minute or so they expire. +`arp -an` 显示系统的 ARP 缓存。`192.0.2.99` 的条目在协议栈等待永远不会到来的 ARP 回复时应显示为不完整。大约一分钟后它们会过期。 ### `sysctl net.link` and `sysctl net.inet` -The network subsystems expose a wealth of per-接口 and per-protocol sysctls. `sysctl net.link.ether` controls 以太网-layer behaviour. `sysctl net.inet.ip` controls IP-layer behaviour. While none of these are specific to `mynet`, they are good to know. A common one when diagnosing pseudo-驱动程序 behaviour is `sysctl net.link.ether.inet.log_arp_wrong_iface=0`, which silences log messages about ARP traffic appearing on unexpected 接口. +网络子系统暴露了丰富的每接口和每协议 sysctl。`sysctl net.link.ether` 控制以太网层行为。`sysctl net.inet.ip` 控制 IP 层行为。虽然这些都不是 `mynet` 特有的,但了解它们是好的。诊断伪驱动程序行为时常用的一个是 `sysctl net.link.ether.inet.log_arp_wrong_iface=0`,它可以静默关于 ARP 流量出现在意外接口上的日志消息。 -### Monitoring Link Events With `ifstated` or `devd` +### 使用 `ifstated` 或 `devd` 监控链路事件 -FreeBSD propagates link-state changes through the routing 套接字. You can observe this live with `route monitor`: +FreeBSD 通过路由套接字传播链路状态变化。你可以用 `route monitor` 实时观察: ```console # route monitor ``` -When you run `ifconfig mynet0 down` followed by `ifconfig mynet0 up`, `route monitor` prints `RTM_IFINFO` messages corresponding to the link-state changes we are announcing through `if_link_state_change`. That is the same mechanism `devd` uses for its `notify` events, and it is how scripts can react to link flaps. +当你运行 `ifconfig mynet0 down` 然后运行 `ifconfig mynet0 up` 时,`route monitor` 会打印与我们通过 `if_link_state_change` 宣布的链路状态变化相对应的 `RTM_IFINFO` 消息。那是 `devd` 用于其 `notify` 事件的相同机制,也是脚本可以响应链路翻转的方式。 -### Testing MTU Changes +### 测试 MTU 变更 ```console # ifconfig mynet0 mtu 9000 @@ -1983,23 +1982,23 @@ When you run `ifconfig mynet0 down` followed by `ifconfig mynet0 up`, `route mon mynet0: ... mtu 9000 ``` -Change the MTU to something reasonable and watch `ifconfig` reflect the change. Try an out-of-range value and verify that the 内核 rejects it: +将 MTU 更改为合理的值并观察 `ifconfig` 反映变化。尝试一个超出范围的值并验证内核拒绝它: ```console # ifconfig mynet0 mtu 10 ifconfig: ioctl SIOCSIFMTU (set mtu): Invalid argument ``` -That error comes from our `SIOCSIFMTU` handler returning `EINVAL`. +该错误来自我们的 `SIOCSIFMTU` 处理程序返回 `EINVAL`。 -### Testing Media Commands +### 测试媒体命令 ```console # ifconfig mynet0 media 10baseT/UTP ifconfig: requested media type not found ``` -This fails because we did not 注册 `IFM_ETHER | IFM_10_T` as an acceptable media type. Register it in `mynet_create_unit` and rebuild to see the command succeed. +这会失败,因为我们没有注册 `IFM_ETHER | IFM_10_T` 作为可接受的媒体类型。在 `mynet_create_unit` 中注册它并重新构建即可使命令成功。 ```console # ifconfig mynet0 media 1000baseT @@ -2007,9 +2006,9 @@ This fails because we did not 注册 `IFM_ETHER | IFM_10_T` as an acceptable med media: Ethernet 1000baseT ``` -### Comparing Against `if_disc` +### 与 `if_disc` 对比 -Load `if_disc` alongside and compare: +同时加载 `if_disc` 并比较: ```console # kldload if_disc @@ -2018,13 +2017,13 @@ disc0 # ifconfig disc0 inet 192.0.2.50/24 up ``` -`disc0` is a simpler pseudo-驱动程序. It ignores every outbound 数据包 by dropping it in its `discoutput` function (not `discoutput` we wrote, but the one in `if_disc.c`). It has no receive path. Running `tcpdump -i disc0` while pinging `192.0.2.50` shows outbound ICMP 帧 but no inbound ARP activity. Compare that with our `mynet0`, which still shows its synthetic ARP 帧 arriving once per second. +`disc0` 是一个更简单的伪驱动程序。它在 `discoutput` 函数中通过丢弃来忽略每个出站数据包。它没有接收路径。在 ping `192.0.2.50` 时运行 `tcpdump -i disc0` 显示出站 ICMP 帧但没有入站 ARP 活动。与我们仍然每秒显示合成 ARP 帧的 `mynet0` 对比。 -The contrast is useful because it shows how small the step is from "drop everything" to "simulate a full 以太网 接口". We added a MAC address, a media 描述符, a callout, and a 数据包 builder. Everything else, including the 接口 registration, the BPF hook, the flags, was already in the pattern. +这种对比是有用的,因为它展示了从"丢弃一切"到"模拟完整以太网接口"的步骤有多小。我们添加了 MAC 地址、媒体描述符、callout 和数据包构建器。其余的一切,包括接口注册、BPF 钩子、标志,都已经在模式中了。 -### Stress Test With `iperf3` +### 使用 `iperf3` 进行压力测试 -`iperf3` can saturate a real 以太网 link. On our pseudo-驱动程序 it will not produce meaningful throughput numbers (the 数据包 go nowhere), but it exercises `if_transmit` very hard: +`iperf3` 可以使真正的以太网链路饱和。在我们的伪驱动程序上它不会产生有意义的吞吐量数字(数据包无处可去),但它会非常用力地测试 `if_transmit`: ```console # iperf3 -c 192.0.2.99 -t 10 @@ -2032,11 +2031,11 @@ Connecting to host 192.0.2.99, port 5201 iperf3: error - unable to connect to server: Connection refused ``` -The connection fails because there is no server, but `netstat -in -I mynet0` will show `Opkts` climbing rapidly with the TCP retransmissions and ARP requests `iperf3` caused. Watch `vmstat 1` in another terminal and make sure the system load remains reasonable. If you see a lot of time spent in the 驱动程序, you may have a locking hot spot that is worth investigating. +连接失败因为没有服务器,但 `netstat -in -I mynet0` 会显示 `Opkts` 随着 `iperf3` 导致的 TCP 重传和 ARP 请求快速攀升。在另一个终端观察 `vmstat 1` 并确保系统负载保持合理。如果你看到大量时间花在驱动程序中,你可能有一个值得调查的锁热点。 -### Scripted Test Runs +### 脚本化测试运行 -You can wrap the above commands into a small shell script that exercises the 驱动程序 in a known sequence. Here is a minimal example: +你可以将上述命令包装成一个以已知顺序测试驱动程序的小型 shell 脚本。以下是一个最小示例: ```sh #!/bin/sh @@ -2067,38 +2066,38 @@ ifconfig mynet0 destroy kldunload mynet ``` -Save it under `examples/part-06/ch28-network-驱动程序/lab05-bpf/run.sh`, mark it executable, and run it as root. It walks the 驱动程序 through its entire lifecycle in under ten seconds. When something breaks later, a scripted baseline like this is priceless for spotting regressions. +将它保存在 `examples/part-06/ch28-network-driver/lab05-bpf/run.sh` 下,标记为可执行,并以 root 身份运行。它在十秒内让驱动程序走过整个生命周期。当以后出现问题时,像这样脚本化的基线对于发现回归是无价的。 -### What to Watch For +### 注意事项 -While testing, keep an eye on: +测试时请注意: -* `dmesg` output during load and unload, for unexpected warnings. -* `netstat -in -I mynet0` before and after operations, to confirm counters move in the expected direction. -* `kldstat` after unload, to confirm the module is gone. -* `ifconfig -a` after `destroy`, to confirm no orphan 接口 is left. -* `vmstat -m | grep mynet` to confirm memory is returned on unload. -* `vmstat -z | grep mbuf` across load test runs, to confirm mbuf counts stabilise. +* 加载和卸载时的 `dmesg` 输出,查看意外警告。 +* 操作前后的 `netstat -in -I mynet0`,确认计数器向预期方向移动。 +* 卸载后的 `kldstat`,确认模块已消失。 +* `destroy` 后的 `ifconfig -a`,确认没有孤立接口留下。 +* `vmstat -m | grep mynet`,确认卸载时内存被释放。 +* 负载测试运行前后的 `vmstat -z | grep mbuf`,确认 mbuf 计数稳定。 -A 驱动程序 that is correct on a cold load can still leak on unload, or leak under load, or panic the 内核 in a rare race. The tools listed above are the first line of defence against all those classes of bugs. +一个在冷加载时正确的驱动程序仍然可能在卸载时泄漏,或在负载下泄漏,或在罕见竞争条件下导致内核崩溃。上面列出的工具是抵御所有这些类别 bug 的第一道防线。 -### Deeper Observability with DTrace +### 使用 DTrace 进行深度观测 -FreeBSD's DTrace implementation is a formidable tool for 驱动程序 observability, and once you know a few patterns you will reach for it often. The basic idea is that every function entry and exit in the 内核 is a 探测 point, and every 探测 point can be instrumented from userland without modifying the code. +FreeBSD 的 DTrace 实现是驱动程序可观测性的强大工具,一旦你知道一些模式,你就会经常使用它。基本思想是内核中的每个函数入口和出口都是探测点,每个探测点都可以从用户态检测而无需修改代码。 -To count how often our transmit function is called: +要统计我们的发送函数被调用的频率: ```console # dtrace -n 'fbt::mynet_transmit:entry { @c = count(); }' ``` -Run that in one terminal, generate traffic in another, and you will see the count climb. To observe each call with the 数据包 length: +在一个终端中运行它,在另一个终端中生成流量,你会看到计数攀升。要观察每次调用的数据包长度: ```console # dtrace -n 'fbt::mynet_transmit:entry { printf("len=%d", args[1]->m_pkthdr.len); }' ``` -DTrace scripts can be much more elaborate. Here is one that counts transmitted 数据包 grouped by source IP, if the 接口 is carrying IPv4 traffic: +DTrace 脚本可以更加精细。以下是一个按源 IP 分组统计已发送数据包的脚本,如果接口承载 IPv4 流量: ```console # dtrace -n 'fbt::mynet_transmit:entry /args[1]->m_pkthdr.len > 34/ { @@ -2107,15 +2106,15 @@ DTrace scripts can be much more elaborate. Here is one that counts transmitted }' ``` -This kind of observability is difficult to add to a 驱动程序 by hand, but DTrace gives it to you for free. Use it. When you cannot tell why a 数据包 did or did not flow, DTrace 探测 on your own functions will almost always reveal the answer. +这种可观测性很难手动添加到驱动程序中,但 DTrace 免费给了你。使用它。当你无法判断一个数据包为什么流动或不流动时,你自己函数上的 DTrace 探测几乎总能揭示答案。 -Some additional useful one-liners for network-驱动程序 work: +网络驱动程序工作中一些额外有用的单行命令: ```console # dtrace -n 'fbt::if_input:entry { @ifs[stringof(args[0]->if_xname)] = count(); }' ``` -This counts every call to `if_input` across the whole system, grouped by 接口 name. It is a quick way to verify that your receive path is reaching the stack. +这统计整个系统中每次 `if_input` 的调用,按接口名称分组。这是验证你的接收路径是否到达协议栈的快速方法。 ```console # dtrace -n 'fbt::if_inc_counter:entry /args[1] == 1/ { @@ -2123,24 +2122,24 @@ This counts every call to `if_input` across the whole system, grouped by 接口 }' ``` -This counts calls to `if_inc_counter` for `IFCOUNTER_IPACKETS` (which is value 1 in the enum) grouped by 接口 name. Compared with `netstat -in`, it lets you see the increments in real time. +这统计 `IFCOUNTER_IPACKETS`(在枚举中值为 1)的 `if_inc_counter` 调用,按接口名称分组。与 `netstat -in` 相比,它让你实时看到增量。 -Do not be afraid of DTrace. It looks intimidating at first because of the script-like syntax, but a 驱动程序 debugging session with DTrace often takes minutes where the equivalent printf-debugging takes hours. Every minute you invest in learning DTrace idioms repays itself many times over. +不要害怕 DTrace。它一开始看起来令人生畏,因为类似脚本的语法,但使用 DTrace 调试驱动程序通常只需几分钟,而等效的 printf 调试需要数小时。你投资学习 DTrace 惯用法每一分钟都会得到多次回报。 -### Kernel Debugger Tips for Drivers +### 驱动程序的内核调试器技巧 -When a 网络驱动程序 panics or hangs, the 内核 debugger (`ddb` or `kgdb`) is the tool of last resort. A few tips specific to 驱动程序 work: +当网络驱动程序崩溃或挂起时,内核调试器(`ddb` 或 `kgdb`)是最后的手段。一些驱动程序特定的技巧: -* After a panic, `show mbuf` (or `show pcpu`, `show alltrace`, `show lockchain` depending on what you are investigating) walks the mbuf allocations or the per-CPU data or the 块ed-thread chains. Knowing which of these to invoke is a matter of practice. -* `show ifnet ` prints the contents of an `ifnet` structure given its address. Useful when a panic message says "ifp = 0xffff...". The equivalent for a softc depends on the 驱动程序. -* `bt` prints a stack trace. Mostly you want `bt ` where `` is the thread ID of interest. -* `continue` resumes execution, but after a real panic it is usually not safe. Collect information and then `reboot`. +* 崩溃后,`show mbuf`(或 `show pcpu`、`show alltrace`、`show lockchain`,取决于你在调查什么)遍历 mbuf 分配或每 CPU 数据或阻塞线程链。知道调用哪个是实践的问题。 +* `show ifnet ` 打印给定地址的 `ifnet` 结构内容。当崩溃消息说"ifp = 0xffff..."时很有用。softc 的等价物取决于驱动程序。 +* `bt` 打印栈跟踪。大多数时候你想要 `bt `,其中 `` 是感兴趣的线程 ID。 +* `continue` 恢复执行,但在真正崩溃后通常不安全。收集信息然后 `reboot`。 -For non-panic debugging, `kgdb /boot/内核/内核 /var/crash/vmcore.0` lets you post-mortem a crash dump. Driver development on a lab VM with a crash dump 分区 is a comfortable workflow: panic, reboot, look at the dump at leisure. +对于非崩溃调试,`kgdb /boot/kernel/kernel /var/crash/vmcore.0` 让你对崩溃转储进行事后分析。在有崩溃转储分区的实验虚拟机上开发驱动程序是一个舒适的工作流程:崩溃、重启、从容地查看转储。 -### `systat -if` for Live Counter Views +### 使用 `systat -if` 查看实时计数器 -`systat -if 1` opens an ncurses view that refreshes every second and shows per-接口 counter rates. It is a useful complement to `netstat -in` because you can watch traffic rise and fall in real time without reading the terminal log. +`systat -if 1` 打开一个每秒刷新的 ncurses 视图,显示每接口的计数器速率。它是 `netstat -in` 的有用补充,因为你可以实时观察流量升降,而不需要阅读终端日志。 ```text /0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /10 @@ -2150,19 +2149,19 @@ For non-panic debugging, `kgdb /boot/内核/内核 /var/crash/vmcore.0` lets you out 0.000 KB/s 0.047 KB/s 0.167 KB ``` -The rates in this view are computed by `systat` from the counters we increment in `if_transmit` and in our receive path. If the rates do not match what you expect, the first suspicion should be that a counter is being updated twice, or that it is being updated after `m_freem`, or that it is using `IFCOUNTER_OPACKETS` where it should use `IFCOUNTER_IPACKETS`. `systat -if` makes those mistakes very visible. +此视图中的速率由 `systat` 从我们在 `if_transmit` 和接收路径中递增的计数器计算得出。如果速率与你期望的不匹配,第一个怀疑应该是某个计数器被更新了两次,或者它在 `m_freem` 之后被更新,或者它使用了 `IFCOUNTER_OPACKETS` 而应该使用 `IFCOUNTER_IPACKETS`。`systat -if` 使这些错误非常明显。 -### 总结 Section 7 +### 第7节小结 -You now have a tested 驱动程序. It loads, configures, carries traffic both directions, reports its state to userland, cooperates with BPF, and reacts to link events. What remains is the final phase of the lifecycle: clean 分离ment, module unload, and some refactoring advice. That is Section 8. +你现在有了一个经过测试的驱动程序。它加载、配置、双向传输流量、向用户态报告状态、与 BPF 合作,并响应链路事件。剩下的是生命周期的最后阶段:干净分离、模块卸载和一些重构建议。那是第 8 节的内容。 -## Section 8: Cleanup, Detach, and Refactoring of the Network Driver +## 第8节:清理、分离和网络驱动程序的重构 -Every 驱动程序 has a beginning and an end. The beginning is the pattern we have built up over the chapter: allocate, configure, 注册, run. The end is the symmetric teardown: quiesce, de注册, free. A 驱动程序 that leaks a single byte on unload is not a correct 驱动程序, no matter how good it is during its active life. In this section we finalise the cleanup path, review the unload discipline, and offer refactoring advice so that the code stays maintainable as it grows. +每个驱动程序都有开始和结束。开始是我们在本章中构建的模式:分配、配置、注册、运行。结束是对称的拆卸:停止、注销、释放。一个在卸载时泄漏单个字节的驱动程序不是一个正确的驱动程序,无论它在活跃生命期间表现多好。在本节中,我们最终确定清理路径,回顾卸载纪律,并提供重构建议,使代码随着增长保持可维护。 -### The Full Teardown Sequence +### 完整的拆卸序列 -Putting everything we have said together, the full teardown of a `mynet` 接口 looks like this: +将我们说过的所有内容放在一起,一个 `mynet` 接口的完整拆卸如下所示: ```c static void @@ -2186,23 +2185,23 @@ mynet_destroy(struct mynet_softc *sc) } ``` -The order matters. Let us walk through it. +顺序很重要。让我们逐步讲解。 -**Step 1: mark not running.** Setting `sc->running = false` and clearing `IFF_DRV_RUNNING` under the 互斥锁 means that any concurrent callout invocation sees the update and exits cleanly. This alone is not enough to stop running callouts, but it does stop new work from being scheduled. +**步骤 1:标记不再运行。** 在互斥锁下设置 `sc->running = false` 并清除 `IFF_DRV_RUNNING` 意味着任何并发的 callout 调用都能看到更新并干净退出。仅此一步不足以停止正在运行的 callout,但它确实阻止了新工作被调度。 -**Step 2: drain the callout.** `callout_drain(&sc->rx_callout)` 块 the calling thread until any in-progress callout invocation has finished and no further invocation will occur. After `callout_drain` returns, it is safe to access the softc without worrying that the callout will fire again. This is the cleanest way to synchronise with a callout and is the pattern we recommend in every 驱动程序 that uses them. +**步骤 2:排空 callout。** `callout_drain(&sc->rx_callout)` 阻塞调用线程,直到任何正在进行的 callout 调用完成,且不会再有进一步的调用发生。`callout_drain` 返回后,可以安全地访问 softc 而不必担心 callout 会再次触发。这是与 callout 同步的最干净方式,也是我们推荐在每个使用 callout 的驱动程序中使用的模式。 -**Step 3: 分离 the 接口.** `ether_if分离(ifp)` undoes what `ether_if附加` did. It calls `if_分离`, which removes the 接口 from the global list, revokes its addresses, and invalidates any cached pointers. It also calls `bpf分离` so that BPF releases its handle. After this call, the 接口 is no longer visible to userland or to the stack. +**步骤 3:分离接口。** `ether_ifdetach(ifp)` 撤销 `ether_ifattach` 所做的工作。它调用 `if_detach`,将接口从全局列表中移除,撤销其地址,并使任何缓存的指针失效。它还调用 `bpfdetach` 以便 BPF 释放其句柄。此调用后,接口不再对用户态或协议栈可见。 -**Step 4: free the ifnet.** `if_free(ifp)` releases the memory. After this call, the `ifp` pointer is invalid and must not be used. +**步骤 4:释放 ifnet。** `if_free(ifp)` 释放内存。此调用后,`ifp` 指针无效,不得使用。 -**Step 5: clean up 驱动程序-private state.** `ifmedia_removeall` frees the media entries we added. `mtx_destroy` tears down the 互斥锁. `free` releases the softc. +**步骤 5:清理驱动程序私有状态。** `ifmedia_removeall` 释放我们添加的媒体条目。`mtx_destroy` 拆除互斥锁。`free` 释放 softc。 -Getting this sequence wrong in any way leads to subtle bugs. Freeing the softc before draining the callout produces use-after-free when the callout fires. Freeing the ifnet before 分离ing it produces cascading failures all over the stack. Destroying the 互斥锁 before draining the callout (which reacquires the 互斥锁 on entry) produces a classic "destroying locked 互斥锁" panic. The discipline of "quiesce, 分离, free" is what keeps the teardown clean. +以任何方式弄错这个序列都会导致微妙的 bug。在排空 callout 之前释放 softc 会导致 callout 触发时的释放后使用。在分离之前释放 ifnet 会导致协议栈各处的级联失败。在排空 callout(它在入口处重新获取互斥锁)之前销毁互斥锁会导致经典的「销毁已加锁互斥锁」崩溃。「停止、分离、释放」的纪律是保持拆卸干净的关键。 -### The Cloner Destroy Path +### 克隆器销毁路径 -Recall that we 注册ed our cloner with `if_clone_simple`, passing `mynet_clone_create` and `mynet_clone_destroy`. The destroy function is called by the cloner 框架 when userland runs `ifconfig mynet0 destroy` or when the module is unloaded and the cloner is 分离ed. Our implementation is a trivial wrapper: +回想一下我们使用 `if_clone_simple` 注册了克隆器,传递了 `mynet_clone_create` 和 `mynet_clone_destroy`。销毁函数在用户态运行 `ifconfig mynet0 destroy` 或模块卸载并克隆器分离时由克隆器框架调用。我们的实现是一个简单的包装器: ```c static void @@ -2212,11 +2211,11 @@ mynet_clone_destroy(struct ifnet *ifp) } ``` -The cloner 框架 walks the list of 接口 it has created and calls the destroy function for each one. It does not do the draining or unlocking itself. That is the 驱动程序's responsibility, and `mynet_destroy` does it correctly. +克隆器框架遍历它创建的接口列表并为每个接口调用销毁函数。它自己不做排空或解锁。那是驱动程序的责任,`mynet_destroy` 正确地完成了它。 -### Module Unload +### 模块卸载 -When `kldunload mynet` is invoked, the 内核 calls the module event handler with `MOD_UNLOAD`. Our module handler does nothing interesting; the heavy lifting is done by the VNET sysuninit we 注册ed: +当调用 `kldunload mynet` 时,内核使用 `MOD_UNLOAD` 调用模块事件处理函数。我们的模块处理函数没有做任何有趣的事情;繁重的工作由我们注册的 VNET sysuninit 完成: ```c static void @@ -2226,9 +2225,9 @@ vnet_mynet_uninit(const void *unused __unused) } ``` -`if_clone_分离` does two things. First, it destroys every 接口 that was created through the cloner by calling our `mynet_clone_destroy` for each one. Second, it un寄存器 the cloner itself so that no new 接口 can be created. After this call, every trace of our 驱动程序 is gone from the 内核's state. +`if_clone_detach` 做两件事。首先,它通过为每个接口调用我们的 `mynet_clone_destroy` 来销毁通过克隆器创建的每个接口。其次,它注销克隆器本身,以便不能再创建新接口。此调用后,我们驱动程序的每个痕迹都从内核状态中消失了。 -Try it: +试试看: ```console # ifconfig mynet create @@ -2239,11 +2238,11 @@ mynet1 # ifconfig -a ``` -`mynet0` and `mynet1` should be gone. No messages on the console, no stray counters, no leftover cloners. That is a successful unload. +`mynet0` 和 `mynet1` 应该消失了。控制台没有消息,没有残留计数器,没有剩余的克隆器。这就是一次成功的卸载。 -### Memory Accounting +### 内存统计 -`vmstat -m | grep mynet` shows the current allocation of our `M_MYNET` tag: +`vmstat -m | grep mynet` 显示我们 `M_MYNET` 标签的当前分配: ```console # vmstat -m | grep mynet @@ -2251,76 +2250,76 @@ mynet1 mynet 0 0K 7 2048 ``` -`InUse 0` and `MemUse 0K` after unload confirm that we are not leaking. `Requests` counts the lifetime allocations. If you unload and reload several times, `Requests` climbs but `InUse` returns to zero each time. If `InUse` ever stays above zero after unload, you have a leak. +卸载后的 `InUse 0` 和 `MemUse 0K` 确认我们没有泄漏。`Requests` 统计生命周期分配。如果你卸载并重新加载多次,`Requests` 会攀升但 `InUse` 每次都回到零。如果 `InUse` 在卸载后曾经保持非零,你就有泄漏。 -### Dealing With Stuck Callouts +### 处理卡住的定时回调 -Occasionally during development you will tweak the 驱动程序 and end up with a callout that does not drain cleanly. The symptom is that `kldunload` hangs, or the system panics with a message about a locked 互斥锁. The root cause is almost always one of: +开发过程中偶尔你会修改驱动程序,导致 callout 无法干净地排空。症状是 `kldunload` 挂起,或系统因关于已加锁互斥锁的消息而崩溃。根本原因几乎总是以下之一: -* The callout handler reacquires the 互斥锁 but does not reschedule itself, and `callout_drain` is called before the last scheduled firing completes. -* The callout handler is stuck waiting on a lock that another thread holds. -* The callout itself was never properly stopped before drain. +* callout 处理程序重新获取了互斥锁但没有重新调度自身,而 `callout_drain` 在最后一次计划触发完成之前被调用。 +* callout 处理程序卡在等待另一个线程持有的锁上。 +* callout 本身在排空之前从未被正确停止。 -The first line of defence is `callout_init_mtx` with the softc 互斥锁: this sets up an automatic acquisition pattern that makes drain correct by construction. The second line is to use `callout_stop` or `callout_drain` consistently and to avoid mixing the two on the same callout. +第一道防线是 `callout_init_mtx` 配合 softc 互斥锁:这设置了一个自动获取模式,使排空在构造上就是正确的。第二道防线是一致地使用 `callout_stop` 或 `callout_drain`,避免在同一个 callout 上混合使用两者。 -If the unload hangs, use `ps -auxw` to find the offending thread, and `kgdb` on a running 内核 (through `/dev/mem` and `bin/kgdb /boot/内核/内核`) to see what it is stuck on. The stuck 帧 is almost always in the callout code, and the fix is almost always to drain before destroying the 互斥锁. +如果卸载挂起,使用 `ps -auxw` 找到有问题的线程,然后对运行中的内核使用 `kgdb`(通过 `/dev/mem` 和 `bin/kgdb /boot/kernel/kernel`)查看它卡在什么上。卡住的帧几乎总是在 callout 代码中,修复几乎总是先排空再销毁互斥锁。 -### VNET Considerations +### VNET 注意事项 -FreeBSD's network stack supports VNETs, virtual network stacks associated with a jail or a VNET instance. A 驱动程序 can be VNET-aware if it wants to allow per-VNET creation of 接口, or it can be non-VNET-aware if one set of 接口 per system is enough. +FreeBSD 的网络协议栈支持 VNET,即与 jail 或 VNET 实例关联的虚拟网络协议栈。如果驱动程序想要允许每个 VNET 创建接口,它可以是 VNET 感知的;如果每系统一组接口就够了,它也可以是非 VNET 感知的。 -We used `VNET_DEFINE_STATIC` and `VNET_SYSINIT`/`VNET_SYSUNINIT` in our cloner registration. That choice makes our 驱动程序 implicitly VNET-aware: each VNET gets its own cloner, and `mynet` 接口 can be created in any VNET. For a small pseudo-驱动程序 this costs us nothing and gains us flexibility. +我们在克隆器注册中使用了 `VNET_DEFINE_STATIC` 和 `VNET_SYSINIT`/`VNET_SYSUNINIT`。这个选择使我们的驱动程序隐式地成为 VNET 感知的:每个 VNET 获得自己的克隆器,`mynet` 接口可以在任何 VNET 中创建。对于一个小型伪驱动程序,这不需要任何成本并为我们带来了灵活性。 -The deeper aspects of VNET, including moving an 接口 between VNETs with `if_vmove` and handling VNET teardown, are beyond the scope of this chapter and will be covered later in the book, in Chapter 30. For now it is enough to know that our 驱动程序 follows the conventions that make it VNET-compatible. +VNET 的更深层方面,包括使用 `if_vmove` 在 VNET 之间移动接口以及处理 VNET 拆卸,超出了本章的范围,将在本书后面的第 30 章中涵盖。现在只需知道我们的驱动程序遵循使其与 VNET 兼容的约定即可。 -### Refactoring Advice +### 重构建议 -The 驱动程序 we have built is a single C file with about 500 lines of code. That is comfortable for a teaching example. In a production 驱动程序 with more features, the file would grow, and you would want to split it up. Here are the splits that almost every 驱动程序 eventually makes. +我们构建的驱动程序是一个约 500 行 C 代码的单文件。对于教学示例来说很舒适。在具有更多功能的生产驱动程序中,文件会增长,你会想要拆分它。以下是几乎每个驱动程序最终都会做的拆分。 -**Separate the ifnet glue from the data path.** The ifnet registration, cloner logic, and ioctl handling tend to be stable over time. The data path, transmit and receive, evolves as hardware features change. Splitting them into `mynet_if.c` and `mynet_data.c` keeps most files small and focused. +**将 ifnet 胶水与数据路径分离。** ifnet 注册、克隆器逻辑和 ioctl 处理随时间趋于稳定。数据路径,即发送和接收,随着硬件功能变化而演进。将它们拆分为 `mynet_if.c` 和 `mynet_data.c` 可以使大多数文件小而专注。 -**Isolate the backend.** In a real NIC 驱动程序, the backend is hardware-specific code: 注册 access, DMA, MSI-X, 环形缓冲区. In a pseudo-驱动程序, the backend is the simulation. Either way, putting the backend in `mynet_backend.c` with a clean 接口 makes it possible to replace the backend without touching the ifnet code. +**隔离后端。** 在真正的网卡驱动程序中,后端是硬件特定的代码:寄存器访问、DMA、MSI-X、环形缓冲区。在伪驱动程序中,后端是模拟。无论哪种方式,将后端放在 `mynet_backend.c` 中并使用干净的接口,可以在不触碰 ifnet 代码的情况下替换后端。 -**Separate sysctl and debugging.** As your 驱动程序 grows, you will add sysctls for diagnostic controls, counters for debugging, and maybe DTrace SDT 探测. These tend to accumulate in messy ways. Keeping them in `mynet_sysctl.c` keeps the main files readable. +**分离 sysctl 和调试。** 随着驱动程序增长,你会添加用于诊断控制的 sysctl、用于调试的计数器,可能还有 DTrace SDT 探测。这些倾向于以混乱的方式积累。将它们保留在 `mynet_sysctl.c` 中可以保持主文件可读。 -**Keep the header public.** A `mynet_var.h` or `mynet.h` header that declares the softc and the cross-file prototypes is the glue that keeps the split compiling. Treat that header as a mini public API. +**保持头文件公开。** 一个声明 softc 和跨文件原型的 `mynet_var.h` 或 `mynet.h` 头文件是保持拆分编译的胶水。将该头文件视为一个迷你公共 API。 -**Version the 驱动程序.** `MODULE_VERSION(mynet, 1)` is the bare minimum. When you add a significant feature, increment the version. Downstream consumers who depend on your module can then require a minimum version, and 内核 users can tell which version of the 驱动程序 they have loaded via `kldstat -v`. +**版本化驱动程序。** `MODULE_VERSION(mynet, 1)` 是最低限度。当你添加重要功能时,递增版本。依赖你模块的下游消费者可以要求最低版本,内核用户可以通过 `kldstat -v` 知道他们加载的是哪个版本的驱动程序。 -### Feature Flags and Capabilities +### 功能标志和能力 -以太网 驱动程序 advertise capabilities through `if_capabilities` and `if_capenable`. We set `IFCAP_VLAN_MTU`. Other capabilities a real 驱动程序 might advertise include: +以太网驱动程序通过 `if_capabilities` 和 `if_capenable` 声明能力。我们设置了 `IFCAP_VLAN_MTU`。真正的驱动程序可能声明的其他能力包括: -* `IFCAP_HWCSUM`: hardware checksum offload. -* `IFCAP_TSO4`, `IFCAP_TSO6`: TCP segmentation offload for IPv4 and IPv6. -* `IFCAP_LRO`: large receive offload. -* `IFCAP_VLAN_HWTAGGING`: hardware VLAN tagging. -* `IFCAP_RXCSUM`, `IFCAP_TXCSUM`: receive and transmit checksum offload. -* `IFCAP_JUMBO_MTU`: jumbo 帧 support. -* `IFCAP_LINKSTATE`: hardware link-state events. -* `IFCAP_NETMAP`: netmap(4) support for high-speed 数据包 I/O. +* `IFCAP_HWCSUM`:硬件校验和卸载。 +* `IFCAP_TSO4`、`IFCAP_TSO6`:IPv4 和 IPv6 的 TCP 分段卸载。 +* `IFCAP_LRO`:大接收卸载。 +* `IFCAP_VLAN_HWTAGGING`:硬件 VLAN 标记。 +* `IFCAP_RXCSUM`、`IFCAP_TXCSUM`:接收和发送校验和卸载。 +* `IFCAP_JUMBO_MTU`:巨型帧支持。 +* `IFCAP_LINKSTATE`:硬件链路状态事件。 +* `IFCAP_NETMAP`:`netmap(4)` 支持,用于高速包 I/O。 -For a pseudo-驱动程序 most of these are not relevant. Advertising them falsely causes problems because the stack will then attempt to use them and expect them to work. Keep the capability set honest: advertise only what your 驱动程序 actually supports. +对于伪驱动程序,大多数这些都不相关。虚假声明它们会导致问题,因为协议栈随后会尝试使用它们并期望它们工作。保持能力集诚实:只声明你的驱动程序实际支持的功能。 -### Writing a Run Script +### 编写运行脚本 -One of the most useful artefacts to produce alongside a 驱动程序 is a small shell script that exercises its entire lifecycle. The skeleton we showed in Section 7 is already 80% of that script. Extend it with: +与驱动程序一起产出的最有用的工件之一是一个小型 shell 脚本,用于测试其整个生命周期。我们在第 7 节中展示的骨架已经是该脚本的 80%。扩展它: -* Consistency checks after each operation (`ifconfig -a | grep mynet0` or `netstat -in -I mynet0 | ...`). -* Optional logging of each step to a file for after-the-fact inspection. -* A cleanup 块 at the end that ensures the system is left in a known state even if an earlier step fails. +* 每次操作后的一致性检查(`ifconfig -a | grep mynet0` 或 `netstat -in -I mynet0 | ...`)。 +* 可选地将每步记录到文件以供事后检查。 +* 末尾的清理块,确保即使前面的步骤失败,系统也处于已知状态。 -A good run script is the single most valuable tool for regression-free development. We encourage you to maintain one as you extend the 驱动程序 in the challenges. +一个好的运行脚本是实现无回归开发的最有价值的工具。我们鼓励你在挑战中扩展驱动程序时维护一个。 -### Tidying Up the File +### 整理文件 -Finally, a word on code style. Real FreeBSD 驱动程序 follow KNF (Kernel Normal Form), the coding style documented in `style(9)`. Summarised: tabs for indentation, braces on the same line as function definitions but on the next line for structures and enums, 80-column lines where possible, no spaces before the opening parenthesis of a function call, and so on. Your 驱动程序 will be easier to merge upstream (and easier to read a year from now) if you follow KNF consistently. +最后,关于代码风格。真正的 FreeBSD 驱动程序遵循 KNF(内核标准格式),即 `style(9)` 中记录的编码风格。总结:用制表符缩进,函数定义的大括号与函数在同一行,结构体和枚举的大括号在下一行,尽可能使用 80 列行宽,函数调用的左括号前不加空格等等。如果你一致地遵循 KNF,你的驱动程序将更容易合并到上游(也更容易在一年后阅读)。 -### Handling Partial Initialisation Failure +### 处理部分初始化失败 -We have focused on the happy path. What happens if `mynet_create_unit` fails partway through? Say `if_alloc` succeeds, `mtx_init` runs, `ifmedia_init` sets up the media, and then `malloc` of some auxiliary 缓冲区 returns NULL. We need to roll back cleanly, because the user just got `ifconfig mynet create` to fail, and we must leave no trace. +我们专注于了顺利的路径。如果 `mynet_create_unit` 中途失败会怎样?假设 `if_alloc` 成功,`mtx_init` 运行了,`ifmedia_init` 设置了媒体,然后某个辅助缓冲区的 `malloc` 返回 NULL。我们需要干净地回滚,因为用户刚刚让 `ifconfig mynet create` 失败了,我们不能留下任何痕迹。 -The idiom for rollback is a 块 of labels near the end of the function, each label undoing one step of the initialisation: +回滚的惯用法是函数末尾附近的一块标签,每个标签撤销初始化的一个步骤: ```c static int @@ -2350,458 +2349,458 @@ fail_alloc: } ``` -This pattern, common in 内核 code, makes rollback boring. Each label takes responsibility for the step immediately above it. The overall shape is "if something in step N fails, jump to label N-1 and unwind from there". +这种模式在内核代码中很常见,使回滚变得枯燥。每个标签负责紧接在其上面的步骤。总体形状是「如果步骤 N 中的某个东西失败,跳转到标签 N-1 并从那里展开」。 -For our 驱动程序 the only realistic failure point early in create is `if_alloc`. If that succeeds, the rest of the setup (互斥锁 init, media init, ether_if附加) is either infallible or sufficiently idempotent that no rollback is needed. But the shape of the rollback matters, because a more complex 驱动程序 will have more failure points, and the same pattern scales cleanly. +对于我们的驱动程序,创建早期唯一现实的失败点是 `if_alloc`。如果它成功了,其余的设置(互斥锁初始化、媒体初始化、ether_ifattach)要么是绝对可靠的,要么是足够幂等的,不需要回滚。但回滚的形状很重要,因为更复杂的驱动程序会有更多失败点,同样的模式可以干净地扩展。 -### Synchronising With In-Flight Callbacks +### 与执行中的回调同步 -Beyond callouts, other asynchronous code might be in flight when we tear down an 接口. Taskqueue tasks, 中断处理程序s, and timer-based rearm functions all need to be stopped before memory is freed. +除了 callout 之外,当我们拆卸接口时其他异步代码可能还在运行。Taskqueue 任务、中断处理程序和基于定时器的重新武装函数都需要在释放内存之前停止。 -The 内核 provides `taskqueue_drain(tq, task)` for taskqueue tasks, analogous to `callout_drain` for callouts. For interrupts, `总线_teardown_intr` and `总线_release_resource` ensure the 中断处理程序 will not be invoked again. For rearmable callouts where the handler reschedules itself, `callout_drain` still does the right thing: it waits for the current invocation to finish and prevents further rearms. +内核为 taskqueue 任务提供了 `taskqueue_drain(tq, task)`,类似于 callout 的 `callout_drain`。对于中断,`bus_teardown_intr` 和 `bus_release_resource` 确保中断处理程序不会再被调用。对于处理程序自行重新调度的可重新武装 callout,`callout_drain` 仍然做正确的事情:它等待当前调用完成并阻止进一步的重新武装。 -A general rule for a teardown path: +拆卸路径的一般规则: -1. Clear any "running" or "armed" flags that the asynchronous code checks. -2. Drain each asynchronous source in turn (taskqueue, callout, interrupt). -3. Detach from upper layers (`ether_if分离`). -4. Free the memory. +1. 清除异步代码检查的任何「运行中」或「已武装」标志。 +2. 依次排空每个异步源(taskqueue、callout、中断)。 +3. 从上层分离(`ether_ifdetach`)。 +4. 释放内存。 -Skipping step 1 is usually the cause of "destroying locked 互斥锁" panics, because the asynchronous code is still running when the 互斥锁 gets destroyed. Skipping step 2 is the cause of use-after-free. Step 3 and step 4 must happen in that order or the stack may try to call into our 回调 after they have been freed. +跳过步骤 1 通常是「销毁已加锁互斥锁」崩溃的原因,因为互斥锁被销毁时异步代码仍在运行。跳过步骤 2 是释放后使用的原因。步骤 3 和步骤 4 必须按此顺序执行,否则协议栈可能会在回调被释放后尝试调用它们。 -### A Worked Error Scenario +### 一个实际的错误场景 -To make the above concrete, imagine a subtle bug. Suppose that during development we call `mtx_destroy` before `callout_drain`. The callout is scheduled, the user runs `ifconfig mynet0 destroy`, our destroy function destroys the 互斥锁, and then the scheduled callout fires. The callout tries to acquire the 互斥锁 (because we 注册ed it with `callout_init_mtx`), sees a destroyed 互斥锁, and triggers an assertion: "acquiring a destroyed 互斥锁". The system panics with a stack trace pointing into the callout code. +为了使上述内容更具体,想象一个微妙的 bug。假设在开发过程中我们在 `callout_drain` 之前调用了 `mtx_destroy`。callout 已被调度,用户运行 `ifconfig mynet0 destroy`,我们的销毁函数销毁了互斥锁,然后已调度的 callout 触发。callout 尝试获取互斥锁(因为我们用 `callout_init_mtx` 注册了它),看到一个已销毁的互斥锁,并触发断言:「获取已销毁的互斥锁」。系统崩溃,栈跟踪指向 callout 代码。 -The fix is to reverse the order: `callout_drain` first, `mtx_destroy` later. The general principle is that synchronisation primitives are destroyed last, after all consumers are known to have stopped. +修复方法是反转顺序:先 `callout_drain`,后 `mtx_destroy`。一般原则是同步原语在所有消费者都已知停止后才最后销毁。 -This kind of bug is easy to introduce and hard to diagnose if you have not seen it before. Having an explicit mental model of "quiesce, 分离, free" prevents it. +这种 bug 很容易引入,但如果你以前没见过就很难诊断。拥有一个明确的「停止、分离、释放」心智模型可以防止它。 -### 总结 Section 8 +### 第8节小结 -The full lifecycle is now in your hands. Load, cloner registration, per-接口 creation, active life with transmit, receive, ioctl, and link events, per-接口 destruction, cloner 分离, module unload. You can build, test, tear down, and rebuild with confidence that the 内核 is returned to a clean state. +完整的生命周期现在掌握在你手中。加载、克隆器注册、每接口创建、带有发送、接收、ioctl 和链路事件的活跃生命周期、每接口销毁、克隆器分离、模块卸载。你可以构建、测试、拆卸和重建,确信内核返回到干净状态。 -The sections that come next are the hands-on part of the chapter: labs that walk you through the milestones we have described, challenges that extend the 驱动程序, troubleshooting pointers, and a wrap-up. +接下来的章节是本章的动手部分:引导你完成我们描述的里程碑的实验、扩展驱动程序的挑战、故障排除提示和总结。 ## 动手实验 -The labs below are ordered to mirror the chapter's flow. Each one builds on the previous, so do them in sequence. The companion files live under `examples/part-06/ch28-network-驱动程序/`, and each lab has its own README with the specific commands. +下面的实验按章节流程排序。每个建立在前一个之上,所以按顺序进行。配套文件位于 `examples/part-06/ch28-network-driver/` 下,每个实验都有自己的 README,包含具体的命令。 -Before starting, make sure you are on a FreeBSD 14.3 lab VM with root access, a clean workspace directory where you can build a 内核模块, and a freshly-snapshot state you can return to if something goes wrong. A snapshot before beginning the labs is a small investment that pays for itself the first time you need it. +开始之前,确保你在一个拥有 root 权限的 FreeBSD 14.3 实验虚拟机上,有一个可以构建内核模块的干净工作区目录,以及一个如果出现问题可以返回的新快照状态。在开始实验之前做快照是一个小的投资,在你第一次需要它时就会收回成本。 -Each lab ends with a brief "checkpoint" 块 listing the specific observations you should record in your logbook. If your logbook already has those observations, you can move on. If it does not, return to the previous step and redo it. The cumulative structure of the labs means that a missed observation in Lab 2 will make Lab 4 confusing. +每个实验都以一个简短的「检查点」块结束,列出你应在实验日志中记录的具体观察。如果你的实验日志已经有这些观察,你可以继续。如果没有,返回上一步重做。实验的累积结构意味着实验 2 中遗漏的观察会使实验 4 变得令人困惑。 -### Lab 1: Build and Load the Skeleton +### 实验1:构建和加载骨架 -**Goal.** Build the skeleton 驱动程序 from Section 3, load it, create an instance, and observe the default state. +**目标。** 构建第 3 节的骨架驱动程序,加载它,创建一个实例,并观察默认状态。 -**Steps.** +**步骤。** -1. `cd examples/part-06/ch28-network-驱动程序/` -2. `make` and watch for warnings. The build should produce `mynet.ko` without warnings. -3. `kldload ./mynet.ko`. No messages should appear on the console; `kldstat` should list `mynet` as present. -4. `ifconfig mynet create` should print `mynet0`. -5. `ifconfig mynet0` and record the output in your logbook. Note especially the flags, the MAC address, the media line, and the status. -6. `kldstat -v | grep mynet` and verify the module is present and loaded at the expected address. -7. `sysctl net.generic.ifclone` and confirm that `mynet` appears in the list of cloners. -8. `ifconfig mynet0 destroy`. The 接口 should disappear. -9. `kldunload mynet`. The module should unload cleanly. -10. `kldstat` and `ifconfig -a` to confirm nothing is left. +1. `cd examples/part-06/ch28-network-driver/` +2. `make` 并注意警告。构建应该产生 `mynet.ko` 且没有警告。 +3. `kldload ./mynet.ko`。控制台不应出现任何消息;`kldstat` 应列出 `mynet` 为已存在。 +4. `ifconfig mynet create` 应打印 `mynet0`。 +5. `ifconfig mynet0` 并在日志中记录输出。特别注意标志、MAC 地址、媒体行和状态。 +6. `kldstat -v | grep mynet` 并验证模块存在且在预期地址加载。 +7. `sysctl net.generic.ifclone` 并确认 `mynet` 出现在克隆器列表中。 +8. `ifconfig mynet0 destroy`。接口应消失。 +9. `kldunload mynet`。模块应干净地卸载。 +10. `kldstat` 和 `ifconfig -a` 确认没有残留。 -**What to watch for.** The `ifconfig mynet0` output should show flags `BROADCAST,SIMPLEX,MULTICAST`, a MAC address, a media line of "以太网 autoselect", and a status of "no carrier". If any of these is missing, recheck the `mynet_create_unit` function and the `ifmedia_init` call. +**注意观察。** `ifconfig mynet0` 输出应显示标志 `BROADCAST,SIMPLEX,MULTICAST`、一个 MAC 地址、一行"Ethernet autoselect"的媒体行和"no carrier"的状态。如果缺少其中任何一个,重新检查 `mynet_create_unit` 函数和 `ifmedia_init` 调用。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record the exact MAC address assigned to `mynet0`. -* Record the initial value of `if_mtu`. -* Note the flags reported before and after `ifconfig mynet0 up`. -* Note whether `status:` changes between "no carrier" and "active". +* 记录分配给 `mynet0` 的确切 MAC 地址。 +* 记录 `if_mtu` 的初始值。 +* 注意 `ifconfig mynet0 up` 前后报告的标志。 +* 注意 `status:` 是否在 "no carrier" 和 "active" 之间变化。 -**If things go wrong.** The most common Lab 1 failure is a build error caused by a missing header. Make sure your 内核 source tree under `/usr/src/sys/` matches the running 内核 version. If `kldload` fails with "module already present", unload any prior instance with `kldunload mynet` and try again. If `ifconfig mynet create` returns "Operation not supported", the cloner did not 注册, and you need to re-check the `VNET_SYSINIT` call. +**如果出现问题。** 最常见的实验 1 失败是由缺少头文件导致的构建错误。确保 `/usr/src/sys/` 下的内核源代码树与运行中的内核版本匹配。如果 `kldload` 失败并显示"module already present",用 `kldunload mynet` 卸载任何先前的实例然后重试。如果 `ifconfig mynet create` 返回"Operation not supported",克隆器未注册,你需要重新检查 `VNET_SYSINIT` 调用。 -### Lab 2: Exercise the Transmit Path +### 实验2:练习发送路径 -**Goal.** Verify that `if_transmit` is called when traffic leaves the 接口. +**目标。** 验证当流量离开接口时 `if_transmit` 被调用。 -**Steps.** +**步骤。** -1. Create the 接口 and bring it up as in Lab 1. -2. `ifconfig mynet0 inet 192.0.2.1/24 up`. Both `UP` and `RUNNING` flags should now appear. -3. In one terminal, run `tcpdump -i mynet0 -nn`. -4. In another, run `ping -c 3 192.0.2.99`. -5. Observe the ARP and ICMP traffic printed by `tcpdump`. -6. `netstat -in -I mynet0` and record the counters. The `Opkts` column should show at least four (three ICMP requests plus the ARP broadcast attempts). -7. Modify the transmit function to return `ENOBUFS` for every call and rebuild. -8. Unload and reload, repeat the `ping`, observe that `Opkts` stops climbing and that `Oerrors` increases instead. -9. Revert the modification and rebuild. -10. Optional: run the DTrace one-liner `dtrace -n 'fbt::mynet_transmit:entry { @c = count(); }'` while generating traffic to confirm each call reaches your transmit function. +1. 如实验 1 那样创建接口并启动它。 +2. `ifconfig mynet0 inet 192.0.2.1/24 up`。`UP` 和 `RUNNING` 标志现在都应出现。 +3. 在一个终端中,运行 `tcpdump -i mynet0 -nn`。 +4. 在另一个终端中,运行 `ping -c 3 192.0.2.99`。 +5. 观察 `tcpdump` 打印的 ARP 和 ICMP 流量。 +6. `netstat -in -I mynet0` 并记录计数器。`Opkts` 列应显示至少四个(三次 ICMP 请求加上 ARP 广播尝试)。 +7. 修改发送函数为每次调用返回 `ENOBUFS` 并重新构建。 +8. 卸载并重新加载,重复 `ping`,观察 `Opkts` 停止增长且 `Oerrors` 增加。 +9. 还原修改并重新构建。 +10. 可选:在生成流量时运行 DTrace 单行命令 `dtrace -n 'fbt::mynet_transmit:entry { @c = count(); }'`,确认每次调用都到达你的发送函数。 -**What to watch for.** In step 5, each `ping` produces one ARP broadcast (because the stack does not know the MAC for `192.0.2.99`) and one ICMP echo request per ping attempt, but the ARP reply never comes, so subsequent pings only add ICMP requests. Understanding why that is, and what it looks like in `tcpdump`, is an important part of this lab. +**注意观察。** 在步骤 5 中,每次 `ping` 产生一个 ARP 广播(因为协议栈不知道 `192.0.2.99` 的 MAC)和每次 ping 尝试一个 ICMP 回显请求,但 ARP 回复永远不会来,所以后续的 ping 只添加 ICMP 请求。理解为什么会这样,以及它在 `tcpdump` 中看起来是什么样,是这个实验的重要部分。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record the exact `Opkts` count after three pings. -* Record the `Obytes` count and verify that it matches the expected sum of ARP 帧 (42 bytes) plus three ICMP 帧. -* Note what changes in `Oerrors` when you deliberately return `ENOBUFS`. +* 记录三次 ping 后的确切 `Opkts` 计数。 +* 记录 `Obytes` 计数并验证它匹配 ARP 帧(42 字节)加上三个 ICMP 帧的预期总和。 +* 注意当你故意返回 `ENOBUFS` 时 `Oerrors` 有什么变化。 -**If things go wrong.** If `Opkts` is zero after the pings, your `if_transmit` 回调 is not being called. Check that `ifp->if_transmit = mynet_transmit` is set during create. If `Obytes` is growing but `Opkts` is not, one of the counter calls is missing or reaching the wrong counter. If `tcpdump` shows no outbound traffic at all, the BPF tap in transmit is missing; add `BPF_MTAP(ifp, m)` before the free. +**如果出现问题。** 如果 ping 后 `Opkts` 为零,你的 `if_transmit` 回调没有被调用。检查创建期间是否设置了 `ifp->if_transmit = mynet_transmit`。如果 `Obytes` 在增长但 `Opkts` 没有,说明某个计数器调用缺失或到达了错误的计数器。如果 `tcpdump` 没有显示出站流量,发送中缺少 BPF 捕获;在释放前添加 `BPF_MTAP(ifp, m)`。 -### Lab 3: Exercise the Receive Path +### 实验3:练习接收路径 -**Goal.** Verify that `if_input` delivers 数据包 into the stack. +**目标。** 验证 `if_input` 将数据包送入协议栈。 -**Steps.** +**步骤。** -1. Create the 接口 and bring it up. -2. `tcpdump -i mynet0 -nn`. -3. Wait five seconds and confirm that one synthesised ARP request per second appears. -4. `netstat -in -I mynet0` and confirm `Ipkts` matches the 数据包 count. -5. Change `sc->rx_interval_hz = hz / 10;` and rebuild. -6. Unload, reload, re-create. Observe that the rate becomes ten 数据包 per second. -7. Revert to one 数据包 per second. -8. Optional: comment out the `BPF_MTAP` call in the receive path, rebuild, and observe that `tcpdump` no longer shows the synthesised ARP but `Ipkts` still increments. This confirms that BPF visibility and counter updates are independent. -9. Optional: comment out the `if_input` call (leave `BPF_MTAP` in place), rebuild, and observe the opposite behaviour: `tcpdump` sees the 帧, but `Ipkts` does not move because the stack never actually got the 帧. +1. 创建接口并启动它。 +2. `tcpdump -i mynet0 -nn`。 +3. 等待五秒并确认每秒出现一个合成 ARP 请求。 +4. `netstat -in -I mynet0` 并确认 `Ipkts` 与数据包计数匹配。 +5. 将 `sc->rx_interval_hz = hz / 10;` 修改并重新构建。 +6. 卸载、重新加载、重新创建。观察速率变为每秒十个数据包。 +7. 还原为每秒一个数据包。 +8. 可选:注释掉接收路径中的 `BPF_MTAP` 调用,重新构建,观察 `tcpdump` 不再显示合成 ARP 但 `Ipkts` 仍然递增。这确认 BPF 可见性和计数器更新是独立的。 +9. 可选:注释掉 `if_input` 调用(保留 `BPF_MTAP`),重新构建,观察相反的行为:`tcpdump` 看到帧,但 `Ipkts` 不动,因为协议栈从未真正收到帧。 -**What to watch for.** The `Ipkts` counter should increment exactly once per synthesised 帧. If it does not, the BPF tap may be seeing the 帧 but `if_input` is not being called, or the calls are racing with teardown. +**注意观察。** `Ipkts` 计数器应该每个合成帧恰好递增一次。如果不是,BPF 捕获可能看到了帧但 `if_input` 没有被调用,或者调用与拆卸存在竞争。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record the interval between consecutive synthesised ARPs as shown by `tcpdump` timestamps. -* Record the MAC addresses in the ARP 帧 and confirm that the source MAC matches the 接口's address. -* Observe what `arp -an` shows before and after; entries for `192.0.2.99` should remain incomplete. +* 记录 `tcpdump` 时间戳显示的连续合成 ARP 之间的间隔。 +* 记录 ARP 帧中的 MAC 地址并确认源 MAC 与接口地址匹配。 +* 观察之前和之后 `arp -an` 显示什么;`192.0.2.99` 的条目应保持不完整。 -**If things go wrong.** If no synthesised ARP appears in `tcpdump`, the callout is not firing. Check that `callout_reset` is called in `mynet_init` and that `sc->running` is true at the time. If `tcpdump` shows the ARP but `Ipkts` is zero, the counter is not being updated (or is being updated after `if_input` which has already freed the mbuf). +**如果出现问题。** 如果 `tcpdump` 中没有合成 ARP 出现,callout 没有触发。检查 `mynet_init` 中是否调用了 `callout_reset` 以及当时 `sc->running` 是否为 true。如果 `tcpdump` 显示 ARP 但 `Ipkts` 为零,计数器没有更新(或者在 `if_input` 之后更新,而 `if_input` 已经释放了 mbuf)。 -### Lab 4: Media and Link State +### 实验4:媒体和链路状态 -**Goal.** Observe the difference between link state, media, and 接口 flags. +**目标。** 观察链路状态、媒体和接口标志之间的区别。 -**Steps.** +**步骤。** -1. Create and configure the 接口. -2. `ifconfig mynet0` and note the `status` and `media` lines. -3. `ifconfig mynet0 down`. -4. `ifconfig mynet0` and note that `status` changes. -5. `ifconfig mynet0 up`. -6. In another terminal, `route monitor` and repeat steps 3 and 5 while watching the output. -7. `ifconfig mynet0 media 1000baseT mediaopt full-duplex` and confirm `ifconfig mynet0` reflects the change. -8. Add a third media entry `IFM_ETHER | IFM_100_TX | IFM_FDX` to `mynet_create_unit`, rebuild, and verify that `ifconfig mynet0 media 100baseTX mediaopt full-duplex` now succeeds. -9. Remove the entry and rebuild. Verify that the same command now fails with "requested media type not found". +1. 创建并配置接口。 +2. `ifconfig mynet0` 并注意 `status` 和 `media` 行。 +3. `ifconfig mynet0 down`。 +4. `ifconfig mynet0` 并注意 `status` 的变化。 +5. `ifconfig mynet0 up`。 +6. 在另一个终端中,`route monitor` 并在观察输出的同时重复步骤 3 和 5。 +7. `ifconfig mynet0 media 1000baseT mediaopt full-duplex` 并确认 `ifconfig mynet0` 反映了更改。 +8. 在 `mynet_create_unit` 中添加第三个媒体条目 `IFM_ETHER | IFM_100_TX | IFM_FDX`,重新构建,验证 `ifconfig mynet0 media 100baseTX mediaopt full-duplex` 现在成功。 +9. 删除该条目并重新构建。验证相同的命令现在以"requested media type not found"失败。 -**What to watch for.** `route monitor` prints `RTM_IFINFO` messages on every link-state transition. The `ifconfig mynet0` `status:` line shows `active` when the 驱动程序 is running and the link is up, and `no carrier` when the 驱动程序 has called `LINK_STATE_DOWN`. +**注意观察。** `route monitor` 在每次链路状态转换时打印 `RTM_IFINFO` 消息。`ifconfig mynet0` 的 `status:` 行在驱动程序运行且链路已连接时显示 `active`,在驱动程序调用 `LINK_STATE_DOWN` 时显示 `no carrier`。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record the exact `RTM_IFINFO` message text from `route monitor`. -* Note the difference between `IFF_UP` and `LINK_STATE_UP` by capturing the output of `ifconfig mynet0` in each of the four possible combinations (up or down cross with link up or down). -* Observe whether `status:` and the 接口 flags stay consistent across all four states. +* 记录 `route monitor` 中确切的 `RTM_IFINFO` 消息文本。 +* 通过在四种可能的组合(up 或 down 与链路 up 或 down 交叉)下捕获 `ifconfig mynet0` 的输出来记录 `IFF_UP` 和 `LINK_STATE_UP` 之间的区别。 +* 观察在所有四种状态下 `status:` 和接口标志是否保持一致。 -**If things go wrong.** If `status:` stays at "no carrier" even after the 接口 is up, you are not calling `if_link_state_change(ifp, LINK_STATE_UP)` from `mynet_init`. If `ifconfig mynet0 media 1000baseT` fails with "requested media type not found", you did not 注册 `IFM_ETHER | IFM_1000_T` via `ifmedia_add`, or you 注册ed it with the wrong flags. +**如果出现问题。** 如果 `status:` 在接口启动后仍然停留在"no carrier",说明你没有从 `mynet_init` 调用 `if_link_state_change(ifp, LINK_STATE_UP)`。如果 `ifconfig mynet0 media 1000baseT` 失败并显示"requested media type not found",说明你没有通过 `ifmedia_add` 注册 `IFM_ETHER | IFM_1000_T`,或者你用错误的标志注册了它。 -### Lab 5: `tcpdump` and BPF +### 实验5:`tcpdump` 和 BPF -**Goal.** Confirm that BPF sees both outbound and inbound 数据包. +**目标。** 确认 BPF 能看到出站和入站数据包。 -**Steps.** +**步骤。** -1. Create and configure the 接口 with IP `192.0.2.1/24`. +1. 创建并配置接口,IP 为 `192.0.2.1/24`。 2. `tcpdump -i mynet0 -nn > /tmp/dump.txt &` -3. Wait ten seconds. -4. `ping -c 3 192.0.2.99`. -5. Wait another ten seconds. -6. `kill %1`. -7. `cat /tmp/dump.txt` and identify the synthesised ARP requests, the ARP broadcasts generated by your `ping`, and the ICMP echo requests. -8. Remove the `BPF_MTAP` call from `mynet_transmit` and rebuild. Repeat. Note that outbound ICMP no longer appears in the `tcpdump` output. -9. Restore the `BPF_MTAP` call. -10. Experiment with filters: `tcpdump -i mynet0 -nn 'arp'` should show only the synthesised ARPs and ARP from your pings, while `tcpdump -i mynet0 -nn 'icmp'` should show only the ICMP echo requests. -11. Observe the link-type line in `tcpdump`'s startup output. It should say `EN10MB (以太网)`, because `ether_if附加` set that up for us. If it says `NULL`, the 接口 was 附加ed without 以太网 semantics. +3. 等待十秒。 +4. `ping -c 3 192.0.2.99`。 +5. 再等待十秒。 +6. `kill %1`。 +7. `cat /tmp/dump.txt` 并识别合成 ARP 请求、你的 `ping` 生成的 ARP 广播以及 ICMP 回显请求。 +8. 从 `mynet_transmit` 中移除 `BPF_MTAP` 调用并重新构建。重复。注意出站 ICMP 不再出现在 `tcpdump` 输出中。 +9. 恢复 `BPF_MTAP` 调用。 +10. 实验过滤器:`tcpdump -i mynet0 -nn 'arp'` 应仅显示合成 ARP 和你 ping 的 ARP,而 `tcpdump -i mynet0 -nn 'icmp'` 应仅显示 ICMP 回显请求。 +11. 观察 `tcpdump` 启动输出中的 link-type 行。它应显示 `EN10MB (Ethernet)`,因为 `ether_ifattach` 为我们设置了这个。如果显示 `NULL`,说明接口没有使用以太网语义附加。 -**What to watch for.** The exercise demonstrates that BPF visibility is not automatic for every 数据包. It is the 驱动程序's job to tap on both the transmit and receive paths. +**注意观察。** 本练习证明 BPF 可见性对每个数据包不是自动的。驱动程序有责任在发送和接收路径上都进行捕获。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record one complete line of `tcpdump` output for each type of 帧 you observed: synthesised ARP, outbound ARP, outbound ICMP echo request. -* Record the link-type line as printed by `tcpdump`. -* Note what happens to the output when you remove `BPF_MTAP` from transmit. +* 记录你观察到的每种帧类型的一行完整 `tcpdump` 输出:合成 ARP、出站 ARP、出站 ICMP 回显请求。 +* 记录 `tcpdump` 打印的 link-type 行。 +* 注意当你从发送中移除 `BPF_MTAP` 时输出发生了什么。 -**If things go wrong.** If `tcpdump` never shows any 数据包 at all, `bpf附加` was not called (usually because you forgot `ether_if附加`). If it shows received 数据包 but not transmitted ones, your transmit tap is missing. If it shows transmitted 数据包 but not received ones, your receive tap is missing. If the link-type is wrong, the 接口 type or the `bpf附加` call is wrong. +**如果出现问题。** 如果 `tcpdump` 从未显示任何数据包,说明 `bpfattach` 没有被调用(通常是因为你忘了 `ether_ifattach`)。如果它显示接收到的数据包但不显示发送的,你的发送捕获缺失。如果它显示发送的数据包但不显示接收的,你的接收捕获缺失。如果链路类型错误,接口类型或 `bpfattach` 调用是错误的。 -### Lab 6: Clean Detach +### 实验6:干净分离 -**Goal.** Verify that unload returns the system to a clean state. +**目标。** 验证卸载将系统返回到干净状态。 -**Steps.** +**步骤。** -1. Create three 接口: `mynet create` three times. -2. Configure each with a different IP in `192.0.2.0/24` (for example, `192.0.2.1/24`, `192.0.2.2/24`, `192.0.2.3/24`). -3. `vmstat -m | grep mynet` and record the allocation count. -4. `kldunload mynet` (do not destroy first). -5. `ifconfig -a` and confirm none of `mynet0`, `mynet1`, `mynet2` remains. -6. `vmstat -m | grep mynet` and confirm `InUse` returns to zero. -7. Repeat steps 1 through 6 five times in sequence. Each round should leave `InUse` at zero and should not leave any orphaned state. -8. Optional: introduce an artificial bug by removing the `callout_drain` call from `mynet_destroy`. Rebuild, load, create an 接口, and unload. Observe what happens (it is usually a panic, and it is a dramatic way to learn why `callout_drain` exists). -9. Restore the `callout_drain` call. +1. 创建三个接口:`mynet create` 三次。 +2. 为每个接口配置 `192.0.2.0/24` 中的不同 IP(例如 `192.0.2.1/24`、`192.0.2.2/24`、`192.0.2.3/24`)。 +3. `vmstat -m | grep mynet` 并记录分配计数。 +4. `kldunload mynet`(不要先销毁)。 +5. `ifconfig -a` 并确认 `mynet0`、`mynet1`、`mynet2` 都不存在了。 +6. `vmstat -m | grep mynet` 并确认 `InUse` 返回零。 +7. 按顺序重复步骤 1 到 6 五次。每轮应使 `InUse` 为零且不应留下任何孤立状态。 +8. 可选:通过从 `mynet_destroy` 中移除 `callout_drain` 调用来引入人工 bug。重新构建、加载、创建接口并卸载。观察会发生什么(通常是崩溃,这是了解 `callout_drain` 为什么存在的戏剧性方式)。 +9. 恢复 `callout_drain` 调用。 -**What to watch for.** The cloner 分离 path should iterate over all three 接口, call `mynet_clone_destroy` on each, and free all memory. If any 接口 remains, or if `InUse` is non-zero, something in the teardown is broken. +**注意观察。** 克隆器分离路径应遍历所有三个接口,在每个上调用 `mynet_clone_destroy`,并释放所有内存。如果任何接口残留,或 `InUse` 非零,说明拆卸中的某些部分有错误。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record the `InUse` values before and after each round of load-create-unload. -* Note the `Requests` column in `vmstat -m | grep mynet`; it should climb monotonically because it records lifetime allocations. -* Record any unexpected messages in `dmesg`. +* 记录每轮加载-创建-卸载前后的 `InUse` 值。 +* 注意 `vmstat -m | grep mynet` 中的 `Requests` 列;它应单调递增,因为它记录了生命周期分配。 +* 记录 `dmesg` 中任何意外消息。 -**If things go wrong.** If `kldunload` hangs, a callout or a taskqueue task is still running. Use `ps -auxw` to find the 内核 thread and `procstat -k ` to see its backtrace. If `InUse` stays above zero after unload, you have a memory leak; the usual suspect is that `mynet_destroy` is not being called on one of the 接口, which means `if_clone_分离` did not find it. +**如果出现问题。** 如果 `kldunload` 挂起,一个 callout 或 taskqueue 任务仍在运行。使用 `ps -auxw` 找到内核线程并使用 `procstat -k ` 查看其栈跟踪。如果卸载后 `InUse` 保持非零,你有内存泄漏;通常的嫌疑是某个接口没有被调用 `mynet_destroy`,这意味着 `if_clone_detach` 没有找到它。 -### Lab 7: Reading the Real Tree +### 实验7:阅读真实源码树 -**Goal.** Connect what you have built to what lives in `/usr/src/sys/net/`. +**目标。** 将你构建的内容与 `/usr/src/sys/net/` 中的内容联系起来。 -**Steps.** +**步骤。** -1. Open `/usr/src/sys/net/if_disc.c` side by side with your `mynet.c`. For each of the following, locate the corresponding code in both files: - * Cloner registration. - * Softc allocation. - * Interface type (`IFT_LOOP` vs `IFT_ETHER`). - * BPF 附加. - * Transmit path. - * Ioctl handling. - * Cloner destroy. -2. Open `/usr/src/sys/net/if_epair.c` and do the same exercise. Note the use of `if_clone_advanced`, the pairing logic, and the use of `ifmedia_init`. -3. Open `/usr/src/sys/net/if_ethersubr.c` and locate `ether_if附加`. Trace through it line by line, and cross-reference each line with what we said it does in Section 3. -4. Open `/usr/src/sys/net/bpf.c` and locate `bpf_mtap_if`, which is the function `BPF_MTAP` expands to. Note the fast-path check for active peers. +1. 将 `/usr/src/sys/net/if_disc.c` 和你的 `mynet.c` 并排打开。对于以下每一项,在两个文件中找到对应的代码: + * 克隆器注册。 + * softc 分配。 + * 接口类型(`IFT_LOOP` vs `IFT_ETHER`)。 + * BPF 附加。 + * 发送路径。 + * ioctl 处理。 + * 克隆器销毁。 +2. 打开 `/usr/src/sys/net/if_epair.c` 并做同样的练习。注意 `if_clone_advanced` 的使用、配对逻辑和 `ifmedia_init` 的使用。 +3. 打开 `/usr/src/sys/net/if_ethersubr.c` 并找到 `ether_ifattach`。逐行追踪,并将每一行与我们在第 3 节中说的它做什么进行交叉参考。 +4. 打开 `/usr/src/sys/net/bpf.c` 并找到 `bpf_mtap_if`,这是 `BPF_MTAP` 展开后的函数。注意活跃对等体的快速路径检查。 -**What to watch for.** The goal of this lab is recognition, not comprehension. You do not need to understand every line of `epair(4)` or `ether_if附加`. You just need to see that the same patterns we used in our 驱动程序 appear in the real tree, and that the new code you might encounter elsewhere is a variation on themes you already know. +**注意观察。** 这个实验的目标是识别,不是理解。你不需要理解 `epair(4)` 或 `ether_ifattach` 的每一行。你只需要看到我们在驱动程序中使用的相同模式出现在真正的源代码树中,你可能遇到的新代码是你已经知道的主题的变体。 -**Logbook checkpoint.** +**实验日志检查点。** -* Record one function name from each of `if_disc.c`, `if_epair.c`, and `if_ethersubr.c` that you now understand well enough to explain aloud. -* Note any pattern in these files that surprised you or that contradicted an assumption you had built from our chapter. +* 从 `if_disc.c`、`if_epair.c` 和 `if_ethersubr.c` 中各记录一个你现在能理解到足以口头解释的函数名。 +* 注意这些文件中任何让你惊讶或与你从本章建立假设相矛盾的模式。 ## 挑战练习 -The challenges below extend the 驱动程序 in small, self-contained directions. Each one is meant to be doable in one or two focused sessions and relies only on what the chapter has taught. +下面的挑战以小型、自包含的方向扩展驱动程序。每个都设计为一到两个集中注意力的会话内可完成,并且只依赖本章已教授的内容。 -### Challenge 1: Shared Queue Between Paired Interfaces +### 挑战1:成对接口之间的共享队列 -**Brief.** Modify `mynet` so that creating two paired 接口 (`mynet0a` and `mynet0b`) behaves like `epair(4)`: transmitting on one 接口 causes the 帧 to appear on the other. +**简要说明。** 修改 `mynet`,使创建两个成对接口(`mynet0a` 和 `mynet0b`)的行为像 `epair(4)`:在一个接口上发送会导致帧出现在另一个接口上。 -**Hints.** Use `if_clone_advanced` with a match function, as `epair.c` does. Share a queue between the two softc structures. Use a callout or a taskqueue to dequeue on the other side and call `if_input`. +**提示。** 使用带有匹配函数的 `if_clone_advanced`,像 `epair.c` 那样。在两个 softc 结构之间共享一个队列。使用 callout 或 taskqueue 在另一端出队并调用 `if_input`。 -**Expected result.** When you `ping` an IP assigned to `mynet0a` from an IP assigned to `mynet0b`, the replies should actually come back. You have built a software simulation of two cables plugged into each other. +**预期结果。** 当你从分配给 `mynet0b` 的 IP ping 分配给 `mynet0a` 的 IP 时,回复应该真的能回来。你已经构建了两个线缆互相插入的软件模拟。 -**Key design questions.** Where do you store the shared queue? How do you ensure that a 数据包 sent on one side cannot be seen by the original sender (the `IFF_SIMPLEX` contract)? How do you handle the case where only one side of the pair is up? +**关键设计问题。** 你在哪里存储共享队列?你如何确保在一侧发送的数据包不能被原始发送者看到(`IFF_SIMPLEX` 契约)?你如何处理只有一对中的一侧启动的情况? -**Suggested structure.** Add a `struct mynet_pair` that owns two softcs, and have each softc carry a pointer to the pair. The transmit function on side A enqueues the mbuf on side B's input queue and schedules a taskqueue. The taskqueue dequeues and calls `if_input` on side B. Use a 互斥锁 in the pair structure to protect the queue. +**建议结构。** 添加一个拥有两个 softc 的 `struct mynet_pair`,让每个 softc 携带一个指向 pair 的指针。A 侧的发送函数将 mbuf 入队到 B 侧的输入队列并调度一个 taskqueue。taskqueue 出队并在 B 侧调用 `if_input`。在 pair 结构中使用互斥锁保护队列。 -### Challenge 2: Link Flap Simulation +### 挑战2:链路翻转模拟 -**Brief.** Add a sysctl `net.mynet.flap_interval` that, when non-zero, causes the 驱动程序 to flap the link up and down every `flap_interval` seconds. +**简要说明。** 添加一个 sysctl `net.mynet.flap_interval`,当非零时,使驱动程序每隔 `flap_interval` 秒翻转链路的上下状态。 -**Hints.** Use a callout that calls `if_link_state_change` alternately with `LINK_STATE_UP` and `LINK_STATE_DOWN`. Observe the effect on `route monitor`. +**提示。** 使用一个 callout,交替调用 `if_link_state_change` 和 `LINK_STATE_UP` 和 `LINK_STATE_DOWN`。观察对 `route monitor` 的影响。 -**Expected result.** While flapping is enabled, `ifconfig mynet0` should alternate between `status: active` and `status: no carrier` at the chosen interval. `route monitor` should print `RTM_IFINFO` messages at each transition. +**预期结果。** 启用翻转时,`ifconfig mynet0` 应在选定间隔交替显示 `status: active` 和 `status: no carrier`。`route monitor` 应在每个转换时打印 `RTM_IFINFO` 消息。 -**Extension.** Make the flap interval per-接口 rather than global. You can do this by creating a sysctl node per 接口 under `net.mynet.`, which requires using `sysctl_add_oid` and similar dynamic-sysctl APIs. +**扩展。** 使翻转间隔为每接口而非全局。你可以通过在 `net.mynet.` 下为每个接口创建 sysctl 节点来实现,这需要使用 `sysctl_add_oid` 和类似的动态 sysctl API。 -### Challenge 3: Error Injection +### 挑战3:错误注入 -**Brief.** Add a sysctl `net.mynet.drop_rate` that sets a percentage of outbound 帧 to be dropped with an error. +**简要说明。** 添加一个 sysctl `net.mynet.drop_rate`,设置出站帧被以错误丢弃的百分比。 -**Hints.** In `mynet_transmit`, roll a random number via `arc4random`. If it falls below the configured percentage, increment `IFCOUNTER_OERRORS`, free the mbuf, and return. Otherwise continue as before. +**提示。** 在 `mynet_transmit` 中,通过 `arc4random` 生成一个随机数。如果它低于配置的百分比,递增 `IFCOUNTER_OERRORS`,释放 mbuf 并返回。否则像以前一样继续。 -**Expected result.** With `drop_rate` set to 50, `ping` should show roughly 50% 数据包 loss instead of 100%. (Remember, the "100% loss" without drop_rate came from no reply ever returning, not from a transmit drop. So with drop_rate=50 you still get 100% ping loss; but if you combine this challenge with Challenge 1's pair, the combined behaviour should be 50% ping loss.) +**预期结果。** `drop_rate` 设置为 50 时,`ping` 应显示大约 50% 的丢包率而不是 100%。(记住,没有 drop_rate 时的"100% 丢包"是因为没有回复返回,不是因为发送丢弃。所以设置 drop_rate=50 你仍然得到 100% ping 丢包;但如果你将此挑战与挑战 1 的成对接口组合,组合行为应该是 50% ping 丢包。) -**Extension.** Add a separate `rx_drop_rate` that drops synthesised receive 帧. Observe how the receive-counter output differs between transmit and receive drops. +**扩展。** 添加一个单独的 `rx_drop_rate` 来丢弃合成接收帧。观察接收计数器输出在发送丢弃和接收丢弃之间的区别。 -### Challenge 4: iperf3 Stress +### 挑战4:iperf3 压力测试 -**Brief.** Use `iperf3` to stress the transmit path and measure how quickly the 驱动程序 can process 帧. +**简要说明。** 使用 `iperf3` 压力测试发送路径并测量驱动程序处理帧的速度。 -**Hints.** Run `iperf3 -c 192.0.2.99 -t 10 -u -b 1G` to generate a UDP flood. Observe `netstat -in -I mynet0` before and after. Observe `vmstat 1` for system load. Consider what you would need to change in the 驱动程序 to support higher rates: per-CPU counters, lock-free transmit paths, taskqueue-based deferred processing. +**提示。** 运行 `iperf3 -c 192.0.2.99 -t 10 -u -b 1G` 来生成 UDP 洪水。观察前后的 `netstat -in -I mynet0`。观察 `vmstat 1` 的系统负载。考虑你需要改变驱动程序中的什么来支持更高速率:每 CPU 计数器、无锁发送路径、基于 taskqueue 的延迟处理。 -**Expected result.** The iperf3 run will not produce meaningful bandwidth numbers (because there is no server to acknowledge anything), but it will push `Opkts` up rapidly. Watch for any CPU hotspot on the transmit path. If you have combined this with Challenge 1, the paired 接口 setup should show 数据包 crossing the simulated link. +**预期结果。** iperf3 运行不会产生有意义的带宽数字(因为没有服务器确认任何东西),但它会快速推高 `Opkts`。注意发送路径上的任何 CPU 热点。如果你已经与挑战 1 组合,成对接口设置应显示数据包穿过模拟链路。 -**Measurement tips.** Use `pmcstat` or `dtrace` to profile where time is spent. The transmit path is a reasonable place to look for lock contention. If you see a high rate of `mtx_lock` on the softc 互斥锁 in `mynet_transmit`, that is a sign that you are contending on a lock that real 驱动程序 would split per-queue. +**测量技巧。** 使用 `pmcstat` 或 `dtrace` 来分析时间花在哪里。发送路径是查找锁竞争的合理位置。如果你在 `mynet_transmit` 中看到 softc 互斥锁上的 `mtx_lock` 高速率,那是你在争用一个真正驱动程序会按队列拆分的锁的迹象。 -### Challenge 5: Per-Interface sysctl Tree +### 挑战5:每接口 sysctl 树 -**Brief.** Expose per-接口 runtime controls and statistics under `net.mynet.mynet0.*`. +**简要说明。** 在 `net.mynet.mynet0.*` 下暴露每接口的运行时控制和统计信息。 -**Hints.** Use `sysctl_add_oid` to dynamically add per-接口 sysctls when the 接口 is created, and remove them when the 接口 is destroyed. A common pattern is to create a per-instance context under a static root node, and to 附加 child leaves for the specific controls and stats. +**提示。** 使用 `sysctl_add_oid` 在接口创建时动态添加每接口 sysctl,在接口销毁时移除它们。一个常见的模式是在静态根节点下创建每实例上下文,并为特定控制和统计信息附加子叶子节点。 -**Expected result.** `sysctl net.mynet.mynet0.rx_interval_hz` should read and write the receive interval, overriding the compile-time default. `sysctl net.mynet.mynet0.rx_数据包_generated` should read a counter that increments every time the synthetic receive timer fires. +**预期结果。** `sysctl net.mynet.mynet0.rx_interval_hz` 应该能读写接收间隔,覆盖编译时默认值。`sysctl net.mynet.mynet0.rx_packets_generated` 应该能读取一个每次合成接收定时器触发时递增的计数器。 -**Extension.** Add an `rx_enabled` sysctl that pauses and resumes the synthetic receive timer. Verify the behaviour by watching `tcpdump` while toggling the sysctl. +**扩展。** 添加一个 `rx_enabled` sysctl 来暂停和恢复合成接收定时器。通过在切换 sysctl 的同时观察 `tcpdump` 来验证行为。 -### Challenge 6: Netgraph Node +### 挑战6:Netgraph 节点 -**Brief.** Expose `mynet` as a netgraph node so that it can be wired into the netgraph 框架. +**简要说明。** 将 `mynet` 暴露为 netgraph 节点,以便可以将其接入 netgraph 框架。 -**Hints.** This is a longer challenge because it requires familiarity with `netgraph(4)`. Read `/usr/src/sys/netgraph/ng_ether.c` for a reference example of an 接口 exposed as a netgraph node. Add a single hook that provides 数据包 interception before or after our `if_transmit` and `if_input`. +**提示。** 这是一个较长的挑战,因为它需要熟悉 `netgraph(4)`。阅读 `/usr/src/sys/netgraph/ng_ether.c` 作为接口暴露为 netgraph 节点的参考示例。添加一个单一钩子,在我们的 `if_transmit` 和 `if_input` 之前或之后提供数据包拦截。 -**Expected result.** After the netgraph node is present, you should be able to use `ngctl` to 附加 a filter or a redirection node and watch 数据包 flow through the netgraph chain. +**预期结果。** netgraph 节点存在后,你应该能够使用 `ngctl` 附加一个过滤器或重定向节点,并观察数据包通过 netgraph 链流动。 -This challenge is the most open-ended of the set. If you reach a working skeleton, you have essentially completed the path from "hello world" 驱动程序 to a 驱动程序 that participates fully in FreeBSD's advanced networking infrastructure. +此挑战是所有挑战中最开放的。如果你达到一个可用的骨架,你本质上已经完成了从"hello world"驱动程序到完全参与 FreeBSD 高级网络基础设施的驱动程序的路径。 -## Troubleshooting and 常见错误 +## 故障排除和常见错误 -Network 驱动程序 fail in a handful of characteristic ways. Learn to spot them and you save hours of debugging. +网络驱动程序以少数几种特征方式失败。学会识别它们可以节省数小时的调试时间。 -### Symptom: `ifconfig mynet create` Returns "Operation not supported" +### 症状:`ifconfig mynet create` 返回 "Operation not supported" -**Likely cause.** The cloner is not 注册ed, or the cloner name does not match. Check that `V_mynet_cloner` is initialised in `vnet_mynet_init`, and that the `mynet_name` string is the one the user is typing. +**可能原因。** 克隆器未注册,或克隆器名称不匹配。检查 `V_mynet_cloner` 是否在 `vnet_mynet_init` 中初始化,以及 `mynet_name` 字符串是否是用户正在输入的。 -**Diagnostic.** `sysctl net.generic.ifclone` lists all 注册ed cloners. If `mynet` is absent, the registration did not happen. +**诊断。** `sysctl net.generic.ifclone` 列出所有已注册的克隆器。如果 `mynet` 缺失,说明注册没有发生。 -### Symptom: `ifconfig mynet0 up` Hangs or Panics +### 症状:`ifconfig mynet0 up` 挂起或崩溃 -**Likely cause.** The `mynet_init` function is doing something that sleeps while holding the softc 互斥锁, or is calling up into the stack with the 互斥锁 held. +**可能原因。** `mynet_init` 函数在持有 softc 互斥锁时做了会睡眠的操作,或者在持有互斥锁的情况下向上调用了协议栈。 -**Diagnostic.** If the system hangs, enter the debugger (`Ctrl-Alt-Esc` in a console) and type `ps` to see which thread is stuck, then `trace TID` to get a backtrace. Look for the offending lock acquisition. +**诊断。** 如果系统挂起,进入调试器(控制台中按 `Ctrl-Alt-Esc`)并输入 `ps` 查看哪个线程卡住了,然后 `trace TID` 获取栈跟踪。寻找有问题的锁获取。 -### Symptom: `tcpdump -i mynet0` Sees No Packets +### 症状:`tcpdump -i mynet0` 看不到任何数据包 -**Likely cause.** `BPF_MTAP` is not being called, or `bpf附加` was not called during 接口 setup. +**可能原因。** `BPF_MTAP` 没有被调用,或者接口设置期间没有调用 `bpfattach`。 -**Diagnostic.** `bpf_peers_present(ifp->if_bpf)` should return true when `tcpdump` is running. If it does not, check that `ether_if附加` was called. If `ether_if附加` was called but `BPF_MTAP` is not in the data path, add the call in both transmit and receive. +**诊断。** `bpf_peers_present(ifp->if_bpf)` 在 `tcpdump` 运行时应返回 true。如果不是,检查是否调用了 `ether_ifattach`。如果 `ether_ifattach` 已调用但数据路径中没有 `BPF_MTAP`,在发送和接收中都添加该调用。 -### Symptom: `ping` Shows 100% Loss (Expected) but `Opkts` Stays Zero +### 症状:`ping` 显示 100% 丢包(预期)但 `Opkts` 保持为零 -**Likely cause.** `if_transmit` is not being called, or it is returning early without incrementing counters. +**可能原因。** `if_transmit` 没有被调用,或者它提前返回而没有递增计数器。 -**Diagnostic.** `dtrace -n 'fbt::mynet_transmit:entry { @[探测func] = count(); }'` counts how often the function is called. If it is zero, the stack is not dispatching to us, and the assignment to `ifp->if_transmit` (or, if you switched to the helper, the `if_settransmitfn` call) during setup is suspect. +**诊断。** `dtrace -n 'fbt::mynet_transmit:entry { @[probefunc] = count(); }'` 统计函数被调用的频率。如果为零,协议栈没有向我们分派,设置期间对 `ifp->if_transmit` 的赋值(或如果你切换到辅助函数,`if_settransmitfn` 调用)有问题。 -### Symptom: `kldunload` Panics with "destroying locked 互斥锁" +### 症状:`kldunload` 因 "destroying locked mutex" 崩溃 -**Likely cause.** The 互斥锁 is being destroyed while another thread (typically a callout) still holds it. +**可能原因。** 互斥锁在另一个线程(通常是 callout)仍持有它时被销毁。 -**Diagnostic.** Audit the teardown order. `callout_drain` must be called before `mtx_destroy`. `ether_if分离` must be called before `if_free`. If the callout locks the softc 互斥锁, `callout_drain` must happen before that 互斥锁 goes away. +**诊断。** 审查拆卸顺序。`callout_drain` 必须在 `mtx_destroy` 之前调用。`ether_ifdetach` 必须在 `if_free` 之前调用。如果 callout 锁定了 softc 互斥锁,`callout_drain` 必须在该互斥锁消失之前发生。 -### Symptom: `netstat -in -I mynet0` Shows `Opkts` Higher Than `Opkts` in `systat -if` +### 症状:`netstat -in -I mynet0` 的 `Opkts` 高于 `systat -if` 中的 `Opkts` -**Likely cause.** One of the counters is being incremented twice in the transmit path. +**可能原因。** 发送路径中某个计数器被递增了两次。 -**Diagnostic.** Inspect the code paths. A common mistake is to increment `IFCOUNTER_OPACKETS` both in the 驱动程序 and in a helper function. +**诊断。** 检查代码路径。一个常见错误是在驱动程序和辅助函数中都递增了 `IFCOUNTER_OPACKETS`。 -### Symptom: Module Loads But `ifconfig mynet create` Produces a Kernel Warning +### 症状:模块加载但 `ifconfig mynet create` 产生内核警告 -**Likely cause.** A field of the `ifnet` is not properly initialised, or `ether_if附加` is called without a valid MAC address. +**可能原因。** `ifnet` 的某个字段未正确初始化,或在没有有效 MAC 地址的情况下调用了 `ether_ifattach`。 -**Diagnostic.** Run `dmesg` after the warning. The 内核 usually prints enough context to identify the offending field. +**诊断。** 警告后运行 `dmesg`。内核通常会打印足够的上下文来识别有问题的字段。 -### Symptom: `kldunload` Returns But `ifconfig -a` Still Shows `mynet0` +### 症状:`kldunload` 返回但 `ifconfig -a` 仍显示 `mynet0` -**Likely cause.** The cloner 分离 did not iterate all 接口. This is usually a sign that the 接口 was created outside the cloner path, or that the `if_clone` data structures are out of sync. +**可能原因。** 克隆器分离没有遍历所有接口。这通常是接口在克隆器路径之外创建的迹象,或 `if_clone` 数据结构不同步。 -**Diagnostic.** `sysctl net.generic.ifclone` after the unload should not list `mynet`. If it does, `if_clone_分离` did not complete. +**诊断。** 卸载后 `sysctl net.generic.ifclone` 不应列出 `mynet`。如果列出了,说明 `if_clone_detach` 没有完成。 -### Symptom: Intermittent Panics Under `iperf3` Load +### 症状:`iperf3` 负载下间歇性崩溃 -**Likely cause.** A race between the transmit path and the ioctl path, typically one not locking when the other does. +**可能原因。** 发送路径和 ioctl 路径之间的竞争,通常是一个路径加锁而另一个没有。 -**Diagnostic.** Run the 内核 with `INVARIANTS` and `WITNESS` enabled. These options add lock-order and assertion checks that catch most races immediately. They are the single best development tool for 网络驱动程序. +**诊断。** 使用启用 `INVARIANTS` 和 `WITNESS` 的内核运行。这些选项添加锁序和断言检查,能立即捕获大多数竞争。它们是网络驱动程序开发的最佳工具。 -### Symptom: `ifconfig mynet0 mtu 9000` Succeeds But Jumbo Frames Fail +### 症状:`ifconfig mynet0 mtu 9000` 成功但巨型帧失败 -**Likely cause.** The 驱动程序 advertises an MTU range it cannot actually transport. Our reference 驱动程序 uses a wide range for simplicity, but a real 驱动程序 has a hard upper limit dictated by hardware. +**可能原因。** 驱动程序声明了它实际无法传输的 MTU 范围。我们的参考驱动程序为了简单使用宽范围,但真正的驱动程序有硬件决定的硬上限。 -**Diagnostic.** Send a 帧 larger than the configured MTU and observe that `IFCOUNTER_OERRORS` increments. Align the advertised upper bound with the actual capability. +**诊断。** 发送一个大于配置 MTU 的帧并观察 `IFCOUNTER_OERRORS` 递增。将声明的上限与实际能力对齐。 -### Symptom: `dmesg` Shows "acquiring a destroyed 互斥锁" +### 症状:`dmesg` 显示 "acquiring a destroyed mutex" -**Likely cause.** A callout, taskqueue task, or 中断处理程序 is acquiring a 互斥锁 after `mtx_destroy` has been called. Almost always caused by incorrect teardown ordering. +**可能原因。** callout、taskqueue 任务或中断处理程序在 `mtx_destroy` 被调用后获取互斥锁。几乎总是由不正确的拆卸顺序导致。 -**Diagnostic.** Trace through your `mynet_destroy`. `callout_drain` and equivalent drain operations must happen before `mtx_destroy`. The correct order is "quiesce, 分离, destroy", not "destroy, quiesce". +**诊断。** 追踪你的 `mynet_destroy`。`callout_drain` 及等价的排空操作必须在 `mtx_destroy` 之前发生。正确的顺序是「停止、分离、销毁」,而不是「销毁、停止」。 -### Symptom: `WITNESS` Reports a Lock-Order Reversal +### 症状:`WITNESS` 报告锁序反转 -**Likely cause.** Two threads acquire the same pair of locks in opposite orders. In a 网络驱动程序 this most commonly happens between the softc 互斥锁 and a stack-internal lock like the ARP table lock or the routing table lock. +**可能原因。** 两个线程以相反的顺序获取同一对锁。在网络驱动程序中,这最常发生在 softc 互斥锁和协议栈内部锁(如 ARP 表锁或路由表锁)之间。 -**Diagnostic.** Read the `WITNESS` output carefully; it shows both backtraces. The fix is usually to release the 驱动程序 互斥锁 before calling into the stack (for example, before `if_input` or `if_link_state_change`), which we recommend throughout this chapter. +**诊断。** 仔细阅读 `WITNESS` 输出;它显示两个栈跟踪。修复通常是在调用协议栈之前释放驱动互斥锁(例如,在 `if_input` 或 `if_link_state_change` 之前),我们在本章中一直建议这样做。 -### Symptom: Packet Loss Under Moderate Load +### 症状:中等负载下丢包 -**Likely cause.** Either mbuf exhaustion (check `vmstat -z | grep mbuf`) or a transmit queue that has no backpressure and silently drops. +**可能原因。** mbuf 耗尽(检查 `vmstat -z | grep mbuf`)或发送队列没有背压并静默丢弃。 -**Diagnostic.** `vmstat -z | grep mbuf` before and after the load. If `mbuf` or `mbuf_cluster` allocations are climbing but not being returned, you have a mbuf leak. If they are being returned but your 驱动程序's internal queue is dropping, you need to either enlarge the queue or implement backpressure. +**诊断。** 负载前后的 `vmstat -z | grep mbuf`。如果 `mbuf` 或 `mbuf_cluster` 分配在攀升但不被归还,你有 mbuf 泄漏。如果它们被归还但驱动程序内部队列在丢弃,你需要扩大队列或实现背压。 -### Symptom: `ifconfig mynet0 inet6 2001:db8::1/64` Has No Effect +### 症状:`ifconfig mynet0 inet6 2001:db8::1/64` 没有效果 -**Likely cause.** IPv6 is not compiled into your 内核, or the 接口 does not advertise `IFF_MULTICAST` (which IPv6 requires). +**可能原因。** IPv6 未编译进你的内核,或接口没有声明 `IFF_MULTICAST`(IPv6 需要它)。 -**Diagnostic.** `sysctl net.inet6.ip6.v6only` and similar tell you whether IPv6 is present. `ifconfig mynet0` shows the flags; ensure `MULTICAST` is one of them. +**诊断。** `sysctl net.inet6.ip6.v6only` 及类似命令告诉你 IPv6 是否存在。`ifconfig mynet0` 显示标志;确保 `MULTICAST` 是其中之一。 -### Symptom: Module Loads But `ifconfig mynet create` Produces No Interface and No Error +### 症状:模块加载但 `ifconfig mynet create` 不产生接口也不报错 -**Likely cause.** The cloner's create function is returning success but never actually allocating an 接口. Easy to cause by returning 0 before calling `if_alloc`. +**可能原因。** 克隆器的创建函数返回成功但从未实际分配接口。很容易通过在调用 `if_alloc` 之前返回 0 来造成。 -**Diagnostic.** Add a `printf("mynet_clone_create called\n")` at the start of your create 回调. If the message appears but no 接口 is created, the bug is between the printf and the `if_附加` call. +**诊断。** 在创建回调开头添加 `printf("mynet_clone_create called\n")`。如果消息出现但没有创建接口,bug 在 printf 和 `if_attach` 调用之间。 -### Symptom: `sysctl net.link.generic` Returns Unexpected Results +### 症状:`sysctl net.link.generic` 返回意外结果 -**Likely cause.** The 驱动程序 has corrupted a field of `ifnet` that the generic sysctl handler reads. This is rare but indicative of deeper bugs. +**可能原因。** 驱动程序损坏了通用 sysctl 处理程序读取的 `ifnet` 字段。这很罕见但表明有更深的 bug。 -**Diagnostic.** Run the 内核 with `INVARIANTS` and look for assertion failures. The offending write is usually near where `ifnet` fields are being initialised. +**诊断。** 使用启用 `INVARIANTS` 的内核运行并查找断言失败。有问题的写入通常在 `ifnet` 字段被初始化的地方附近。 -## 快速参考 Tables +## 快速参考表 -The tables below summarise the most frequently-used APIs and constants introduced in this chapter. Keep the page open as you work through the labs. +下表总结了本章介绍的最常用 API 和常量。在实验过程中保持此页打开。 -### Lifecycle Functions +### 生命周期函数 | Function | Purpose | | --- | --- | | `if_alloc(type)` | Allocate a new `ifnet` of the given IFT_ type. | -| `if_free(ifp)` | Free an `ifnet` after 分离. | -| `if_附加(ifp)` | Register the 接口 with the stack. | -| `if_分离(ifp)` | Un注册 the 接口. | -| `ether_if附加(ifp, mac)` | Register an 以太网-like 接口. Wraps `if_附加` plus `bpf附加` and sets 以太网 defaults. | -| `ether_if分离(ifp)` | Undo `ether_if附加`. | -| `if_initname(ifp, family, unit)` | Set the 接口 name. | -| `bpf附加(ifp, dlt, hdrlen)` | Register with BPF manually. Done automatically by `ether_if附加`. | -| `bpf分离(ifp)` | Un注册 from BPF. Done automatically by `ether_if分离`. | +| `if_free(ifp)` | Free an `ifnet` after detach. | +| `if_attach(ifp)` | Register the interface with the stack. | +| `if_detach(ifp)` | Unregister the interface. | +| `ether_ifattach(ifp, mac)` | Register an Ethernet-like interface. Wraps `if_attach` plus `bpfattach` and sets Ethernet defaults. | +| `ether_ifdetach(ifp)` | Undo `ether_ifattach`. | +| `if_initname(ifp, family, unit)` | Set the interface name. | +| `bpfattach(ifp, dlt, hdrlen)` | Register with BPF manually. Done automatically by `ether_ifattach`. | +| `bpfdetach(ifp)` | Unregister from BPF. Done automatically by `ether_ifdetach`. | | `if_clone_simple(name, create, destroy, minifs)` | Register a simple cloner. | | `if_clone_advanced(name, minifs, match, create, destroy)` | Register a cloner with a custom match function. | -| `if_clone_分离(cloner)` | Tear down a cloner and all its 接口. | -| `callout_init_mtx(co, mtx, flags)` | Initialise a callout associated with a 互斥锁. | +| `if_clone_detach(cloner)` | Tear down a cloner and all its interfaces. | +| `callout_init_mtx(co, mtx, flags)` | Initialise a callout associated with a mutex. | | `callout_reset(co, ticks, fn, arg)` | Schedule or rearm a callout. | | `callout_stop(co)` | Cancel a callout. | | `callout_drain(co)` | Synchronously wait for a callout to finish. | -| `ifmedia_init(ifm, mask, change, status)` | Initialise a media 描述符. | +| `ifmedia_init(ifm, mask, change, status)` | Initialise a media descriptor. | | `ifmedia_add(ifm, word, data, aux)` | Add a supported media entry. | | `ifmedia_set(ifm, word)` | Choose the default media. | | `ifmedia_ioctl(ifp, ifr, ifm, cmd)` | Handle `SIOCGIFMEDIA` and `SIOCSIFMEDIA`. | | `ifmedia_removeall(ifm)` | Free all media entries on teardown. | -### Data-Path Functions +### 数据路径函数 | Function | Purpose | | --- | --- | -| `if_transmit(ifp, m)` | The 驱动程序's outbound 回调. | +| `if_transmit(ifp, m)` | The driver's outbound callback. | | `if_input(ifp, m)` | Deliver a mbuf to the stack. | -| `if_qflush(ifp)` | Flush any 驱动程序-internal queues. | -| `BPF_MTAP(ifp, m)` | Tap a 帧 to BPF if any observers. | +| `if_qflush(ifp)` | Flush any driver-internal queues. | +| `BPF_MTAP(ifp, m)` | Tap a frame to BPF if any observers. | | `bpf_mtap2(bpf, data, dlen, m)` | Tap with a prepended header. | | `m_freem(m)` | Free an entire mbuf chain. | | `m_free(m)` | Free a single mbuf. | -| `MGETHDR(m, how, type)` | Allocate a mbuf as the head of a 数据包. | +| `MGETHDR(m, how, type)` | Allocate a mbuf as the head of a packet. | | `MGET(m, how, type)` | Allocate a mbuf as a chain continuation. | | `m_gethdr(how, type)` | Alternative form of MGETHDR. | | `m_pullup(m, len)` | Ensure the first len bytes are contiguous. | | `m_copydata(m, off, len, buf)` | Read bytes from a chain without consuming it. | | `m_defrag(m, how)` | Flatten a chain into a single mbuf. | | `mtod(m, type)` | Cast `m_data` to the requested type. | -| `if_inc_counter(ifp, ctr, n)` | Increment a per-接口 counter. | +| `if_inc_counter(ifp, ctr, n)` | Increment a per-interface counter. | | `if_link_state_change(ifp, state)` | Report a link transition. | -### Common `IFF_` Flags +### 常用 `IFF_` 标志 | Flag | Meaning | | --- | --- | | `IFF_UP` | Administratively up. User-controlled. | | `IFF_BROADCAST` | Supports broadcast. | | `IFF_DEBUG` | Debug tracing requested. | -| `IFF_LOOPBACK` | Loopback 接口. | +| `IFF_LOOPBACK` | Loopback interface. | | `IFF_POINTOPOINT` | Point-to-point link. | | `IFF_RUNNING` | Alias for `IFF_DRV_RUNNING`. | | `IFF_NOARP` | ARP disabled. | @@ -2812,7 +2811,7 @@ The tables below summarise the most frequently-used APIs and constants introduce | `IFF_DRV_RUNNING` | Driver-private: resources allocated. | | `IFF_DRV_OACTIVE` | Driver-private: transmit queue full. | -### Common `IFCAP_` Capabilities +### 常用 `IFCAP_` 能力 | Capability | Meaning | | --- | --- | @@ -2825,14 +2824,14 @@ The tables below summarise the most frequently-used APIs and constants introduce | `IFCAP_LRO` | Large receive offload. | | `IFCAP_VLAN_HWTAGGING` | Hardware VLAN tagging. | | `IFCAP_VLAN_MTU` | VLAN over standard MTU. | -| `IFCAP_JUMBO_MTU` | Jumbo 帧 supported. | +| `IFCAP_JUMBO_MTU` | Jumbo frames supported. | | `IFCAP_POLLING` | Polled rather than interrupt-driven. | -| `IFCAP_WOL_MAGIC` | Wake-on-LAN magic 数据包. | +| `IFCAP_WOL_MAGIC` | Wake-on-LAN magic packet. | | `IFCAP_NETMAP` | `netmap(4)` support. | | `IFCAP_TOE` | TCP offload engine. | | `IFCAP_LINKSTATE` | Hardware link-state events. | -### Common `IFCOUNTER_` Counters +### 常用 `IFCOUNTER_` 计数器 | Counter | Meaning | | --- | --- | @@ -2840,20 +2839,20 @@ The tables below summarise the most frequently-used APIs and constants introduce | `IFCOUNTER_IERRORS` | Receive errors. | | `IFCOUNTER_OPACKETS` | Packets transmitted. | | `IFCOUNTER_OERRORS` | Transmit errors. | -| `IFCOUNTER_COLLISIONS` | Collisions (以太网). | +| `IFCOUNTER_COLLISIONS` | Collisions (Ethernet). | | `IFCOUNTER_IBYTES` | Bytes received. | | `IFCOUNTER_OBYTES` | Bytes transmitted. | -| `IFCOUNTER_IMCASTS` | Multicast 数据包 received. | -| `IFCOUNTER_OMCASTS` | Multicast 数据包 transmitted. | +| `IFCOUNTER_IMCASTS` | Multicast packets received. | +| `IFCOUNTER_OMCASTS` | Multicast packets transmitted. | | `IFCOUNTER_IQDROPS` | Receive queue drops. | | `IFCOUNTER_OQDROPS` | Transmit queue drops. | | `IFCOUNTER_NOPROTO` | Packets for unknown protocol. | -### Common Interface Ioctls +### 常用接口 ioctl | Ioctl | When issued | Driver responsibility | | --- | --- | --- | -| `SIOCSIFFLAGS` | `ifconfig up` / `down` | Bring the 驱动程序 up or down. | +| `SIOCSIFFLAGS` | `ifconfig up` / `down` | Bring the driver up or down. | | `SIOCSIFADDR` | `ifconfig inet 1.2.3.4` | Address assignment. Usually handled by `ether_ioctl`. | | `SIOCSIFMTU` | `ifconfig mtu N` | Validate and update `if_mtu`. | | `SIOCADDMULTI` | Multicast group joined | Reprogram hardware filter. | @@ -2861,270 +2860,270 @@ The tables below summarise the most frequently-used APIs and constants introduce | `SIOCGIFMEDIA` | `ifconfig` display | Return current media. | | `SIOCSIFMEDIA` | `ifconfig media X` | Reprogram PHY or equivalent. | | `SIOCSIFCAP` | `ifconfig ±offloads` | Toggle offloads. | -| `SIOCSIFNAME` | `ifconfig name X` | Rename the 接口. | +| `SIOCSIFNAME` | `ifconfig name X` | Rename the interface. | -## Reading Real Network Drivers +## 阅读真实的网络驱动程序 -One of the best ways to solidify your understanding is to read real 驱动程序 in the FreeBSD tree. This section walks you through a handful of 驱动程序 that illustrate important patterns, and it suggests a reading order that builds on what this chapter has taught you. You do not need to understand every line in these files. The goal is recognition: seeing the familiar bones of `ether_if附加`, `if_transmit`, `if_input`, `ifmedia_init`, and so on inside 驱动程序 of very different sizes and purposes. +巩固你理解的最佳方式之一是阅读 FreeBSD 源代码树中的真实驱动程序。本节引导你浏览几个说明重要模式的驱动程序,并建议一个建立在你所学内容之上的阅读顺序。你不需要理解这些文件中的每一行。目标是识别:在不同大小和用途的驱动程序内部看到 `ether_ifattach`、`if_transmit`、`if_input`、`ifmedia_init` 等熟悉的骨架。 -### Reading `/usr/src/sys/net/if_tuntap.c` +### 阅读 `/usr/src/sys/net/if_tuntap.c` -The `tun(4)` and `tap(4)` 驱动程序 are implemented together in this file. They give userland a file 描述符 through which 数据包 can flow in and out of the 内核. Reading `if_tuntap.c` shows you how a 驱动程序 can bridge the userland-character-设备 world of Chapter 14 with the network-stack world of this chapter. +`tun(4)` 和 `tap(4)` 驱动程序在此文件中一起实现。它们给用户态一个文件描述符,通过它数据包可以在内核内外流动。阅读 `if_tuntap.c` 向你展示驱动程序如何桥接第 14 章的用户态字符设备世界和本章的网络协议栈世界。 -Open the file and look for the following landmarks: +打开文件并寻找以下标志: -* The `cdevsw` declaration at the top, which is how userland opens `/dev/tun0` or `/dev/tap0`. -* The `tunstart` function, which moves 数据包 from the 内核 接口 queue to userland reads. -* The `tunwrite` function, which moves 数据包 from userland writes into the 内核 via `if_input`. -* The `tuncreate` function, which allocates an ifnet and 寄存器 it. +* 顶部的 `cdevsw` 声明,这是用户态打开 `/dev/tun0` 或 `/dev/tap0` 的方式。 +* `tunstart` 函数,将数据包从内核接口队列移动到用户态读取。 +* `tunwrite` 函数,将数据包从用户态写入通过 `if_input` 移入内核。 +* `tuncreate` 函数,分配 ifnet 并注册它。 -You will see `ether_if附加` for `tap` and plain `if_附加` for `tun`, because the two flavours differ in link-layer semantics: `tap` is an 以太网-looking tunnel, while `tun` is a pure IP tunnel without a link layer. This file is an excellent case study in how the choice of `ether_if附加` vs `if_附加` ripples through the rest of the 驱动程序. +你会看到 `tap` 使用 `ether_ifattach`,`tun` 使用普通的 `if_attach`,因为两种风格在链路层语义上不同:`tap` 是一个看起来像以太网的隧道,而 `tun` 是没有链路层的纯 IP 隧道。此文件是展示选择 `ether_ifattach` 还是 `if_attach` 如何波及驱动程序其余部分的绝佳案例研究。 -Notice that `tuntap` does not use an 接口 cloner in the same way `disc` does. It creates 接口 on-demand when userland opens `/dev/tapN`, which shows yet another way 接口 can be brought into being. This is a variant of the cloner pattern, rather than a departure from it. +注意 `tuntap` 没有像 `disc` 那样以相同方式使用接口克隆器。它在用户态打开 `/dev/tapN` 时按需创建接口,这展示了接口可以产生的又一种方式。这是克隆器模式的变体,而不是对它的偏离。 -### Reading `/usr/src/sys/net/if_bridge.c` +### 阅读 `/usr/src/sys/net/if_bridge.c` -The bridge 驱动程序 implements software 以太网 bridging between multiple 接口. It is a larger file (more than three thousand lines) but its core is the same: it creates an ifnet per bridge, receives 帧 from member 接口 via `if_input` hooks, looks up destinations in a MAC-address-to-port table, and forwards 帧 through `if_transmit` on the outbound port. +网桥驱动程序实现了多个接口之间的软件以太网桥接。它是一个更大的文件(超过三千行),但其核心是相同的:它为每个网桥创建一个 ifnet,通过 `if_input` 钩子从成员接口接收帧,在 MAC 地址到端口的表中查找目的地,并通过出站端口上的 `if_transmit` 转发帧。 -What makes `if_bridge.c` particularly instructive is that it is itself both a client and a provider of the `ifnet` 接口. It is a client because it transmits 帧 to member 接口. It is a provider because it exposes a bridge 接口 that other code can use. Reading it shows you how to write a 驱动程序 that is transparently layered on top of other 驱动程序. +`if_bridge.c` 特别有教益的地方在于它本身既是 `ifnet` 接口的客户端又是提供者。它是客户端,因为它向成员接口发送帧。它是提供者,因为它暴露了其他代码可以使用的网桥接口。阅读它向你展示了如何编写一个透明地分层在其他驱动程序之上的驱动程序。 -### Reading `/usr/src/sys/dev/e1000/if_em.c` +### 阅读 `/usr/src/sys/dev/e1000/if_em.c` -The `em(4)` 驱动程序 is the canonical example of a PCI 以太网 驱动程序 for Intel's e1000-class hardware. It is significantly larger than our pseudo-驱动程序 because it does everything real hardware requires: PCI 附加, 注册 programming, EEPROM reading, MSI-X allocation, ring-缓冲区 management, DMA, interrupt handling, and so on. +`em(4)` 驱动程序是 Intel e1000 级硬件的 PCI 以太网驱动程序的典型示例。它比我们的伪驱动程序大得多,因为它做了真正硬件所需的一切:PCI 附加、寄存器编程、EEPROM 读取、MSI-X 分配、环形缓冲区管理、DMA、中断处理等等。 -However, if you squint past the hardware-specific parts, you will see our familiar patterns everywhere: +然而,如果你眯起眼睛跳过硬件特定的部分,你会到处看到我们熟悉的模式: -* `em_if_附加_pre` allocates a softc. -* `em_if_附加_post` populates the ifnet. -* `em_if_init` is the `if_init` 回调. -* `em_if_ioctl` is the `if_ioctl` 回调. -* `em_if_tx` is the transmit 回调 (wrapped through iflib). -* `em_if_rx` is the receive 回调 (wrapped through iflib). -* `em_if_分离` is the 分离 function. +* `em_if_attach_pre` 分配 softc。 +* `em_if_attach_post` 填充 ifnet。 +* `em_if_init` 是 `if_init` 回调。 +* `em_if_ioctl` 是 `if_ioctl` 回调。 +* `em_if_tx` 是发送回调(通过 iflib 包装)。 +* `em_if_rx` 是接收回调(通过 iflib 包装)。 +* `em_if_detach` 是分离函数。 -The 驱动程序 uses `iflib(9)` rather than raw `ifnet` calls, but iflib is itself a thin layer over the same APIs we have been using. Reading `em` is a good way to see how a real 驱动程序 scales up from our small teaching example. +该驱动程序使用 `iflib(9)` 而不是原始 `ifnet` 调用,但 iflib 本身就是我们一直使用的相同 API 之上的薄层。阅读 `em` 是看到真正驱动程序如何从我们的小型教学示例扩展的好方法。 -Focus on the transmit function first. You will see 描述符-ring management, DMA mapping, TSO handling, and checksum offload decisions. The 挂载 of state is larger, but each decision has a clear purpose that maps to one of the concepts we discussed. +先关注发送函数。你会看到描述符环管理、DMA 映射、TSO 处理和校验和卸载决策。状态量更大,但每个决策都有明确的目的,映射到我们讨论过的某个概念。 -### Reading `/usr/src/sys/dev/virtio/network/if_vtnet.c` +### 阅读 `/usr/src/sys/dev/virtio/network/if_vtnet.c` -The `vtnet(4)` 驱动程序 is for VirtIO network adapters used by virtual machines. It is smaller than `em` but still larger than our pseudo-驱动程序. It uses `virtio(9)` as its transport rather than `总线_space(9)` plus DMA rings, which makes the code easier to follow if you are less familiar with PCI hardware. +`vtnet(4)` 驱动程序用于虚拟机使用的 VirtIO 网络适配器。它比 `em` 小但仍然比我们的伪驱动程序大。它使用 `virtio(9)` 作为其传输层而不是 `bus_space(9)` 加 DMA 环,如果你不太熟悉 PCI 硬件,这使代码更容易跟随。 -`vtnet` is a particularly good second real 驱动程序 to read after `mynet` because: +`vtnet` 在 `mynet` 之后是特别好的第二个真实驱动程序阅读选择,因为: -* It is used in almost every FreeBSD VM. -* Its source is clean and well-commented. -* It demonstrates multi-queue transmit and receive. -* It shows how offloads interact with the transmit path. +* 它在几乎所有 FreeBSD 虚拟机中使用。 +* 其源代码干净且注释良好。 +* 它演示了多队列发送和接收。 +* 它展示了卸载如何与发送路径交互。 -Spend an evening reading the transmit path and the receive path. You will probably find yourself recognising 70 to 80 percent of the patterns immediately, and the unfamiliar 20 percent will be things like VirtIO queue management that belong to the transport rather than to the 网络驱动程序 contract. +花一个晚上阅读发送路径和接收路径。你可能会发现自己立即识别出 70% 到 80% 的模式,不熟悉的 20% 将是像 VirtIO 队列管理这样属于传输层而非网络驱动程序契约的东西。 -### Reading `/usr/src/sys/net/if_lagg.c` +### 阅读 `/usr/src/sys/net/if_lagg.c` -The link aggregation 驱动程序 implements 802.3ad LACP, round-robin, failover, and other bonding protocols. It is an ifnet itself and aggregates over member ifnets. Reading it is an exercise in seeing how aggregate 驱动程序 can be layered on top of leaf 驱动程序, and it shows you the full power of the `ifnet` abstraction: a bond 接口 looks the same to the stack as a single NIC. +链路聚合驱动程序实现了 802.3ad LACP、轮询、故障转移和其他绑定协议。它本身是一个 ifnet 并在成员 ifnet 之上聚合。阅读它是了解聚合驱动程序如何分层在叶子驱动程序之上的练习,它向你展示了 `ifnet` 抽象的全部威力:绑定接口对协议栈来说看起来与单个网卡一样。 -### Suggested Reading Order +### 建议阅读顺序 -If you have time for a deeper study, read in this order: +如果你有时间进行更深入的学习,按以下顺序阅读: -1. `if_disc.c`: the smallest pseudo-驱动程序. You will recognise everything. -2. `if_tuntap.c`: pseudo-驱动程序 plus userland character-设备 接口. -3. `if_epair.c`: paired pseudo-驱动程序 with simulated wire. -4. `if_bridge.c`: ifnet-layered 驱动程序. -5. `if_vtnet.c`: small real 驱动程序 for VirtIO. -6. `if_em.c`: full-featured real 驱动程序 using iflib. -7. `if_lagg.c`: aggregate 驱动程序. -8. `if_wg.c`: WireGuard tunnel 驱动程序. Modern, cryptographic, interesting. +1. `if_disc.c`:最小的伪驱动程序。你会认出其中的所有内容。 +2. `if_tuntap.c`:伪驱动程序加上用户空间字符设备接口。 +3. `if_epair.c`:带有模拟线路的成对伪驱动程序。 +4. `if_bridge.c`:基于 ifnet 层的驱动程序。 +5. `if_vtnet.c`:小型 VirtIO 真实驱动程序。 +6. `if_em.c`:使用 iflib 的全功能真实驱动程序。 +7. `if_lagg.c`:聚合驱动程序。 +8. `if_wg.c`:WireGuard 隧道驱动程序。现代、加密、有趣。 -After this sequence you will have seen enough 驱动程序 that almost any 驱动程序 in the tree becomes readable. The unfamiliar parts will fall into "this is hardware-specific" or "this is a subsystem I have not studied yet", both of which are finite and conquerable. +按此顺序后你将看到足够多的驱动程序,以至于源代码树中几乎任何驱动程序都变得可读了。不熟悉的部分将归类为「这是硬件特定的」或「这是我还没学过的子系统」,两者都是有限且可征服的。 -### Reading as a Habit +### 养成阅读习惯 -Cultivate the habit of reading one 驱动程序 per month. Pick one at random, read the 附加 function, and skim the transmit and receive paths. You will be surprised how quickly your vocabulary and your reading speed grow. By the end of a year, you will recognise patterns in 驱动程序 you have never seen before, and the instinct for "where should I look for this feature" becomes sharper. +培养每月阅读一个驱动程序的习惯。随机挑选一个,阅读附加函数,浏览发送和接收路径。你会惊讶于你的词汇量和阅读速度增长得有多快。到年底,你将能在从未见过的驱动程序中识别模式,「我应该在哪里寻找这个功能」的直觉会变得更敏锐。 -Reading is also the best preparation for writing. The moment you need to add a new feature to a 驱动程序 you have never touched, the experience of having read thirty 驱动程序 means you know roughly where to look and what to imitate. +阅读也是写作的最佳准备。当你需要给从未接触过的驱动程序添加新功能的那一刻,读过三十个驱动程序的经验意味着你大致知道去哪里找、模仿什么。 -## Production Considerations +## 生产环境考量 -Most of this chapter has been about understanding. Before we close, a short section on what changes when you move from a teaching 驱动程序 to a 驱动程序 that will live in a production environment. +本章大部分内容是关于理解的。在结束之前,简短一节关于从教学驱动程序转向将在生产环境中生存的驱动程序时什么会改变。 -### Performance +### 性能 -A production 驱动程序 is usually measured in 数据包 per second, bytes per second, or latency in microseconds. The pseudo-驱动程序 we built in this chapter is not stressed in any of those dimensions. If you try to take `mynet` to a real workload, you will quickly hit the limits of a single-互斥锁 design, synchronous `m_freem`, and single-queue dispatch. +生产驱动程序通常以每秒数据包数、每秒字节数或以微秒为单位的延迟来衡量。我们在本章构建的伪驱动程序在这些维度上都没有压力。如果你尝试将 `mynet` 用于真正的工作负载,你会很快碰到单互斥锁设计、同步 `m_freem` 和单队列分派的限制。 -The refinements typically include: +典型的改进包括: -* Per-queue locks rather than a softc-level lock. -* `drbr(9)` for per-CPU transmit rings. -* Taskqueue-based deferred receive processing. -* Pre-allocated mbuf pools with `m_getcl`. -* Bypass of `if_input` via direct dispatch helpers in some paths. -* Flow hashing to pin 套接字s to specific CPUs. -* Netmap support for 内核-bypass workloads. +* 每队列锁而非 softc 级锁。 +* `drbr(9)` 用于每 CPU 发送环。 +* 基于 taskqueue 的延迟接收处理。 +* 使用 `m_getcl` 预分配 mbuf 池。 +* 在某些路径中通过直接分派辅助函数绕过 `if_input`。 +* 流哈希以将套接字固定到特定 CPU。 +* 用于内核旁路工作负载的 Netmap 支持。 -Each of these optimisations adds code. A production-quality 驱动程序 for a 10 Gbps NIC might be 3000 to 10000 lines of C, compared with our 500-line teaching 驱动程序. +每个优化都增加代码。一个 10 Gbps 网卡的生产质量驱动程序可能有 3000 到 10000 行 C 代码,相比之下我们的教学驱动程序只有 500 行。 -### Reliability +### 可靠性 -A production 驱动程序 is expected to survive months of continuous operation without leaking memory, crashing the 内核, or drifting in its counter values. The practices that make this possible include: +生产驱动程序预期可以在持续运行数月而不泄漏内存、崩溃内核或计数器值漂移。使之成为可能的实践包括: -* Running the 内核 with `INVARIANTS` and `WITNESS` in QA, so that assertions catch bugs early. -* Writing regression tests that exercise every lifecycle path. -* Running the 驱动程序 through stress tests (like `iperf3`, pktgen, or netmap pkt-gen) for extended periods. -* Instrumenting the 驱动程序 with counters for every error path, so that operators can diagnose problems in the field. -* Providing clear diagnostics through `dmesg`, sysctl, and SDT 探测. +* 在 QA 中使用启用 `INVARIANTS` 和 `WITNESS` 的内核运行,以便断言能及早捕获 bug。 +* 编写覆盖每个生命周期路径的回归测试。 +* 让驱动程序通过压力测试(如 `iperf3`、pktgen 或 netmap pkt-gen)长时间运行。 +* 为每个错误路径配备计数器来仪表化驱动程序,以便运维人员能在现场诊断问题。 +* 通过 `dmesg`、sysctl 和 SDT 探测提供清晰的诊断信息。 -These practices are not optional for a 驱动程序 that will be deployed at scale. They are the cost of entry. +这些实践对于将在规模上部署的驱动程序来说不是可选的。它们是准入成本。 -### Observability +### 可观测性 -A well-written production 驱动程序 exposes enough state through sysctl, counters, and DTrace 探测 that an operator can diagnose most problems without adding printfs or rebuilding the 内核. The rule of thumb is that every significant code path should have a counter or a 探测 point, and every decision that depends on runtime state should be queryable without a 内核 rebuild. +一个编写良好的生产驱动程序通过 sysctl、计数器和 DTrace 探测暴露足够的状态,使得运维人员可以在不添加 printf 或重新构建内核的情况下诊断大多数问题。经验法则是每个重要代码路径都应该有计数器或探测点,每个依赖运行时状态的决策都应该可以在不重建内核的情况下查询。 -For `mynet` we have only the built-in ifnet counters. A production version would add per-驱动程序 counters for things like transmit-path entries, receive-path drops, and interrupt-handler invocations. These counters are cheap to increment and priceless when a problem arrives. +对于 `mynet` 我们只有内置的 ifnet 计数器。生产版本会添加用于发送路径入口、接收路径丢弃和中断处理程序调用等内容的每驱动程序计数器。这些计数器递增很廉价,当问题到来时无价。 -### Backward Compatibility +### 向后兼容性 -A 驱动程序 that ships in a release must work on future releases too, ideally without modification. The FreeBSD 内核 evolves its internal APIs over time, and 驱动程序 that reach too deep into structures may break when those structures change. +发布在发行版中的驱动程序也必须在未来的发行版上工作,最好不需要修改。FreeBSD 内核随时间演进其内部 API,深入接触结构的驱动程序可能会在这些结构变化时崩溃。 -The accessor API we introduced in Section 2 is one of the defences. Using `if_setflagbits` rather than `ifp->if_flags |= flag` insulates you from layout changes. Similarly, `if_inc_counter` rather than direct counter updates insulates you from counter-representation changes. +我们在第 2 节中介绍的访问器 API 是防御之一。使用 `if_setflagbits` 而不是 `ifp->if_flags |= flag` 使你免受布局变化的影响。同样,`if_inc_counter` 而不是直接计数器更新使你免受计数器表示变化的影响。 -For production 驱动程序, prefer the accessor style whenever it is readily available. +对于生产驱动程序,只要访问器现成就优先使用访问器风格。 -### Licensing and Upstreaming +### 许可证和上游提交 -A 驱动程序 you intend to merge upstream must be licensed compatibly with the FreeBSD tree, which is typically a two-clause BSD license. It should also follow KNF (`style(9)`), include manual pages under `share/man/man4`, include a module Makefile under `sys/modules`, and be submitted through the FreeBSD contribution process (Phabricator reviews as of this writing). +你打算合并到上游的驱动程序必须与 FreeBSD 源代码树兼容地许可,通常是两条款 BSD 许可证。它还应该遵循 KNF(`style(9)`),包含 `share/man/man4` 下的手册页,包含 `sys/modules` 下的模块 Makefile,并通过 FreeBSD 贡献流程提交(截至本文撰写时为 Phabricator 审查)。 -Teaching 驱动程序 like `mynet` do not need to worry about upstreaming, but if you are writing a 驱动程序 with the intent to ship it to others, these are the additional considerations that turn your C code into a community artefact. +像 `mynet` 这样的教学驱动程序不需要担心上游合并,但如果你编写驱动程序的意图是发布给其他人,这些是将你的 C 代码变成社区工件的额外考量。 ## 总结 -Take a moment to appreciate what you have just done. You have: +停下来欣赏一下你刚刚做了什么。你: -* Built your first 网络驱动程序, from scratch. -* Registered it with the network stack through `ifnet` and `ether_if附加`. -* Implemented a transmit path that accepts mbufs, taps BPF, updates counters, and cleans up. -* Implemented a receive path that constructs mbufs, hands them to BPF, and delivers them to the stack. -* Handled 接口 flags, link-state transitions, and media 描述符. -* Tested the 驱动程序 with `ifconfig`, `netstat`, `tcpdump`, `ping`, and `route monitor`. -* Cleaned up on 接口 destroy and on module unload, without leaks. +* 从头构建了你的第一个网络驱动程序。 +* 通过 `ifnet` 和 `ether_ifattach` 将其注册到网络协议栈。 +* 实现了接受 mbuf、捕获 BPF、更新计数器并清理的发送路径。 +* 实现了构建 mbuf、交给 BPF 并传递给协议栈的接收路径。 +* 处理了接口标志、链路状态转换和媒体描述符。 +* 使用 `ifconfig`、`netstat`、`tcpdump`、`ping` 和 `route monitor` 测试了驱动程序。 +* 在接口销毁和模块卸载时干净清理,没有泄漏。 -More important than any of these individual accomplishments, you have internalised a mental model. A 网络驱动程序 is a participant in a contract with the 内核's network stack. The contract has a fixed shape: a few 回调 going down, one call going up, a handful of flags, a few counters, a media 描述符, a link state. Once you can see that shape clearly, every 网络驱动程序 in the FreeBSD tree becomes comprehensible. The production 驱动程序 are bigger, but they are not fundamentally different. +比这些单独成就更重要的是你内化了一个心智模型。网络驱动程序是与内核网络协议栈契约的参与者。契约有固定的形状:几个向下的回调,一个向上的调用,少数标志,几个计数器,一个媒体描述符,一个链路状态。一旦你能清楚地看到这个形状,FreeBSD 源代码树中的每个网络驱动程序都变得可理解。生产驱动程序更大,但它们在根本上没有不同。 -### What This Chapter Did Not Cover +### 本章未涵盖的内容 -A few topics are within reach but were deliberately deferred to keep this chapter tractable. +有几个主题在可达范围内,但被有意推迟以保持本章的可控性。 -**iflib(9).** The modern NIC 驱动程序 框架 that most production 驱动程序 use on FreeBSD 14. iflib shares transmit and receive 环形缓冲区 across many 驱动程序 and provides a simpler 回调-oriented model for hardware NICs. The patterns we have written by hand in this chapter are exactly what iflib automates, so everything you learned here is still valid. We will look at iflib in later chapters when we study specific hardware 驱动程序. +**iflib(9)。** 大多数生产驱动程序在 FreeBSD 14 上使用的现代网卡驱动程序框架。iflib 在许多驱动程序之间共享发送和接收环形缓冲区,并为硬件网卡提供更简单的面向回调模型。我们在本章手工编写的模式正是 iflib 自动化的内容,所以你在这里学到的一切仍然有效。我们将在后面研究特定硬件驱动程序的章节中讨论 iflib。 -**DMA for receive and transmit.** Real NICs move 数据包 data through DMA-mapped 环形缓冲区. The `总线_dma(9)` API we introduced in earlier chapters is how that is done. Adding DMA to a 驱动程序 turns the mbuf construction story into "map the mbuf, hand the mapped address to hardware, wait for the completion interrupt, unmap". That is a significant 挂载 of additional code, and it deserves its own treatment in a later chapter. +**DMA 接收和发送。** 真正的网卡通过 DMA 映射的环形缓冲区移动数据包数据。我们在前面章节中介绍的 `bus_dma(9)` API 就是实现方式。向驱动程序添加 DMA 将 mbuf 构建故事变成「映射 mbuf,将映射地址交给硬件,等待完成中断,取消映射」。那是大量的额外代码,值得在后面的章节中单独处理。 -**MSI-X and interrupt moderation.** Modern NICs have multiple interrupt vectors and support interrupt coalescing. We used a callout because we are a pseudo-驱动程序. Real 驱动程序 use 中断处理程序s. Interrupt moderation (letting the hardware aggregate several completion events into a single interrupt) is critical for performance. +**MSI-X 和中断调节。** 现代网卡有多个中断向量并支持中断合并。我们使用 callout 因为是伪驱动程序。真正的驱动程序使用中断处理程序。中断调节(让硬件将多个完成事件聚合为更少的中断)对性能至关重要。 -**netmap(4).** The 内核-bypass fast path used by some high-performance applications. Drivers opt in by calling `netmap_附加()` and exposing per-queue 环形缓冲区. It is a specialisation for throughput-sensitive use cases. +**netmap(4)。** 一些高性能应用使用的内核旁路快速路径。驱动程序通过调用 `netmap_attach()` 并暴露每队列环形缓冲区来选择加入。它是吞吐量敏感用例的专门化。 -**polling(4).** An older technique where the 驱动程序 is polled for 数据包 by a 内核 thread rather than driven by interrupts. Still available but less commonly used than it once was. +**polling(4)。** 一种较旧的技术,驱动程序由内核线程轮询而非由中断驱动。仍然可用但不如以前常用。 -**VNET in detail.** We set up the 驱动程序 to be VNET-compatible, but we did not explore what it means to move 接口 between VNETs with `if_vmove`, or what a VNET teardown looks like from the 驱动程序's perspective. Chapter 30 will visit that territory. +**VNET 详解。** 我们设置驱动程序为 VNET 兼容的,但没有探索使用 `if_vmove` 在 VNET 之间移动接口意味着什么,或从驱动程序角度 VNET 拆卸看起来是什么样。第 30 章将访问该领域。 -**Hardware offloads.** Checksum offload, TSO, LRO, VLAN tagging, encryption offload. All of these are capabilities a real NIC might expose. A 驱动程序 that advertises them has to honour them, and that leads into a rich design space we have not touched. +**硬件卸载。** 校验和卸载、TSO、LRO、VLAN 标记、加密卸载。所有这些都是真正的网卡可能暴露的能力。声明它们的驱动程序必须兑现它们,这导向了一个我们未触及的丰富设计空间。 -**Wireless.** `wlan(4)` 驱动程序 are radically different from 以太网 驱动程序 because they deal with 802.11 帧 formats, scanning, authentication, and management 帧. The `ifnet` is still present, but it sits on top of a very different link layer. We will visit wireless 驱动程序 in a later chapter. +**无线。** `wlan(4)` 驱动程序与以太网驱动程序根本不同,因为它们处理 802.11 帧格式、扫描、认证和管理帧。`ifnet` 仍然存在,但它位于一个非常不同的链路层之上。我们将在后面的章节中讨论无线驱动程序。 -**Network graph (`netgraph(4)`).** FreeBSD's 数据包-filtering and classification 框架. It is largely orthogonal to 驱动程序 writing but worth knowing about for advanced network architectures. +**网络图(`netgraph(4)`)。** FreeBSD 的包过滤和分类框架。它很大程度上正交于驱动程序编写,但值得了解用于高级网络架构。 -**Bridging and VLAN 接口.** Virtual 接口 that aggregate or modify traffic. They are built on top of `ifnet`, exactly like our 驱动程序, but their role is quite different. +**桥接和 VLAN 接口。** 聚合或修改流量的虚拟接口。它们构建在 `ifnet` 之上,与我们的驱动程序完全一样,但角色非常不同。 -Each of these topics deserves its own chapter. What you have built here is the stable base camp from which those expeditions set out. +这些主题每个都值得自己的章节。你在这里构建的是那些探险出发的稳定大本营。 -### Final Reflection +### 最后的思考 -Network 驱动程序 have a reputation as a demanding subfield of 内核 engineering. They deserve it: the constraints are tight, the interactions with the stack are many, the performance expectations are high, and the user-facing commands are numerous. But the structure of a 网络驱动程序 is clean once you can see it. That is what this chapter has given you: the ability to see the structure. +网络驱动程序有作为内核工程苛刻子领域的名声。它们当之无愧:约束很紧、与协议栈的交互很多、性能期望很高、面向用户的命令很多。但一旦你能看到它,网络驱动程序的结构是干净的。这就是本章给你的:看到结构的能力。 -Read `if_em.c`, `if_bge.c`, or `if_tuntap.c` now. You will recognise the skeleton. The softc. The `ether_if附加` call. The `if_transmit`. The `if_ioctl` switch. The `if_input` in the receive handler. The `bpf附加` and `BPF_MTAP`. Wherever the code adds complexity, it is adding complexity to a skeleton you have already built in miniature. +现在去读 `if_em.c`、`if_bge.c` 或 `if_tuntap.c`。你会认出骨架。softc。`ether_ifattach` 调用。`if_transmit`。`if_ioctl` 的 switch。接收处理程序中的 `if_input`。`bpfattach` 和 `BPF_MTAP`。无论代码在哪里增加复杂性,它都是在你已经以微缩形式构建的骨架上增加复杂性。 -Like 第27章, this chapter is long because the topic is layered. We have tried to make every layer land softly before the next arrives. If a particular section did not settle, go back and do the corresponding lab again. Kernel learning is strongly cumulative. A second pass through one section often does more than a first pass through the next one. +与第 27 章一样,本章很长,因为主题是分层的。我们试图让每一层在下一层到来之前平稳着陆。如果某个特定小节没有沉淀下来,回去重做对应的实验。内核学习是强烈累积的。重新过一遍某个小节通常比第一次过下一节效果更好。 -### Further Reading +### 延伸阅读 -**Manual pages.** `ifnet(9)`, `ifmedia(9)`, `mbuf(9)`, `ether(9)`, `bpf(9)`, `polling(9)`, `ifconfig(8)`, `netstat(1)`, `tcpdump(1)`, `route(8)`, `ngctl(8)`. Read them in that order. +**手册页。** `ifnet(9)`、`ifmedia(9)`、`mbuf(9)`、`ether(9)`、`bpf(9)`、`polling(9)`、`ifconfig(8)`、`netstat(1)`、`tcpdump(1)`、`route(8)`、`ngctl(8)`。按此顺序阅读。 -**The FreeBSD Architecture Handbook.** The networking chapters are a good complement. +**FreeBSD 架构手册。** 网络章节是很好的补充材料。 -**Kirk McKusick et al., "The Design and Implementation of the FreeBSD Operating System".** The network-stack chapters are especially relevant. +**Kirk McKusick 等人的「FreeBSD 操作系统的设计与实现」。** 网络栈章节特别相关。 -**"TCP/IP Illustrated, Volume 2" by Wright and Stevens.** A classic walk-through of a BSD-derived network stack. Dated but still unique in its depth. +**Wright 和 Stevens 的「TCP/IP 详解 卷2」。** BSD 派生网络栈的经典逐步解析。虽然有些过时,但在深度上仍然独一无二。 -**The FreeBSD source tree.** `/usr/src/sys/net/`, `/usr/src/sys/netinet/`, `/usr/src/sys/dev/e1000/`, `/usr/src/sys/dev/bge/`, `/usr/src/sys/dev/mlx5/`. Every pattern discussed in this chapter is grounded in that code. +**FreeBSD 源码树。** `/usr/src/sys/net/`、`/usr/src/sys/netinet/`、`/usr/src/sys/dev/e1000/`、`/usr/src/sys/dev/bge/`、`/usr/src/sys/dev/mlx5/`。本章讨论的每个模式都扎根于该代码中。 -**The mailing list archives.** `freebsd-net@` is the most relevant list. Reading historic threads is a great way to pick up idioms that never made it into formal documentation. +**邮件列表档案。** `freebsd-net@` 是最相关的列表。阅读历史讨论是学习从未进入正式文档的习语的好方法。 -**Commit history on GitHub mirrors.** The FreeBSD repository has an excellent history. `git log --follow sys/net/if_var.h` is a good starting point for seeing how the ifnet abstraction evolved. +**GitHub 镜像上的提交历史。** FreeBSD 仓库有出色的历史记录。`git log --follow sys/net/if_var.h` 是查看 ifnet 抽象如何演进的良好起点。 -**The FreeBSD Developer Summit slides.** When available, these often include networking-focused sessions. +**FreeBSD 开发者峰会幻灯片。** 在可用时,这些通常包括以网络为主题的会议。 -**Other BSDs.** NetBSD and OpenBSD have slightly different network-驱动程序 框架, but the core ideas are identical. Reading a 驱动程序 in another BSD after reading its FreeBSD equivalent is a good way to understand what is universal and what is FreeBSD-specific. +**其他 BSD。** NetBSD 和 OpenBSD 有略微不同的网络驱动程序框架,但核心思想是相同的。在阅读 FreeBSD 对应物后阅读另一个 BSD 的驱动程序是理解什么是通用的、什么是 FreeBSD 特有的好方法。 -## Field Guide to Related ifnet Subsystems +## ifnet 相关子系统指南 -You have built a 驱动程序. You have read a handful of real 驱动程序. Before we close the chapter, let us survey the surrounding subsystems so that you know where to look when you need them. +你已经构建了一个驱动程序。你已经阅读了一些真正的驱动程序。在结束本章之前,让我们调查一下周围的子系统,以便你知道在需要时去哪里找。 -### `arp(4)` and Neighbour Discovery +### `arp(4)` 和邻居发现 -ARP for IPv4 lives in `/usr/src/sys/netinet/if_ether.c`. It is the subsystem that maps IP addresses to MAC addresses. Drivers do not usually interact with ARP directly; they carry 数据包 (including ARP requests and replies) through their transmit and receive paths, and the ARP code inside `ether_input` and `arpresolve` does the rest. +IPv4 的 ARP 位于 `/usr/src/sys/netinet/if_ether.c`。它是将 IP 地址映射到 MAC 地址的子系统。驱动程序通常不直接与 ARP 交互;它们通过发送和接收路径携带数据包(包括 ARP 请求和回复),`ether_input` 和 `arpresolve` 内部的 ARP 代码处理其余的事情。 -The IPv6 equivalent is neighbour discovery, in `/usr/src/sys/netinet6/nd6.c`. It uses ICMPv6 rather than a separate protocol, but the role is the same: map IPv6 addresses to MAC addresses for on-link delivery. +IPv6 的等价物是邻居发现,位于 `/usr/src/sys/netinet6/nd6.c`。它使用 ICMPv6 而不是单独的协议,但角色相同:为链路本地交付将 IPv6 地址映射到 MAC 地址。 ### `bpf(4)` -The Berkeley Packet Filter subsystem lives in `/usr/src/sys/net/bpf.c`. BPF is the userland-visible mechanism for 数据包 capture. `tcpdump(1)`, `libpcap(3)`, and many other tools use BPF. Drivers 注册 with BPF through `bpf附加` (done automatically by `ether_if附加`) and tap 数据包 to BPF through `BPF_MTAP` (which you do manually). +Berkeley 数据包过滤器子系统位于 `/usr/src/sys/net/bpf.c`。BPF 是用户态可见的数据包捕获机制。`tcpdump(1)`、`libpcap(3)` 和许多其他工具使用 BPF。驱动程序通过 `bpfattach` 注册到 BPF(由 `ether_ifattach` 自动完成)并通过 `BPF_MTAP` 将数据包捕获到 BPF(你需要手动做)。 -BPF filters are programs written in the BPF pseudo-machine language, compiled to bytecode in userland and executed in the 内核. They are what allows `tcpdump 'port 80'` to work efficiently: the filter runs before the 数据包 is copied to userland, so only matching 数据包 are transferred. +BPF 过滤器是用 BPF 伪机器语言编写的程序,在用户态编译为字节码并在内核中执行。它们是让 `tcpdump 'port 80'` 高效工作的原因:过滤器在数据包被复制到用户态之前运行,所以只传输匹配的数据包。 ### `route(4)` -The routing subsystem lives in `/usr/src/sys/net/route.c` and is growing over time (the recent `nhop(9)` next-hop abstraction is a notable change). Drivers interact with routing indirectly: when they report link state changes, the routing subsystem updates metrics; when they transmit, the stack has already done the route lookup. `route monitor`, which we used in a lab, subscribes to routing events and displays them. +路由子系统位于 `/usr/src/sys/net/route.c` 并且随时间增长(最近的 `nhop(9)` 下一跳抽象是一个显著变化)。驱动程序间接地与路由交互:当它们报告链路状态变化时,路由子系统更新度量;当它们发送时,协议栈已经完成了路由查找。我们在实验中使用的 `route monitor` 订阅路由事件并显示它们。 ### `if_clone(4)` -The cloner subsystem in `/usr/src/sys/net/if_clone.c` is what we have been using throughout this chapter. It manages the list of per-驱动程序 cloners and dispatches `ifconfig create` and `ifconfig destroy` requests to the correct 驱动程序. +`/usr/src/sys/net/if_clone.c` 中的克隆器子系统是我们在本章中一直使用的。它管理每驱动程序克隆器列表并将 `ifconfig create` 和 `ifconfig destroy` 请求分派到正确的驱动程序。 ### `pf(4)` -The 数据包 filter lives in `/usr/src/sys/netpfil/pf/`. It is independent of any specific 驱动程序 and runs as a hook on 数据包 paths through `pfil(9)`. Drivers do not usually interact with `pf` directly; traffic passing through the stack is filtered transparently. +包过滤器位于 `/usr/src/sys/netpfil/pf/`。它独立于任何特定驱动程序,通过 `pfil(9)` 作为数据包路径上的钩子运行。驱动程序通常不直接与 `pf` 交互;通过协议栈的流量被透明过滤。 ### `netmap(4)` -`netmap(4)` is a 内核-bypass 数据包-I/O 框架 in `/usr/src/sys/dev/netmap/`. Drivers that support netmap expose their 环形缓冲区 directly to userland, bypassing the normal `if_input` and `if_transmit` paths. This allows applications to receive and transmit 数据包 at line rate without 内核 involvement. Only a handful of 驱动程序 support netmap natively; the rest use a shim that emulates netmap semantics at the cost of some performance. +`netmap(4)` 是 `/usr/src/sys/dev/netmap/` 中的内核旁路数据包 I/O 框架。支持 netmap 的驱动程序将它们的环形缓冲区直接暴露给用户态,绕过正常的 `if_input` 和 `if_transmit` 路径。这允许应用程序以线速接收和发送数据包而无需内核参与。只有少数驱动程序原生支持 netmap;其余的使用一个 shim 以牺牲一些性能为代价模拟 netmap 语义。 ### `netgraph(4)` -`netgraph(4)` is FreeBSD's modular 数据包-processing 框架, in `/usr/src/sys/netgraph/`. It lets you build arbitrary graphs of 数据包-processing nodes in the 内核, configured from userland via `ngctl`. Drivers can expose themselves as netgraph nodes (see `ng_ether.c`), and netgraph can be used to implement tunnels, PPP over 以太网, encrypted links, and many other features without modifying the stack itself. +`netgraph(4)` 是 FreeBSD 的模块化数据包处理框架,位于 `/usr/src/sys/netgraph/`。它让你在内核中构建任意的数据包处理节点图,从用户态通过 `ngctl` 配置。驱动程序可以将自己暴露为 netgraph 节点(参见 `ng_ether.c`),netgraph 可用于实现隧道、以太网上的 PPP、加密链路和许多其他功能,而无需修改协议栈本身。 ### `iflib(9)` -`iflib(9)` is the modern 框架 for high-performance 以太网 驱动程序 in `/usr/src/sys/net/iflib.c`. It takes over the rote parts of a NIC 驱动程序 (ring-缓冲区 management, interrupt handling, TSO fragmentation, LRO aggregation) and leaves the 驱动程序 writer to provide the hardware-specific 回调. On the 驱动程序 that have been converted to iflib to date, 驱动程序 code typically shrinks by 30 to 50 percent compared with the equivalent plain-ifnet implementation. See Appendix F for a reproducible line-count comparison across the iflib and non-iflib 驱动程序 corpora. Appendix F's iflib section also pins a specific per-驱动程序 measurement on the ixgbe conversion commit at roughly the lower edge of this range. +`iflib(9)` 是 `/usr/src/sys/net/iflib.c` 中用于高性能以太网驱动程序的现代框架。它接管网卡驱动程序中的例行部分(环形缓冲区管理、中断处理、TSO 分段、LRO 聚合),让驱动程序作者提供硬件特定的回调。在已转换为 iflib 的驱动程序中,驱动程序代码通常比等效的纯 ifnet 实现减少 30% 到 50%。参见附录 F 获取跨 iflib 和非 iflib 驱动程序语料库的可重现行数比较。附录 F 的 iflib 部分还在该范围的下限处对 ixgbe 转换提交固定了一个具体的每驱动程序测量。 -For now, `iflib` is beyond the scope of this chapter. Appendix F's iflib section offers a reproducible line-count comparison that shows how much code the 框架 saves on 驱动程序 that have been converted to it. +目前,`iflib` 超出了本章的范围。附录 F 的 iflib 部分提供了一个可重现的行数比较,显示了框架在已转换驱动程序上节省了多少代码。 -### Summary of the Landscape +### 环境概览 -A 网络驱动程序 lives in a rich environment. Above it are ARP, IP, TCP, UDP, and the 套接字 layer. Alongside it are BPF, `pf`, netmap, and netgraph. Below it is hardware, or a transport simulation, or a pipe to userland. Each of these components has its own conventions, and learning any of them in depth is a meaningful investment. What this chapter has given you is enough familiarity with the central object, the `ifnet`, that you can approach any of these subsystems without being intimidated. +网络驱动程序生活在丰富的环境中。它之上是 ARP、IP、TCP、UDP 和套接字层。它旁边是 BPF、`pf`、netmap 和 netgraph。它之下是硬件,或传输模拟,或到用户态的管道。这些组件每一个都有自己的约定,深入学习其中任何一个都是有意义的投资。本章给你的,是对中央对象 `ifnet` 足够的熟悉度,使你能接近这些子系统中的任何一个而不被吓倒。 -## Debugging Scenarios: A Worked Example +## 调试场景:一个完整示例 -One of the best ways to close a chapter about 驱动程序-writing is to walk through a specific debugging session. The scenario below is composite: it combines symptoms and fixes from several different 驱动程序 bugs into one narrative, so that the full arc of "something is wrong, let us find it" is visible. +结束关于驱动程序编写章节的最佳方式之一是走一遍具体的调试会话。下面的场景是复合的:它将几种不同驱动程序 bug 的症状和修复组合成一个叙述,以便「出问题了,让我们找到它」的完整弧线可见。 -### The Problem +### 问题描述 -You load `mynet`, create an 接口, assign an IP, and run `ping`. The ping reports 100% loss, as expected (our pseudo-驱动程序 has nothing on the other end). But `netstat -in -I mynet0` shows `Opkts 0` even after several pings. Something in the transmit path is broken. +你加载 `mynet`,创建接口,分配 IP,运行 `ping`。ping 报告 100% 丢包,正如预期(我们的伪驱动程序另一端什么也没有)。但 `netstat -in -I mynet0` 在多次 ping 后仍然显示 `Opkts 0`。发送路径中的某个东西坏了。 -### First Hypothesis: the transmit function is not being called. +### 第一个假设:发送函数没有被调用。 -You run `dtrace -n 'fbt::mynet_transmit:entry { printf("called"); }'`. No output, even during the ping. That confirms that `if_transmit` is not being invoked. +你运行 `dtrace -n 'fbt::mynet_transmit:entry { printf("called"); }'`。即使在 ping 期间也没有输出。这确认了 `if_transmit` 没有被调用。 -### Investigating Why +### 调查原因 -You open the source and find that `ifp->if_transmit = mynet_transmit;` is present. You check `ifp->if_transmit` at runtime by grabbing the ifnet pointer via `ifconfig`'s reporting (there is no direct way to read function pointers from userland, but a DTrace 探测 can do it): +你打开源代码,发现 `ifp->if_transmit = mynet_transmit;` 存在。你通过 `ifconfig` 的报告在运行时检查 `ifp->if_transmit`(没有直接的方法从用户空间读取函数指针,但 DTrace 探针可以做到): ```console # dtrace -n 'fbt::ether_output_frame:entry { @@ -3132,27 +3131,27 @@ You open the source and find that `ifp->if_transmit = mynet_transmit;` is presen }' ``` -The output shows a different address than you expected. Closer inspection reveals that `ether_if附加` overwrote `if_transmit` with its own wrapper. You grep for `if_transmit` in `if_ethersubr.c` and confirm that `ether_if附加` sets `ifp->if_output = ether_output` but does not touch `if_transmit`. So `if_transmit` should still be your function. +输出显示的地址与你预期的不同。仔细检查发现 `ether_ifattach` 用自己的包装器覆盖了 `if_transmit`。你在 `if_ethersubr.c` 中 grep `if_transmit` 并确认 `ether_ifattach` 设置了 `ifp->if_output = ether_output` 但没有触碰 `if_transmit`。所以 `if_transmit` 应该仍然是你的函数。 -You go back to your source and notice that you set `ifp->if_transmit = mynet_transmit;` before `ether_if附加`, but you inadvertently set it through the legacy `if_start` field in a second assignment that you forgot to remove. The legacy `if_start` mechanism takes precedence under some conditions, and the 内核 ends up calling `if_start` instead of `if_transmit`. +你回到源代码,注意到你在 `ether_ifattach` 之前设置了 `ifp->if_transmit = mynet_transmit;`,但你不小心在第二次赋值中通过遗留的 `if_start` 字段进行了设置,而你忘了删除。遗留的 `if_start` 机制在某些条件下优先,内核最终调用 `if_start` 而不是 `if_transmit`。 -You remove the stray `if_start` assignment and rebuild. The transmit function is now called. +你删除多余的 `if_start` 赋值并重新构建。发送函数现在被调用了。 -### Second Problem: counter disagreement +### 第二个问题:计数器不一致 -Transmit is now called, and `Opkts` climbs. But `Obytes` is suspiciously low: it is incremented by one per ping, not by the ping's byte length. You re-inspect the counter update code: +发送函数现在被调用了,`Opkts` 在增长。但 `Obytes` 低得可疑:它每次 ping 只增加一,而不是按 ping 的字节长度增加。你重新检查计数器更新代码: ```c if_inc_counter(ifp, IFCOUNTER_OBYTES, 1); ``` -The constant `1` should be `len`. You typed the wrong argument. You change it to `if_inc_counter(ifp, IFCOUNTER_OBYTES, len)` and rebuild. `Obytes` now climbs by the expected 挂载. +常量 `1` 应该是 `len`。你输入了错误的参数。你将其改为 `if_inc_counter(ifp, IFCOUNTER_OBYTES, len)` 并重新构建。`Obytes` 现在按预期数量增长。 -### Third Problem: the receive path seems intermittent +### 第三个问题:接收路径似乎间歇性失效 -Synthesised ARPs appear most of the time but occasionally stop for several seconds. You add a DTrace 探测 to `mynet_rx_timer` and see that the function is being called at regular intervals, but that some calls early-return without generating a 帧. +合成的 ARP 大部分时间出现,但偶尔会停止几秒钟。你向 `mynet_rx_timer` 添加一个 DTrace 探针,看到函数在固定间隔被调用,但有些调用提前返回而没有生成帧。 -You inspect `mynet_rx_fake_arp` and find that it uses `M_NOWAIT` for its mbuf allocation. Under memory pressure, `M_NOWAIT` returns NULL, and the receive path silently drops. You instrument the allocation failure path: +你检查 `mynet_rx_fake_arp`,发现它使用 `M_NOWAIT` 进行 mbuf 分配。在内存压力下,`M_NOWAIT` 返回 NULL,接收路径静默丢弃。你在分配失败路径添加检测: ```c if (m == NULL) { @@ -3161,64 +3160,64 @@ if (m == NULL) { } ``` -And you check the counter: it matches the missing 帧. You have found the cause: transient mbuf pressure on your test VM. The fix is to either accept occasional drops (they are legitimate and correctly counted) or to switch to `M_WAITOK` if the callout can tolerate sleeping (it cannot, because callouts run in a non-sleepable context). +你检查计数器:它与丢失的帧数匹配。你找到了原因:你的测试虚拟机上的瞬时 mbuf 压力。修复方案要么接受偶尔的丢包(它们是合法的并且被正确计数),要么如果 callout 可以容忍睡眠则切换到 `M_WAITOK`(它不能,因为 callout 在不可睡眠的上下文中运行)。 -In this case, accepting the drops is correct. The fix is therefore to make the behaviour visible in a dashboard: you add a sysctl that exposes `IFCOUNTER_IQDROPS` on this specific 接口, and note it in the 驱动程序 documentation. +在这种情况下,接受丢包是正确的。因此修复方案是使行为在仪表板上可见:你添加一个 sysctl 暴露此特定接口上的 `IFCOUNTER_IQDROPS`,并在驱动程序文档中注明。 -### What This Scenario Teaches +### 这个场景教给我们什么 -Three separate bugs. None of them was catastrophic. Each one required a different combination of tools to diagnose: DTrace for function tracing, code reading for understanding the API, and counters for observing the runtime effect. +三个独立的 bug。没有一个是灾难性的。每一个都需要不同的工具组合来诊断:DTrace 用于函数追踪,代码阅读用于理解 API,计数器用于观察运行时效果。 -The lesson is that 驱动程序 bugs tend to hide in plain sight. The first rule of 驱动程序 debugging is "do not trust, verify". The second rule is "the counters and the tools will tell you". The third rule is "if the counters do not tell you what you need, add more counters or more 探测". +教训是驱动程序 bug 倾向于隐藏在显眼的地方。驱动程序调试的第一条规则是"不要信任,要验证"。第二条规则是"计数器和工具会告诉你"。第三条规则是"如果计数器不能告诉你需要什么,添加更多计数器或更多探针"。 -With practice, debugging sessions like this become faster. You develop an instinct for which tool to reach for first, and the difference between a 驱动程序 that works on the first load and a 驱动程序 that took six iterations becomes a shorter debugging cycle. +通过练习,这样的调试会话变得更快。你培养了首先选择哪个工具的直觉,一个在第一次加载就工作的驱动程序和一个需要六次迭代的驱动程序之间的区别变成了更短的调试周期。 -## A Note on Testing Discipline +## 关于测试纪律的说明 -Before we truly close the chapter, a few paragraphs on testing discipline. A teaching 驱动程序 can be tested casually. A 驱动程序 you intend to maintain over time deserves a more rigorous approach. +在我们真正关闭本章之前,关于测试纪律的几段话。教学驱动程序可以随意测试。一个你打算长期维护的驱动程序值得更严谨的方法。 -### Unit-Level Thinking +### 单元级思维 -Every 回调 in your 驱动程序 has a small, well-defined contract. `mynet_transmit` takes an ifnet and a mbuf, validates, counts, taps, and frees. `mynet_ioctl` takes an ifnet and an ioctl code, dispatches, and returns an errno. Each of these can be exercised independently. +你的驱动程序中的每个回调都有一个小而定义明确的契约。`mynet_transmit` 接收一个 ifnet 和一个 mbuf,验证、计数、tap 并释放。`mynet_ioctl` 接收一个 ifnet 和一个 ioctl 代码,分发并返回一个 errno。这些都可以独立地被测试。 -In practice, unit testing 内核 code is hard because the 内核 is not easy to embed in a userland test harness. But you can approximate the discipline by designing the code so that most of each 回调 is pure: given inputs, produce outputs, without touching global state. The validation 块 in `mynet_transmit` is a good example: it does not touch anything except `ifp->if_mtu` and local variables. +在实践中,单元测试内核代码很困难,因为内核不容易嵌入到用户空间测试框架中。但你可以通过设计代码使每个回调的大部分是纯粹的来近似这种规范:给定输入,产生输出,不触碰全局状态。`mynet_transmit` 中的验证块就是一个好例子:它不触碰任何东西,除了 `ifp->if_mtu` 和局部变量。 -A mental model of "this 回调 has a contract; here are the cases that exercise the contract; here are the expected behaviours for each case" is the foundation of good testing. +"这个回调有一个契约;这里是行使该契约的用例;这里是每个用例的预期行为"这种心智模型是良好测试的基础。 -### Lifecycle Tests +### 生命周期测试 -Every 驱动程序 should be tested across its full lifecycle: load, create, configure, carry traffic, stop, destroy, unload. The Lab 6 script is a minimum version of such a test. A more rigorous version would include: +每个驱动程序都应该在其完整生命周期内进行测试:加载、创建、配置、承载流量、停止、销毁、卸载。实验 6 的脚本是这种测试的最低版本。更严格的版本将包括: -* Multiple 接口 created concurrently. -* Unload while traffic is flowing (at low rate, to be safe). -* Repeated load/unload cycles to catch leaks. -* Tests with INVARIANTS and WITNESS enabled. +* 同时创建多个接口。 +* 在流量流动时卸载(以低速率,以确保安全)。 +* 重复的加载/卸载循环以捕获泄漏。 +* 启用 INVARIANTS 和 WITNESS 的测试。 -### Error-Path Tests +### 错误路径测试 -Every error-path in the 驱动程序 needs to be exercisable. If `if_alloc` fails, does the create function roll back cleanly? If an ioctl returns an error, does the caller cope? If the callout fails to allocate a mbuf, does the 驱动程序 stay consistent? +驱动程序中的每个错误路径都需要可以被测试到。如果 `if_alloc` 失败,创建函数是否干净地回滚?如果 ioctl 返回错误,调用者是否能处理?如果 callout 无法分配 mbuf,驱动程序是否保持一致? -One useful technique is fault injection: add a sysctl that probabilistically fails specific operations (`if_alloc`, `m_gethdr`, and so on), and run your lifecycle tests with the fault injection enabled. This exposes error paths that almost never fire in production but can still happen under load. +一个有用的技术是故障注入:添加一个 sysctl 来概率性地使特定操作失败(`if_alloc`、`m_gethdr` 等),并在启用故障注入的情况下运行生命周期测试。这暴露了在生产中几乎从不触发但仍然可能在负载下发生的错误路径。 -### Regression Tests +### 回归测试 -Whenever you fix a bug, add a test that would have caught it. Even a simple shell script that loads the 驱动程序, exercises a specific feature, and checks a counter is a regression test. +每当你修复一个 bug,添加一个能捕获它的测试。即使是一个简单的 shell 脚本——加载驱动程序、测试特定功能并检查计数器——也是一个回归测试。 -Over time, a regression-test suite becomes a guardrail against reintroducing bugs. It also documents the behaviour you guarantee. A new contributor reading the test suite gains a clearer picture of what the 驱动程序 promises than any 挂载 of code reading could provide. +随着时间的推移,回归测试套件成为防止重新引入 bug 的护栏。它还记录了你保证的行为。一个新贡献者阅读测试套件比阅读任何数量的代码更能清楚地了解驱动程序承诺了什么。 -### Watching for Latent Issues +### 警惕潜在问题 -Some issues only manifest after hours or days of operation: slow memory leaks, counter drift, rare race conditions. Long-running tests are the only way to find these. A 驱动程序 deployed to production without at least a 24-hour soak under representative load is not ready. +有些问题只在数小时或数天的操作后才显现:缓慢的内存泄漏、计数器漂移、罕见的竞态条件。长时间运行的测试是发现这些问题的唯一方法。一个没有在代表负载下浸泡至少 24 小时就部署到生产的驱动程序还没有准备好。 -For `mynet` the soak might be as simple as "leave the 驱动程序 loaded for a day and check `vmstat -m` and `vmstat -z` at the end". For a real 驱动程序, the soak might involve terabyte-hours of traffic under a real workload. The scale differs; the principle is the same. +对于 `mynet`,浸泡可能简单到"让驱动程序加载一天,最后检查 `vmstat -m` 和 `vmstat -z`"。对于真正的驱动程序,浸泡可能涉及在真实工作负载下的太字节小时级流量。规模不同;原则相同。 -## A Complete Walkthrough of `mynet.c` +## `mynet.c` 完整走读 -Before we close the chapter, it is worth showing a concise end-to-end walkthrough of the reference 驱动程序. The goal is to see the entire 驱动程序 once in one place, with short annotations at each step, so that you can visualise the full shape without having to jump between Sections 3 through 6. +在我们关闭本章之前,值得展示参考驱动程序的简明端到端走读。目标是在一个地方看到整个驱动程序,每一步都有简短注释,这样你可以在不需要在第 3 到第 6 节之间跳转的情况下可视化完整形状。 -### File-Level Preamble +### 文件级前言 -The 驱动程序 opens with a license header, the copyright notice, and the include 块 we described in Section 3. After the includes, the file declares the memory type, the cloner variable, and the softc structure: +驱动程序以许可证头、版权声明和我们在第 3 节中描述的 include 块开始。在 include 之后,文件声明了内存类型、克隆器变量和 softc 结构: ```c static const char mynet_name[] = "mynet"; @@ -3242,11 +3241,11 @@ struct mynet_softc { #define MYNET_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) ``` -Every field and macro here has a purpose we discussed earlier. The softc carries the per-instance state; the locking macros document when the 互斥锁 should be held; the VNET-aware cloner is the mechanism by which `ifconfig mynet create` produces new 接口. +这里的每个字段和宏都有我们之前讨论过的目的。softc 承载每实例状态;锁定宏记录何时应持有互斥锁;VNET 感知的克隆器是 `ifconfig mynet create` 产生新接口的机制。 -### Forward Declarations +### 前向声明 -A small 块 of forward declarations for the static functions the 驱动程序 exposes as 回调: +一小块驱动程序作为回调暴露的静态函数的前向声明: ```c static int mynet_clone_create(struct if_clone *, int, caddr_t); @@ -3267,11 +3266,11 @@ static void vnet_mynet_init(const void *); static void vnet_mynet_uninit(const void *); ``` -Forward declarations are a courtesy to the reader. They let you scan the top of the file and see every named function the 驱动程序 exports, without searching for definitions. +前向声明是对读者的礼貌。它们让你扫描文件顶部就能看到驱动程序导出的每个命名函数,无需搜索定义。 -### Cloner Dispatch +### 克隆器分发 -The cloner create and destroy functions are thin wrappers that delegate the real work to the per-unit helpers: +克隆器的创建和销毁函数是薄包装器,将真正的工作委托给每单元辅助函数: ```c static int @@ -3287,11 +3286,11 @@ mynet_clone_destroy(struct ifnet *ifp) } ``` -Keeping the cloner 回调 small is a convention worth following. It makes it easy to test the real work functions (`mynet_create_unit`, `mynet_destroy`) in isolation and it makes the cloner glue boring. +保持克隆器回调小巧是一个值得遵循的惯例。它使真正的工作函数(`mynet_create_unit`、`mynet_destroy`)容易独立测试,并使克隆器粘合代码变得枯燥无趣。 -### Per-Unit Creation +### 每单元创建 -The per-unit creation function is where the real setup happens: +每单元创建函数是真正设置发生的地方: ```c static int @@ -3336,11 +3335,11 @@ mynet_create_unit(int unit) } ``` -You can see every concept from Section 3 in one place: softc and ifnet allocation, MAC fabrication, field configuration, media setup, callout initialisation, and the final `ether_if附加` that 寄存器 the 接口 with the stack. +你可以在这里一处看到第 3 节中的每个概念:softc 和 ifnet 分配、MAC 制造、字段配置、媒体设置、callout 初始化,以及最终向协议栈注册接口的 `ether_ifattach`。 -### Destruction +### 销毁 -Destruction mirrors creation in reverse: +销毁以相反的顺序镜像创建: ```c static void @@ -3364,11 +3363,11 @@ mynet_destroy(struct mynet_softc *sc) } ``` -Again, every step is one we discussed. The order is quiesce, 分离, free. +同样,每一步都是我们讨论过的。顺序是静默、分离、释放。 -### Init and Stop +### 初始化和停止 -The transitions between "not running" and "running" are handled by two small functions: +"未运行"和"运行"之间的转换由两个小函数处理: ```c static void @@ -3400,11 +3399,11 @@ mynet_stop(struct mynet_softc *sc) } ``` -Both are symmetric, both honour the rule about dropping the lock before `if_link_state_change`, and both maintain the coherence rules we described in Section 6. +两者是对称的,都遵循在 `if_link_state_change` 之前释放锁的规则,并且都维护我们在第 6 节中描述的一致性规则。 -### The Data Path +### 数据路径 -Transmit and the simulated receive are the heart of the 驱动程序: +发送和模拟接收是驱动程序的核心: ```c static int @@ -3465,7 +3464,7 @@ mynet_rx_timer(void *arg) } ``` -The fake-ARP helper builds the synthetic 帧 and hands it to the stack: +伪造 ARP 辅助函数构建合成帧并将其传递给协议栈: ```c static void @@ -3517,9 +3516,9 @@ mynet_rx_fake_arp(struct mynet_softc *sc) } ``` -### Ioctl and Media Callbacks +### ioctl 和媒体回调 -The ioctl handler and the two media 回调: +ioctl 处理程序和两个媒体回调: ```c static int @@ -3591,9 +3590,9 @@ mynet_media_status(struct ifnet *ifp, struct ifmediareq *imr) } ``` -### Module Glue and Cloner Registration +### 模块胶水和克隆器注册 -The bottom of the file holds the module handler, the VNET sysinit/sysuninit functions, and the module declarations: +文件底部是模块处理程序、VNET sysinit/sysuninit 函数和模块声明: ```c static void @@ -3636,398 +3635,398 @@ MODULE_DEPEND(mynet, ether, 1, 1, 1); MODULE_VERSION(mynet, 1); ``` -### Line Count and Density +### 代码行数与密度 -The complete `mynet.c` is about 500 lines of C code. The entire teaching 驱动程序, from the license header at the top to the `MODULE_VERSION` at the bottom, is shorter than many single functions in production 驱动程序. That compactness is not a coincidence: pseudo-驱动程序 have no hardware to talk to, so they can focus on the `ifnet` contract and nothing else. +完整的 `mynet.c` 大约有 500 行 C 代码。整个教学驱动程序,从顶部的许可证头到底部的 `MODULE_VERSION`,比生产驱动程序中许多单个函数还要短。这种紧凑性并非巧合:伪驱动程序没有硬件需要通信,因此它们可以专注于 `ifnet` 契约,仅此而已。 -Read through the complete file in the companion materials. Type your own copy if you have not already done so. Build it. Load it. Mutate it. Until you have internalised the shape, do not move on to the next chapter. +请阅读配套材料中的完整文件。如果你还没有这样做,请自己输入一份副本。构建它。加载它。修改它。在你内化其形态之前,不要继续下一章。 -## A Complete Lifecycle Trace +## 完整生命周期追踪 -It helps to see, end to end, the sequence of events that happens when the reader runs the ordinary commands from a shell. The trace below follows the mental model we have built up, but stitches it together into one continuous story. Read it as an animated flipbook rather than as a reference table. +端到端地查看读者从 shell 运行普通命令时发生的事件序列会很有帮助。下面的追踪遵循我们已经建立的心智模型,但将其编织成一个连续的故事。把它当作动画翻页书来读,而不是参考表格。 -### Trace 1: From kldload to ifconfig up +### 追踪1:从 kldload 到 ifconfig up -Imagine you are sitting at the keyboard with a fresh FreeBSD 14.3 machine. You have never loaded `mynet` before. You type the first command: +想象你坐在一台全新的 FreeBSD 14.3 机器的键盘前。你以前从未加载过 `mynet`。你输入第一条命令: ```console # kldload ./mynet.ko ``` -What happens next? The loader reads the ELF header of `mynet.ko`, relocates the module into 内核 memory, and walks the module's `modmetadata_set` linker set. It finds the `DECLARE_MODULE` record for `mynet` and calls `mynet_modevent(mod, MOD_LOAD, data)`. Our handler returns zero without doing any work. The loader also processes the `MODULE_DEPEND` records, and because `ether` is already part of the base 内核, the dependency is satisfied immediately. +接下来会发生什么?加载器读取 `mynet.ko` 的 ELF 头,将模块重定位到内核内存中,并遍历模块的 `modmetadata_set` 链接器集。它找到 `mynet` 的 `DECLARE_MODULE` 记录并调用 `mynet_modevent(mod, MOD_LOAD, data)`。我们的处理程序不做任何工作,直接返回零。加载器还处理 `MODULE_DEPEND` 记录,由于 `ether` 已经是基本内核的一部分,依赖关系立即得到满足。 -Then the linker set for `VNET_SYSINIT` is walked. Our `vnet_mynet_init()` fires. It calls `if_clone_simple()` with the name `mynet` and the two 回调 `mynet_clone_create` and `mynet_clone_destroy`. The 内核 寄存器 a new cloner in the VNET cloner list. At this point, no 接口 exists yet: the cloner is only a factory. +然后遍历 `VNET_SYSINIT` 的链接器集。我们的 `vnet_mynet_init()` 被触发。它调用 `if_clone_simple()`,传入名称 `mynet` 和两个回调 `mynet_clone_create` 与 `mynet_clone_destroy`。内核在 VNET 克隆器列表中注册一个新的克隆器。此时,还没有任何接口存在:克隆器只是一个工厂。 -The shell prompt returns. You type: +Shell 提示符返回。你输入: ```console # ifconfig mynet create ``` -`ifconfig(8)` opens a datagram 套接字 and issues the `SIOCIFCREATE2` ioctl on it, passing the name `mynet`. The 内核's clone dispatcher finds the `mynet` cloner and calls `mynet_clone_create(cloner, unit, params, params_len)` with the first available unit number, which is zero. Our 回调 allocates a `mynet_softc`, locks its 互斥锁, calls `if_alloc(IFT_ETHER)`, fills in the 回调, initialises the media table, generates a MAC address, calls `ether_if附加()`, and returns zero. Inside `ether_if附加()`, the 内核 calls `if_附加()` which links the 接口 into the global 接口 list, calls `bpf附加()` so `tcpdump(8)` can observe it, publishes the 设备 to userland through `devd(8)`, and runs any 注册ed `ifnet_arrival_event` handlers. +`ifconfig(8)` 打开一个数据报套接字并在其上发出 `SIOCIFCREATE2` ioctl,传入名称 `mynet`。内核的克隆分发器找到 `mynet` 克隆器并调用 `mynet_clone_create(cloner, unit, params, params_len)`,使用第一个可用的单元号,即零。我们的回调分配一个 `mynet_softc`,锁定其互斥锁,调用 `if_alloc(IFT_ETHER)`,填充回调,初始化媒体表,生成 MAC 地址,调用 `ether_ifattach()`,并返回零。在 `ether_ifattach()` 内部,内核调用 `if_attach()`,它将接口链接到全局接口列表,调用 `bpfattach()` 以便 `tcpdump(8)` 可以观察它,通过 `devd(8)` 将设备发布到用户空间,并运行所有已注册的 `ifnet_arrival_event` 处理程序。 -The shell prompt returns again. You type: +Shell 提示符再次返回。你输入: ```console # ifconfig mynet0 up ``` -Same 套接字, same kind of ioctl, different command: `SIOCSIFFLAGS`. The 内核 looks up the 接口 by name, finds `mynet0`, and calls `mynet_ioctl(ifp, SIOCSIFFLAGS, data)`. Our handler observes that `IFF_UP` is set but `IFF_DRV_RUNNING` is not, so it calls `mynet_init()`. That function flips `running` to true, sets `IFF_DRV_RUNNING` on the 接口, schedules the first callout tick, and returns. The ioctl returns zero. The shell prompt returns. +相同的套接字,相同类型的 ioctl,不同的命令:`SIOCSIFFLAGS`。内核按名称查找接口,找到 `mynet0`,并调用 `mynet_ioctl(ifp, SIOCSIFFLAGS, data)`。我们的处理程序观察到 `IFF_UP` 已设置但 `IFF_DRV_RUNNING` 未设置,因此它调用 `mynet_init()`。该函数将 `running` 翻转为 true,在接口上设置 `IFF_DRV_RUNNING`,调度第一个 callout 节拍,然后返回。ioctl 返回零。Shell 提示符返回。 -You type: +你输入: ```console # ping -c 1 -t 1 192.0.2.99 ``` -At this point the network stack attempts ARP resolution. It builds an ARP request 数据包, formatted as 以太网 + ARP, and calls `ether_output()` for the 接口. `ether_output()` prepends the 以太网 header, calls `if_transmit()`, which is a macro that calls our `mynet_transmit()` function. Our transmit function increments counters, taps BPF, frees the mbuf, and returns zero. `tcpdump -i mynet0` would have seen the ARP request in flight. +此时,网络栈尝试 ARP 解析。它构建一个 ARP 请求包,格式为 Ethernet + ARP,并为该接口调用 `ether_output()`。`ether_output()` 前置以太网头,调用 `if_transmit()`,这是一个调用我们 `mynet_transmit()` 函数的宏。我们的发送函数递增计数器、tap BPF、释放 mbuf 并返回零。`tcpdump -i mynet0` 会看到正在传输的 ARP 请求。 -Meanwhile, because our 驱动程序 is also generating fake inbound ARP responses on its callout timer, the next callout tick synthesises an ARP reply, calls `if_input()`, and the stack believes it has heard from `192.0.2.99`. `ping` sends the ICMP echo request, our 驱动程序 taps it, frees the mbuf, and records success. `ping` never gets a reply, because our 驱动程序 only fakes ARP; but the lifecycle worked exactly as expected, and nothing crashed. +与此同时,因为我们的驱动程序也在 callout 定时器上生成伪造的入站 ARP 响应,下一个 callout 节拍合成一个 ARP 回复,调用 `if_input()`,协议栈相信它收到了来自 `192.0.2.99` 的响应。`ping` 发送 ICMP 回显请求,我们的驱动程序 tap 它,释放 mbuf,并记录成功。`ping` 永远不会收到回复,因为我们的驱动程序只伪造 ARP;但生命周期完全按预期工作,而且没有崩溃。 -This sequence, trivial as it looks, exercises almost every code path in your 驱动程序. Internalise it. +这个序列看起来微不足道,但它几乎执行了驱动程序中的每个代码路径。内化它。 -### Trace 2: From ifconfig down to kldunload +### 追踪2:从 ifconfig down 到 kldunload -Now you are cleaning up. You type: +现在你来清理。你输入: ```console # ifconfig mynet0 down ``` -`SIOCSIFFLAGS` again, this time with `IFF_UP` cleared. Our ioctl handler sees `IFF_DRV_RUNNING` set but `IFF_UP` unset, so it calls `mynet_stop()`. That function flips `running` to false, clears `IFF_DRV_RUNNING`, drains the callout, and returns. Subsequent transmit attempts will be refused by `mynet_transmit()` because of the `running` check. +又是 `SIOCSIFFLAGS`,这次 `IFF_UP` 被清除。我们的 ioctl 处理程序看到 `IFF_DRV_RUNNING` 已设置但 `IFF_UP` 未设置,因此它调用 `mynet_stop()`。该函数将 `running` 翻转为 false,清除 `IFF_DRV_RUNNING`,排空 callout,然后返回。后续的发送尝试将被 `mynet_transmit()` 拒绝,因为有 `running` 检查。 ```console # ifconfig mynet0 destroy ``` -`SIOCIFDESTROY` ioctl. The 内核 finds the cloner that owns this 接口, and calls `mynet_clone_destroy(cloner, ifp)`. Our 回调 calls `mynet_stop()` (belt and braces: the 接口 was already down), then `ether_if分离()`, which calls `if_分离()` internally. `if_分离()` unlinks the 接口 from the global list, drains any references, calls `bpf分离()`, notifies `devd(8)`, and runs the `ifnet_departure_event` handlers. Our 回调 then calls `ifmedia_removeall()` to free the media list, destroys the 互斥锁, frees the `ifnet` with `if_free()`, and frees the softc with `free()`. +`SIOCIFDESTROY` ioctl。内核找到拥有此接口的克隆器,并调用 `mynet_clone_destroy(cloner, ifp)`。我们的回调调用 `mynet_stop()`(双重保险:接口已经 down 了),然后调用 `ether_ifdetach()`,后者内部调用 `if_detach()`。`if_detach()` 将接口从全局列表中取消链接,排空所有引用,调用 `bpfdetach()`,通知 `devd(8)`,并运行 `ifnet_departure_event` 处理程序。我们的回调然后调用 `ifmedia_removeall()` 释放媒体列表,销毁互斥锁,用 `if_free()` 释放 `ifnet`,并用 `free()` 释放 softc。 ```console # kldunload mynet ``` -The loader walks `VNET_SYSUNINIT` and calls `vnet_mynet_uninit()`, which 分离 the cloner with `if_clone_分离()`. Then `mynet_modevent(mod, MOD_UNLOAD, data)` runs and returns zero. The loader unmaps the module from 内核 memory. The system is clean. +加载器遍历 `VNET_SYSUNINIT` 并调用 `vnet_mynet_uninit()`,后者通过 `if_clone_detach()` 分离克隆器。然后 `mynet_modevent(mod, MOD_UNLOAD, data)` 运行并返回零。加载器将模块从内核内存中取消映射。系统干净了。 -Each command in the sequence corresponds to a specific 回调 in your 驱动程序. If a command hangs, the broken 回调 is usually obvious. If a command crashes, the stack trace points directly at it. Practise this trace until it feels mechanical; you will spend the rest of your career as a 驱动程序 author walking variants of it. +序列中的每个命令对应驱动程序中的一个特定回调。如果某个命令挂起,损坏的回调通常是显而易见的。如果某个命令崩溃,堆栈追踪直接指向它。练习这个追踪直到它变得机械化;你的余生作为驱动程序作者都在走它的变体。 -## Common Misconceptions About Network Drivers +## 关于网络驱动程序的常见误解 -Beginners arrive at this chapter with a handful of recurring misconceptions. Naming them explicitly helps you avoid subtle bugs later. +初学者带着一些反复出现的误解来到本章。明确指出它们有助于你避免日后出现微妙的 bug。 -**"The 驱动程序 parses 以太网 headers."** Not quite. For reception, the 驱动程序 does not parse the 以太网 header at all: it hands the raw 帧 to `ether_input()` (called from `if_input()` under the 以太网 框架), and `ether_input()` does the parsing. For transmission, `ether_output()` in the generic layer prepends the 以太网 header; your transmit 回调 usually sees the complete 帧 and simply moves its bytes out to the wire. The 驱动程序's job is to move 帧, not to understand protocols. +**"驱动程序解析以太网头。"** 并非如此。对于接收,驱动程序根本不解析以太网头:它将原始帧交给 `ether_input()`(在以太网框架下从 `if_input()` 调用),`ether_input()` 负责解析。对于发送,通用层的 `ether_output()` 前置以太网头;你的发送回调通常看到的是完整的帧,只需将其字节移出即可。驱动程序的工作是移动帧,而不是理解协议。 -**"The 驱动程序 must know about IP addresses."** No. An 以太网 驱动程序 operates below IP entirely. It handles MAC addresses, 帧 sizes, multicast filters, and link state, but it never looks at IP headers. When you 附加 a 网络驱动程序 to an address using `ifconfig mynet0 192.0.2.1/24`, the assignment is stored in a protocol-family-specific structure (a `struct in_ifaddr`) which the 驱动程序 never touches. The 驱动程序 only sees outbound 帧 and only produces inbound 帧: whether those 帧 carry IPv4, IPv6, ARP, or something exotic is above its pay grade. +**"驱动程序必须了解 IP 地址。"** 不需要。以太网驱动程序完全在 IP 之下操作。它处理 MAC 地址、帧大小、多播过滤器和链路状态,但从不查看 IP 头。当你使用 `ifconfig mynet0 192.0.2.1/24` 将网络驱动程序附加到地址时,该分配存储在一个特定于协议族的结构中(一个 `struct in_ifaddr`),驱动程序从不接触它。驱动程序只看到出站帧和只产生入站帧:这些帧携带的是 IPv4、IPv6、ARP 还是其他异类协议,都不在它的职责范围内。 -**"`IFF_UP` means the 接口 can send 数据包."** Partially true. `IFF_UP` means the administrator has said, "I want this 接口 to be active." The 驱动程序 responds by initialising hardware (or, in our case, flipping `running` to true) and setting `IFF_DRV_RUNNING`. The distinction matters. `IFF_UP` is user intent; `IFF_DRV_RUNNING` is 驱动程序 state. Only the latter reliably indicates that the 驱动程序 is prepared to send 帧. If you check `IFF_UP` alone before transmitting, you will occasionally send 帧 into a half-initialised hardware state and watch the machine panic. +**"`IFF_UP` 意味着接口可以发送数据包。"** 部分正确。`IFF_UP` 意味着管理员说"我希望这个接口处于活动状态"。驱动程序通过初始化硬件(或者在我们的情况下,将 `running` 翻转为 true)并设置 `IFF_DRV_RUNNING` 来响应。这个区别很重要。`IFF_UP` 是用户意图;`IFF_DRV_RUNNING` 是驱动程序状态。只有后者可靠地指示驱动程序已准备好发送帧。如果你在发送前只检查 `IFF_UP`,你偶尔会将帧发送到半初始化的硬件状态并看着机器崩溃。 -**"BPF is something you enable for debugging."** BPF is always on for every 网络驱动程序. The `bpf附加()` call inside `ether_if附加()` 寄存器 the 接口 with the Berkeley Packet Filter 框架 unconditionally. When no BPF listeners exist, `BPF_MTAP()` is cheap; it checks an atomic counter and returns. When listeners exist, the mbuf is cloned and delivered to each one. You do not need to do anything special to make `tcpdump` work on your 驱动程序; you only need to call `BPF_MTAP()` on both paths. Forgetting that single call is the most common reason a new 驱动程序 shows 数据包 in counters but nothing in `tcpdump`. +**"BPF 是调试时才启用的东西。"** BPF 对每个网络驱动程序始终处于开启状态。`ether_ifattach()` 内部的 `bpfattach()` 调用无条件地将接口注册到 Berkeley 包过滤器框架。当没有 BPF 监听器时,`BPF_MTAP()` 很便宜;它检查一个原子计数器然后返回。当存在监听器时,mbuf 被克隆并传递给每个监听器。你不需要做任何特殊的事情就能让 `tcpdump` 在你的驱动程序上工作;你只需要在两个路径上都调用 `BPF_MTAP()`。忘记那一个调用是新驱动程序在计数器中显示数据包但在 `tcpdump` 中什么也不显示的最常见原因。 -**"The 内核 will clean up if my 驱动程序 crashes."** False. A crash inside a 驱动程序 is a crash inside the 内核. There is no process boundary to contain the damage. If your transmit function dereferences a null pointer, the machine panics. If your 回调 leaks a 互斥锁, every subsequent call that touches the 接口 will hang. Write defensively. Test under load. Use INVARIANTS and WITNESS builds. +**"如果我的驱动程序崩溃,内核会清理。"** 错误。驱动程序内部的崩溃就是内核内部的崩溃。没有进程边界来控制损害。如果你的发送函数解引用空指针,机器就会崩溃。如果你的回调泄漏了一个互斥锁,每个后续触及该接口的调用都会挂起。防御性地编写代码。在负载下测试。使用 INVARIANTS 和 WITNESS 构建。 -**"Network 驱动程序 are slower than 存储驱动程序."** Not inherently. Modern NICs process tens of millions of 数据包 per second, and a well-written 驱动程序 using `iflib(9)` can keep pace. The confusion comes from the fact that each individual 数据包 is tiny compared to a storage request, so the per-数据包 overhead of clumsy designs becomes visible immediately. A sloppy 存储驱动程序 might still hit 80% of line rate because a single I/O moves 64 KiB; a sloppy 网络驱动程序 will fall apart at 10% of line rate because each 帧 is 1.5 KiB and the per-帧 overhead dominates. +**"网络驱动程序比存储驱动程序慢。"** 本质上并非如此。现代网卡每秒处理数千万个数据包,使用 `iflib(9)` 的良好驱动程序可以跟上。困惑来自于每个单独的数据包与存储请求相比非常小,因此笨拙设计的逐包开销会立即可见。一个粗糙的存储驱动程序可能仍然能达到线速的 80%,因为单次 I/O 移动 64 KiB;一个粗糙的网络驱动程序在线速的 10% 就会崩溃,因为每帧只有 1.5 KiB,逐帧开销占主导地位。 -**"Once my 驱动程序 passes `ifconfig`, I'm done."** Not even close. A 驱动程序 that passes `ifconfig up` but fails under `jail`, `vnet`, or module unload can still break production systems. The rigorous test matrix you built in the testing section is the real bar. Many production bugs are discovered only at the intersection of features: VLAN plus TSO, jumbo 帧 plus checksum offload, promiscuous mode plus multicast filtering, rapid up/down cycles plus BPF listeners. +**"一旦我的驱动程序通过了 `ifconfig`,我就完成了。"** 远非如此。一个通过 `ifconfig up` 但在 `jail`、`vnet` 或模块卸载下失败的驱动程序仍然可能破坏生产系统。你在测试部分构建的严格测试矩阵才是真正的标准。许多生产 bug 只在功能交叉点被发现:VLAN 加 TSO、巨型帧加校验和卸载、混杂模式加多播过滤、快速 up/down 循环加 BPF 监听器。 -Each misconception can trace back to a piece of earlier reading that was technically accurate but incomplete. Now that you have written a 驱动程序, these edges come into focus. +每个误解都可以追溯到之前阅读中技术上准确但不完整的片段。既然你已经编写了一个驱动程序,这些边缘就变得清晰了。 -## How Packets Actually Reach and Leave Your Driver +## 数据包如何实际到达和离开你的驱动 -It is worth slowing down and tracing the exact path a 数据包 takes. The geography of the FreeBSD network stack is older than you might think, and much of it is invisible from the 驱动程序's perspective. Knowing the geography makes the bugs you encounter easier to diagnose. +值得放慢脚步,追踪数据包经过的确切路径。FreeBSD 网络栈的地理结构比你想象的更古老,其中大部分从驱动程序的角度是不可见的。了解这个地理结构会让你遇到的 bug 更容易诊断。 -### The outbound path +### 出站路径 -When a userland process calls `send()` on a UDP 套接字, the path looks like this: +当用户空间进程在 UDP 套接字上调用 `send()` 时,路径如下: -1. The system call enters the 内核 and reaches the 套接字 layer. The data is copied from userland into 内核 mbufs using `sosend()`. -2. The 套接字 layer hands the mbufs to the protocol layer, which in this case is UDP. UDP prepends a UDP header and hands the 数据包 to IP. -3. IP prepends the IP header, selects an output route using the routing table, and hands the 数据包 to the 接口-specific output function via the route's `rt_ifp` pointer. For an 以太网 接口, that function is `ether_output()`. -4. `ether_output()` calls `arpresolve()` to find the destination MAC address. If the ARP cache has an entry, execution continues. If not, the 数据包 is queued inside ARP and an ARP request is transmitted; the queued 数据包 will be released later when the reply arrives. -5. `ether_output()` prepends the 以太网 header and calls `if_transmit(ifp, m)`, which is a thin macro over the 驱动程序's `if_transmit` 回调. -6. Your `mynet_transmit()` runs. It may queue the mbuf onto hardware, tap BPF, update counters, and free or retain the mbuf depending on whether it owns it. +1. 系统调用进入内核并到达套接字层。数据使用 `sosend()` 从用户空间复制到内核 mbuf 中。 +2. 套接字层将 mbuf 交给协议层,在本例中是 UDP。UDP 前置 UDP 头并将数据包交给 IP。 +3. IP 前置 IP 头,使用路由表选择输出路由,并通过路由的 `rt_ifp` 指针将数据包交给接口特定的输出函数。对于以太网接口,该函数是 `ether_output()`。 +4. `ether_output()` 调用 `arpresolve()` 查找目标 MAC 地址。如果 ARP 缓存有条目,执行继续。如果没有,数据包在 ARP 内部排队,并发送 ARP 请求;排队的数据包将在回复到达时被释放。 +5. `ether_output()` 前置以太网头并调用 `if_transmit(ifp, m)`,这是驱动程序 `if_transmit` 回调上的一个薄宏。 +6. 你的 `mynet_transmit()` 运行。它可以将 mbuf 排队到硬件、tap BPF、更新计数器,并根据是否拥有 mbuf 来释放或保留它。 -Six layers, and only one of them is your 驱动程序. The rest is scenery you never have to touch. But when a bug occurs, understanding which layer might be responsible is the difference between a two-hour fix and a two-day fix. +六层,其中只有一层是你的驱动程序。其余的都是你永远不必触碰的场景。但是当 bug 发生时,理解哪一层可能负责是两小时修复和两天修复之间的区别。 -### The inbound path +### 入站路径 -For the receive side, the path runs in the opposite direction: +对于接收侧,路径以相反方向运行: -1. A 帧 arrives on the wire (or, in our case, is synthesised by the 驱动程序). -2. The 驱动程序 builds an mbuf with `m_gethdr()`, populates `m_pkthdr.rcvif`, taps BPF with `BPF_MTAP()`, and calls `if_input(ifp, m)`. -3. `if_input()` is a thin wrapper that calls the 接口's `if_input` 回调. For 以太网 接口, `ether_if附加()` sets this 回调 to `ether_input()`. -4. `ether_input()` examines the 以太网 header, looks up the 以太网 type (IPv4, IPv6, ARP, etc.), and calls the appropriate demux routine: `netisr_dispatch(NETISR_IP, m)` for IPv4, `netisr_dispatch(NETISR_ARP, m)` for ARP, and so on. -5. The netisr 框架 optionally defers the 数据包 to a worker thread, then delivers it to the protocol-specific input routine. For IPv4, this is `ip_input()`. -6. IP parses the header, performs source/destination checks, consults the routing table to decide whether the 数据包 is local or transit, and either delivers it up to the transport layer or sends it back down for forwarding. -7. If the 数据包 is for the local host and the protocol is UDP, `udp_input()` validates the UDP checksum and delivers the payload to the matching 套接字's receive 缓冲区. -8. The userland process that called `recv()` wakes up and reads the data. +1. 一个帧到达线路(或者在我们的情况下,由驱动程序合成)。 +2. 驱动程序用 `m_gethdr()` 构建 mbuf,填充 `m_pkthdr.rcvif`,用 `BPF_MTAP()` tap BPF,并调用 `if_input(ifp, m)`。 +3. `if_input()` 是一个薄包装器,调用接口的 `if_input` 回调。对于以太网接口,`ether_ifattach()` 将此回调设置为 `ether_input()`。 +4. `ether_input()` 检查以太网头,查找以太网类型(IPv4、IPv6、ARP 等),并调用适当的多路分解例程:IPv4 调用 `netisr_dispatch(NETISR_IP, m)`,ARP 调用 `netisr_dispatch(NETISR_ARP, m)`,依此类推。 +5. netisr 框架可选地将数据包推迟到工作线程,然后将其传递给特定协议的输入例程。对于 IPv4,这是 `ip_input()`。 +6. IP 解析头,执行源/目标检查,查询路由表以决定数据包是本地的还是转发的,然后将其上送到传输层或将其送回进行转发。 +7. 如果数据包是给本地主机的且协议是 UDP,`udp_input()` 验证 UDP 校验和并将有效载荷传递到匹配套接字的接收缓冲区。 +8. 调用 `recv()` 的用户空间进程被唤醒并读取数据。 -Eight layers on reception, and again, only one of them is your 驱动程序. But look at how many places `m_pullup()` might be called to make a header contiguous in memory, how many places the mbuf might be freed, how many places a counter might be bumped. If you see `ifconfig mynet0` reporting 数据包 received but `tcpdump -i mynet0` showing nothing, the gap is most likely between step 2 and step 3 (your `BPF_MTAP()` is missing or wrong). If `tcpdump` shows the 数据包 but `netstat -s` shows them being dropped, the gap is most likely between step 6 and step 7 (the routing table doesn't think the 接口 owns the destination address). +接收侧有八层,同样,只有一层是你的驱动程序。但是看看 `m_pullup()` 可能在多少个地方被调用来使头在内存中连续,mbuf 可能在多少个地方被释放,计数器可能在多少个地方被递增。如果你看到 `ifconfig mynet0` 报告收到了数据包但 `tcpdump -i mynet0` 什么也没显示,差距最可能出现在步骤 2 和步骤 3 之间(你的 `BPF_MTAP()` 缺失或错误)。如果 `tcpdump` 显示了数据包但 `netstat -s` 显示它们被丢弃,差距最可能出现在步骤 6 和步骤 7 之间(路由表不认为接口拥有目标地址)。 -### Why this geography matters for 驱动程序 authors +### 为什么这些路径知识对驱动作者很重要 -Understanding the geography gives you diagnostic power. When something breaks, you can ask focused questions. Is the counter incrementing? Step 6 in the outbound path fired. Is BPF seeing the 数据包? Your `BPF_MTAP()` call is present and the 接口 is marked running. Is the 数据包 reaching the peer? The hardware actually transmitted it. Each question corresponds to a specific checkpoint in the geography, and each checkpoint narrows the range of possible bugs. +理解这个地理结构赋予你诊断能力。当出现问题时,你可以提出有针对性的问题。计数器在递增吗?出站路径的步骤 6 触发了。BPF 看到数据包了吗?你的 `BPF_MTAP()` 调用存在且接口标记为运行中。数据包到达对端了吗?硬件实际发送了它。每个问题对应地理结构中的一个特定检查点,每个检查点缩小了可能 bug 的范围。 -Production 驱动程序 extend this geography with transmit and receive rings, batch processing, hardware offloads, and interrupt moderation. Each optimisation changes the path; none of them changes the overall shape. The shape is worth memorising now, before the optimisations confuse it. +生产驱动程序通过发送和接收环、批处理、硬件卸载和中断调节扩展了这个地理。每个优化改变了路径;但没有一个改变了整体形状。这个形状现在就值得记住,在优化使其变得混乱之前。 -## Things This Chapter Did Not Cover +## 本章未涵盖的其他内容 -An honest list of omissions helps you know what to learn next, and it sets up Chapter 29 more precisely than an artificial summary would. +一份诚实的省略清单帮助你了解接下来该学什么,它比人为的总结更精确地为第 29 章做了铺垫。 -**Real hardware initialisation.** We did not touch PCI enumeration, 总线 resource allocation, interrupt setup, or DMA ring construction. For that, read 驱动程序 like `/usr/src/sys/dev/e1000/if_em.c` carefully, especially `em_附加()` and `em_allocate_transmit_structures()`. You will see `总线_alloc_resource_any()`, `总线_setup_intr()`, `总线_dma_tag_create()`, and `总线_dmamap_create()` in action. Those are the functions that make a physical NIC actually move bits. +**硬件初始化。** 我们没有涉及 PCI 枚举、总线资源分配、中断设置或 DMA 环构建。为此,请仔细阅读 `/usr/src/sys/dev/e1000/if_em.c` 等驱动程序,特别是 `em_attach()` 和 `em_allocate_transmit_structures()`。你会看到 `bus_alloc_resource_any()`、`bus_setup_intr()`、`bus_dma_tag_create()` 和 `bus_dmamap_create()` 的实际运用。这些是让物理网卡真正移动数据的函数。 -**iflib.** The `iflib(9)` 框架 abstracts most of the fiddly parts of a modern 以太网 驱动程序. As a rough order-of-magnitude figure, a new NIC 驱动程序 in FreeBSD 14.3 often consists of around 1,500 lines of hardware-specific code plus calls into `iflib`, rather than the roughly 10,000 lines of open-coded ring management a fully hand-written 驱动程序 would need. We mentioned `iflib` without teaching it, because the teaching 驱动程序 is simpler without it. A real 驱动程序 in production in 2026 probably uses `iflib`. +**iflib。** `iflib(9)` 框架抽象了现代以太网驱动程序的大部分繁琐部分。作为粗略的数量级估计,FreeBSD 14.3 中的新网卡驱动程序通常由大约 1,500 行硬件特定代码加上对 `iflib` 的调用组成,而不是完全手写环管理所需的约 10,000 行代码。我们提到了 `iflib` 但没有教授它,因为教学驱动程序不用它更简单。2026 年生产中的真正驱动程序可能使用 `iflib`。 -**Checksum offload.** Modern NICs compute TCP, UDP, and IP checksums in hardware. Setting up `IFCAP_RXCSUM`, `IFCAP_TXCSUM`, and their IPv6 counterparts requires both 驱动程序 support and mbuf flag manipulation (`CSUM_DATA_VALID`, `CSUM_PSEUDO_HDR`, etc.). Get it wrong and you silently corrupt traffic for some users only. The best 引言 is `if_em.c`'s `em_transmit_checksum_setup()` function, paired with `ether_input()` to see how the flags propagate up. +**校验和卸载。** 现代网卡在硬件中计算 TCP、UDP 和 IP 校验和。设置 `IFCAP_RXCSUM`、`IFCAP_TXCSUM` 及其 IPv6 对应项需要驱动程序支持和 mbuf 标志操作(`CSUM_DATA_VALID`、`CSUM_PSEUDO_HDR` 等)。弄错了会默默地只为某些用户损坏流量。最好的入门是 `if_em.c` 的 `em_transmit_checksum_setup()` 函数,配合 `ether_input()` 查看标志如何向上传播。 -**Segmentation offload.** TSO (transmit), LRO (receive), and GSO (generic segmentation offload) let the host hand the NIC multi-segment 帧 that the hardware (or a 驱动程序-level helper) breaks into MTU-sized fragments. For a primer, read `tcp_output()` and trace how it cooperates with `if_hwtsomax` and `IFCAP_TSO4`. +**分段卸载。** TSO(发送)、LRO(接收)和 GSO(通用分段卸载)让主机将多段帧交给网卡,由硬件(或驱动程序级助手)将其拆分为 MTU 大小的片段。作为入门,请阅读 `tcp_output()` 并追踪它如何与 `if_hwtsomax` 和 `IFCAP_TSO4` 协作。 -**Multicast filtering.** Real 驱动程序 program hardware multicast hash tables based on the memberships advertised through `SIOCADDMULTI`. We stubbed the ioctls; a real implementation walks `ifp->if_multiaddrs` and pokes a hash 注册 on the NIC. +**多播过滤。** 真正的驱动程序根据通过 `SIOCADDMULTI` 通告的成员资格来编程硬件多播哈希表。我们 stub 了这些 ioctl;真正的实现遍历 `ifp->if_multiaddrs` 并操作网卡上的哈希寄存器。 -**VLAN processing.** Real 驱动程序 set `IFCAP_VLAN_HWTAGGING` and allow `vlan(4)` to hand off tagging and untagging to the hardware. Without it, every VLAN-tagged 帧 goes through software `vlan_input()` and `vlan_output()`, slower but simpler. Our 驱动程序 is VLAN-transparent: it carries tagged 帧 as-is. +**VLAN 处理。** 真正的驱动程序设置 `IFCAP_VLAN_HWTAGGING` 并允许 `vlan(4)` 将标记和去标记交给硬件处理。没有它,每个 VLAN 标记的帧都通过软件 `vlan_input()` 和 `vlan_output()` 处理,速度较慢但更简单。我们的驱动程序是 VLAN 透明的:它原样携带标记帧。 -**Offload negotiation via SIOCSIFCAP.** `ifconfig mynet0 -rxcsum` toggles capabilities at runtime. Real 驱动程序 must gracefully handle the capability changing mid-flight: flush rings, reconfigure hardware, then accept traffic again. +**通过 SIOCSIFCAP 进行卸载协商。** `ifconfig mynet0 -rxcsum` 在运行时切换能力。真正的驱动程序必须优雅地处理能力在运行中途改变的情况:刷新环、重新配置硬件,然后再次接受流量。 -**SR-IOV.** Single-root I/O virtualisation lets a physical NIC present multiple virtual functions to a hypervisor. The FreeBSD support (`iov(9)`) is non-trivial. We did not go near it. +**SR-IOV。** 单根 I/O 虚拟化让物理网卡向虚拟机监控器呈现多个虚拟功能。FreeBSD 的支持(`iov(9)`)是不简单的。我们没有涉及它。 -**Wireless.** Wireless 驱动程序 use `net80211(4)`, a separate 框架 layered on top of `ifnet`. They have a rich state machine, complex rate control, encryption offload, and a completely different regulatory compliance story. Reading `/usr/src/sys/dev/ath/if_ath.c` is a worthwhile afternoon, but most of what it teaches is orthogonal to what we built here. +**无线。** 无线驱动程序使用 `net80211(4)`,一个构建在 `ifnet` 之上的独立框架。它们有丰富的状态机、复杂的速率控制、加密卸载和完全不同的监管合规要求。阅读 `/usr/src/sys/dev/ath/if_ath.c` 是值得花一个下午的,但它教授的大部分内容与我们这里构建的正交。 -**InfiniBand and RDMA.** Out of scope entirely. These use `/usr/src/sys/ofed/` and a separate OS-agnostic verb 框架. +**InfiniBand 和 RDMA。** 完全超出范围。它们使用 `/usr/src/sys/ofed/` 和一个独立的 OS 无关 verb 框架。 -**Virtualisation-specific acceleration.** `netmap(4)`, `vhost(4)`, and DPDK-style user-space fastpaths exist and matter in 2026 production environments. They are later-career topics. +**虚拟化专用加速。** `netmap(4)`、`vhost(4)` 和 DPDK 风格的用户空间快速路径存在且在 2026 年的生产环境中很重要。它们是职业生涯后期的主题。 -We cover none of these in full. We gave you pointers to each, so that when your job demands one of them, you know where to begin reading. +我们没有完整涵盖这些中的任何一个。我们给你每个的指引,所以当你的工作需要其中之一时,你知道从哪里开始阅读。 -## Historical Context: Why ifnet Looks the Way It Does +## 历史背景:为什么 ifnet 看起来是这样 -A last stop before the bridge: a short history lesson. Understanding where `ifnet` came from makes some of its rough edges less surprising. +跨过桥之前的最后一站:一堂简短的历史课。了解 `ifnet` 从何而来,使其一些粗糙边缘不那么令人惊讶。 -The earliest UNIX network stacks, in the late 1970s, had no `ifnet` structure at all. Each 驱动程序 provided an ad hoc set of 回调 注册ed through patchy conventions. When 4.2BSD introduced the 套接字s API and the modern TCP/IP stack in 1983, the BSD team also introduced `struct ifnet` as a uniform 接口 between the protocol code and the 驱动程序 code. The early version had about a dozen fields: a name, a unit number, a set of flags, an output 回调, and a handful of counters. Compared to modern `struct ifnet`, it looks almost empty. +最早的 UNIX 网络协议栈在 1970 年代末根本没有 `ifnet` 结构。每个驱动程序通过零散的约定提供一组临时的回调。当 4.2BSD 在 1983 年引入套接字 API 和现代 TCP/IP 协议栈时,BSD 团队也引入了 `struct ifnet` 作为协议代码和驱动程序代码之间的统一接口。早期版本大约有十几个字段:名称、单元号、一组标志、一个输出回调和一些计数器。与现代 `struct ifnet` 相比,它看起来几乎是空的。 -Over the next four decades, `struct ifnet` grew. BPF was added in the late 1980s. Multicast support arrived in the early 1990s. IPv6 support bolted on in the late 1990s. Interface cloning, media layer, and link-state events arrived through the 2000s. Offload capabilities, VNETs, checksum offload flags, TSO, LRO, and VLAN offload appeared through the 2010s. By the time FreeBSD 11 arrived in 2016, the structure had become unwieldy enough that the project introduced the `if_t` opaque type and the `if_get*`/`if_set*` accessor functions, so that the structure's layout could change without breaking binary compatibility for modules. +在接下来的四十年中,`struct ifnet` 不断增长。BPF 在 1980 年代末被添加。多播支持在 1990 年代初到达。IPv6 支持在 1990 年代末被添加。接口克隆、媒体层和链路状态事件在 2000 年代出现。卸载能力、VNET、校验和卸载标志、TSO、LRO 和 VLAN 卸载在 2010 年代出现。到 FreeBSD 11 在 2016 年发布时,该结构已经变得足够笨重,以至于项目引入了 `if_t` 不透明类型和 `if_get*`/`if_set*` 访问器函数,以便结构的布局可以在不破坏模块二进制兼容性的情况下改变。 -That history explains several things. It explains why `ifnet` has both `if_ioctl` and `if_ioctl2`; why some fields are accessed through macros and others directly; why `IFF_*` and `IFCAP_*` exist as parallel flag spaces; why the cloner API has both `if_clone_simple()` and `if_clone_advanced()`; why `ether_if附加()` exists as a wrapper over `if_附加()`. Each addition solved a real problem. The accumulated weight is the cost of living inside a running system that never had the luxury of a clean slate. +这段历史解释了几件事。它解释了为什么 `ifnet` 同时有 `if_ioctl` 和 `if_ioctl2`;为什么有些字段通过宏访问而其他的直接访问;为什么 `IFF_*` 和 `IFCAP_*` 作为并行的标志空间存在;为什么克隆器 API 同时有 `if_clone_simple()` 和 `if_clone_advanced()`;为什么 `ether_ifattach()` 作为 `if_attach()` 的包装器存在。每个添加都解决了一个真实的问题。累积的重量是生活在一个从未有过干净重启机会的运行系统内部的代价。 -For you, the practical takeaway is that ifnet's surface area is large and a little inconsistent. Read it as geology, not as architecture. The strata record real events in the history of UNIX networking. Once you know they are strata, the inconsistencies become navigable. +对你来说,实际的收获是 ifnet 的表面积很大且有点不一致。把它当作地质学而不是建筑学来读。地层记录了 UNIX 网络历史中的真实事件。一旦你知道它们是地层,不一致就变得可导航了。 -## Self-Assessment: Do You Really Know This Material? +## 自我评估:你真的掌握了这些内容吗? -Before moving on, measure your own understanding against a concrete rubric. A 网络驱动程序 author should be able to answer every question below without looking at the chapter. Work through them honestly. If you cannot answer one, re-read the relevant section; do not just skim until the answer looks familiar. +在继续之前,用具体的评分标准衡量自己的理解。网络驱动程序作者应该能够在不看本章的情况下回答以下每个问题。诚实地完成。如果你无法回答某个问题,重新阅读相关小节;不要只是浏览直到答案看起来熟悉。 -**Conceptual questions.** +**概念问题。** -1. What is the difference between `IFF_UP` and `IFF_DRV_RUNNING`, and which one decides whether a 帧 is actually sent? -2. Name three 回调 your 驱动程序 must provide, and for each one, describe what failing to implement it correctly would cause. -3. Why does the 内核 generate a random locally-administered MAC address for pseudo-接口, and what bit must be set to mark an address locally administered? -4. When `ether_input()` receives an 以太网 帧, which field of `m_pkthdr` tells the stack which 接口 the 帧 came from, and why does every inbound mbuf need it set correctly? -5. What does `net_epoch` protect, and why is it considered lighter weight than a traditional read lock? +1. `IFF_UP` 和 `IFF_DRV_RUNNING` 之间有什么区别,哪一个决定帧是否实际被发送? +2. 说出你的驱动程序必须提供的三个回调,对于每一个,描述未能正确实现它会导致什么后果。 +3. 为什么内核为伪接口生成随机本地管理的 MAC 地址,必须设置什么位来标记地址为本地管理? +4. 当 `ether_input()` 接收到以太网帧时,`m_pkthdr` 的哪个字段告诉栈帧来自哪个接口,为什么每个入站 mbuf 都需要正确设置它? +5. `net_epoch` 保护什么,为什么它被认为比传统读锁更轻量? -**Mechanical questions.** +**机械问题。** -6. Write, from memory, the sequence of function calls from `if_alloc()` through `ether_if附加()` that creates a minimum viable 接口. You do not need to remember argument lists; just the names and the order. -7. Write the exact macro call that feeds an outbound mbuf to BPF. Write the exact macro call for inbound. -8. Given an mbuf chain that might be fragmented, which helper gives you a single flat 缓冲区 suitable for DMA? Which helper ensures at least the first `n` bytes are contiguous? -9. Which ioctl does `ifconfig mynet0 192.0.2.1/24` produce? Which layer in the 内核 actually processes it: the generic `ifioctl()` dispatcher, `ether_ioctl()`, or your 驱动程序's `if_ioctl` 回调? Why? -10. Your 驱动程序 uses `callout_init_mtx(&sc->tick, &sc->mtx, 0)`. What is the purpose of the 互斥锁 argument, and what bug would arise if you passed `NULL`? +6. 凭记忆写出从 `if_alloc()` 到 `ether_ifattach()` 创建最小可行接口的函数调用序列。你不需要记住参数列表;只需名称和顺序。 +7. 写出将出站 mbuf 馈送给 BPF 的确切宏调用。写出入站的对应宏调用。 +8. 给定一个可能被分片的 mbuf 链,哪个辅助函数给你一个适合 DMA 的单一平坦缓冲区?哪个辅助函数确保至少前 `n` 个字节是连续的? +9. `ifconfig mynet0 192.0.2.1/24` 产生哪个 ioctl?内核中哪一层实际处理它:通用 `ifioctl()` 分发器、`ether_ioctl()` 还是你的驱动程序的 `if_ioctl` 回调?为什么? +10. 你的驱动程序使用 `callout_init_mtx(&sc->tick, &sc->mtx, 0)`。互斥锁参数的目的是什么,如果传 `NULL` 会出现什么 bug? -**Debugging questions.** +**调试问题。** -11. `ifconfig mynet0 up` returns instantly, but `netstat -in` shows the 接口 with zero 数据包 after ten minutes of `ping`. Describe the three most likely causes and the commands you would run to distinguish between them. -12. The module loads cleanly. `ifconfig mynet create` succeeds. `ifconfig mynet0 destroy` panics with a "locking assertion" message. What is the most likely bug? How would you fix it? -13. `tcpdump -i mynet0` shows outbound 数据包 but never inbound, even though `netstat -in` shows RX counters incrementing. Which function call is almost certainly missing, and on which code path? -14. You run `kldunload mynet` while an 接口 still exists. What happens? What safe sequence should the user have followed? How might a production 驱动程序 refuse to unload under these conditions? -15. Running `ifconfig mynet0 up` followed immediately by `ifconfig mynet0 down` a hundred times in a loop causes the machine to panic on the fiftieth iteration with a corrupted mbuf queue. Walk through the likely class of bug and the fix. +11. `ifconfig mynet0 up` 瞬间返回,但 `ping` 十分钟后 `netstat -in` 显示接口有零个数据包。描述最可能的三个原因以及你会运行哪些命令来区分它们。 +12. 模块干净地加载。`ifconfig mynet create` 成功。`ifconfig mynet0 destroy` 因"锁定断言"消息而崩溃。最可能的 bug 是什么?你会如何修复它? +13. `tcpdump -i mynet0` 显示出站数据包但从不说入站的,即使 `netstat -in` 显示 RX 计数器在递增。几乎可以确定缺少哪个函数调用,在哪个代码路径上? +14. 你在接口仍然存在的情况下运行 `kldunload mynet`。会发生什么?用户应该遵循什么安全序列?生产驱动程序如何在这些条件下拒绝卸载? +15. 循环运行 `ifconfig mynet0 up` 后立即 `ifconfig mynet0 down` 一百次,导致机器在第五十次迭代时因 mbuf 队列损坏而崩溃。分析可能的 bug 类别和修复方法。 -**Advanced questions.** +**高级问题。** -16. Explain in your own words what `net_epoch` provides that a 互斥锁 does not, and when you would use one versus the other inside a 网络驱动程序. -17. If your 驱动程序 advertises `IFCAP_VLAN_HWTAGGING`, how does that change the mbufs your transmit 回调 sees compared to the default? -18. The 内核 has two distinct delivery paths for inbound 帧: one via `netisr_dispatch()`, one via direct dispatch. What are they, and when would a 驱动程序 care which one is used? -19. What is the difference between `if_transmit` and the older `if_start`/`if_output` pair, and which should a new 驱动程序 use? -20. Describe the lifecycle of a VNET on a FreeBSD 14.3 system, and explain why a cloner 注册ed with `VNET_SYSINIT` produces a cloner in every VNET rather than a single global cloner. +16. 用你自己的话解释 `net_epoch` 提供了什么而互斥锁不能提供的,以及在网络驱动程序中何时使用其中一个而不是另一个。 +17. 如果你的驱动程序声明 `IFCAP_VLAN_HWTAGGING`,与默认情况相比,这如何改变你的发送回调看到的 mbuf? +18. 内核有两条不同的入站帧传递路径:一条通过 `netisr_dispatch()`,一条通过直接分发。它们是什么,驱动程序何时需要关心使用哪一条? +19. `if_transmit` 和较老的 `if_start`/`if_output` 对之间有什么区别,新驱动程序应该使用哪个? +20. 描述 FreeBSD 14.3 系统上 VNET 的生命周期,并解释为什么通过 `VNET_SYSINIT` 注册的克隆器在每个 VNET 中产生一个克隆器而不是单个全局克隆器。 -If you answered every question without hesitation, you are ready for Chapter 29. If five or more questions gave you trouble, spend another session with this chapter before moving forward. The next chapter builds on the assumption that you know this material cold. +如果你毫不犹豫地回答了每个问题,你就为第 29 章做好了准备。如果五个或更多问题让你感到困惑,在继续之前再花一个会话时间学习本章。下一章建立在你已经牢固掌握这些材料的基础上。 -## Further Reading and Source Code Study +## 延伸阅读和源码学习 -The bibliography below is small, targeted, and ordered by usefulness for a 驱动程序 author at your current stage. Treat it as a reading list for the weeks after you finish 第28章, not an overwhelming bookshelf. +下面的参考书目很小、有针对性,并按对你当前阶段驱动程序作者的有用程度排序。把它当作完成第 28 章后几周的阅读清单,而不是一个压倒性的书架。 -**Must read, in order.** +**必读,按顺序。** -- `/usr/src/sys/net/if.c`: the generic 接口 machinery. Start with `if_alloc()`, `if_附加()`, `if_分离()`, and the ioctl dispatcher `ifioctl()`. This is the file that actually runs the lifecycle functions you call in your 驱动程序. -- `/usr/src/sys/net/if_ethersubr.c`: 以太网 framing. Read `ether_if附加()`, `ether_if分离()`, `ether_output()`, `ether_input()`, and `ether_ioctl()`. These four functions form the contract between your 驱动程序 and the 以太网 layer. -- `/usr/src/sys/net/if_disc.c`: the minimal pseudo-驱动程序. Less than 200 lines. A reference for the absolute minimum viable `ifnet`. -- `/usr/src/sys/net/if_epair.c`: the paired pseudo-驱动程序. The cleanest reference for writing a cloner with a shared structure between two instances. -- `/usr/src/sys/dev/virtio/network/if_vtnet.c`: a modern paravirtual 驱动程序. Small enough to read fully, realistic enough to teach you about rings, checksum offload, multiqueue, and hardware-like resource management. +- `/usr/src/sys/net/if.c`:通用接口机制。从 `if_alloc()`、`if_attach()`、`if_detach()` 和 ioctl 分发器 `ifioctl()` 开始。这是实际运行你在驱动程序中调用的生命周期函数的文件。 +- `/usr/src/sys/net/if_ethersubr.c`:以太网成帧。阅读 `ether_ifattach()`、`ether_ifdetach()`、`ether_output()`、`ether_input()` 和 `ether_ioctl()`。这四个函数构成了你的驱动程序与以太网层之间的契约。 +- `/usr/src/sys/net/if_disc.c`:最小伪驱动程序。不到 200 行。绝对最小可行 `ifnet` 的参考。 +- `/usr/src/sys/net/if_epair.c`:成对伪驱动程序。编写在两个实例之间共享结构的克隆器的最清晰参考。 +- `/usr/src/sys/dev/virtio/network/if_vtnet.c`:现代半虚拟化驱动程序。足够小可以完整阅读,足够真实可以教你关于环、校验和卸载、多队列和类似硬件的资源管理。 -**Read next, when the time comes.** +**接下来阅读,当时机成熟时。** -- `/usr/src/sys/dev/e1000/if_em.c` and the accompanying `em_txrx.c`, `if_em.h`: a production Intel NIC 驱动程序. Larger and more elaborate, but representative of real-world 驱动程序 complexity. -- `/usr/src/sys/net/iflib.c` and `/usr/src/sys/net/iflib.h`: the iflib 框架. Read after you have studied `if_em.c` so you can recognise the structures iflib takes over. -- `/usr/src/sys/net/if_lagg.c`: the link aggregation 驱动程序. A detailed study of multi-接口 orchestration, failover, and mode selection. -- `/usr/src/sys/net/if_bridge.c`: software bridging. Excellent for learning multicast forwarding, learning bridges, and the STP state machine. +- `/usr/src/sys/dev/e1000/if_em.c` 及附带的 `em_txrx.c`、`if_em.h`:生产级 Intel 网卡驱动程序。更大、更精细,但代表了真实世界的驱动程序复杂性。 +- `/usr/src/sys/net/iflib.c` 和 `/usr/src/sys/net/iflib.h`:iflib 框架。在研究了 `if_em.c` 之后阅读,这样你可以识别 iflib 接管的那些结构。 +- `/usr/src/sys/net/if_lagg.c`:链路聚合驱动程序。多接口编排、故障转移和模式选择的详细研究。 +- `/usr/src/sys/net/if_bridge.c`:软件桥接。学习多播转发、学习型网桥和 STP 状态机的极佳材料。 -**Worthwhile manual pages.** +**值得阅读的手册页。** -- `ifnet(9)`: the 接口 框架. -- `mbuf(9)`: the 数据包 缓冲区 system. -- `bpf(9)` and `bpf(4)`: the Berkeley Packet Filter. -- `ifmedia(9)`: the media 框架. -- `ether(9)`: 以太网 helpers. -- `vnet(9)`: virtualised network stacks. -- `net_epoch(9)`: the network epoch synchronisation primitive. -- `iflib(9)`: the iflib 框架. -- `netmap(4)`: high-speed user-space 数据包 I/O. -- `netgraph(4)` and `netgraph(3)`: the netgraph 框架. -- `if_clone(9)`: 接口 cloning. +- `ifnet(9)`:接口框架。 +- `mbuf(9)`:数据包缓冲区系统。 +- `bpf(9)` 和 `bpf(4)`:Berkeley 包过滤器。 +- `ifmedia(9)`:媒体框架。 +- `ether(9)`:以太网辅助函数。 +- `vnet(9)`:虚拟化网络栈。 +- `net_epoch(9)`:网络 epoch 同步原语。 +- `iflib(9)`:iflib 框架。 +- `netmap(4)`:高速用户空间包 I/O。 +- `netgraph(4)` 和 `netgraph(3)`:netgraph 框架。 +- `if_clone(9)`:接口克隆。 **Books and papers.** -The 4.4BSD design books (particularly "The Design and Implementation of the 4.4BSD Operating System" by McKusick, Bostic, Karels, and Quarterman) remain the best long-form explanation of how the 套接字s and 接口 layers came to exist. The FreeBSD Developer's Handbook sections on 内核 programming and loadable modules are the next stop for general background. For 数据包 processing at speed, the `netmap` papers by Luigi Rizzo are foundational; they explain both the techniques and the rationale behind modern high-performance 数据包 pipelines. +4.4BSD 设计书籍(特别是 McKusick、Bostic、Karels 和 Quarterman 的「4.4BSD 操作系统的设计与实现」)仍然是关于套接字和接口层如何产生的最佳长篇解释。FreeBSD 开发者手册中关于内核编程和可加载模块的章节是下一步的一般背景。对于高速数据包处理,Luigi Rizzo 的 `netmap` 论文是基础性的;它们解释了现代高性能数据包管道背后的技术和原理。 -Keep a reading journal. When you finish a file, write a paragraph summarising what surprised you, what you want to revisit, and what you think you might steal for your own 驱动程序. Over six months of this practice, your intuition for how production 驱动程序 are structured will grow faster than you expect. +保持阅读日志。当你读完一个文件时,写一段话总结什么让你惊讶、你想重新看什么、以及你认为可能为自己的驱动程序偷用什么。经过六个月的这种练习,你对生产驱动程序结构的直觉增长速度将超出你的预期。 -## Frequently Asked Questions +## 常见问题 -New 驱动程序 authors tend to ask the same questions as they work through their first `ifnet` 驱动程序. Here are the most common ones, with short, pointed answers. Each answer is a signpost, not an exhaustive treatment; follow the bread crumbs back to the relevant section of the chapter if you want more detail. +新驱动程序作者在编写第一个 `ifnet` 驱动程序时倾向于问相同的问题。以下是最常见的问题,附有简短、有针对性的回答。每个回答都是一个路标,不是详尽的论述;如果你想要更多细节,沿着面包屑回到本章的相关小节。 -**Q: Can I write an 以太网 驱动程序 without using `ether_if附加`?** +**Q: 我可以不使用 `ether_ifattach` 编写以太网驱动程序吗?** -Technically yes; practically no. `ether_if附加()` sets `if_input` to `ether_input()`, hooks BPF with `bpf附加()`, and configures a dozen small default behaviours. Skipping it means reimplementing every one of those defaults by hand. The only reason to bypass `ether_if附加()` is if your 驱动程序 is not actually 以太网, in which case you will use `if_附加()` directly and supply your own framing 回调. +技术上可以;实际上不行。`ether_ifattach()` 将 `if_input` 设置为 `ether_input()`,用 `bpfattach()` 钩住 BPF,并配置十几个小的默认行为。跳过它意味着手动重新实现每一个默认值。绕过 `ether_ifattach()` 的唯一原因是如果你的驱动程序实际上不是以太网,那种情况下你会直接使用 `if_attach()` 并提供自己的成帧回调。 -**Q: What is the difference between `if_transmit` and `if_output`?** +**Q: `if_transmit` 和 `if_output` 有什么区别?** -`if_output` is the older, protocol-agnostic output 回调. For 以太网 驱动程序, it is set to `ether_output()` by `ether_if附加()`, and it handles ARP resolution and 以太网 framing before calling `if_transmit`. `if_transmit` is the 驱动程序-specific 回调 you write. In short: `if_output` is what the stack calls; `if_transmit` is what `if_output` calls; your 驱动程序 supplies the latter. +`if_output` 是较老的、协议无关的输出回调。对于以太网驱动程序,它被 `ether_ifattach()` 设置为 `ether_output()`,它在调用 `if_transmit` 之前处理 ARP 解析和以太网成帧。`if_transmit` 是你编写的驱动程序特定回调。简而言之:`if_output` 是协议栈调用的;`if_transmit` 是 `if_output` 调用的;你的驱动程序提供后者。 -**Q: Do I need to handle `SIOCSIFADDR` in my ioctl 回调?** +**Q: 我需要在 ioctl 回调中处理 `SIOCSIFADDR` 吗?** -Not directly. `ether_ioctl()` handles address configuration for 以太网 接口. Your 回调 should delegate unrecognised ioctls to `ether_ioctl()` via the `default:` arm of its switch statement, and address-related ioctls will flow through that path correctly. +不需要直接处理。`ether_ioctl()` 处理以太网接口的地址配置。你的回调应该通过 switch 语句的 `default:` 分支将未识别的 ioctl 委托给 `ether_ioctl()`,地址相关的 ioctl 将通过该路径正确流动。 -**Q: How do I know when a 帧 has actually been transmitted by the hardware?** +**Q: 我如何知道帧何时真正被硬件发送了?** -For our pseudo-驱动程序, "transmit" is synchronous: `mynet_transmit()` frees the mbuf immediately. For a real NIC 驱动程序, the hardware signals completion via an interrupt or a ring 描述符 flag; the 驱动程序's transmit completion handler (sometimes called the "tx reaper") walks the ring, releases the mbufs, and updates counters. Read `if_em.c`'s `em_txeof()` for a concrete example. +对于我们的伪驱动程序,「发送」是同步的:`mynet_transmit()` 立即释放 mbuf。对于真正的网卡驱动程序,硬件通过中断或环描述符标志发出完成信号;驱动程序的发送完成处理程序(有时称为「tx reaper」)遍历环、释放 mbuf 并更新计数器。阅读 `if_em.c` 的 `em_txeof()` 获取具体示例。 -**Q: Why does `ifconfig mynet0 delete` not call my 驱动程序?** +**Q: 为什么 `ifconfig mynet0 delete` 不调用我的驱动程序?** -Because address configuration lives in the protocol layer, not the 接口 layer. Removing an address from an 以太网 接口 is handled by `in_control()` (for IPv4) or `in6_control()` (for IPv6). Your 驱动程序 is unaware of these operations; it only sees them indirectly through route changes and ARP table updates. +因为地址配置存在于协议层,而不是接口层。从以太网接口删除地址由 `in_control()`(对于 IPv4)或 `in6_control()`(对于 IPv6)处理。你的驱动程序不知道这些操作;它只通过路由变更和 ARP 表更新间接地感知它们。 -**Q: Why is my 驱动程序 panicking when I call `if_inc_counter()` from a callout?** +**Q: 为什么我的驱动程序在从 callout 调用 `if_inc_counter()` 时会崩溃?** -Almost certainly because you are holding a non-recursive 互斥锁 that was acquired elsewhere. `if_inc_counter()` is safe from any context on modern FreeBSD, but if your callout acquires a lock that the callout infrastructure already holds, you deadlock. The safest pattern is to call `if_inc_counter()` without holding any 驱动程序-specific locks, and to update your own counters separately inside the lock. +几乎可以确定是因为你持有一个在其他地方获取的非递归互斥锁。`if_inc_counter()` 在现代 FreeBSD 上从任何上下文调用都是安全的,但如果你的 callout 获取了一个 callout 基础设施已经持有的锁,就会死锁。最安全的模式是在不持有任何驱动程序特定锁的情况下调用 `if_inc_counter()`,并在锁内单独更新你自己的计数器。 -**Q: How do I make my 驱动程序 show up in `sysctl net.link.generic.ifdata.mynet0.link`?** +**Q: 如何让我的驱动程序出现在 `sysctl net.link.generic.ifdata.mynet0.link` 中?** -You do not. That sysctl tree is populated automatically by the generic `ifnet` layer. Every 接口 注册ed via `if_附加()` (directly or via `ether_if附加()`) receives a sysctl node. If yours is missing, your 接口 did not 附加 correctly. +你不需要。该 sysctl 树由通用 `ifnet` 层自动填充。每个通过 `if_attach()`(直接或通过 `ether_ifattach()`)注册的接口都会获得一个 sysctl 节点。如果你的缺失了,说明你的接口没有正确附加。 -**Q: My 驱动程序 works on FreeBSD 14.3 but fails to build on FreeBSD 13.x. Why?** +**Q: 我的驱动程序在 FreeBSD 14.3 上工作但在 FreeBSD 13.x 上构建失败。为什么?** -The `if_t` opaque type and the associated accessor functions were stabilised across FreeBSD 13 and 14, but several helper APIs only arrived in 14. For example, `if_clone_simple()` has existed for years, but some of the counter accessor helpers are new. Either use `__FreeBSD_version` guards to compile cleanly on both, or state clearly in your 驱动程序 that FreeBSD 14.0 or later is required. +`if_t` 不透明类型及关联的访问器函数在 FreeBSD 13 和 14 之间已稳定,但一些辅助 API 只在 14 中出现。例如,`if_clone_simple()` 已经存在多年,但一些计数器访问器辅助函数是新的。要么使用 `__FreeBSD_version` 守卫在两个版本上干净编译,要么在驱动程序中明确声明需要 FreeBSD 14.0 或更高版本。 -**Q: I want to write a 驱动程序 that accepts 数据包 on one 接口 and retransmits them on another. Is that a 网络驱动程序?** +**Q: 我想编写一个在一个接口上接收数据包并在另一个接口上重新发送的驱动程序。那是网络驱动程序吗?** -Not quite. That is a bridge or a forwarder. The FreeBSD 内核 has `if_bridge(4)` for bridging, `netgraph(4)` for arbitrary 数据包 pipelines, and `pf(4)` for filtering and policy. Writing your own forwarding code from scratch is almost never the right answer in 2026; the existing 框架 are better-maintained, faster, and more flexible. Read them and configure them before writing a new 驱动程序. +不完全是。那是一个桥接器或转发器。FreeBSD 内核有 `if_bridge(4)` 用于桥接,`netgraph(4)` 用于任意包管道,`pf(4)` 用于过滤和策略。在 2026 年从零开始编写自己的转发代码几乎从来不是正确的答案;现有的框架维护得更好、更快、更灵活。在编写新驱动程序之前,先阅读和配置它们。 -**Q: Do I need to worry about endianness inside my 网络驱动程序?** +**Q: 我需要担心网络驱动程序中的字节序吗?** -Only at specific boundaries. 以太网 帧 are network byte order (big-endian) by convention; if you parse an 以太网 header yourself, the `ether_type` field needs `ntohs()`. Inside the mbuf, the data is stored in network byte order, not the host's native order. The `ether_input()` and `ether_output()` functions handle the conversions for you, so most 驱动程序 code does not touch endianness directly. +只在特定边界上。以太网帧按照约定是网络字节序(大端序);如果你自己解析以太网头,`ether_type` 字段需要 `ntohs()`。在 mbuf 内部,数据以网络字节序存储,而不是主机本机字节序。`ether_input()` 和 `ether_output()` 函数为你处理转换,因此大多数驱动程序代码不直接接触字节序。 -**Q: When do I use `m_pullup()` versus `m_copydata()`?** +**Q: 我何时使用 `m_pullup()` 还是 `m_copydata()`?** -`m_pullup(m, n)` mutates the mbuf chain so that the first `n` bytes are stored contiguously in memory, making them safe to access with a pointer cast. `m_copydata(m, off, len, buf)` copies bytes out of the mbuf chain into a separate 缓冲区 you provide. Use `m_pullup()` when you want to read and potentially modify header fields in place. Use `m_copydata()` when you want a snapshot for inspection without disturbing the mbuf. +`m_pullup(m, n)` 改变 mbuf 链,使前 `n` 个字节在内存中连续存储,使得用指针类型转换安全访问它们。`m_copydata(m, off, len, buf)` 从 mbuf 链中复制字节到你提供的单独缓冲区。当你想就地读取并可能修改头字段时使用 `m_pullup()`。当你想获取一个快照用于检查而不扰动 mbuf 时使用 `m_copydata()`。 -**Q: Why does `netstat -I mynet0 1` sometimes show zero bytes even when 数据包 are being exchanged?** +**Q: 为什么 `netstat -I mynet0 1` 有时即使数据包正在交换也显示零字节?** -You may be incrementing `IFCOUNTER_IPACKETS` or `IFCOUNTER_OPACKETS` without also incrementing `IFCOUNTER_IBYTES` or `IFCOUNTER_OBYTES`. The per-second display shows bytes separately; if the byte counters never move, `netstat -I` reports zero throughput. Always update 数据包 count and byte count together. +你可能递增了 `IFCOUNTER_IPACKETS` 或 `IFCOUNTER_OPACKETS` 但没有同时递增 `IFCOUNTER_IBYTES` 或 `IFCOUNTER_OBYTES`。每秒显示单独显示字节;如果字节计数器从未移动,`netstat -I` 报告零吞吐量。始终同时更新包计数和字节计数。 -**Q: How do I destroy all cloned 接口 on module unload?** +**Q: 如何在模块卸载时销毁所有克隆接口?** -The simplest approach is to let `if_clone_分离()` do it for you; the clone 分离 helper walks the cloner's 接口 list and destroys each one. If you want to defend against leaks, you can also enumerate the 接口 belonging to the cloner and destroy them explicitly before calling `if_clone_分离()`. The shorter path is usually the better one, because the helper is tested and yours probably is not. +最简单的方法是让 `if_clone_detach()` 替你做;克隆分离辅助函数遍历克隆器的接口列表并逐个销毁。如果你想防止泄漏,也可以在调用 `if_clone_detach()` 之前显式枚举属于克隆器的接口并销毁它们。较短的路径通常更好,因为辅助函数经过了测试,而你的可能没有。 -**Q: My 驱动程序 works under `ping` but crashes during a large `iperf3` run. What is typical?** +**Q: 我的驱动程序在 `ping` 下工作但在大型 `iperf3` 运行时崩溃。这通常是什么原因?** -At high 数据包 rates, all the subtle concurrency bugs in a 驱动程序 become exposed. Common causes include: a counter updated outside a lock that runs on multiple CPUs, a mbuf queue that is not properly drained before free, a callout that fires during shutdown, a `BPF_MTAP()` call after the 接口 was 分离ed. Run with WITNESS and INVARIANTS enabled; the locking assertions almost always catch it. +在高包速率下,驱动程序中所有微妙的并发 bug 都会暴露出来。常见原因包括:在锁外更新在多个 CPU 上运行的计数器、释放前未正确排空的 mbuf 队列、在关机期间触发的 callout、接口分离后调用的 `BPF_MTAP()`。启用 WITNESS 和 INVARIANTS 运行;锁定断言几乎总能捕获它。 -## A Short Closing Note on Craft +## 关于工艺的简短结语 -We have spent many pages on mechanics: 回调, locks, mbufs, ioctls, counters. The mechanics are necessary, but they are not sufficient. A good 网络驱动程序 is the product of a disciplined author, not merely a correct set of 回调. +我们在机制上花了很多页:回调、锁、mbuf、ioctl、计数器。机制是必要的,但还不够。一个好的网络驱动程序是一个有纪律的作者的产物,而不仅仅是一组正确的回调。 -That discipline shows up in small places. It shows up in the decision to drain a callout on 分离 even though the test suite never catches a leak. It shows up in the decision to update a counter in the right order so that `netstat -s` adds up across a long run. It shows up in the decision to log once, clearly, when a resource cannot be allocated, rather than either staying silent or flooding the log. It shows up in the decision to use `M_ZERO` when allocating a softc, so that any future field added to the structure starts at a known zero even if the explicit initialisation is forgotten. +那种纪律体现在小地方。它体现在即使在测试套件从未捕获泄漏的情况下也决定在分离时排空 callout。它体现在决定以正确的顺序更新计数器,使 `netstat -s` 在长时间运行中数据一致。它体现在决定当资源无法分配时清晰记录一次日志,而不是保持沉默或淹没日志。它体现在决定在分配 softc 时使用 `M_ZERO`,这样即使忘记显式初始化,结构中未来添加的任何字段也从已知的零开始。 -Each decision is small. The accumulated effect is the difference between a 驱动程序 that works on the first day and a 驱动程序 that works on the thousandth day. You are training a habit, not memorising a syntax. Be patient with yourself while the habit forms; it takes years. +每个决定都是小的。累积的效果是一个在第一天有效的驱动程序和一个在第一千天有效的驱动程序之间的区别。你正在训练一种习惯,而不是记忆一种语法。在习惯形成期间对自己有耐心;这需要数年时间。 -The great FreeBSD 驱动程序 authors, the ones whose names you see in the `$FreeBSD$` tags and the commit logs, did not become great by knowing the API better than you. They became great by reviewing their own work as if someone else wrote it, and fixing every small flaw they found. That practice scales. Pick it up early. +伟大的 FreeBSD 驱动程序作者,你在 `$FreeBSD$` 标签和提交日志中看到名字的那些人,不是因为他们比你更了解 API 而变得伟大的。他们之所以伟大是因为像审视别人的作品一样审视自己的作品,并修复他们发现的每一个小缺陷。这种实践是可以扩展的。尽早养成这个习惯。 -## Mini-术语表 of Network Driver Terms +## 网络驱动程序术语小词典 -A short glossary follows, aimed at the reader who wants to revisit the chapter's core vocabulary in one place. Use it as a refresher, not as a replacement for the explanations in the main text. +下面是一个简短的术语表,面向希望在一个地方回顾本章核心词汇的读者。把它当作复习参考,而不是正文解释的替代品。 -- **ifnet.** The 内核 data structure representing a 网络接口. Each 附加ed 接口 has exactly one `ifnet`. The opaque handle `if_t` is used by most modern code. -- **ether_if附加.** The wrapper over `if_附加()` that sets up 以太网-specific defaults, including BPF hooks and the standard `if_input` function. -- **cloner.** A factory for pseudo-接口. Registered with `if_clone_simple()` or `if_clone_advanced()`. Responsible for creating and destroying 接口 in response to `ifconfig name create` and `ifconfig name0 destroy`. -- **mbuf.** The 内核's 数据包 缓冲区. A small struct with metadata, an optional embedded payload, and pointers to additional 缓冲区 for chained data. Allocated with `m_gethdr()`, freed with `m_freem()`. -- **softc.** Per-instance 驱动程序 state. Allocated with `malloc(M_ZERO)` in the cloner create 回调 and freed in the cloner destroy 回调. Traditionally points to 互斥锁, media 描述符, callout, and the 接口. -- **BPF.** The Berkeley Packet Filter, a 框架 for userland tools like `tcpdump` to observe the traffic on an 接口. Drivers hook into it with `BPF_MTAP()` on both transmit and receive paths. -- **IFF_UP.** The administrative flag set by `ifconfig name0 up`. Indicates user intent to activate the 接口. -- **IFF_DRV_RUNNING.** The 驱动程序-controlled flag indicating the 驱动程序 is prepared to send and receive 数据包. Set inside the 驱动程序 after hardware (or pseudo-hardware) initialisation completes. -- **Media.** The abstraction for link speed, duplex, autonegotiation, and related physical-layer properties. Managed through the `ifmedia(9)` 框架. -- **Link state.** A three-valued indicator (`LINK_STATE_UP`, `LINK_STATE_DOWN`, `LINK_STATE_UNKNOWN`) reported via `if_link_state_change()`. Used by routing daemons and userland tools. -- **VNET.** FreeBSD's virtualised network stack. Each VNET has its own 接口 list, routing table, and 套接字s. Pseudo-驱动程序 typically use `VNET_SYSINIT` to 注册 cloners in every VNET. -- **net_epoch.** A lightweight synchronisation primitive used to delimit read-side critical sections in the network stack. Faster than a traditional read lock. -- **IFCAP.** A bitfield of capabilities (`IFCAP_RXCSUM`, `IFCAP_TSO4`, etc.) negotiated between the 驱动程序 and the stack. Controls which offloads are active on a given 接口. -- **IFCOUNTER.** A named counter (`IFCOUNTER_IPACKETS`, `IFCOUNTER_OBYTES`, etc.) displayed by `netstat`. Updated by 驱动程序 via `if_inc_counter()`. -- **以太网 type.** The 16-bit field in an 以太网 帧 header identifying the encapsulated protocol. Values are defined in `net/ethernet.h`, with `ETHERTYPE_IP` and `ETHERTYPE_ARP` being the most common. -- **Jumbo 帧.** An 以太网 帧 larger than the standard 1500-byte MTU, typically 9000 bytes. Drivers advertise support through `ifp->if_capabilities |= IFCAP_JUMBO_MTU`. -- **Promiscuous mode.** A mode in which the 接口 delivers every observed 帧 to the stack, not only those addressed to its own MAC. Controlled via `IFF_PROMISC`. Used by network analysis tools. -- **Multicast.** Frames addressed to a group of receivers rather than a single destination. Drivers track group memberships through `SIOCADDMULTI` and `SIOCDELMULTI`, typically programming a hardware hash filter. -- **Checksum offload.** A capability where the NIC computes TCP, UDP, and IP header checksums in hardware. Negotiated through `IFCAP_RXCSUM` and `IFCAP_TXCSUM`; flagged per mbuf via `m_pkthdr.csum_flags`. -- **TSO (TCP Segmentation Offload).** A capability where the host hands the NIC a large TCP segment and the NIC splits it into MTU-sized fragments. Negotiated via `IFCAP_TSO4` and `IFCAP_TSO6`. -- **LRO (Large Receive Offload).** The receive-side counterpart to TSO. The NIC or software layer aggregates sequential inbound segments into a single large mbuf chain before handing it to the stack. -- **VLAN tagging.** A four-byte shim in the 以太网 帧 that identifies the VLAN membership. Drivers may advertise `IFCAP_VLAN_HWTAGGING` to offload the insertion and removal to hardware. -- **MSI-X.** Message-signalled interrupts, the modern replacement for wired IRQs. Allows the NIC to raise separate interrupts per queue. -- **Interrupt moderation.** A technique where the NIC coalesces multiple completion events into fewer interrupts, reducing overhead at high 数据包 rates. -- **Ring 缓冲区.** A circular queue of 描述符 shared between the 驱动程序 and the NIC. Transmit rings feed 数据包 to hardware; receive rings deliver 数据包 from hardware. -- **iflib.** FreeBSD's modern NIC 驱动程序 框架. Abstracts ring management, interrupt handling, and mbuf flow so the 驱动程序 author can focus on hardware-specific code. -- **netmap.** A high-performance 数据包 I/O 框架 that gives userland direct access to 驱动程序 rings, bypassing most of the network stack. -- **netgraph.** A flexible 框架 for composing 数据包-processing pipelines out of reusable nodes. Largely orthogonal to 驱动程序 writing but often relevant to network architecture. -- **pf.** FreeBSD's 数据包 filter. A firewall and NAT engine that sits inline with `ether_input()` and `ether_output()` via `pfil(9)` hooks. Drivers do not interact with it directly; the hooks are inserted by the generic layers. -- **pfil.** The 数据包 filter 接口 through which firewalls 附加 to the forwarding path. Gives 框架 like `pf` and `ipfw` a stable place to observe and modify 数据包. -- **if_transmit.** The per-驱动程序 outbound 回调, set during 接口 allocation. Receives an mbuf chain, is responsible for queueing it for hardware or discarding it. -- **if_input.** The per-接口 inbound 回调. For 以太网 驱动程序, set to `ether_input()` by `ether_if附加()`. The 驱动程序 calls it via the `if_input(ifp, m)` helper to hand received 帧 up to the stack. -- **if_ioctl.** The per-驱动程序 ioctl 回调. Handles 接口-level ioctls such as `SIOCSIFFLAGS`, `SIOCSIFMTU`, and `SIOCSIFMEDIA`. Delegates unknown ioctls to `ether_ioctl()` for 以太网 驱动程序. +- **ifnet.** 表示网络接口的内核数据结构。每个已附加的接口恰好有一个 `ifnet`。大多数现代代码使用不透明句柄 `if_t`。 +- **ether_ifattach.** `if_attach()` 之上的包装器,设置以太网特定的默认值,包括 BPF 钩子和标准 `if_input` 函数。 +- **克隆器 (cloner).** 伪接口的工厂。通过 `if_clone_simple()` 或 `if_clone_advanced()` 注册。负责响应 `ifconfig name create` 和 `ifconfig name0 destroy` 创建和销毁接口。 +- **mbuf.** 内核的数据包缓冲区。一个带有元数据的小结构,可选的嵌入有效载荷,以及指向链式数据额外缓冲区的指针。用 `m_gethdr()` 分配,用 `m_freem()` 释放。 +- **softc.** 每实例的驱动程序状态。在克隆器创建回调中用 `malloc(M_ZERO)` 分配,在克隆器销毁回调中释放。传统上指向互斥锁、媒体描述符、callout 和接口。 +- **BPF.** Berkeley 包过滤器,一个让 `tcpdump` 等用户空间工具观察接口流量的框架。驱动程序在发送和接收路径上都通过 `BPF_MTAP()` 钩入它。 +- **IFF_UP.** 由 `ifconfig name0 up` 设置的管理标志。指示用户激活接口的意图。 +- **IFF_DRV_RUNNING.** 驱动程序控制的标志,指示驱动程序已准备好发送和接收数据包。在硬件(或伪硬件)初始化完成后在驱动程序内部设置。 +- **媒体 (Media).** 链路速度、双工、自动协商和相关物理层属性的抽象。通过 `ifmedia(9)` 框架管理。 +- **链路状态 (Link state).** 一个三值指示器(`LINK_STATE_UP`、`LINK_STATE_DOWN`、`LINK_STATE_UNKNOWN`),通过 `if_link_state_change()` 报告。由路由守护进程和用户空间工具使用。 +- **VNET.** FreeBSD 的虚拟化网络栈。每个 VNET 有自己的接口列表、路由表和套接字。伪驱动程序通常使用 `VNET_SYSINIT` 在每个 VNET 中注册克隆器。 +- **net_epoch.** 用于划分网络栈中读侧临界区的轻量级同步原语。比传统读锁更快。 +- **IFCAP.** 驱动程序和协议栈之间协商的能力位字段(`IFCAP_RXCSUM`、`IFCAP_TSO4` 等)。控制给定接口上哪些卸载处于活动状态。 +- **IFCOUNTER.** 由 `netstat` 显示的命名计数器(`IFCOUNTER_IPACKETS`、`IFCOUNTER_OBYTES` 等)。驱动程序通过 `if_inc_counter()` 更新。 +- **以太网类型 (Ethernet type).** 以太网帧头中标识封装协议的 16 位字段。值定义在 `net/ethernet.h` 中,`ETHERTYPE_IP` 和 `ETHERTYPE_ARP` 是最常见的。 +- **巨型帧 (Jumbo frame).** 大于标准 1500 字节 MTU 的以太网帧,通常为 9000 字节。驱动程序通过 `ifp->if_capabilities |= IFCAP_JUMBO_MTU` 声明支持。 +- **混杂模式 (Promiscuous mode).** 接口将每个观察到的帧传递给协议栈的模式,不仅仅是那些寻址到自身 MAC 的帧。通过 `IFF_PROMISC` 控制。用于网络分析工具。 +- **多播 (Multicast).** 寻址到一组接收者而不是单个目的地的帧。驱动程序通过 `SIOCADDMULTI` 和 `SIOCDELMULTI` 跟踪组成员资格,通常编程硬件哈希过滤器。 +- **校验和卸载 (Checksum offload).** 网卡在硬件中计算 TCP、UDP 和 IP 头校验和的能力。通过 `IFCAP_RXCSUM` 和 `IFCAP_TXCSUM` 协商;通过 `m_pkthdr.csum_flags` 按 mbuf 标记。 +- **TSO(TCP 分段卸载).** 主机将大型 TCP 段交给网卡,网卡将其拆分为 MTU 大小的片段的能力。通过 `IFCAP_TSO4` 和 `IFCAP_TSO6` 协商。 +- **LRO(大接收卸载).** TSO 的接收侧对应。网卡或软件层在将顺序入站段交给协议栈之前将它们聚合成单个大型 mbuf 链。 +- **VLAN 标记.** 以太网帧中标识 VLAN 成员资格的四字节插入。驱动程序可以声明 `IFCAP_VLAN_HWTAGGING` 以将插入和移除卸载到硬件。 +- **MSI-X.** 消息信号中断,有线 IRQ 的现代替代。允许网卡按队列引发独立中断。 +- **中断调节.** 网卡将多个完成事件合并为更少中断的技术,在高包速率下减少开销。 +- **环形缓冲区 (Ring buffer).** 驱动程序和网卡之间共享的描述符循环队列。发送环将数据包馈送给硬件;接收环从硬件传递数据包。 +- **iflib.** FreeBSD 的现代网卡驱动程序框架。抽象环管理、中断处理和 mbuf 流,使驱动程序作者可以专注于硬件特定代码。 +- **netmap.** 高性能包 I/O 框架,给用户空间直接访问驱动环的权限,绕过大部分网络栈。 +- **netgraph.** 用于从可重用节点组合包处理管道的灵活框架。大部分与驱动程序编写正交,但通常与网络架构相关。 +- **pf.** FreeBSD 的包过滤器。一个防火墙和 NAT 引擎,通过 `pfil(9)` 钩子内联在 `ether_input()` 和 `ether_output()` 之间。驱动程序不直接与它交互;钩子由通用层插入。 +- **pfil.** 包过滤器接口,防火墙通过它附加到转发路径。为 `pf` 和 `ipfw` 等框架提供观察和修改数据包的稳定位置。 +- **if_transmit.** 每驱动程序的出站回调,在接口分配期间设置。接收 mbuf 链,负责将其排队到硬件或丢弃它。 +- **if_input.** 每接口的入站回调。对于以太网驱动程序,由 `ether_ifattach()` 设置为 `ether_input()`。驱动程序通过 `if_input(ifp, m)` 辅助函数调用它,将接收到的帧向上传递给协议栈。 +- **if_ioctl.** 每驱动程序的 ioctl 回调。处理接口级 ioctl,如 `SIOCSIFFLAGS`、`SIOCSIFMTU` 和 `SIOCSIFMEDIA`。将以太网驱动程序未知的 ioctl 委托给 `ether_ioctl()`。 -Keep this glossary nearby as you read Chapter 29 and the chapters that follow. Each term recurs often enough that a quick reference pays for itself. +在阅读第 29 章及后续章节时,请将本术语表放在手边。每个术语出现的频率足够高,快速参考的价值不言而喻。 -## 第6部分 Checkpoint +## 第6部分检查点 -第6部分 put the discipline of Parts 1 through 5 under three very different transports: USB, GEOM-backed storage, and `ifnet`-based network. Before Part 7 returns to the cumulative `myfirst` arc and starts pushing on portability, security, performance, and craft, confirm that the three transport vocabularies have settled into the same underlying model. +第 6 部分将第 1 到第 5 部分的规范置于三种截然不同的传输方式之下:USB、基于 GEOM 的存储和基于 `ifnet` 的网络。在第 7 部分回到累积的 `myfirst` 主线并开始推进可移植性、安全性、性能和工艺之前,确认这三种传输方式的词汇已经沉淀为相同的底层模型。 -By the end of 第6部分 you should be able to do each of the following: +到第 6 部分结束时,你应该能够做到以下每一项: -- Attach to a USB 设备 through the `usb_request_methods` 框架: configure transfers for control, bulk, interrupt, and isochronous 端点; dispatch read and write through the 传输回调; and survive 热插拔 and 热拔出 as normal operating conditions. -- Write a 存储驱动程序 that plugs into GEOM: provision a provider through `g_new_providerf`, service BIO requests in the class's `start` routine, walk the `g_down`/`g_up` threads in your head, and tear down cleanly under 挂载ed load. -- Write a 网络驱动程序 that presents an `ifnet` through `ether_if附加`: implement `if_transmit` for the outbound path, call `if_input` for the inbound path, integrate with `bpf` and media state, and clean up through `ether_if分离`. -- Explain why the three transports look so different at the surface but share the same underlying discipline from Parts 1 through 5: New总线 附加, softc management, resource allocation, locking, 分离 ordering, observability, production discipline. +- 通过 `usb_request_methods` 框架附加到 USB 设备:为控制、批量、中断和等时端点配置传输;通过传输回调分发读写;并将热插拔和热拔作为正常操作条件来处理。 +- 编写一个插入 GEOM 的存储驱动程序:通过 `g_new_providerf` 配置提供者,在类的 `start` 例程中服务 BIO 请求,在脑中走通 `g_down`/`g_up` 线程,并在挂载负载下干净地拆解。 +- 编写一个通过 `ether_ifattach` 呈现 `ifnet` 的网络驱动程序:为出站路径实现 `if_transmit`,为入站路径调用 `if_input`,集成 `bpf` 和媒体状态,并通过 `ether_ifdetach` 清理。 +- 解释为什么这三种传输方式在表面上看起来如此不同,但共享第 1 到第 5 部分中相同的底层规范:Newbus 附加、softc 管理、资源分配、锁定、拆解顺序、可观测性、生产规范。 -If any of those still feels unsteady, the labs to revisit are: +如果其中任何一项仍然感觉不稳定,需要重新复习的实验是: -- USB path: Lab 2 (Building and Loading the USB Driver Skeleton), Lab 3 (A Bulk Loopback Test), Lab 6 (Observing Hot-Plug Lifecycle), and Lab 7 (Building a ucom(4) Skeleton from Scratch) in 第26章. -- GEOM storage path: Lab 2 (Build the Skeleton Driver), Lab 3 (Implement the BIO Handler), Lab 4 (Increase Size and Mount UFS), and Lab 10 (Break It On Purpose) in 第27章. -- Network path: Lab 1 (Build and Load the Skeleton), Lab 2 (Exercise the Transmit Path), Lab 3 (Exercise the Receive Path), Lab 5 (`tcpdump` and BPF), and Lab 6 (Clean Detach) in 第28章. +- USB 路径:第 26 章的实验 2(构建和加载 USB 驱动程序骨架)、实验 3(批量环回测试)、实验 6(观察热插拔生命周期)和实验 7(从零构建 ucom(4) 骨架)。 +- GEOM 存储路径:第 27 章的实验 2(构建骨架驱动程序)、实验 3(实现 BIO 处理程序)、实验 4(增加大小并挂载 UFS)和实验 10(故意破坏)。 +- 网络路径:第 28 章的实验 1(构建和加载骨架)、实验 2(练习发送路径)、实验 3(练习接收路径)、实验 5(`tcpdump` 和 BPF)和实验 6(干净分离)。 -Part 7 expects the following as a baseline: +第 7 部分期望以下作为基线: -- Comfort switching between `cdevsw`, GEOM, and `ifnet` as three idioms over the same New总线-and-softc core, rather than as three disconnected subjects. -- Understanding that Part 7 returns to the single-thread `myfirst` arc for the final polish on portability, security, performance, tracing, 内核-debugger work, and the craft of engaging with the community. The transport-specific demos of 第6部分 do not continue; their lessons do. -- A mental library of three real transports you have touched with your own hands, so that when Chapter 29 talks about abstraction across backends, you are drawing on experience rather than on examples you have only read about. +- 舒适地在 `cdevsw`、GEOM 和 `ifnet` 之间切换,将它们视为同一 Newbus-and-softc 核心之上的三种惯用语,而不是三个不相关的主题。 +- 理解第 7 部分回到单线程 `myfirst` 主线进行可移植性、安全性、性能、追踪、内核调试器工作和与社区互动工艺的最后打磨。第 6 部分的传输特定演示不再继续;它们的教训会延续。 +- 一个你亲手触摸过的三种真实传输方式的心理库,这样当第 29 章谈论跨后端抽象时,你是从经验中汲取,而不是从你只读过的例子中。 -If those hold, Part 7 is ready for you. The final nine chapters are the part of the book that turns a capable 驱动程序 author into a craftsperson; the groundwork Parts 1 through 6 have laid is what makes that transition possible. +如果这些都成立,第 7 部分就为你准备好了。最后九章是本书将一个有能力的驱动程序作者转变为工匠的部分;第 1 到第 6 部分奠定的基础是使这种转变成为可能的东西。 -## Looking Ahead: 通往第 29 +## 展望:通往第29章的桥梁 -You have just written a 网络驱动程序. The next chapter, **Portability and Driver Abstraction**, zooms out from the concrete details you have mastered and asks: how do we write 驱动程序 that work well across FreeBSD's many supported architectures, and how do we structure 驱动程序 code so that parts of it can be reused across different hardware backends? +你刚刚编写了一个网络驱动程序。下一章 **可移植性与驱动程序抽象** 从你已经掌握的具体细节中拉远,提出一个问题:我们如何编写在 FreeBSD 众多支持的架构上良好工作的驱动程序,以及我们如何构建驱动程序代码使其部分可以在不同硬件后端之间重用? -That question is sharper after 第28章 than it was before. You have now written 驱动程序 for three very different subsystems: 字符设备 on top of `cdevsw`, storage 设备 on top of GEOM, and network 设备 on top of `ifnet`. The three look different on the surface, but they share a surprising 挂载 of plumbing: 探测 and 附加, softc allocation, resource management, lifecycle control, unloading cleanliness. Chapter 29 will turn that observation into a practical refactoring: isolating the hardware-dependent code, separating backends behind a common API, preparing the 驱动程序 to compile on x86, ARM, and RISC-V alike. +这个问题在第 28 章之后比之前更加尖锐。你现在已经为三个截然不同的子系统编写了驱动程序:基于 `cdevsw` 的字符设备、基于 GEOM 的存储设备和基于 `ifnet` 的网络设备。这三者在表面上看起来不同,但它们共享惊人的管道量:探测和附加、softc 分配、资源管理、生命周期控制、卸载干净度。第 29 章将把这一观察转化为实际的重构:隔离硬件相关代码,在公共 API 后面分离后端,准备驱动程序在 x86、ARM 和 RISC-V 上同样编译。 -You will not be writing a new kind of 驱动程序 in Chapter 29. You will be learning how to make the 驱动程序 you already wrote more ro总线t, more portable, and more maintainable. That is a different kind of progress, one that matters the moment you start working on a 驱动程序 that will live for years. +你不会在第 29 章中编写新类型的驱动程序。你将学习如何使你已经编写的驱动程序更健壮、更可移植、更可维护。这是一种不同类型的进步,当你开始开发一个将要存活多年的驱动程序时,这种进步就很重要了。 -Before you move on, unload every module you created in this chapter, destroy every 接口, and make sure `netstat -in` is back to a boring baseline. Close your lab logbook with a brief note on what worked and what puzzled you. Rest your eyes for a minute. Then, when you are ready, turn the page. +在继续之前,卸载你在本章中创建的每个模块,销毁每个接口,确保 `netstat -in` 回到无聊的基线。在实验日志本上简要记下什么有效、什么让你困惑来结束。让眼睛休息一分钟。然后,当你准备好时,翻到下一页。 -You have earned the step. +你已经赢得了这一步。 diff --git a/translations/zh_CN/chapters/part7/chapter-30.md b/translations/zh_CN/chapters/part7/chapter-30.md index 5ea050a..3a2663c 100644 --- a/translations/zh_CN/chapters/part7/chapter-30.md +++ b/translations/zh_CN/chapters/part7/chapter-30.md @@ -17,367 +17,367 @@ language: "zh-CN" ## 引言 -You arrive at Chapter 30 with a new habit of mind. Chapter 29 taught you how to shape a driver so that it absorbs variation in hardware, bus, and architecture without collapsing into a maze of conditionals. You have learned to push the parts that change into small, backend-specific files and to let the core remain clean. You have met the idea that a driver is not written for a single machine; it is written for a family of machines that share a programming model. That lesson carries a great deal of weight in this chapter, because the environment around your driver can now change in a way that is more radical than anything Chapter 29 considered. The machine itself may not be real. +当你来到第30章时,你已经养成了一种新的思维习惯。第29章教会了你如何塑造一个驱动程序,使其能够适应硬件、总线和架构的变化,而不会陷入条件语句的迷宫中。你已经学会了将变化的部分推入小型的、特定于后端的文件中,让核心保持简洁。你已经接触到了这样的理念:驱动程序不是为单台机器编写的,而是为共享编程模型的一族机器编写的。这一教训在本章中具有极大的分量,因为驱动程序周围的环境现在可能以一种比第29章所考虑的任何情况都更激进的方式发生变化。机器本身可能并不是真实的。 -This chapter is about what happens when the hardware under your driver is not a physical card plugged into a physical slot, but a software simulation presented to a guest operating system by a hypervisor; or when the driver is asked to attach inside a jail that sees only part of the device tree; or when the network stack it cooperates with is one of several stacks running side by side inside a single kernel. Each of these situations is a departure from the "one kernel, one machine, one device tree" mental model that the earlier chapters built. Each one changes what your driver may assume, what it may do, and what a user of your driver may safely expect from it. +本章讨论的是当驱动程序下面的硬件不是插在物理插槽中的物理卡,而是由虚拟机监控程序(hypervisor)呈现给客户操作系统的软件模拟时会发生什么;或者当驱动程序被要求附加到一个只能看到设备树一部分的 jail 中时会发生什么;或者当它所配合的网络栈是单个内核中并行运行的多个栈之一时会发生什么。这些情况中的每一种都偏离了前面章节所建立的"一个内核、一台机器、一个设备树"的心智模型。每一种情况都改变了驱动程序可以假设什么、可以做什么,以及驱动程序的用户可以安全地期望什么。 -The word "virtualisation" can mean several different things depending on who is speaking. To a system administrator running a cloud fleet, it means virtual machines with full kernels of their own. To a FreeBSD user, it often means `jail(8)` and its descendants, which isolate processes and filesystems without giving each one a kernel. To a driver author, it means both, and more. It means paravirtual devices like VirtIO that are explicitly designed to be easy for a guest to drive. It means emulated devices that a hypervisor presents to a guest as if they were physical hardware. It means passthrough devices where a real piece of hardware is handed to a guest more or less directly, with the hypervisor stepping aside as much as it safely can. It means jails whose view of `devfs` is trimmed by a ruleset so that the containerised processes inside cannot see every device the host can see. It means VNET jails that own an entire network stack of their own, complete with an `ifnet` that was loaned to them by the host. +"虚拟化"这个词的含义因说话者的不同而异。对于管理云舰队集群的系统管理员来说,它意味着拥有自己完整内核的虚拟机。对于 FreeBSD 用户来说,它通常指的是 `jail(8)` 及其后继者,它们隔离进程和文件系统,而不给每个进程一个独立的内核。对于驱动程序作者来说,它意味着这两者以及更多。它意味着像 VirtIO 这样明确设计为便于客户驱动的半虚拟化设备。它意味着虚拟机监控程序像物理硬件一样呈现给客户的模拟设备。它意味着直通设备,即一块真实的硬件或多或少直接地交给客户,虚拟机监控程序尽可能安全地退居幕后。它意味着其 `devfs` 视图被规则集修剪过的 jail,使得内部的容器化进程无法看到主机能看到的所有设备。它意味着拥有自己完整网络栈的 VNET jail,包括由主机借给它们的 `ifnet`。 -If that list already feels like a lot, take a breath. The chapter will introduce each of these pieces one at a time, with enough real FreeBSD grounding that you will be able to close the book and open the source tree and find the relevant files with your own hands. Nothing in this chapter is impossible to learn; it is a set of distinct but related ideas that share a common thread. The thread is this: a driver stops being the single most important piece of software in its particular hardware path. Above it sits a hypervisor, a jail framework, or a container runtime; beside it sit other guests or jails that share the host; below it sits a piece of silicon that the driver no longer owns exclusively. Writing drivers for that world is not harder than writing drivers for bare metal, but it is different in ways that are easy to miss if you have not been shown them. +如果上面的列表已经让你觉得内容很多,请深呼吸。本章将逐一介绍这些部分,并提供足够的 FreeBSD 实践基础,使你能够合上书本、打开源代码树,亲手找到相关的文件。本章中的任何内容都不是不可能学会的;它是一组独特但相互关联的想法,共享一条共同的线索。这条线索是:驱动程序不再是其特定硬件路径中最重要的软件。在它之上是虚拟机监控程序、jail 框架或容器运行时;在它旁边是共享主机的其他客户或 jail;在它之下是一块驱动程序不再独占的硅片。为那个世界编写驱动程序并不比为裸金属编写驱动程序更难,但如果你没有被指出其中的差异,它们很容易被忽略。 -Two distinct directions run through the chapter. The first direction is about **writing guest drivers**: code that runs inside a virtual machine and talks to devices the hypervisor presents. You will spend the bulk of your time in this direction, because it is where most of the novel programming happens. VirtIO is the canonical example, and we will return to it often. The second direction is about **cooperating with FreeBSD's own virtualisation infrastructure** from the host side: understanding how your driver attaches inside a jail, how it behaves when the host moves an interface into a VNET jail, how it handles a user inside a jail trying to call an `ioctl` that only root on the host should be allowed to call, and how to test it all without ruining a running host. This direction is less about exotic new APIs and more about discipline, privilege boundaries, and a careful mental model of what is visible from where. +本章贯穿两个不同的方向。第一个方向是关于**编写客户驱动程序**:在虚拟机内运行并与虚拟机监控程序呈现的设备进行通信的代码。你将在这个方向上花费大部分时间,因为这是大多数新颖编程发生的地方。VirtIO 是典型的例子,我们会经常回到它。第二个方向是关于从主机侧**配合 FreeBSD 自身的虚拟化基础设施**:理解你的驱动程序如何在 jail 中附加,当主机将接口移入 VNET jail 时它的行为如何,它如何处理 jail 内的用户试图调用只应允许主机上的 root 调用的 `ioctl`,以及如何在不破坏正在运行的主机的情况下测试这一切。这个方向与其说是关于奇特的新 API,不如说是关于纪律、权限边界和关于从哪里可以看到什么的谨慎心智模型。 -The chapter does not try to teach you how to write a hypervisor, how to implement a new VirtIO transport, or how to build a container runtime from scratch. Those are large topics with their own books. What it teaches is how a driver author should think about, prepare for, and work with virtualised and containerised environments, so that the drivers you write make sense everywhere they are loaded. By the end of the chapter, you will recognise a VirtIO guest driver when you see one, you will know how to detect whether your driver is running in a virtual machine, you will be able to explain what `devfs_ruleset(8)` does and why it matters for device exposure, you will be able to reason about the differences between VNET jails and ordinary jails for a network driver, and you will have written a tiny VirtIO guest driver of your own against a FreeBSD `bhyve(8)` backend. +本章不试图教你如何编写虚拟机监控程序、如何实现新的 VirtIO 传输或如何从头构建容器运行时。这些都是有自己的书籍的大型主题。它所教的是驱动程序作者应该如何思考、准备和使用虚拟化和容器化环境,以便你编写的驱动程序在它们被加载的任何地方都是合理的。到本章结束时,你将能够识别 VirtIO 客户驱动程序,你将知道如何检测驱动程序是否在虚拟机中运行,你将能够解释 `devfs_ruleset(8)` 的作用及其对设备暴露的重要性,你将能够推理 VNET jail 和普通 jail 对网络驱动程序的差异,并且你将编写自己的一个针对 FreeBSD `bhyve(8)` 后端的小型 VirtIO 客户驱动程序。 -Before we begin, a word about the tone of what follows. Some of the subjects in this chapter, especially hypervisor internals and jail security boundaries, have acquired a reputation for being exotic. A driver author who has never looked under the hood can feel intimidated by their jargon. You should not. The code is FreeBSD code; the APIs are FreeBSD APIs; the mindset is the same mindset you have been building since Chapter 1. We will move slowly, and we will keep coming back to real files you can open. Let us begin. +在开始之前,关于接下来内容的语气说一句话。本章中的一些主题,特别是虚拟机监控程序内部机制和 jail 安全边界,已经获得了神秘的声誉。从未深入了解过其内部机制的驱动程序作者可能会被它们的术语所吓倒。你不应该这样。代码是 FreeBSD 代码;API 是 FreeBSD API;思维方式是你从第1章以来一直在建立的相同思维方式。我们将慢慢地推进,并不断回到你可以打开的真实文件。让我们开始吧。 ## 读者指南:如何使用本章 -This chapter sits in a different place in the learning progression from Chapter 29. Chapter 29 was about how your driver is organised on disk. Chapter 30 is about what the world around your driver looks like at runtime. That difference matters for how you should read and practise. The patterns of Chapter 29 can be absorbed by reading carefully and typing along. The patterns of this chapter land more firmly if you also boot a virtual machine, create a jail, and watch the driver behave inside them. Plan accordingly. +本章在学习进度中处于与第29章不同的位置。第29章是关于驱动程序在磁盘上如何组织的。第30章是关于驱动程序周围的世界在运行时是什么样子的。这种差异对你应该如何阅读和实践很重要。第29章的模式可以通过仔细阅读和跟着输入来吸收。本章的模式如果你还启动一个虚拟机、创建一个 jail 并观察驱动程序在其中的行为,会更加牢固。请相应地安排计划。 -If you choose the **reading-only path**, plan for roughly two to three focused hours. At the end you will understand the conceptual map: what paravirtual, emulated, and passthrough devices are; how VirtIO uses shared rings and feature negotiation; how jails and VNET isolate devices and network stacks; what `rctl(8)` controls from the driver's point of view. You will not yet have the reflexes of a driver author who has debugged a virtqueue mismatch at three in the morning, and that is fine. The reading pass is a legitimate first encounter, and the material has enough depth that a second pass with labs later on will extract much more value from it. +如果你选择**仅阅读路径**,计划大约两到三个专注的小时。最后你将理解概念图:什么是半虚拟化、模拟和直通设备;VirtIO 如何使用共享环和特性协商;jail 和 VNET 如何隔离设备和网络栈;从驱动程序的角度看 `rctl(8)` 控制什么。你还不会拥有一个在凌晨三点调试过虚拟队列不匹配的驱动程序作者的条件反射,这没关系。阅读遍是合理的第一次接触,材料有足够的深度,稍后带着实验再读一遍会从中获取更多价值。 -If you choose the **reading-plus-labs path**, plan for six to ten hours spread across two or three sessions. You will install `bhyve(8)` on your lab machine, boot a FreeBSD 14.3 guest on top of it with VirtIO devices, write a small VirtIO pseudo-device driver called `vtedu`, and observe it attach, service requests from the host-side device, and detach cleanly. You will also create a simple jail, attach the driver to it under different `devfs` rulesets, and watch what happens when the driver exposes a device inside the jail. The labs are structured so that each one stands on its own, leaves you with a working system, and reinforces a specific concept from the main text. +如果你选择**阅读加实验路径**,计划六到十个小时,分两到三次进行。你将在实验机器上安装 `bhyve(8)`,在它上面启动一个带有 VirtIO 设备的 FreeBSD 14.3 客户机,编写一个名为 `vtedu` 的小型 VirtIO 伪设备驱动程序,并观察它附加、服务来自主机侧设备的请求以及干净地分离。你还将创建一个简单的 jail,在不同的 `devfs` 规则集下将驱动程序附加到它,并观察当驱动程序在 jail 内暴露设备时会发生什么。实验的结构使得每个实验都独立运作,让你拥有一个可工作的系统,并强化正文中的特定概念。 -If you choose the **reading-plus-labs-plus-challenges path**, plan for a long weekend or a handful of evenings. The challenges push the baseline labs into more realistic territory: extending `vtedu` to accept multiple virtqueues, writing a small tool that probes the guest's hypervisor through `vm.guest` and adapts behaviour, building a VNET jail and moving a tap interface into it, and writing a short report on how a driver that exports an `ioctl` surface should decide which ioctls should be accessible from inside a jail. Each challenge is invitational rather than mandatory, and each one is sized to be completable without a second weekend. +如果你选择**阅读加实验加挑战路径**,计划一个长周末或几个晚上。挑战将基线实验推向更现实的领域:扩展 `vtedu` 以接受多个虚拟队列,编写一个小工具通过 `vm.guest` 探测客户的虚拟机监控程序并调整行为,构建一个 VNET jail 并将 tap 接口移入其中,以及写一份关于导出 `ioctl` 接口的驱动程序应如何决定哪些 ioctl 可以从 jail 内部访问的简短报告。每个挑战都是邀请性的而非强制性的,每个挑战的规模都可以在一个周末内完成。 -A note on the lab environment. You will continue to use the throwaway FreeBSD 14.3 machine you established in earlier chapters. That machine will act as the **host** in this chapter. On top of it you will run `bhyve(8)` guests, which are smaller FreeBSD installations managed by your host. You will also create a few jails directly on the host. This nesting sounds complicated the first time it is described, but it is genuinely simple in practice: your host runs FreeBSD, inside the host you start a `bhyve` virtual machine that also runs FreeBSD, and inside either the host or the guest you create jails. Each layer is independent, each layer has its own `dmesg`, and each layer is cheap to recreate from scratch if something goes wrong. +关于实验环境的一点说明。你将继续使用在前几章中建立的一次性 FreeBSD 14.3 机器。该机器将作为本章的**主机**。在它之上你将运行 `bhyve(8)` 客户机,这些是由你的主机管理的较小 FreeBSD 安装。你还将在主机上直接创建一些 jail。这种嵌套在第一次描述时听起来很复杂,但在实践中确实很简单:你的主机运行 FreeBSD,在主机内部你启动一个也运行 FreeBSD 的 `bhyve` 虚拟机,在主机或客户机内部你创建 jail。每一层都是独立的,每一层都有自己的 `dmesg`,如果出了问题,从头重新创建每一层的成本都很低。 -Make a snapshot of the host before you start. The chapter will ask you to change `/etc/devfs.rules`, to load and unload kernel modules, and to create small VMs. None of these are risky if handled carefully, but accidents happen, and the snapshot turns any mistake into a two-minute rollback. If your host is itself a VM in VirtualBox or VMware, the platform's own snapshot tool is the fastest way to do this. If your host is bare metal, a ZFS boot environment with `bectl(8)` is a good substitute. +在开始之前为主机做一个快照。本章会要求你更改 `/etc/devfs.rules`、加载和卸载内核模块以及创建小型虚拟机。这些操作如果小心处理都不危险,但意外总会发生,快照可以将任何错误变成两分钟的回滚。如果你的主机本身是 VirtualBox 或 VMware 中的虚拟机,平台自己的快照工具是最快的方法。如果你的主机是裸金属,使用 `bectl(8)` 的 ZFS 启动环境是一个好的替代方案。 -One more note. This chapter's labs need a few packages that you may not already have installed. You will want `bhyve-firmware` for UEFI guest support, `vm-bhyve` for a more convenient front end to `bhyve` and its accessories, and `jq` for parsing JSON output during some of the more elaborate tests. The commands to install them are in the labs; do not install them now, but be aware that they are coming. +还有一点说明。本章的实验需要一些你可能尚未安装的软件包。你需要 `bhyve-firmware` 用于 UEFI 客户支持,`vm-bhyve` 作为 `bhyve` 及其附件的更便捷前端,以及 `jq` 用于在一些更精细的测试中解析 JSON 输出。安装它们的命令在实验中;现在不要安装它们,但要知道它们即将用到。 ### 先决条件 -You should be comfortable with everything from earlier chapters. In particular, this chapter assumes that you already know how to write a loadable kernel module from scratch, how `probe()` and `attach()` fit together in the driver lifecycle, how softc is allocated and used, and how `device_t` relates to `devclass`. It assumes fluency with the `bus_read_*` and `bus_write_*` accessors from Chapter 15, basic familiarity with interrupt handlers from Chapter 18, and the portable-driver habits from Chapter 29. If any of that feels uncertain, a brief revisit to the earlier material will save you time here. +你应该对前面章节的所有内容感到熟悉。特别是,本章假设你已经知道如何从头编写一个可加载的内核模块,`probe()` 和 `attach()` 在驱动程序生命周期中如何配合,softc 如何分配和使用,以及 `device_t` 与 `devclass` 的关系。它假设你熟练掌握第15章中的 `bus_read_*` 和 `bus_write_*` 访问器,基本熟悉第18章的中断处理程序,以及第29章的可移植驱动程序习惯。如果其中任何内容感觉不确定,简要回顾前面的材料将为你在这里节省时间。 -You should also be comfortable with ordinary FreeBSD system administration: reading `dmesg`, editing `/etc/rc.conf`, using `sysctl(8)`, and creating and destroying jails with `jail(8)` or its wrapper `service jail`. You do not need prior bhyve experience; the labs will walk you through it. You do not need prior container experience either, since FreeBSD's container story is ultimately jails dressed in different operational clothing. +你还应该熟悉普通的 FreeBSD 系统管理:阅读 `dmesg`、编辑 `/etc/rc.conf`、使用 `sysctl(8)`,以及使用 `jail(8)` 或其包装器 `service jail` 创建和销毁 jail。你不需要有 bhyve 经验;实验会引导你完成。你也不需要有容器经验,因为 FreeBSD 的容器方案最终就是以不同运维外衣出现的 jail。 ### 本章不涵盖的内容 -A responsible chapter tells you what it leaves out. This chapter does not teach the internals of the `bhyve(8)` hypervisor. It does not teach `libvirt(3)`, `qemu(1)`, or the Linux KVM subsystem. It does not turn you into an OCI container expert. It does not cover the `xen(4)` paravirtualisation code, since Xen has become a narrower niche in the FreeBSD ecosystem and `bhyve` is the FreeBSD-native story worth learning first. It mentions `jail(8)` at exactly the level a driver author needs, not at the depth a jail administrator would want. For the missing topics, the FreeBSD Handbook and the respective manual pages are your friends, and I will point to them when they are relevant. +一个负责任的章节会告诉你它省略了什么。本章不教你 `bhyve(8)` 虚拟机监控程序的内部机制。不教你 `libvirt(3)`、`qemu(1)` 或 Linux KVM 子系统。不会把你变成 OCI 容器专家。不涵盖 `xen(4)` 半虚拟化代码,因为 Xen 在 FreeBSD 生态系统中已成为一个较窄的细分领域,而 `bhyve` 是值得首先学习的 FreeBSD 原生方案。它以驱动程序作者所需的精确深度提及 `jail(8)`,而不是 jail 管理员想要的深度。对于缺失的主题,FreeBSD 手册和各自的手册页是你最好的参考,我会在相关处指向它们。 -Several topics that could plausibly appear in a virtualisation chapter have homes elsewhere in this book. Secure coding against hostile input is Chapter 31's subject, not this chapter's; you will meet privilege boundaries and jail visibility here, but the deeper security discipline (Capsicum, MAC framework, sanitiser-driven fuzzing) waits for the next chapter. Advanced DMA under virtualisation (IOMMU setup, mapping pages with `bus_dmamap`) is touched conceptually here and developed more fully in later chapters. Performance tuning under virtualisation (how to measure paravirtual overhead, how to decide between emulated and passthrough for a given workload) is a theme that returns in Chapter 35. We will mention these where they connect, but we will not go deep. +有几个本可以合理出现在虚拟化章节中的主题在本书的其他地方有其归属。针对恶意输入的安全编码是第31章的主题,不是本章的;你将在这里遇到权限边界和 jail 可见性,但更深层次的安全规范(Capsicum、MAC 框架、基于 sanitizer 的模糊测试)要等到下一章。虚拟化下的高级 DMA(IOMMU 设置、使用 `bus_dmamap` 映射页面)在这里有概念性的涉及,并在后续章节中更充分地展开。虚拟化下的性能调优(如何测量半虚拟化开销、如何为给定工作负载在模拟和直通之间做选择)是第35章中回归的主题。我们会在相关连接处提及这些,但不会深入讨论。 ### 结构与节奏 -Section 1 establishes the mental model: what virtualisation and containerization mean for a driver author, and how they differ from "hardware, but slower." Section 2 explains the three styles of guest device (emulated, paravirtualised, passthrough) and what each one implies for the driver. Section 3 takes a careful, beginner-friendly tour of VirtIO: the shared-ring model, feature negotiation, and the `virtqueue(9)` APIs you will use. Section 4 teaches how a driver detects its runtime environment through `vm_guest` and friends, and when that detection is and is not a good idea. Section 5 turns to the host side and looks at `bhyve(8)`, `vmm(4)`, and PCI passthrough. Section 6 covers jails, `devfs`, and VNET: the FreeBSD containerisation story from the driver's perspective. Section 7 addresses resource limits and privilege boundaries. Section 8 talks about testing and refactoring. Section 9 revisits time, memory, and interrupt handling through the lens of virtualisation, the quieter topics where beginner drivers often fail in subtle ways. Section 10 widens the lens to FreeBSD on arm64 and riscv64, whose virtualisation stories have their own shape. The labs and challenges follow, along with a troubleshooting appendix and a closing bridge into Chapter 31. +第1节建立心智模型:虚拟化和容器化对驱动程序作者意味着什么,以及它们与"硬件,但更慢"有何不同。第2节解释客户设备的三种风格(模拟、半虚拟化、直通)以及每种风格对驱动程序的意味。第3节仔细而友好地介绍 VirtIO:共享环模型、特性协商以及你将使用的 `virtqueue(9)` API。第4节教驱动程序如何通过 `vm_guest` 及其伙伴检测运行时环境,以及这种检测何时是个好主意、何时不是。第5节转向主机侧,审视 `bhyve(8)`、`vmm(4)` 和 PCI 直通。第6节涵盖 jail、`devfs` 和 VNET:从驱动程序角度看 FreeBSD 的容器化方案。第7节讨论资源限制和权限边界。第8节讨论测试和重构。第9节通过虚拟化的视角重新审视时间、内存和中断处理——这些安静的主题是新手驱动程序经常以微妙方式失败的地方。第10节将视野拓宽到 FreeBSD 在 arm64 和 riscv64 上的情况,它们的虚拟化方案有自己的形态。实验和挑战紧随其后,还有故障排除附录和通向第31章的收尾桥梁。 -Read the sections in order. Each one assumes the previous one, and the labs depend on the earlier sections having been read and internalised. +按顺序阅读各节。每一节都假设你已读过前一节,实验也依赖于更早的节次已被阅读和吸收。 ### 逐节学习 -A recurring pattern in this book is that each section does one thing. Do not try to read two sections at a time, and do not skip ahead to a "more interesting" section if something in the current one feels difficult. The interesting parts of this chapter rest on the foundational ones, and a reader who has skipped the foundation will spend more time reverse-engineering the labs than the careful reader spends on the whole chapter. +本书中一个反复出现的模式是每节只做一件事。不要试图同时阅读两节,如果当前节的某些内容感觉困难,不要跳到"更有趣"的节。本章有趣的部分建立在基础部分之上,跳过基础的读者花在逆向推导实验上的时间会比细心读者花在整个章节上的时间更多。 ### 保持参考驱动程序在手边 -Several labs in this chapter build on a small pedagogical driver called `vtedu`. You will find it under `examples/part-07/ch30-virtualisation/`, organised the same way as earlier chapters' examples. Each lab directory contains the state of the driver at that step, along with Makefile, README, and supporting scripts. Clone the directory, type along, and load the module after each change. Refactoring a VirtIO guest driver in your head is harder than refactoring one on disk; the feedback from the build system and from `dmesg` is half the lesson. +本章的几个实验构建在一个名为 `vtedu` 的小型教学驱动程序之上。你可以在 `examples/part-07/ch30-virtualisation/` 下找到它,组织方式与前面章节的示例相同。每个实验目录包含该步骤驱动程序的状态,以及 Makefile、README 和支持脚本。克隆该目录,跟着输入,每次更改后加载模块。在脑海中重构 VirtIO 客户驱动程序比在磁盘上重构更难;来自构建系统和 `dmesg` 的反馈是课程的一半。 ### 打开 FreeBSD 源代码树 -Several sections will point to real FreeBSD files. The ones that repay careful reading in this chapter are `/usr/src/sys/dev/virtio/random/virtio_random.c` (the smallest complete VirtIO driver in the tree), `/usr/src/sys/dev/virtio/virtio.h` and `/usr/src/sys/dev/virtio/virtqueue.h` (the public API surfaces), `/usr/src/sys/dev/virtio/virtqueue.c` (the ring machinery), `/usr/src/sys/dev/virtio/pci/virtio_pci.c` and `/usr/src/sys/dev/virtio/mmio/virtio_mmio.c` (the two transport backends), `/usr/src/sys/sys/systm.h` (for `vm_guest`), `/usr/src/sys/kern/subr_param.c` (for the `vm.guest` sysctl), `/usr/src/sys/net/vnet.h` (for VNET primitives), and `/usr/src/sys/kern/kern_jail.c` (for prison and jail APIs). Open them when the text says to, and read around the exact spot the text points at. The files are not decoration; they are the source of truth. +本章的几个小节会指向真实的 FreeBSD 文件。值得仔细阅读的文件有 `/usr/src/sys/dev/virtio/random/virtio_random.c`(代码树中最小的完整 VirtIO 驱动程序)、`/usr/src/sys/dev/virtio/virtio.h` 和 `/usr/src/sys/dev/virtio/virtqueue.h`(公共 API 接口)、`/usr/src/sys/dev/virtio/virtqueue.c`(环机制)、`/usr/src/sys/dev/virtio/pci/virtio_pci.c` 和 `/usr/src/sys/dev/virtio/mmio/virtio_mmio.c`(两个传输后端)、`/usr/src/sys/sys/systm.h`(`vm_guest` 相关)、`/usr/src/sys/kern/subr_param.c`(`vm.guest` sysctl 相关)、`/usr/src/sys/net/vnet.h`(VNET 原语相关)以及 `/usr/src/sys/kern/kern_jail.c`(prison 和 jail API 相关)。当文本提示时打开它们,并阅读文本所指的确切位置周围的代码。这些文件不是装饰;它们是真相的来源。 ### 保持实验日志 -Continue the lab logbook from earlier chapters. For this chapter, log a short note for each major lab: which commands you ran, which modules loaded, what `dmesg` said, what surprised you. Virtualisation work is easy to forget the details of after a few days, and a paper trail turns every future debugging session into a one-minute lookup rather than a half-hour re-derivation. +继续使用前面章节的实验日志。对于本章,为每个主要实验记录一个简短的笔记:你运行了哪些命令,加载了哪些模块,`dmesg` 显示了什么,什么让你感到意外。几天后虚拟化工作的细节很容易忘记,一条书面记录将未来的每个调试会话变成一分钟的查找,而不是半小时的重新推导。 ### 调整节奏 -Several ideas in this chapter will feel new the first time you meet them: shared-ring memory, feature negotiation, VNET's thread-local current vnet, the devfs ruleset number system. That newness is normal. If you feel your understanding blur during a particular subsection, stop. Re-read the previous paragraph, try a small experiment in the shell, and come back fresh in an hour. Consistent thirty-minute sessions produce better understanding than a single exhausted all-day effort. +本章中的几个想法在你第一次遇到时会感觉新颖:共享环内存、特性协商、VNET 的线程局部当前 vnet、devfs 规则集编号系统。这种新颖感是正常的。如果你在某个小节中感到理解模糊,停下来。重新阅读前一段,在 shell 中尝试一个小实验,一小时后精神饱满地回来。持续的三十分钟会话比一次精疲力竭的全天努力产生更好的理解。 ## 如何从本章获得最大收益 -Chapter 30 rewards curiosity, patience, and a willingness to experiment. The specific patterns it introduces, the ring structures, the feature bits, the prison and vnet scopes, are not abstract. Each one corresponds to code you can read, state you can observe with `sysctl` or `vmstat`, and behaviour you can trigger with short commands. The most valuable habit you can build while reading the chapter is to move freely between the text, the source tree, and the running system. +第30章回报好奇心、耐心和实验意愿。它引入的特定模式——环结构、特性位、prison 和 vnet 作用域——都不是抽象的。每一个都对应你可以阅读的代码、你可以用 `sysctl` 或 `vmstat` 观察的状态,以及你可以用短命令触发的行为。你在阅读本章时能建立的的最有价值的习惯是在文本、源代码树和运行中的系统之间自由切换。 ### 阅读时打开源代码树 -Do not read the VirtIO section without `virtio.h`, `virtqueue.h`, and `virtio_random.c` open in another window. When the text says that a driver calls `virtqueue_enqueue` to hand a buffer to the host, scroll to that function and see it in context. When the text mentions the `VIRTIO_DRIVER_MODULE` macro, open `virtio.h` and see the two `DRIVER_MODULE` lines it expands into. The FreeBSD kernel is far more approachable than its reputation suggests, and the only way to confirm that is to keep opening it. +不要在没有 `virtio.h`、`virtqueue.h` 和 `virtio_random.c` 在另一个窗口中打开的情况下阅读 VirtIO 节。当文本说驱动程序调用 `virtqueue_enqueue` 将缓冲区交给主机时,滚动到该函数并在上下文中查看它。当文本提到 `VIRTIO_DRIVER_MODULE` 宏时,打开 `virtio.h` 看它展开成的两行 `DRIVER_MODULE`。FreeBSD 内核比它的名声所暗示的要容易接近得多,确认这一点的唯一方法就是不断打开它。 ### 输入实验代码 -Every line of code in the labs is there to teach something. Typing it yourself slows you down enough to notice the structure. Copy-pasting the code often feels productive and usually is not; the finger-memory of typing kernel code is part of how you learn it. If you must copy, copy one function at a time, and read each line as you paste it. +实验中的每一行代码都在教你一些东西。自己输入会让你慢到足以注意到结构。复制粘贴代码通常感觉高效但实际上并非如此;输入内核代码的手指记忆是你学习它的方式。如果你必须复制,一次复制一个函数,在粘贴时阅读每一行。 ### 运行你阅读的内容 -When the text introduces a command, run it. When the text introduces a `sysctl` name, query it. When the text introduces a kernel module, load it. The running system will surprise you sometimes (the `vm.guest` value may not be what you expect if your lab itself is a VM), and every surprise is an opportunity to learn something the text did not need to explain explicitly. A running FreeBSD system is a patient tutor. +当文本介绍一个命令时,运行它。当文本介绍一个 `sysctl` 名称时,查询它。当文本介绍一个内核模块时,加载它。运行中的系统有时会让你感到惊讶(如果你的实验环境本身就是一个 VM,`vm.guest` 的值可能不是你期望的),每一次惊讶都是学习文本不需要明确解释的某件事的机会。一个运行中的 FreeBSD 系统是一位耐心的导师。 ### 将 dmesg 视为文稿的一部分 -A significant fraction of what this chapter teaches is visible only in the kernel's log output. A VirtIO device's negotiated feature set, the attach sequence of a guest driver, the interaction between a module and a jail, all of these surface in `dmesg`. Read it often. Tail it during the labs. Copy relevant lines into your logbook when they teach something non-obvious. Do not treat `dmesg` as noise; treat it as the ground truth of what the kernel actually did. +本章所教内容的很大一部分只在内核的日志输出中可见。VirtIO 设备的已协商特性集、客户驱动程序的附加序列、模块与 jail 之间的交互——所有这些都浮现在 `dmesg` 中。经常阅读它。在实验期间跟踪它。当相关行教会你一些非显而易见的东西时,将它们复制到你的日志中。不要把 `dmesg` 当作噪声;把它当作内核实际做了什么的真实依据。 ### 故意破坏事物 -At three points in the chapter I will suggest deliberately breaking something to see what happens. These are the most educational moments you can give yourself. Unload a required module before a driver that depends on it and see the dependency graph complain. Remove a devfs rule and see the device vanish from inside the jail. Boot a guest with one CPU and then with four and compare the virtqueue setup. Deliberate failures teach in a way that success cannot. +在章中的三个地方,我会建议你故意破坏某些东西来观察会发生什么。这些是你能给自己最有教育意义的时刻。在一个依赖它的驱动程序之前卸载一个所需的模块,看看依赖图如何抱怨。移除一个 devfs 规则,看看设备如何从 jail 内部消失。用一个 CPU 启动客户机,然后用四个 CPU 启动并比较 virtqueue 的设置。故意的失败以一种成功无法做到的方式教你东西。 ### 尽可能结对学习 -If you have a study partner, this is a great chapter to pair on. One of you can run the host and watch `dmesg`, while the other runs the guest and drives the driver. The two perspectives teach different things, and each of you will notice what the other missed. If you are working alone, use two terminal tabs and alternate attention between them. +如果你有学习伙伴,这是一个非常适合结对学习的章节。你们中一个可以运行主机并观察 `dmesg`,另一个运行客户机并操作驱动程序。两个视角教会不同的东西,你们各自会注意到对方遗漏的。如果你独自工作,使用两个终端标签并在它们之间交替关注。 -### 信任迭代, Not the Memorisation +### 信任迭代,而非记忆 -You will not remember every flag, every enum, every macro in this chapter on the first read. That is fine. What matters is that you remember where to look, what the overall shape of the subject is, and how to tell when your driver is doing the right thing. The specific identifiers will become second nature after you have written and debugged two or three virtualisation-aware drivers of your own; they are not a memorisation exercise. +你不会在第一次阅读时记住本章中的每个标志、每个枚举、每个宏。这没关系。重要的是你记住去哪里查找、主题的整体形状是什么,以及如何判断你的驱动程序是否在正确地做事。在你编写和调试了两三个自己的虚拟化感知驱动程序之后,特定的标识符会变成第二天性;它们不是一项记忆练习。 ### 休息 -Virtualisation-aware debugging has a particular cognitive cost. You are tracking state on several sides at once: the host, the guest, the driver, the device model, the jail. Your mind gets fatigued faster than when you are working on a single-threaded bare-metal driver. Two hours of focused work followed by a real break is almost always more productive than four hours of grinding. +虚拟化感知的调试有特殊的认知成本。你同时跟踪多个方面的状态:主机、客户机、驱动程序、设备模型、jail。你的大脑比处理单线程裸金属驱动程序时更容易疲劳。两小时的专注工作加上一次真正的休息几乎总是比四小时的苦干更有成效。 -With those habits in place, let us begin. +有了这些习惯,让我们开始吧。 ## 第1节:虚拟化与容器化对驱动程序作者意味着什么 -Before we touch any code, we need to agree on what we are talking about. The words "virtualisation" and "containerization" have been worn smooth by marketing language, and they carry different meanings depending on where you encounter them. A vendor's white paper uses "virtualisation" as a synonym for running multiple operating systems on the same hardware; a cloud provider's documentation uses it as shorthand for any managed workload; a FreeBSD administrator uses it for anything from `bhyve(8)` to `jail(8)`. For a driver author, those meanings are not interchangeable. The shape of the problem you are solving changes depending on which kind of virtualisation your driver meets. This section anchors the vocabulary for the rest of the chapter. +在我们接触任何代码之前,我们需要就我们讨论的内容达成一致。"虚拟化"和"容器化"这两个词已被营销语言磨得光滑,根据你遇到它们的地方带有不同的含义。供应商的白皮书将"虚拟化"用作在同一硬件上运行多个操作系统的同义词;云服务提供商的文档将其作为任何托管工作负载的简写;FreeBSD 管理员将其用于从 `bhyve(8)` 到 `jail(8)` 的任何东西。对于驱动程序作者来说,这些含义是不可互换的。你正在解决的问题的形状会根据你的驱动程序遇到的虚拟化类型而改变。本节为本章的其余部分奠定词汇基础。 -### Two Families, Not One +### 两个家族,不是一个 -The first distinction to draw is between **virtual machines** and **containers**. They solve different problems and produce different constraints for driver authors. Conflating them is the single most common confusion in this territory. +首先要区分的是**虚拟机**和**容器**。它们解决不同的问题,对驱动程序作者产生不同的约束。将它们混为一谈是这个领域中最常见的混淆。 -A **virtual machine** is a software-emulated computer. A hypervisor, which itself runs on real hardware, creates an execution environment that looks like a complete machine to the software inside it. The machine has a BIOS or UEFI, memory, CPUs, disks, and network cards. The operating system inside the VM boots from scratch just as it would on real hardware, loads a kernel, and attaches drivers. The observation that matters is that the **guest kernel is a full kernel**, independent of the host kernel. A FreeBSD guest running under a FreeBSD host is not sharing kernel code with the host; the two kernels are peers, separated by the hypervisor and by the barrier between guest memory and host memory. +**虚拟机**是一个软件模拟的计算机。虚拟机监控程序(hypervisor)本身运行在真实硬件上,创建一个对内部软件看起来像完整机器的执行环境。该机器有 BIOS 或 UEFI、内存、CPU、磁盘和网卡。VM 内部的操作系统像在真实硬件上一样从头启动、加载内核并附加驱动程序。重要的观察是**客户内核是一个完整的内核**,独立于主机内核。在 FreeBSD 主机下运行的 FreeBSD 客户机并不与主机共享内核代码;两个内核是对等的,被虚拟机监控程序以及客户内存与主机内存之间的屏障隔开。 -A **container**, on the FreeBSD sense of the word, is a different animal. A container is a namespaced partition of a single kernel. The host kernel is the only kernel in the picture; the containers are separate process groups, separate filesystem views, and often separate network stacks, but all of them run on the same kernel with the same drivers. On FreeBSD, the classical container is a `jail(8)`. Modern container runtimes like `ocijail` and `pot` add scripting and orchestration around that same jail primitive. The observation here is that **there is only one kernel**. A driver in the host is visible to every jail, subject to the rules the host imposes; a jail cannot load a driver of its own, and it does not have a kernel into which to load one. +**容器**,在 FreeBSD 的意义上,是另一种不同的东西。容器是单个内核的命名空间分区。主机内核是唯一的内核;容器是独立的进程组、独立的文件系统视图,通常也是独立的网络栈,但它们都运行在具有相同驱动程序的同一个内核上。在 FreeBSD 上,经典的容器是一个 `jail(8)`。像 `ocijail` 和 `pot` 这样的现代容器运行时在同一 jail 原语之上添加脚本编排。这里的观察是**只有一个内核**。主机中的驱动程序对所有 jail 可见,受主机施加的规则约束;jail 不能加载自己的驱动程序,它也没有一个可以加载驱动的内核。 -These two families overlap only in superficial ways. A VM and a jail both look like "another system" from the outside. A VM and a jail both have their own `/`, their own network, and their own users. But the kernel boundary is nowhere near the same, and that matters enormously to drivers. +这两个家族只在表面上重叠。从外部看,VM 和 jail 都像是"另一个系统"。VM 和 jail 都有自己的 `/`、自己的网络和自己的用户。但内核边界完全不同,这对驱动程序来说关系重大。 -A VM runs a full guest kernel; the kernel sees virtualised (or passthrough) hardware; the driver you write for that hardware is a **guest driver** that attaches inside the guest. A jail shares the host's kernel; no guest driver is being written, because there is no guest kernel to load it into; instead, the question is how a **host driver** exposes its services to processes running inside the jail. The techniques you use in each case are different. +VM 运行完整的客户内核;内核看到虚拟化(或直通)的硬件;你为该硬件编写的驱动程序是一个在客户机内部附加的**客户驱动程序**。jail 共享主机的内核;不需要编写客户驱动程序,因为没有客户内核可以加载它;相反,问题是**主机驱动程序**如何向 jail 内运行的进程暴露其服务。你在每种情况下使用的技术是不同的。 -For the rest of this chapter, when the text says "virtualisation," it usually means the VM case unless the context makes clear that jails are being discussed. When the text says "containerization," it usually means the jail case. Read those words with the families in mind, and you will avoid most of the confusion that newcomers have. +在本章的其余部分,当文本说"虚拟化"时,通常指 VM 的情况,除非上下文明确表示正在讨论 jail。当文本说"容器化"时,通常指 jail 的情况。带着这两个家族来读这些词,你将避免大多数新手的困惑。 -### Virtual Machines as an Environment for Drivers +### 虚拟机作为驱动程序的环境 -A VM presents hardware to the guest. Exactly what that hardware looks like depends on the hypervisor's configuration. There are three broad styles of device that a guest may meet, each of which changes the driver problem. +VM 向客户机呈现硬件。该硬件具体长什么样取决于虚拟机监控程序的配置。客户机可能遇到三种广泛的设备风格,每种都改变了驱动程序的问题。 -**Emulated devices** are the oldest approach. The hypervisor presents to the guest a device that imitates a real, usually well-known, physical device: a `ne2000` Ethernet card, for example, or a PIIX IDE controller, or a serial port compatible with the venerable 16550 UART. The hypervisor's device model implements the same register interface the real hardware would expose. The guest loads the driver it would have loaded on real hardware, and the driver runs unchanged. The price is performance: every register access in the guest traps into the hypervisor, which emulates the behaviour in software, which is much slower than real hardware. Emulated devices are perfect for compatibility and for booting unmodified guest kernels; they are poor for serious workloads. +**模拟设备**是最古老的方法。虚拟机监控程序向客户机呈现一个模仿真实的、通常是知名的物理设备的设备:例如 `ne2000` 以太网卡、PIIX IDE 控制器或与古老的 16550 UART 兼容的串口。虚拟机监控程序的设备模型实现了与真实硬件会暴露的相同寄存器接口。客户机加载它在真实硬件上会加载的驱动程序,驱动程序无需更改即可运行。代价是性能:客户机中的每次寄存器访问都会陷入虚拟机监控程序,后者在软件中模拟该行为,这比真实硬件慢得多。模拟设备非常适合兼容性和启动未经修改的客户机内核;对于严肃的工作负载则表现不佳。 -**Paravirtual devices** solve the performance problem by replacing the compatibility interface with one designed to be cheap for both sides. Instead of imitating physical hardware, the device defines a new interface that is efficient when implemented in software. VirtIO is the canonical example and the one this chapter will spend most of its time on. A VirtIO device does not look like any real hardware; it looks like a VirtIO device, which is a standardised interface that exposes shared memory rings and a few control registers and very little else. The guest must have a driver for VirtIO specifically; that driver is smaller and faster than the equivalent emulated-device driver, because the interface was designed for software on both sides. +**半虚拟化设备**通过用一种为双方都设计得廉价高效的接口来替换兼容性接口来解决性能问题。该设备不模仿物理硬件,而是定义一个在软件中实现时高效的新接口。VirtIO 是典型的例子,也是本章将花最多时间的例子。VirtIO 设备看起来不像任何真实硬件;它看起来像一个 VirtIO 设备,这是一个标准化接口,暴露共享内存环和少量控制寄存器,几乎没有其他东西。客户机必须有专门为 VirtIO 编写的驱动程序;该驱动程序比等效的模拟设备驱动程序更小更快,因为接口是为双方都是软件而设计的。 -**Passthrough devices** go in the other direction. The hypervisor steps aside and hands the guest a real piece of hardware: a physical NIC, a physical GPU, a physical NVMe SSD. The guest's driver talks to that hardware more or less directly. The hypervisor still mediates (through an IOMMU, for example, to constrain which memory the device can reach) but it no longer emulates or paravirtualises. Passthrough is fast but brittle: the device is no longer shared with other guests, and moving the VM to a different host is no longer trivial. +**直通设备**走另一个方向。虚拟机监控程序退到一边,将真实硬件直接交给客户机:一块物理网卡、一块物理 GPU、一块物理 NVMe SSD。客户机的驱动程序或多或少直接与该硬件通信。虚拟机监控程序仍然进行中介(例如通过 IOMMU 来约束设备可以访问的内存),但它不再模拟或半虚拟化。直通速度快但脆弱:设备不再与其他客户机共享,将 VM 迁移到不同主机也不再简单。 -Each style of device imposes a different design on your driver. An emulated-device driver is typically an old, well-tested driver for the emulated hardware, which just happens to be running on a virtualised version of the same hardware. A paravirtual driver is usually a driver written specifically for the paravirtual interface, with no expectation that the "hardware" exists in real silicon. A passthrough driver is the same driver that would have run on bare metal, with one subtlety: the guest's memory is not the same memory the device DMAs into, and the IOMMU mapping must be correct for the device to work. +每种设备风格对你的驱动程序施加不同的设计。模拟设备驱动程序通常是模拟硬件的旧的、经过良好测试的驱动程序,恰好运行在相同硬件的虚拟化版本上。半虚拟化驱动程序通常是为半虚拟化接口专门编写的驱动程序,不期望"硬件"存在于真实硅片中。直通驱动程序与在裸金属上运行的驱动程序相同,只有一个微妙之处:客户机的内存不是设备 DMA 进入的内存,IOMMU 映射必须正确才能使设备工作。 -The rest of this chapter leans strongly into the second style, because paravirtualisation is where most of the novel driver work in virtualised environments happens, and because it illustrates a programming model (shared rings, feature bits, descriptor-based transactions) that generalises to other parts of FreeBSD. +本章的其余部分强烈倾向于第二种风格,因为半虚拟化是虚拟化环境中大多数新颖驱动程序工作发生的地方,并且它说明了一种编程模型(共享环、特性位、基于描述符的事务),该模型可以推广到 FreeBSD 的其他部分。 -### Containers as an Environment for Drivers +### 容器作为驱动程序的环境 -A jail is a different kind of environment, and it asks a different question of a driver. The driver is not running inside the jail; it is running in the single shared kernel. What the jail does is change what the processes in the jail see. +jail 是一种不同的环境,它向驱动程序提出不同的问题。驱动程序不是在 jail 内部运行;它运行在单个共享内核中。jail 所做的是改变 jail 中进程能看到什么。 -From the host's kernel, nothing changes when a jail is created. The host kernel still has all the drivers it had before; the drivers still attach to the same devices; the same `/dev/` entries still exist in the devfs mounted at the host's root. From inside the jail, a devfs mount is also performed, but that devfs is configured with a ruleset that hides some devices and exposes others. A `/dev/mem` is not normally visible inside a jail, because a process inside a jail should not be able to peek at kernel memory; a `/dev/kvm` equivalent (if FreeBSD had one) would be similarly hidden. A `/dev/null` and `/dev/zero` are visible, because there is no reason to hide them. +从主机的内核来看,创建 jail 时没有任何变化。主机内核仍然拥有之前的所有驱动程序;驱动程序仍然附加到相同的设备;主机根目录挂载的 devfs 中仍然存在相同的 `/dev/` 条目。从 jail 内部来看,也会执行一次 devfs 挂载,但该 devfs 配置了隐藏某些设备并暴露其他设备的规则集。`/dev/mem` 通常在 jail 内部不可见,因为 jail 内的进程不应该能够窥视内核内存;`/dev/kvm` 的等效项(如果 FreeBSD 有的话)也会被类似地隐藏。`/dev/null` 和 `/dev/zero` 是可见的,因为没有理由隐藏它们。 -So what is a "driver problem" in a container? Two things, mostly. First, when your driver creates device nodes, you must decide whether those nodes should be visible to jailed processes, and if so, under what conditions. If your driver exposes an `ioctl` that allows a process to change the routing table, that ioctl should not be accessible to a process inside a jail that does not have the privilege to reconfigure the host's network. Second, when your driver cooperates with VNET (the FreeBSD virtual network stack framework), you must be careful about which global state is per-vnet and which is shared. An `ifnet` moved into a VNET jail should behave correctly inside that jail, which means your driver must have declared the right VNET-scoped variables and must not have cached any cross-vnet state. +那么在容器中什么是"驱动程序问题"?主要是两件事。首先,当你的驱动程序创建设备节点时,你必须决定这些节点是否应该对 jail 内的进程可见,如果可见,在什么条件下可见。如果你的驱动程序暴露一个允许进程更改路由表的 `ioctl`,该 ioctl 不应被没有重新配置主机网络权限的 jail 内进程访问。其次,当你的驱动程序与 VNET(FreeBSD 虚拟网络栈框架)配合时,你必须注意哪些全局状态是 per-vnet 的,哪些是共享的。移入 VNET jail 的 `ifnet` 应该在该 jail 内正确运行,这意味着你的驱动程序必须声明正确的 VNET 作用域变量,并且不能缓存任何跨 vnet 的状态。 -These are different concerns from those of VM drivers, and they deserve their own sections. Sections 6 and 7 of this chapter work through them in detail. +这些是与 VM 驱动程序不同的关注点,它们值得有自己的节。本章的第6节和第7节详细讨论了它们。 -### Why This Matters for Driver Authors +### 为什么这对驱动程序作者很重要 -It is fair to ask: why should a driver author care about any of this? Until recently, most drivers were written for physical hardware on bare metal, and the "virtualisation story" was something that happened upstream. Today, and for the foreseeable future, the majority of FreeBSD installations are virtual machines. A driver that works only on bare metal is a driver that works in a minority of deployments. A driver that works only on the host, and not inside a jail, is a driver that cannot be used in any modern containerised FreeBSD environment. Virtualisation-aware driver design is not optional anymore; it is part of writing drivers at all. +可以公平地问:为什么驱动程序作者应该关心这些?直到最近,大多数驱动程序是为裸金属上的物理硬件编写的,"虚拟化方案"是上游发生的事情。今天,以及在可预见的未来,大多数 FreeBSD 安装是虚拟机。一个只在裸金属上工作的驱动程序是一个只在少数部署中工作的驱动程序。一个只在主机上工作而在 jail 内不工作的驱动程序是一个无法在任何现代容器化 FreeBSD 环境中使用的驱动程序。虚拟化感知的驱动程序设计不再是可选的;它是编写驱动程序的一部分。 -There are three concrete reasons the topic matters. +有三个具体的原因说明这个主题很重要。 -First, **most of your users are inside a guest**. The FreeBSD VMs running in public clouds, in private clouds, and in local `bhyve` labs outnumber the FreeBSD installations on real hardware, perhaps by a wide margin. A driver whose design fails in a virtual environment will fail for most of its users. +首先,**你的大多数用户在客户机内部**。在公有云、私有云和本地 `bhyve` 实验室中运行的 FreeBSD VM 可能远超 FreeBSD 在真实硬件上的安装数量。一个在虚拟环境中设计失败的驱动程序将对其大多数用户失败。 -Second, **host-side drivers expose services to jails**. Even if your driver is about a physical device that lives in the host, the moment a jail wants to use its services, the driver faces the jail question. It may need to expose a device node through the jail's devfs, or decide that certain ioctls are jailed-off. +其次,**主机侧驱动程序向 jail 暴露服务**。即使你的驱动程序是关于主机中物理设备的,一旦 jail 想使用其服务,驱动程序就面临 jail 问题。它可能需要通过 jail 的 devfs 暴露设备节点,或者决定某些 ioctl 对 jail 是被禁止的。 -Third, **performance at scale matters more than ever**. In a virtualised environment, the difference between an emulated driver and a paravirtual one is often a factor of ten or more in throughput. Knowing how to write and recognise paravirtual patterns is worth real engineering time. A few extra paragraphs of understanding about `virtqueue(9)` can save you a day of debugging later. +第三,**规模化的性能比以往任何时候都更重要**。在虚拟化环境中,模拟驱动程序和半虚拟化驱动程序之间的差异在吞吐量上通常是十倍或更多。知道如何编写和识别半虚拟化模式值得真正的工程时间。对 `virtqueue(9)` 多几段的理解可以在以后省去你一天的调试。 -### Virtualisation Is Not Just Hardware But Slower +### 虚拟化不只是更慢的硬件 -A common misconception is that virtualisation simply makes hardware slower. That view misses the mechanism entirely. In a well-designed virtualised environment, the guest driver does not see "slower hardware"; it sees different hardware with different access patterns. A VirtIO driver does not make one slow register read per descriptor and then complain about the overhead; it batches a dozen descriptors into a shared ring, notifies the host once, and waits for a single completion. The difference between a naive port of a physical-hardware driver to VirtIO and an idiomatic VirtIO driver is not a matter of tuning; it is a matter of architectural intent. +一个常见的误解是虚拟化只是使硬件变慢。这种观点完全错过了机制。在一个设计良好的虚拟化环境中,客户驱动程序看到的不是"更慢的硬件";它看到的是具有不同访问模式的不同硬件。VirtIO 驱动程序不会对每个描述符进行一次慢速寄存器读取然后抱怨开销;它将一打描述符批量放入共享环,通知主机一次,然后等待单个完成。一个物理硬件驱动程序到 VirtIO 的朴素移植和一个惯用的 VirtIO 驱动程序之间的区别不在于调优;而在于架构意图。 -Similarly, containerization is not "processes, but confined." It is a reorganisation of visibility, privilege, and global state. A driver that exports a sysctl tree has to decide whether that tree should be visible inside a jail, and whether writes from inside the jail should affect only the jail's view or the host's. These are not just configuration questions; they are design questions that shape the code. +类似地,容器化不是"进程,但受限"。它是可见性、权限和全局状态的重组。一个导出 sysctl 树的驱动程序必须决定该树是否应该在 jail 内可见,以及 jail 内的写入是只影响 jail 的视图还是影响主机的。这些不仅仅是配置问题;它们是塑造代码的设计问题。 -If you take one thing from this section, let it be this: **the environment your driver runs in is not a transparent wrapper around a machine**. It imposes its own concerns, offers its own APIs, and rewards or punishes driver designs that respect or ignore them. +如果你从本节只带走一件事,那就是:**你的驱动程序运行的环境不是围绕一台机器的透明包装器**。它强加了自身的关注点,提供了自身的 API,并奖励或惩罚尊重或忽视它们的驱动程序设计。 -### A Quick Taxonomy +### 快速分类 -To fix the vocabulary in your mind, here is a compact taxonomy of the environments we will discuss in this chapter. Treat it as a map you can return to when a later section mentions a term. +为了在你脑海中固定词汇,这里有一个我们将本章讨论的环境的紧凑分类。把它当作你可以在后面节次提到术语时返回的地图。 -| Environment | Kernel Boundary | What the Driver Sees | Typical FreeBSD Example | +| 环境 | 内核边界 | 驱动程序看到的 | 典型 FreeBSD 示例 | |------------|-----------------|----------------------|-------------------------| -| Bare metal | Full | Real hardware | Any driver | -| Emulated VM device | Full, at guest kernel | Imitation of real hardware | `xn`, `em` emulated by QEMU | -| Paravirtual VM device | Full, at guest kernel | Shared-ring interface | `virtio_blk`, `if_vtnet` | -| Passthrough VM device | Full, at guest kernel | Real hardware with IOMMU constraints | `em` on a passthrough NIC | -| Jail (no VNET) | Shared with host | Host-side driver; jail sees host's devfs filtered by ruleset | `devfs` visibility for `/dev/null` | -| VNET jail | Shared with host | Host-side driver; jail owns its network stack; interfaces moved via `if_vmove()` | `vnet.jail=1` in `jail.conf` | +| 裸金属 | 完整 | 真实硬件 | 任何驱动程序 | +| 模拟 VM 设备 | 完整,在客户内核处 | 真实硬件的模仿 | `xn`、被 QEMU 模拟的 `em` | +| 半虚拟化 VM 设备 | 完整,在客户内核处 | 共享环接口 | `virtio_blk`、`if_vtnet` | +| 直通 VM 设备 | 完整,在客户内核处 | 带 IOMMU 约束的真实硬件 | 直通 NIC 上的 `em` | +| Jail(无 VNET) | 与主机共享 | 主机侧驱动程序;jail 看到被规则集过滤的主机 devfs | `/dev/null` 的 `devfs` 可见性 | +| VNET jail | 与主机共享 | 主机侧驱动程序;jail 拥有自己的网络栈;接口通过 `if_vmove()` 移入 | `jail.conf` 中的 `vnet.jail=1` | -Notice the kernel-boundary column. The boundary is the single most important feature of each row. VMs have a boundary; jails do not. Everything else follows from that. +注意内核边界列。边界是每行最重要的特征。VM 有边界;jail 没有。其他一切都由此而来。 ### 总结 -We have drawn the first map of the chapter. Virtual machines and containers are two different families. VMs present hardware (emulated, paravirtual, or passthrough) to a full guest kernel. Containers partition a single host kernel into isolated process environments, changing what they see and what they may do, but not introducing a second kernel. A driver author deals with each family differently: writing guest drivers for VMs, adapting host drivers for jails. The next section takes the first of those two worlds and looks at the three device styles a guest may meet, in enough detail to build intuition before we touch VirtIO specifically. +我们已经画出了本章的第一张地图。虚拟机和容器是两个不同的家族。VM 向完整的客户内核呈现硬件(模拟的、半虚拟化的或直通的)。容器将单个主机内核划分为隔离的进程环境,改变它们能看到什么和能做什么,但不引入第二个内核。驱动程序作者以不同方式处理每个家族:为 VM 编写客户驱动程序,为 jail 调整主机驱动程序。下一节将这两个世界中的第一个,审视客户可能遇到的三种设备风格,详细到足以在我们专门接触 VirtIO 之前建立直觉。 ## 第2节:客户驱动程序、模拟设备与半虚拟化设备 -A guest kernel running inside a VM must attach drivers to the devices its hypervisor has given it. Those devices fall into the three styles introduced in Section 1: emulated, paravirtual, and passthrough. Each style produces a different kind of driver, a different kind of bug, and a different kind of optimisation opportunity. This section examines them in the order you are most likely to encounter them, and begins to build the vocabulary we will need in Section 3 for VirtIO specifically. +在 VM 内运行的客户内核必须将驱动程序附加到其虚拟机监控程序给它的设备上。这些设备分为第1节中介绍的三种风格:模拟、半虚拟化和直通。每种风格产生不同类型的驱动程序、不同类型的错误和不同类型的优化机会。本节按照你最可能遇到它们的顺序进行考察,并开始构建我们在第3节专门讨论 VirtIO 时所需的词汇。 -### Emulated Devices in Detail +### 模拟设备详解 -An emulated device is the simplest story to tell. The hypervisor implements, in software, a faithful imitation of a known physical device. The classical FreeBSD examples include the emulated `em(4)` Ethernet NIC (the Intel 8254x family), the emulated `ahci(4)` SATA controller, the emulated 16550-compatible serial port, and the emulated VGA video adapter. +模拟设备是最简单的故事。虚拟机监控程序在软件中实现了对一个已知物理设备的忠实模仿。经典的 FreeBSD 示例包括模拟的 `em(4)` 以太网 NIC(Intel 8254x 系列)、模拟的 `ahci(4)` SATA 控制器、模拟的 16550 兼容串口和模拟的 VGA 视频适配器。 -From the guest's point of view, nothing unusual is happening. The PCI device enumerator finds an Intel card; the `em(4)` driver probes it and attaches; the driver issues its usual register writes; packets eventually appear on the wire. Under the hood, each of those register writes is a trap into the hypervisor, which consults its model of the Intel chip, applies the state change, and possibly generates a virtual interrupt back into the guest. +从客户机的角度来看,没有发生任何不寻常的事情。PCI 设备枚举器发现一张 Intel 卡;`em(4)` 驱动程序探测它并附加;驱动程序发出其常规的寄存器写入;数据包最终出现在线路上。在底层,每次寄存器写入都是一次陷入虚拟机监控程序的操作,虚拟机监控程序查询其 Intel 芯片模型,应用状态变更,并可能生成一个虚拟中断回到客户机。 -This approach has one huge virtue and one large vice. The virtue is compatibility: the guest kernel needs no special driver at all. A stock FreeBSD install image boots on an emulated `em(4)` card as easily as it boots on a real one. The vice is cost. Every trap into the hypervisor, every software emulation of a register behaviour, every synthesised interrupt, costs CPU cycles. For a busy workload with millions of register accesses per second, emulated devices are measurably slow. +这种方法有一个巨大的优点和一个大的缺点。优点是兼容性:客户内核根本不需要特殊驱动程序。一个标准的 FreeBSD 安装镜像在模拟的 `em(4)` 卡上启动就像在真实卡上一样容易。缺点是成本。每次陷入虚拟机监控程序、每次寄存器行为的软件模拟、每次合成的中断,都消耗 CPU 周期。对于每秒数百万次寄存器访问的繁忙工作负载,模拟设备明显很慢。 -### What Emulated Devices Imply for Driver Code +### 模拟设备对驱动程序代码的意味 -From the driver author's perspective, an emulated device looks like real hardware. The implication is that you do not normally write a "special" driver for emulated hardware; you write one driver that works on the real silicon and lean on emulation for the compatibility case. Most of the emulated-device drivers in `/usr/src/sys/dev/` are therefore the same files that drive the real cards. +从驱动程序作者的角度来看,模拟设备看起来像真实硬件。这意味着你通常不需要为模拟硬件编写"特殊"的驱动程序;你编写一个在真实硅片上工作的驱动程序,并依赖模拟来实现兼容性。`/usr/src/sys/dev/` 中的大多数模拟设备驱动程序因此是驱动真实卡的相同文件。 -There are two small exceptions that matter for our purposes. First, some drivers include a short early-boot probe that distinguishes "this is a real card" from "this is a hypervisor imitating a card." The `em(4)` driver, for example, logs a slightly different message when it detects that the environment is virtualised, because some diagnostic counters are meaningful only on real silicon. Second, a few drivers bypass hardware-specific optimisations in virtualised environments because those optimisations would be counterproductive: prefetching blocks that the hypervisor's emulation already has in RAM is wasteful, for instance. These are rare and usually framed as conditional performance tweaks rather than architectural changes. +有两个小的例外对我们的目的很重要。首先,一些驱动程序包含一个简短的早期启动探测,用于区分"这是一张真实的卡"和"这是虚拟机监控程序在模仿一张卡"。例如,`em(4)` 驱动程序在检测到环境已虚拟化时会记录略有不同的消息,因为一些诊断计数器只在真实硅片上有意义。其次,一些驱动程序在虚拟化环境中绕过硬件特定的优化,因为这些优化会适得其反:预取虚拟机监控程序模拟已经放在 RAM 中的块是浪费的。这些很少见,通常被构架为条件性的性能调整而非架构更改。 -In practice, the first time you care about emulated-versus-real is when you are looking at a trace or a sysctl and wondering why a counter is zero. It is almost never a correctness problem. +在实践中,你第一次关心模拟与真实的区别是当你查看跟踪或 sysctl 并想知道为什么某个计数器为零时。这几乎从来不是正确性问题。 -### Why Emulation Exists at All +### 为什么模拟设备存在 -It is worth pausing to ask why emulated devices exist, given that they are slower than alternatives. The answer is threefold. +值得停下来问为什么模拟设备存在,考虑到它们比替代方案更慢。答案有三方面。 -First, emulation provides compatibility with existing guest kernels. A hypervisor that offered only paravirtual devices would need to persuade every guest operating system to install paravirtual drivers. That is a solved problem today, but in the early 2000s (when modern hypervisors were being designed) it was a significant barrier. Emulated devices let guests run unmodified; they gained a performance path (paravirtual) later. +首先,模拟提供了与现有客户内核的兼容性。一个只提供半虚拟化设备的虚拟机监控程序需要说服每个客户操作系统安装半虚拟化驱动程序。今天这是一个已解决的问题,但在2000年代初(现代虚拟机监控程序设计时),这是一个重大的障碍。模拟设备让客户机未经修改即可运行;它们后来才获得了性能路径(半虚拟化)。 -Second, emulation is often good enough for low-frequency workloads. A guest that makes one disk I/O per second does not suffer measurably from emulation. A guest that makes a hundred thousand disk I/Os per second suffers badly. The majority of workloads are closer to the first than the second, and for them, emulation is a fine choice. +其次,模拟对于低频工作负载通常已经足够好。一个每秒进行一次磁盘 I/O 的客户机不会因模拟而受到可衡量的影响。一个每秒进行十万次磁盘 I/O 的客户机则会受到严重影响。大多数工作负载更接近前者而非后者,对它们来说模拟是一个不错的选择。 -Third, emulation is easier to implement correctly than paravirtualisation when the guest side is an existing driver. A hypervisor author who wants to support, say, VMware-format disk images does not have to write a paravirtual disk driver for every guest OS; they write a VMware-compatible emulated disk controller, and the existing VMware guest drivers work. +第三,当客户侧是现有驱动程序时,模拟比半虚拟化更容易正确实现。一个想要支持 VMware 格式磁盘镜像的虚拟机监控程序作者不需要为每个客户操作系统编写半虚拟化磁盘驱动程序;他们编写一个兼容 VMware 的模拟磁盘控制器,现有的 VMware 客户驱动程序就能工作。 -In FreeBSD's `bhyve(8)`, emulated devices include the LPC bridge (for serial ports and the RTC), PCI-IDE and AHCI controllers (for some storage cases), and the E1000 NIC (through the `e1000` backend). These are used for installers and for compatibility with older guests. For performance-oriented work, VirtIO devices are the common choice. +在 FreeBSD 的 `bhyve(8)` 中,模拟设备包括 LPC 桥(用于串口和 RTC)、PCI-IDE 和 AHCI 控制器(用于某些存储场景)以及 E1000 NIC(通过 `e1000` 后端)。这些用于安装程序和与较旧客户机的兼容性。对于面向性能的工作,VirtIO 设备是常见的选择。 -### Passthrough as Seen by the Guest +### 从客户机角度看直通 -Passthrough deserves a deeper look from the guest's perspective, because it is the most "hardware-like" of the three styles and introduces subtleties that a novice driver author might not expect. +直通值得从客户机的角度更深入地审视,因为它是三种风格中最"硬件化"的,并且引入了新手驱动程序作者可能不会预料到的微妙之处。 -When a PCI device is passed through, the guest sees an exact copy of the device's PCI configuration: vendor ID, device ID, subsystem IDs, BARs, capabilities, MSI-X table. The guest's PCI enumerator claims the device with the same driver it would have used on bare metal. The driver programs the device through register accesses; those accesses are, for the most part, direct (not trapped and emulated), because the hardware virtualisation extensions (Intel VT-x, AMD-V) support mapping a device's MMIO into a guest's address space. +当 PCI 设备被直通时,客户机看到设备 PCI 配置的精确副本:厂商 ID、设备 ID、子系统 ID、BAR、能力、MSI-X 表。客户机的 PCI 枚举器使用与裸金属上相同的驱动程序来声明该设备。驱动程序通过寄存器访问编程设备;这些访问在很大程度上是直接的(不陷入和模拟的),因为硬件虚拟化扩展(Intel VT-x、AMD-V)支持将设备的 MMIO 映射到客户机的地址空间。 -DMA is where subtlety enters. The guest programs physical addresses into the device's DMA registers, but those addresses are guest-physical, not host-physical. Without help, the device would DMA to host-physical addresses that do not correspond to guest memory at all, which would be a security disaster. The help comes from the IOMMU: Intel VT-d or AMD-Vi sits between the device and the host memory bus, and it remaps device-issued addresses to the correct host memory. +DMA 是微妙之处所在。客户机将物理地址编程到设备的 DMA 寄存器中,但这些地址是客户机物理地址,不是主机物理地址。没有帮助的话,设备会 DMA 到与客户机内存完全不对应的主机物理地址,这将是安全灾难。帮助来自 IOMMU:Intel VT-d 或 AMD-Vi 位于设备和主机内存总线之间,它将设备发出的地址重新映射到正确的主机内存。 -From the guest driver's perspective, all of this is invisible, as long as the driver uses `bus_dma(9)` correctly. The `bus_dma(9)` framework records which physical addresses are valid for a given DMA handle, and the kernel sets up the IOMMU mappings to match. A driver that bypasses `bus_dma(9)` and programs physical addresses directly (perhaps by calling `vtophys` on a kernel pointer) is a driver that will work on bare metal but break under passthrough. +从客户驱动程序的角度来看,只要驱动程序正确使用 `bus_dma(9)`,所有这些都是不可见的。`bus_dma(9)` 框架记录哪些物理地址对给定的 DMA 句柄有效,内核设置匹配的 IOMMU 映射。一个绕过 `bus_dma(9)` 并直接编程物理地址的驱动程序(也许通过对内核指针调用 `vtophys`)将在裸金属上工作但在直通下崩溃。 -Interrupts under passthrough are handled by MSI or MSI-X exclusively; legacy pin-based interrupts cannot be passed through usefully. The guest driver configures MSI/MSI-X in the usual way, and the hypervisor sets up interrupt remapping so that the device's interrupts are delivered to the guest's virtual interrupt controller rather than to the host's. +直通下的中断专门由 MSI 或 MSI-X 处理;传统的基于引脚的中断无法被有效地直通。客户驱动程序以通常的方式配置 MSI/MSI-X,虚拟机监控程序设置中断重映射,使设备的中断被投递到客户机的虚拟中断控制器而不是主机的。 -### Firmware and Platform Dependencies Under Passthrough +### 直通下的固件和平台依赖 -One area where passthrough can surprise driver authors is firmware. Many modern devices expect their firmware to be loaded by the host, not by the device itself. A device whose driver assumes firmware has already been loaded (perhaps by a boot-time BIOS routine on the host) may fail to initialise inside a guest, because the guest's BIOS has not done the firmware-loading work. +直通可能让驱动程序作者感到意外的一个领域是固件。许多现代设备期望其固件由主机加载,而不是由设备自身加载。一个假设固件已经加载的设备驱动程序(也许是由主机上的启动时 BIOS 例程加载的)可能在客户机内初始化失败,因为客户机的 BIOS 没有做固件加载工作。 -The solution is usually for the driver to carry firmware and load it explicitly. FreeBSD's `firmware(9)` framework makes this straightforward: the driver registers the firmware image (typically a blob compiled into a loadable module), and at attach time it calls `firmware_get` and uploads the blob to the device. A driver that works on both bare metal and passthrough is a driver that does the firmware load itself, rather than relying on platform code. +解决方案通常是让驱动程序自带固件并显式加载。FreeBSD 的 `firmware(9)` 框架使这变得简单:驱动程序注册固件镜像(通常是编译到可加载模块中的 blob),在附加时调用 `firmware_get` 并将 blob 上传到设备。一个在裸金属和直通下都能工作的驱动程序是一个自己加载固件的驱动程序,而不是依赖平台代码的驱动程序。 -Similarly, ACPI tables and other platform tables may be different between the host and a guest. A driver that reads an ACPI table to determine board-specific routing (for example, to identify which GPIO controls a power rail) will find a different table in a guest, because the guest's virtual BIOS generates its own. The driver must either provide defaults for cases where the table is missing or treat the missing table as an unsupported platform. +类似地,ACPI 表和其他平台表在主机和客户机之间可能不同。一个读取 ACPI 表来确定板卡特定路由的驱动程序(例如,识别哪个 GPIO 控制电源轨)在客户机中会找到不同的表,因为客户机的虚拟 BIOS 生成自己的表。驱动程序必须为缺少表的情况提供默认值,或将缺少的表视为不支持的平台。 -### When to Prefer Which Device Style +### 何时选择哪种设备风格 -The three device styles are not mutually exclusive on a single VM. A `bhyve(8)` guest can have an emulated LPC bridge, a VirtIO block device, a passthrough NIC, and a VirtIO console, all at the same time. The administrator chooses which style to use for each role based on the trade-offs. +三种设备风格在单个 VM 上不是互斥的。一个 `bhyve(8)` 客户机可以同时拥有模拟的 LPC 桥、VirtIO 块设备、直通 NIC 和 VirtIO 控制台。管理员根据权衡为每个角色选择使用哪种风格。 -For installation and legacy guests, emulated devices are right. They require nothing from the guest and they work out of the box. +对于安装和遗留客户机,模拟设备是正确的选择。它们不需要客户机做任何事情,开箱即用。 -For typical FreeBSD guests doing ordinary work, VirtIO devices are right. They are fast, standardised, and well supported in FreeBSD's tree. Most production `bhyve(8)` deployments use VirtIO for disk, network, and console. +对于做普通工作的典型 FreeBSD 客户机,VirtIO 设备是正确的选择。它们快速、标准化,在 FreeBSD 的源代码树中得到良好支持。大多数生产环境的 `bhyve(8)` 部署使用 VirtIO 处理磁盘、网络和控制台。 -For performance-critical or hardware-specific workloads, passthrough is right. A guest that runs a GPU-accelerated workload needs a passthrough GPU; a guest that needs real network-card offload features needs a passthrough NIC. +对于性能关键或硬件特定的工作负载,直通是正确的选择。运行 GPU 加速工作负载的客户机需要直通 GPU;需要真实网卡卸载功能的客户机需要直通 NIC。 -As a driver author, the most likely device style you will write for is VirtIO, because that is where the new driver work is. Emulated and passthrough drivers are usually existing drivers; VirtIO drivers are designed from scratch for the paravirtual interface. +作为驱动程序作者,你最可能编写的设备风格是 VirtIO,因为那是新驱动程序工作所在。模拟和直通驱动程序通常是现有的驱动程序;VirtIO 驱动程序是为半虚拟化接口从头设计的。 -### Paravirtual Devices in Detail +### 半虚拟化设备详解 -Paravirtual devices are a deeper change. The hypervisor declines to imitate any physical device and instead defines an interface optimised for software on both sides. The guest must have a driver written for that interface; a stock legacy driver will not work. The benefit is performance: a paravirtual interface can batch, amortise, and simplify the host-guest interaction in ways that a realistic hardware model cannot. +半虚拟化设备是更深层的变化。虚拟机监控程序拒绝模仿任何物理设备,而是定义一个为双方软件优化过的接口。客户机必须有为该接口编写的驱动程序;标准的遗留驱动程序将不起作用。好处是性能:半虚拟化接口可以批量、摊销和简化主机-客户机交互,这是现实的硬件模型无法做到的。 -The dominant paravirtual family on FreeBSD is VirtIO. VirtIO is not a FreeBSD invention; it is a cross-platform standard designed for use across Linux, FreeBSD, and other guest operating systems. FreeBSD's VirtIO implementation lives under `/usr/src/sys/dev/virtio/`, with individual drivers for block devices (`virtio_blk`), network devices (`if_vtnet`), serial consoles (`virtio_console`), SCSI (`virtio_scsi`), entropy (`virtio_random`), and memory ballooning (`virtio_balloon`). Other VirtIO device types exist (9p filesystems, input devices, sockets), and they too have FreeBSD drivers in varying states of maturity. +FreeBSD 上占主导地位的半虚拟化家族是 VirtIO。VirtIO 不是 FreeBSD 的发明;它是一个跨平台标准,设计用于 Linux、FreeBSD 和其他客户操作系统。FreeBSD 的 VirtIO 实现位于 `/usr/src/sys/dev/virtio/` 下,包含用于块设备(`virtio_blk`)、网络设备(`if_vtnet`)、串行控制台(`virtio_console`)、SCSI(`virtio_scsi`)、熵(`virtio_random`)和内存 ballooning(`virtio_balloon`)的各个驱动程序。还存在其他 VirtIO 设备类型(9p 文件系统、输入设备、套接字),它们也有处于不同成熟状态的 FreeBSD 驱动程序。 -From the outside, a VirtIO device looks like a PCI device (when attached via PCI) or a memory-mapped device (when attached via MMIO, which is common on embedded and ARM systems). The guest kernel enumerates it the same way it would any other device: a PCI bus scan finds a device with vendor ID 0x1af4 and a device ID indicating the type, or the guest's device tree advertises a VirtIO MMIO transport with a known compatible string. +从外部看,VirtIO 设备看起来像一个 PCI 设备(通过 PCI 附加时)或一个内存映射设备(通过 MMIO 附加时,这在嵌入式和 ARM 系统上很常见)。客户机内核以枚举任何其他设备相同的方式枚举它:PCI 总线扫描找到一个厂商 ID 为 0x1af4 且设备 ID 指示类型的设备,或者客户机的设备树通告一个具有已知兼容字符串的 VirtIO MMIO 传输。 -Once probed and attached, the driver talks to the device through a small set of primitives: device feature bits, device status, device configuration space, and a set of **virtqueues**. The virtqueues are the heart of the VirtIO model. Each one is a ring of descriptors in shared memory, writable by the guest and readable by the host; the host has a parallel ring of used descriptors that the guest reads to discover completions. All the actual I/O happens through the rings; the registers the driver touches are almost exclusively used for setup, notification, and feature negotiation. +一旦探测并附加,驱动程序通过一小组原语与设备通信:设备特性位、设备状态、设备配置空间和一组**虚拟队列(virtqueue)**。虚拟队列是 VirtIO 模型的核心。每个虚拟队列都是共享内存中的描述符环,可由客户机写入并由主机读取;主机有一个平行的已使用描述符环,客户机从中读取以发现完成。所有实际的 I/O 都通过环进行;驱动程序接触的寄存器几乎专门用于设置、通知和特性协商。 -This design is radically different from an emulated-device driver. A VirtIO driver almost never issues a register write during normal operation. It posts buffers into rings, notifies the host that new work is available, and reads completions from the ring when they arrive. The per-request overhead is a handful of memory accesses, not a register trap. When the system is busy, the driver can post many requests and notify once; the host can batch many completions and signal once. The result is an order-of-magnitude performance improvement over an equivalent emulated driver. +这种设计与模拟设备驱动程序根本不同。VirtIO 驱动程序在正常操作期间几乎从不发出寄存器写入。它将缓冲区发布到环中,通知主机有新工作可用,并在完成到达时从环中读取。每次请求的开销是少量内存访问,而不是寄存器陷入。当系统繁忙时,驱动程序可以发布多个请求并通知一次;主机可以批量处理多个完成并信号一次。结果是与等效模拟驱动程序相比一个数量级的性能提升。 -### Paravirtual Devices and the Driver Author +### 半虚拟化设备与驱动程序作者 -For a driver author, paravirtual devices are where a lot of new work happens in FreeBSD's driver ecosystem. VirtIO is well-defined and stable, and writing a new VirtIO-backed device type is a reasonable weekend project once you have read the foundational drivers. More importantly, the patterns of VirtIO (shared rings, feature negotiation, descriptor-based transactions) echo through other FreeBSD subsystems (notably `if_netmap` and portions of the network stack), so time invested in understanding them pays dividends. +对于驱动程序作者来说,半虚拟化设备是 FreeBSD 驱动程序生态系统中大量新工作发生的地方。VirtIO 定义良好且稳定,一旦你阅读了基础驱动程序,编写一个新的基于 VirtIO 的设备类型是一个合理的周末项目。更重要的是,VirtIO 的模式(共享环、特性协商、基于描述符的事务)在其他 FreeBSD 子系统中也有体现(特别是 `if_netmap` 和网络栈的部分),因此投入理解它们的时间会产生回报。 -This chapter will spend all of Section 3 on VirtIO fundamentals. For now, what matters is the framing: a paravirtual driver is a first-class guest driver that was designed to live inside a VM, with the performance characteristics that design affords. +本章将在整个第3节中讲解 VirtIO 基础知识。现在重要的是框架:半虚拟化驱动程序是一流的客户驱动程序,被设计为在 VM 内运行,具有该设计所赋予的性能特征。 -### Passthrough Devices in Detail +### 直通设备详解 -Passthrough is the third style, and in some ways the most interesting because it collapses the virtualisation question back into the bare-metal question, with a twist. +直通是第三种风格,在某些方面最有趣,因为它将虚拟化问题折叠回裸金属问题,但有一个转折。 -In passthrough, the hypervisor declines to abstract the device at all. It hands the guest a real PCI or PCIe device: for example, a specific physical NIC in one of the host's slots, or a specific NVMe SSD, or a specific GPU. The guest's driver talks to that real hardware as if it were the host. The guest even receives the device's interrupts, through a mechanism the hypervisor provides. +在直通中,虚拟机监控程序完全拒绝抽象设备。它将一个真实的 PCI 或 PCIe 设备交给客户机:例如,主机某个插槽中的特定物理 NIC,或特定的 NVMe SSD,或特定的 GPU。客户机的驱动程序像它是主机一样与真实硬件通信。客户机甚至通过虚拟机监控程序提供的机制接收设备的中断。 -There are three reasons passthrough exists. First, performance: a passthrough NIC delivers line-rate traffic to the guest with no software overhead per packet. Second, access to hardware features the hypervisor does not emulate: GPU acceleration, NVMe-specific queuing, hardware crypto engines. Third, licensing or certification: some proprietary drivers only work with real hardware and cannot be used through any emulation layer. +直通存在三个原因。首先是性能:直通 NIC 以线路速率向客户机传递流量,每个数据包没有软件开销。其次是访问虚拟机监控程序不模拟的硬件特性:GPU 加速、NVMe 特定队列、硬件加密引擎。第三是许可或认证:一些专有驱动程序只在真实硬件上工作,不能通过任何模拟层使用。 -The cost of passthrough is isolation. Once a device is passed through to a guest, the host no longer owns it in any useful sense; it cannot use the NIC itself, and other guests cannot share it. Live migration becomes difficult or impossible, because the target host may not have the same physical device in the same slot. The guest owns the hardware until the guest stops running. +直通的代价是隔离性。一旦设备被直通给客户机,主机就不再以任何有意义的方式拥有它;它不能自己使用 NIC,其他客户机也不能共享它。实时迁移变得困难或不可能,因为目标主机可能没有在相同插槽中的相同物理设备。客户机拥有该硬件直到客户机停止运行。 -### Passthrough and the IOMMU +### 直通与 IOMMU -Passthrough sounds simple in principle, but it requires one major piece of hardware support: an IOMMU. An IOMMU is to DMA what an MMU is to CPU memory access: a hardware-enforced translation table between the view of memory a device has (its "DMA address") and real physical memory. Without an IOMMU, a passthrough device could DMA into any physical memory on the host, including the host's kernel data, with obvious and terrifying consequences. With an IOMMU, the hypervisor can constrain the device to DMA only into the memory regions assigned to the guest, preserving the security boundary. +直通在原则上听起来简单,但它需要一个主要的硬件支持:IOMMU。IOMMU 对 DMA 的作用就像 MMU 对 CPU 内存访问的作用:一个硬件强制的转换表,在设备看到的内存视图(其"DMA 地址")和真实物理内存之间进行转换。没有 IOMMU,直通设备可以 DMA 到主机上的任何物理内存,包括主机的内核数据,后果是显而易见且可怕的。有了 IOMMU,虚拟机监控程序可以约束设备只 DMA 到分配给客户机的内存区域,从而保持安全边界。 -On amd64 systems, the IOMMU is Intel VT-d (on Intel CPUs) or AMD-Vi (on AMD CPUs). It is usually enabled through a kernel configuration option and some BIOS settings. FreeBSD's `bhyve(8)` uses the IOMMU through the `pci_passthru(4)` mechanism, which we will meet in Section 5. +在 amd64 系统上,IOMMU 是 Intel VT-d(在 Intel CPU 上)或 AMD-Vi(在 AMD CPU 上)。它通常通过内核配置选项和一些 BIOS 设置启用。FreeBSD 的 `bhyve(8)` 通过 `pci_passthru(4)` 机制使用 IOMMU,我们将在第5节中遇到它。 -For the driver author, the IOMMU is invisible most of the time. The `bus_dma(9)` API in the guest behaves the same way it does on bare metal; the guest driver's `bus_dmamem_alloc()` and `bus_dmamap_load()` calls produce DMA addresses that, from the guest's point of view, look the same as they would on bare metal. The IOMMU translation happens one layer below, between the device and the real memory, and the guest driver does not participate in it. +对于驱动程序作者来说,IOMMU 在大多数时候是不可见的。客户机中的 `bus_dma(9)` API 行为与裸金属上相同;客户驱动程序的 `bus_dmamem_alloc()` 和 `bus_dmamap_load()` 调用产生的 DMA 地址,从客户机的角度看,与裸金属上看起来相同。IOMMU 转换发生在下面一层,在设备和真实内存之间,客户驱动程序不参与其中。 -The one place where the IOMMU matters for the driver author is when the IOMMU is misconfigured or missing, and DMA starts to fail in mysterious ways. If you ever see "DMA timeout" messages from a passthrough driver, the IOMMU is often the first suspect. Chapter 32 will go deeper into this. +IOMMU 对驱动程序作者唯一重要的地方是当 IOMMU 配置错误或缺失时,DMA 开始以神秘的方式失败。如果你在直通驱动程序中看到"DMA timeout"消息,IOMMU 通常是第一个嫌疑对象。第32章将更深入地讨论这个问题。 -### The Driver Author's Mental Model +### 驱动程序作者的心智模型 -If you step back from these three styles, a clear pattern emerges. The guest kernel always loads a driver; the driver always sees a device; the device's behaviour is always defined by some interface. What changes between the styles is which interface and who implements it. +如果你从这三种风格中退后一步,一个清晰的模式出现了。客户内核总是加载驱动程序;驱动程序总是看到设备;设备的行为总是由某个接口定义的。风格之间变化的是哪个接口以及谁实现了它。 -In emulated devices, the interface is the real hardware's register model, and the hypervisor implements it in software. The driver is the real-hardware driver. +在模拟设备中,接口是真实硬件的寄存器模型,虚拟机监控程序在软件中实现它。驱动程序就是真实硬件的驱动程序。 -In paravirtual devices, the interface is a bespoke software-optimised model, and the hypervisor implements it natively. The driver is paravirtual-specific. +在半虚拟化设备中,接口是一个定制的软件优化模型,虚拟机监控程序原生实现它。驱动程序是半虚拟化专用的。 -In passthrough devices, the interface is the real hardware's register model, and the hardware itself implements it, with the IOMMU as a gatekeeper. The driver is the real-hardware driver, running in the guest, with DMA addresses translated transparently. +在直通设备中,接口是真实硬件的寄存器模型,硬件本身实现它,IOMMU 作为守门人。驱动程序是真实硬件的驱动程序,运行在客户机中,DMA 地址被透明地转换。 -The driver author is therefore working with the same skills in all three cases. The shape of the work differs only in which interface is in play. Once you understand that, the rest of this chapter becomes a study of specific interfaces, specific FreeBSD APIs, and specific deployment contexts. +因此驱动程序作者在所有三种情况下使用相同的技能。工作的形状只在于使用哪个接口有所不同。一旦你理解了这一点,本章的其余部分就变成了对特定接口、特定 FreeBSD API 和特定部署上下文的研究。 -### A Note on Hybrid Models +### 关于混合模型的说明 -Real systems often mix these styles. A single guest may have an emulated serial port for early boot logging, a paravirtual NIC for main network traffic, a paravirtual block device for the root filesystem, and a passthrough GPU for acceleration. Each of those devices is governed by its own driver, and the guest's driver toolkit needs to know the patterns for all three. This is not unusual; it is the common case for any non-trivial VM. +真实系统经常混合这些风格。单个客户机可能有一个用于早期启动日志的模拟串口、一个用于主要网络流量的半虚拟化 NIC、一个用于根文件系统的半虚拟化块设备和一个用于加速的直通 GPU。这些设备中的每一个都由自己的驱动程序管理,客户机的驱动程序工具包需要了解所有三种的模式。这不是异常情况;这是任何非平凡 VM 的常见情况。 -As a driver author, the implication is that you usually do not need to build a universal driver for all three styles. You build the driver for the style your device uses, and you coexist with drivers for the other styles. The per-device decisions about which style to use are made by the hypervisor administrator, not by the driver. +作为驱动程序作者,其含义是你通常不需要为所有三种风格构建通用驱动程序。你为你的设备使用的风格构建驱动程序,并与其他风格的驱动程序共存。关于使用哪种风格的逐设备决定由虚拟机监控程序管理员做出,而不是由驱动程序做出。 ### 总结 -Three styles of guest device, three kinds of driver work, one underlying mental model: a driver talks to an interface, and the interface is implemented by whichever layer the hypervisor chooses. Emulated is easy but slow; paravirtual is fast and requires custom drivers; passthrough is near-native and requires an IOMMU. The rest of this chapter concentrates on the paravirtual style, with VirtIO as the example, because that is where most of the interesting new driver work in FreeBSD happens. In Section 3 we open the VirtIO toolkit and start examining its parts. +三种客户设备风格、三种驱动程序工作、一个底层心智模型:驱动程序与接口对话,接口由虚拟机监控程序选择的任何层实现。模拟简单但慢;半虚拟化快速但需要定制驱动程序;直通接近原生但需要 IOMMU。本章的其余部分集中于半虚拟化风格,以 VirtIO 为例,因为那是 FreeBSD 中大多数有趣的新驱动程序工作发生的地方。在第3节中我们将打开 VirtIO 工具箱并开始检查它的各个部分。 ## 第3节:VirtIO 基础与 virtqueue(9) -VirtIO is a standard. It defines a way for a guest to talk to a device that exists only in software, without reference to any physical hardware. The standard is maintained by the OASIS VirtIO Technical Committee and is implemented by a number of hypervisors, including `bhyve(8)`, QEMU, and the Linux KVM family. Because the standard is shared, a VirtIO guest driver written for a FreeBSD guest will talk to a VirtIO device presented by any conforming hypervisor. +VirtIO 是一个标准。它定义了一种方式,让客户机能够与只存在于软件中的设备通信,而不涉及任何物理硬件。该标准由 OASIS VirtIO 技术委员会维护,并由多个虚拟机监控程序实现,包括 `bhyve(8)`、QEMU 和 Linux KVM 家族。因为标准是共享的,为 FreeBSD 客户机编写的 VirtIO 客户驱动程序可以与任何符合标准的虚拟机监控程序呈现的 VirtIO 设备通信。 -This section introduces the VirtIO model at the level of detail a driver author needs. It is long, because VirtIO has enough moving parts to justify the space, and short compared to the VirtIO specification itself, which spans hundreds of pages. We will focus on the parts you need to write a FreeBSD guest driver. +本节以驱动程序作者所需的详细程度介绍 VirtIO 模型。它很长,因为 VirtIO 有足够多的组成部分值得占据这些篇幅;但与跨越数百页的 VirtIO 规范本身相比,它又很短。我们将专注于你编写 FreeBSD 客户驱动程序所需的部分。 -### The Ingredients of a VirtIO Device +### VirtIO 设备的组成部分 -A VirtIO device exposes a small number of elements to its guest driver. Understanding each one is the foundation for everything that follows. +VirtIO 设备向其客户驱动程序暴露少量元素。理解每一个元素是后续所有内容的基础。 -The first element is the **transport**. VirtIO devices can appear over several transports: VirtIO over PCI (the usual case on amd64 desktops, servers, and cloud), VirtIO over MMIO (the usual case on ARM and embedded systems), and VirtIO over channel I/O (used on IBM mainframes). From the guest's view, the transport dictates how the device is enumerated and how registers are read, but once the driver has hold of a `device_t`, the transport recedes into the background. FreeBSD's VirtIO framework provides a transport-agnostic API. +第一个元素是**传输层(transport)**。VirtIO 设备可以通过多种传输层出现:基于 PCI 的 VirtIO(amd64 桌面、服务器和云上的常见情况)、基于 MMIO 的 VirtIO(ARM 和嵌入式系统上的常见情况)和基于通道 I/O 的 VirtIO(用于 IBM 大型机)。从客户机的角度看,传输层决定了设备如何被枚举以及寄存器如何被读取,但一旦驱动程序获得了 `device_t`,传输层就退到幕后。FreeBSD 的 VirtIO 框架提供了与传输层无关的 API。 -The second element is the **device type**. Every VirtIO device has a single-byte type identifier (`VIRTIO_ID_NETWORK` is 1, `VIRTIO_ID_BLOCK` is 2, `VIRTIO_ID_CONSOLE` is 3, `VIRTIO_ID_ENTROPY` is 4, `VIRTIO_ID_BALLOON` is 5, `VIRTIO_ID_SCSI` is 8, and so on, as listed in `/usr/src/sys/dev/virtio/virtio_ids.h`). The type tells the guest what the device does; the guest dispatches to the right driver based on the type. +第二个元素是**设备类型**。每个 VirtIO 设备都有一个单字节的类型标识符(`VIRTIO_ID_NETWORK` 为 1,`VIRTIO_ID_BLOCK` 为 2,`VIRTIO_ID_CONSOLE` 为 3,`VIRTIO_ID_ENTROPY` 为 4,`VIRTIO_ID_BALLOON` 为 5,`VIRTIO_ID_SCSI` 为 8,等等,列在 `/usr/src/sys/dev/virtio/virtio_ids.h` 中)。类型告诉客户机设备做什么;客户机根据类型分派到正确的驱动程序。 -The third element is the **device feature bits**. Each device type defines a set of optional features, each represented by a bit in a 64-bit mask. Some features are universal (the ability to use indirect descriptors, for example), and some are device-specific (VirtIO block devices may advertise write-caching, discard support, geometry information, and more). The guest driver reads the device's advertised features, selects which of them the driver knows how to use, and writes back a negotiated feature mask. The device then agrees to the negotiated set and rejects any attempt to use a feature outside it. This negotiation is the mechanism by which VirtIO devices and drivers evolve without breaking each other. +第三个元素是**设备特性位**。每种设备类型定义一组可选特性,每个特性由 64 位掩码中的一个位表示。一些特性是通用的(例如使用间接描述符的能力),一些是设备特定的(VirtIO 块设备可以通告写缓存、discard 支持、几何信息等)。客户驱动程序读取设备通告的特性,选择驱动程序知道如何使用的特性,然后写回一个协商后的特性掩码。设备随后同意协商后的集合,并拒绝使用集合之外特性的任何尝试。这种协商是 VirtIO 设备和驱动程序在不破坏彼此的情况下演进的机制。 -The fourth element is the **device status**. A small byte-level register reports where in the lifecycle the device sits: acknowledged by the driver, driver found for this device type, features negotiated, device set up and ready, and so on. Writing to the status register drives the device through its lifecycle; reading it tells the driver where it is. +第四个元素是**设备状态**。一个小的字节级寄存器报告设备处于生命周期中的哪个阶段:已被驱动程序确认、已找到此设备类型的驱动程序、特性已协商、设备已设置就绪等等。写入状态寄存器驱动设备通过其生命周期;读取它告诉驱动程序当前处于哪里。 -The fifth element is the **device configuration space**. Each device type has its own small layout of bytes that carry device-specific configuration: a block device's capacity, a network device's MAC address, a console device's port count. The guest reads the configuration space to learn device-specific details and occasionally writes to it to request a configuration change. +第五个元素是**设备配置空间**。每种设备类型都有自己的小字节布局,承载设备特定的配置:块设备的容量、网络设备的 MAC 地址、控制台设备的端口数。客户机读取配置空间以了解设备特定的细节,偶尔也会写入以请求配置更改。 -The sixth element, and the most important for this chapter, is the **set of virtqueues**. Each VirtIO device has one or more virtqueues, and the virtqueues are where almost all the actual work happens. Think of each virtqueue as a bounded-size bidirectional conveyor belt between the guest and the host. The guest places requests on the belt; the host consumes them, acts on them, and places completions on a parallel return belt; the guest reads the completions to learn what happened. The conveyor belt is implemented as a ring of descriptors in shared memory. +第六个元素,也是本章最重要的,是**虚拟队列集合**。每个 VirtIO 设备有一个或多个虚拟队列,虚拟队列是几乎所有实际工作发生的地方。把每个虚拟队列想象成客户机和主机之间一个有界大小的双向传送带。客户机将请求放在传送带上;主机消费它们、执行操作,并将完成放在平行的回传传送带上;客户机读取完成以了解发生了什么。传送带实现为共享内存中的描述符环。 -### Virtqueues and the Shared-Ring Model +### 虚拟队列与共享环模型 -At the heart of VirtIO is the virtqueue, the single most important abstraction in the whole protocol. A virtqueue is a ring of descriptors, held in memory that both the guest and the host can read and write. Its size is a power of two, chosen at device initialisation; typical values are 128 or 256 entries, though larger values are permitted. +VirtIO 的核心是虚拟队列,这是整个协议中最重要的抽象。虚拟队列是一个描述符环,保存在客户机和主机都可以读写的内存中。其大小是 2 的幂,在设备初始化时选择;典型值为 128 或 256 个条目,但也允许更大的值。 -Each descriptor in the ring describes a single scatter-gather buffer in guest memory: its guest physical address, its length, and a couple of flags (is this buffer readable or writable from the device's point of view, does this descriptor chain to a next descriptor, does it point to an indirect descriptor table). The driver fills descriptors, chains them as needed to represent multi-buffer transactions, and writes to a small index to announce that new descriptors are available. The host's device implementation walks the descriptors, performs the work they describe, and writes to its own index to announce that the work is done. +环中的每个描述符描述客户机内存中的一个分散-聚集缓冲区:其客户机物理地址、长度和几个标志(从设备的角度看此缓冲区是可读还是可写的、此描述符是否链接到下一个描述符、是否指向间接描述符表)。驱动程序填充描述符,根据需要链接它们以表示多缓冲区事务,并写入一个小索引来通告有新的描述符可用。主机的设备实现遍历描述符,执行它们描述的工作,并写入自己的索引来通告工作已完成。 -There are three rings inside a virtqueue, not one. The **descriptor table** holds the actual descriptors. The **available ring** (driven by the guest) lists the indices of descriptor chains the driver has made available. The **used ring** (driven by the host) lists the indices of descriptor chains the device has consumed and whose results are ready. The split is subtle but important: the driver writes to the available ring and reads from the used ring, while the host does the opposite. Each side reads what the other side wrote, without locks, through careful use of memory barriers and atomic index updates. +虚拟队列内部有三个环,不是一个。**描述符表**保存实际的描述符。**可用环**(由客户机驱动)列出驱动程序已提供的描述符链的索引。**已用环**(由主机驱动)列出设备已消费且结果已就绪的描述符链的索引。这种分割微妙但重要:驱动程序写入可用环并从已用环读取,而主机则相反。每一方读取另一方写入的内容,不使用锁,通过谨慎使用内存屏障和原子索引更新来实现。 -From the driver author's point of view, you almost never manipulate the rings by hand. FreeBSD's `virtqueue(9)` API abstracts them behind a handful of functions. You call `virtqueue_enqueue()` to push a scatter-gather list onto the available ring. You call `virtqueue_notify()` to let the host know new work is available. You call `virtqueue_dequeue()` to pull the next completion off the used ring. If you are polling rather than taking interrupts, you call `virtqueue_poll()` to wait for the next completion. The API hides the index arithmetic, the memory barriers, and the flag juggling; your code deals with scatter-gather lists and cookies. +从驱动程序作者的角度来看,你几乎从不手动操作环。FreeBSD 的 `virtqueue(9)` API 将它们抽象在少量函数之后。你调用 `virtqueue_enqueue()` 将分散-聚集列表推到可用环上。你调用 `virtqueue_notify()` 让主机知道有新工作可用。你调用 `virtqueue_dequeue()` 从已用环拉取下一个完成。如果你在轮询而不是接收中断,你调用 `virtqueue_poll()` 等待下一个完成。API 隐藏了索引算术、内存屏障和标志操作;你的代码只处理分散-聚集列表和 cookie。 -The cookie mechanism deserves a line. When you enqueue a scatter-gather list, you supply an opaque pointer, the cookie, which the API remembers. When you dequeue a completion, you receive that cookie back. This lets the driver associate each completion with the request that produced it, without the ring having to carry any driver-specific context. A driver typically passes the pointer to a softc-level request structure as the cookie; dequeue gives back the same pointer, and the driver resumes processing. +cookie 机制值得一提。当你入队一个分散-聚集列表时,你提供一个不透明指针(cookie),API 会记住它。当你出队一个完成时,你会收到那个 cookie 返回。这让驱动程序能将每个完成与产生它的请求关联起来,而不需要环携带任何驱动程序特定的上下文。驱动程序通常传递指向 softc 级别请求结构的指针作为 cookie;出队时返回相同的指针,驱动程序继续处理。 -### Feature Negotiation in Practice +### 特性协商的实践 -Before the driver uses any of these mechanisms, it must negotiate features. The sequence is simple and looks the same in every VirtIO driver. +在驱动程序使用这些机制之前,它必须协商特性。这个序列很简单,在每个 VirtIO 驱动程序中看起来都一样。 -First, the driver reads the device's advertised feature bits with `virtio_negotiate_features()`. The argument is a mask of features the driver is prepared to use; the return value is the intersection of the driver's mask and the device's advertised bits. The device has now committed to supporting only that subset, and the driver knows exactly which features are in play. +首先,驱动程序通过 `virtio_negotiate_features()` 读取设备播发的特性位。参数是驱动程序准备使用的特性掩码;返回值是驱动程序掩码与设备播发位的交集。此时设备已承诺仅支持该子集,驱动程序也确切知道哪些特性生效。 -Second, the driver calls `virtio_finalize_features()` to seal the negotiation. After this call, the device will reject any attempt to enable features outside the negotiated set. The driver's subsequent setup code can inspect the negotiated mask through `virtio_with_feature()`, which returns true if a given feature bit is present. +其次,驱动程序调用 `virtio_finalize_features()` 来锁定协商结果。此调用之后,设备将拒绝任何尝试启用协商集合之外特性的操作。驱动程序的后续设置代码可以通过 `virtio_with_feature()` 检查协商后的掩码,如果给定的特性位存在则返回 true。 -Third, the driver allocates virtqueues. The exact number and per-queue parameters depend on the device type. A `virtio_random` device allocates one virtqueue; a `virtio_net` device allocates at least two (one for receive, one for transmit), more if multiple queues are negotiated. Allocation uses `virtio_alloc_virtqueues()`, passing an array of `struct vq_alloc_info`, each entry describing one queue's name, callback, and maximum indirect-descriptor size. +第三,驱动程序分配虚拟队列。确切的队列数量和每队列参数取决于设备类型。`virtio_random` 设备分配一个虚拟队列;`virtio_net` 设备至少分配两个(一个用于接收,一个用于发送),如果协商了多队列则会更多。分配使用 `virtio_alloc_virtqueues()`,传入一个 `struct vq_alloc_info` 数组,每个条目描述一个队列的名称、回调和最大间接描述符大小。 -Fourth, the driver sets up interrupts with `virtio_setup_intr()`. The interrupt handlers are the callbacks from step three. When the host has posted a completion to a queue, the guest receives a virtual interrupt, the handler runs, and it processes the completions by calling `virtqueue_dequeue()` in a loop. +第四,驱动程序通过 `virtio_setup_intr()` 设置中断。中断处理程序就是第三步中的回调函数。当主机向队列提交完成时,客户机收到一个虚拟中断,处理程序运行,通过循环调用 `virtqueue_dequeue()` 来处理完成项。 -This four-step sequence is the backbone of every VirtIO driver in `/usr/src/sys/dev/virtio/`. Read `vtrnd_attach()` in `/usr/src/sys/dev/virtio/random/virtio_random.c` and you will see it clearly: feature negotiation, queue allocation, and interrupt setup, in exactly that order. Read `vtblk_attach()` in `/usr/src/sys/dev/virtio/block/virtio_blk.c` and you will see the same sequence, with more moving parts because the device is more complex, but the same skeleton. +这四个步骤的序列是 `/usr/src/sys/dev/virtio/` 中每个 VirtIO 驱动程序的骨架。阅读 `/usr/src/sys/dev/virtio/random/virtio_random.c` 中的 `vtrnd_attach()`,你会清楚地看到:特性协商、队列分配和中断设置,严格按照这个顺序。阅读 `/usr/src/sys/dev/virtio/block/virtio_blk.c` 中的 `vtblk_attach()`,你会看到相同的序列,只是因为设备更复杂所以有更多的活动部件,但骨架是一样的。 -### A Walkthrough of `virtio_random` +### `virtio_random` 详解 -Because `virtio_random` is the smallest complete VirtIO driver in the FreeBSD tree, it is the best one to read first. The whole file is under four hundred lines, and every line is there for a reason. Let us trace through the important parts. +因为 `virtio_random` 是 FreeBSD 代码树中最小的完整 VirtIO 驱动程序,所以它是最好的入门读物。整个文件不到四百行,每一行都有其存在的理由。让我们追踪其中的重要部分。 -The softc is small: +softc 很小: ```c struct vtrnd_softc { @@ -391,9 +391,9 @@ struct vtrnd_softc { }; ``` -The fields are the device handle, the negotiated feature mask (the device has no feature bits so this will always be zero), a pointer to the single virtqueue, an event handler tag for shutdown hooks, a flag that is set to true during teardown, a scatter-gather list used for every enqueue, and a buffer in which the device will store each batch of entropy. +字段包括设备句柄、协商的特性掩码(设备没有特性位所以这总是零)、指向单一虚拟队列的指针、用于关机钩子的事件处理程序标签、在拆卸期间设置为 true 的标志、用于每次入队的分散-聚集列表,以及设备将在其中存储每批熵的缓冲区。 -The device methods table is the standard newbus skeleton: +设备方法表是标准的 newbus 骨架: ```c static device_method_t vtrnd_methods[] = { @@ -416,9 +416,9 @@ MODULE_DEPEND(virtio_random, virtio, 1, 1, 1); MODULE_DEPEND(virtio_random, random_device, 1, 1, 1); ``` -`VIRTIO_DRIVER_MODULE` is a short macro that expands to two `DRIVER_MODULE` declarations, one for `virtio_pci` and one for `virtio_mmio`. This is how the same driver attaches on both transports without any transport-specific code of its own; the framework routes it to whichever transport finds a matching device. +`VIRTIO_DRIVER_MODULE` 是一个简短的宏,展开为两个 `DRIVER_MODULE` 声明,一个用于 `virtio_pci`,一个用于 `virtio_mmio`。这就是同一个驱动程序在两种传输上附加而不需要任何自己的传输特定代码的方式;框架将它路由到找到匹配设备的任何传输。 -The `probe` function is one line: +`probe` 函数只有一行: ```c static int @@ -428,9 +428,9 @@ vtrnd_probe(device_t dev) } ``` -`VIRTIO_SIMPLE_PROBE` consults the PNP match table that was declared above through `VIRTIO_SIMPLE_PNPINFO`. The match table tells the kernel that this driver wants devices whose VirtIO type is `VIRTIO_ID_ENTROPY`. +`VIRTIO_SIMPLE_PROBE` 查询上面通过 `VIRTIO_SIMPLE_PNPINFO` 声明的 PNP 匹配表。匹配表告诉内核该驱动程序想要 VirtIO 类型为 `VIRTIO_ID_ENTROPY` 的设备。 -The `attach` function is more substantial. It allocates the entropy buffer and the scatter-gather list, sets up features, allocates a single virtqueue, installs a shutdown event handler, registers itself with the FreeBSD `random(4)` framework, and posts its first buffer into the virtqueue: +`attach` 函数更为重要。它分配熵缓冲区和分散-聚集列表、设置特性、分配一个单一虚拟队列、安装关机事件处理程序、向 FreeBSD `random(4)` 框架注册自己,并将第一个缓冲区发布到虚拟队列中: ```c sc = device_get_softc(dev); @@ -455,7 +455,7 @@ random_source_register(&random_vtrnd); vtrnd_enqueue(sc); ``` -Feature negotiation is trivial because the driver advertises `VTRND_FEATURES = 0`: +特性协商是简单的,因为驱动程序通告 `VTRND_FEATURES = 0`: ```c static int @@ -469,9 +469,9 @@ vtrnd_negotiate_features(struct vtrnd_softc *sc) } ``` -The feature mask of the device is irrelevant; the driver wants no features and gets no features, and the finalisation succeeds trivially. A more complex driver would build a non-zero mask and check it afterwards. +设备的特性掩码无关紧要;驱动程序不需要特性也不获得特性,终结化简单地成功。更复杂的驱动程序会构建非零掩码并在之后检查它。 -The virtqueue allocation asks for a single queue: +虚拟队列分配请求一个单一队列: ```c static int @@ -487,9 +487,9 @@ vtrnd_alloc_virtqueue(struct vtrnd_softc *sc) } ``` -The first argument to `VQ_ALLOC_INFO_INIT` is the maximum indirect-descriptor-table size, which is zero for this driver because it does not use indirect descriptors. The second argument is the interrupt handler callback, which is `NULL` because this driver uses polling rather than interrupt-driven completion. The third is the argument to that handler. The fourth is the output pointer for the virtqueue handle. The fifth is a format string that produces the queue's name. +`VQ_ALLOC_INFO_INIT` 的第一个参数是最大间接描述符表大小,此驱动程序为零,因为它不使用间接描述符。第二个参数是中断处理回调,为 `NULL`,因为此驱动程序使用轮询而非中断驱动的完成。第三个是该处理程序的参数。第四个是虚拟队列句柄的输出指针。第五个是生成队列名称的格式字符串。 -The enqueue function is short: +入队函数很短: ```c static void @@ -507,9 +507,9 @@ vtrnd_enqueue(struct vtrnd_softc *sc) } ``` -This pushes a scatter-gather list describing the entropy buffer onto the ring. The cookie is `sc` itself. The next two arguments are "readable segments" (none, the device writes the buffer) and "writable segments" (one, the entropy buffer). `virtqueue_notify()` kicks the host so it starts filling the buffer. +这会将描述熵缓冲区的分散-聚集列表推到环上。cookie 是 `sc` 本身。接下来两个参数是"可读段"(无,设备写入缓冲区)和"可写段"(一个,熵缓冲区)。`virtqueue_notify()` 踢一下主机,让它开始填充缓冲区。 -Because there are no interrupts, the driver uses polling to retrieve completions: +因为没有中断,驱动程序使用轮询来检索完成: ```c static int @@ -534,29 +534,29 @@ vtrnd_harvest(struct vtrnd_softc *sc, void *buf, size_t *sz) } ``` -The lifecycle here is the full VirtIO cycle. Enqueue posts a buffer; the host fills it with entropy and marks the descriptor "used"; the driver dequeues the used descriptor, extracts the cookie and the length, copies the result out to its caller, and re-posts the buffer for the next round. If the queue is empty (no completion yet), `virtqueue_dequeue()` returns `NULL` and the driver returns `EAGAIN`. +这里的生命周期是完整的 VirtIO 循环。入队发布一个缓冲区;主机用熵填充它并将描述符标记为"已用";驱动程序出队已用的描述符,提取 cookie 和长度,将结果复制给调用者,并为下一轮重新发布缓冲区。如果队列为空(尚无完成),`virtqueue_dequeue()` 返回 `NULL`,驱动程序返回 `EAGAIN`。 -This is the full shape of a VirtIO driver. Everything else, from `virtio_blk` to `if_vtnet`, is elaboration on this base: more queues, more features, more work per completion, more bookkeeping per request. The skeleton is the same. +这是 VirtIO 驱动程序的完整形态。其他一切,从 `virtio_blk` 到 `if_vtnet`,都是在这个基础上的扩展:更多队列、更多特性、每次完成更多工作、每个请求更多簿记。骨架是相同的。 -### What the `virtqueue(9)` API Buys You +### `virtqueue(9)` API 给你带来了什么 -Step back for a moment and consider how much complexity the API abstracts away. The ring arithmetic, with its wraparound and its careful handling of available versus used indices, is entirely hidden. The memory barriers that keep the guest and the host in sync, which are subtle enough to be a common source of bugs in handwritten ring code, are placed by the API. The optional features (indirect descriptors, event indexes) are turned on and off based on negotiation without the driver having to know how they work. +退后一步,想想 API 抽象掉了多少复杂性。带有环绕和仔细的可用与已用索引处理的环算术完全被隐藏了。保持客户机和主机同步的内存屏障——在手写环代码中足够微妙以致成为常见 bug 来源——由 API 放置。可选特性(间接描述符、事件索引)基于协商打开和关闭,驱动程序不需要知道它们如何工作。 -The cost of that abstraction is that a driver author who only ever uses the API will not understand the rings themselves in depth. That is usually fine, but on the rare occasion when you debug a ring-layer mismatch (because you posted a descriptor with the wrong writable count, say, and the host is rejecting it) you will want to know what is going on. The VirtIO specification is the reference for the underlying ring layout, and `/usr/src/sys/dev/virtio/virtio_ring.h` is the FreeBSD side of the same layout. They repay reading at least once. +这种抽象的代价是只使用 API 的驱动程序作者不会深入理解环本身。这通常没问题,但在罕见的情况下,当你调试环层不匹配时(因为你发布了错误可写计数的描述符,主机正在拒绝它),你会想知道发生了什么。VirtIO 规范是底层环布局的参考,`/usr/src/sys/dev/virtio/virtio_ring.h` 是相同布局的 FreeBSD 侧。它们值得至少阅读一次。 -### Indirect Descriptors +### 间接描述符 -A small optimisation worth knowing about is the indirect-descriptor feature (`VIRTIO_RING_F_INDIRECT_DESC`). When negotiated, it allows a driver to describe a multi-buffer transaction in an indirect descriptor table rather than a chain of descriptors on the main ring. The ring entry becomes a single descriptor that points to a block of descriptors, so a large scatter-gather list consumes only one slot on the ring rather than many. +一个值得了解的小优化是间接描述符特性(`VIRTIO_RING_F_INDIRECT_DESC`)。协商后,它允许驱动程序在间接描述符表中而非主环上的描述符链中描述多缓冲区事务。环条目变成一个指向描述符块的单个描述符,因此大的分散-聚集列表只消耗环上的一个槽而不是多个。 -Indirect descriptors matter in workloads that do large, scatter-gather-heavy transactions, such as network drivers sending packets with many fragments. For small drivers, they are an optional flourish. The `virtqueue(9)` API handles the mechanism transparently: if you pass a non-zero `vqai_maxindirsz` during queue allocation, the kernel can use indirects; if you pass zero, it cannot. +间接描述符在执行大型、分散-聚集密集型事务的工作负载中很重要,例如发送具有许多片段的数据包的网络驱动程序。对于小型驱动程序,它们是可选的修饰。`virtqueue(9)` API 透明地处理该机制:如果在队列分配期间传递非零的 `vqai_maxindirsz`,内核可以使用间接描述符;如果传递零,则不能。 -### A Deeper Look at the Ring Layout +### 深入了解环布局 -For a reader who wants to know what `virtqueue(9)` is hiding, here is a brief tour of the underlying layout. The details matter only when you are debugging a ring-layer issue; you can skip this subsection on first reading. +对于想知道 `virtqueue(9)` 隐藏了什么的读者,这里是底层布局的简要介绍。细节只在调试环层问题时重要;你可以在首次阅读时跳过此小节。 -Each virtqueue has three main structures in memory, allocated contiguously (with alignment requirements that differ slightly between legacy and modern VirtIO). +每个虚拟队列在内存中有三个主要结构,连续分配(对齐要求在传统和现代 VirtIO 之间略有不同)。 -The **descriptor table** is an array of `struct vring_desc`, one entry per descriptor slot: +**描述符表** 是一个 `struct vring_desc` 数组,每个描述符槽位对应一个条目: ```c struct vring_desc { @@ -567,9 +567,9 @@ struct vring_desc { }; ``` -The descriptor table has as many entries as the queue size (typically 128 or 256). Unused descriptors are linked into a free list maintained by the driver; used descriptors form chains that describe single transactions. +描述符表有与队列大小相同数量的条目(通常为 128 或 256)。未使用的描述符被链接到由驱动程序维护的空闲列表中;已使用的描述符形成描述单个事务的链。 -The **available ring** is what the driver writes and the device reads: +**可用环**是驱动程序写入、设备读取的部分: ```c struct vring_avail { @@ -580,9 +580,9 @@ struct vring_avail { }; ``` -When the driver enqueues a new transaction, it picks a chain of descriptors from the free list, fills them in, places the head descriptor's index into `ring[idx % QUEUE_SIZE]`, and then increments `idx`. The increment uses a release-style memory barrier so that the device sees the new `ring` entry before it sees the new `idx`. +当驱动程序入队一个新事务时,它从空闲列表中选取一个描述符链,填充它们,将头描述符的索引放入 `ring[idx % QUEUE_SIZE]`,然后递增 `idx`。递增使用释放式内存屏障,使设备在看到新的 `idx` 之前先看到新的 `ring` 条目。 -The **used ring** is what the device writes and the driver reads: +**已用环**是设备写入、驱动程序读取的部分: ```c struct vring_used_elem { @@ -598,95 +598,95 @@ struct vring_used { }; ``` -When the device finishes a transaction, it writes an entry to `ring[idx % QUEUE_SIZE]` with the head index and the byte count, then increments `idx`. The driver observes the increment and dequeues accordingly. +当设备完成一个事务时,它向 `ring[idx % QUEUE_SIZE]` 写入一个条目,包含头索引和字节计数,然后递增 `idx`。驱动程序观察到递增并相应地出队。 -The subtlety of the format is the synchronisation. Guest and host are not synchronising through locks (they do not share locks); they are synchronising through ordered writes and atomic index updates. The spec is careful to specify the memory barriers on each side, and the `virtqueue(9)` implementation places them correctly. Getting the barriers wrong is a common bug in hand-rolled ring implementations; that is one reason to use the framework. +格式的微妙之处在于同步。客户机和主机不是通过锁来同步的(它们不共享锁);它们通过有序写入和原子索引更新来同步。规范仔细地指定了每一侧的内存屏障,`virtqueue(9)` 实现正确地放置了它们。在手写环实现中弄错屏障是一个常见的 bug;这就是使用框架的原因之一。 -### Event Indexes: A Performance Detail +### 事件索引:一个性能细节 -The `VIRTIO_F_RING_EVENT_IDX` feature allows both sides to suppress notifications when they are not needed. The mechanism is two extra fields, `used_event` in the available ring and `avail_event` in the used ring. Each side writes a value saying "interrupt me only when the other side's producer index passes this value". +`VIRTIO_F_RING_EVENT_IDX` 特性允许双方在不需要时抑制通知。该机制是两个额外字段:可用环中的 `used_event` 和已用环中的 `avail_event`。每一方写入一个值,表示"仅当对方的生产者索引超过此值时才中断我"。 -The practical effect is that a driver producing requests at a high rate does not cause the host to be interrupted on every enqueue; instead, the host reads the current `used_event` and only delivers a notification when the producer index catches up. Similarly, a device completing transactions at a high rate does not cause the guest to be interrupted on every dequeue; the guest sets `avail_event` to suppress notifications it does not need. +实际效果是,以高速率产生请求的驱动程序不会导致主机在每次入队时都被中断;相反,主机读取当前的 `used_event`,只在水者索引追上时才投递通知。类似地,以高速率完成事务的设备不会导致客户机在每次出队时都被中断;客户机设置 `avail_event` 来抑制它不需要的通知。 -This optimisation halves the notification overhead in worst-case workloads. It is a feature that most modern VirtIO drivers negotiate, and the `virtqueue(9)` API handles it transparently. As a driver author, you simply negotiate the feature and do not have to think about the details. +这种优化在最坏情况工作负载中将通知开销减半。这是大多数现代 VirtIO 驱动程序协商的特性,`virtqueue(9)` API 透明地处理它。作为驱动程序作者,你只需协商该特性,不必考虑细节。 -### Legacy Versus Modern VirtIO +### 传统与现代 VirtIO -VirtIO has two major versions. Legacy (sometimes called "virtio 0.9") was the original specification; modern ("virtio 1.0" and up) came later with a cleaner design. FreeBSD supports both. +VirtIO 有两个主要版本。传统版本(有时称为"virtio 0.9")是原始规范;现代版本("virtio 1.0"及以上)后来带着更简洁的设计出现。FreeBSD 两者都支持。 -The practical differences are in configuration-space layout, byte order, and a few feature-bit semantics. Legacy VirtIO puts configuration in native byte order; modern VirtIO is always little-endian. Legacy mandates some fields in a specific position; modern uses capability structures to describe the layout flexibly. Legacy defines a specific set of feature bits below bit 32; modern extends them above bit 32. +实际差异在于配置空间布局、字节序和一些特性位语义。传统 VirtIO 以本机字节序放置配置;现代 VirtIO 始终为小端序。传统模式要求某些字段在特定位置;现代模式使用能力结构来灵活描述布局。传统模式在第32位以下定义特定的特性位集;现代模式将它们扩展到第32位以上。 -For driver authors, the framework hides most of these differences. Negotiating `VIRTIO_F_VERSION_1` puts the driver in modern mode; not negotiating it puts the driver in legacy mode. The `virtio_with_feature` helper checks the negotiated state. As long as your driver follows the `virtqueue(9)` API and uses `virtio_read_device_config` rather than direct configuration-space access, you can ignore the legacy/modern distinction almost entirely. +对于驱动程序作者来说,框架隐藏了大部分这些差异。协商 `VIRTIO_F_VERSION_1` 将驱动程序置于现代模式;不协商它将驱动程序置于传统模式。`virtio_with_feature` 辅助函数检查协商状态。只要你的驱动程序遵循 `virtqueue(9)` API 并使用 `virtio_read_device_config` 而非直接配置空间访问,你几乎可以完全忽略传统/现代的区别。 -The one place where the distinction leaks is in how configuration-space fields are accessed. Legacy VirtIO uses `virtio_read_device_config` with a size argument and assumes native byte order; modern VirtIO assumes little-endian and uses helpers that byte-swap if the host is big-endian. The framework handles this, but a driver that does configuration-space access by hand (rather than through the framework) would have to be aware. +区别泄漏的唯一地方是配置空间字段的访问方式。传统 VirtIO 使用带大小参数的 `virtio_read_device_config` 并假设本机字节序;现代 VirtIO 假设小端序,并在主机为大端序时使用字节交换辅助函数。框架处理了这一点,但手动进行配置空间访问(而非通过框架)的驱动程序需要意识到这一点。 -### Feature Bits Worth Knowing +### 值得了解的特性位 -Each VirtIO device type has its own set of feature bits. A few are worth knowing in the abstract, because they show up in many drivers. +每种 VirtIO 设备类型都有自己的特性位集。有几个在抽象层面值得了解,因为它们出现在许多驱动程序中。 -- `VIRTIO_F_VERSION_1` indicates that the device supports the modern, version 1 of the VirtIO specification. Almost all modern drivers negotiate this bit. -- `VIRTIO_F_RING_EVENT_IDX` enables a more efficient form of interrupt suppression. When both sides support it, notifications and interrupts are only sent when they are actually useful, reducing overhead under load. -- `VIRTIO_F_RING_INDIRECT_DESC`, already mentioned, allows indirect descriptors. -- `VIRTIO_F_ANY_LAYOUT` relaxes the rules about how descriptors are ordered in a chain. +- `VIRTIO_F_VERSION_1` 表示设备支持现代的 VirtIO 规范版本 1。几乎所有现代驱动程序都协商此位。 +- `VIRTIO_F_RING_EVENT_IDX` 启用更高效的中断抑制形式。当双方都支持时,通知和中断只在实际有用时才发送,减少了负载下的开销。 +- `VIRTIO_F_RING_INDIRECT_DESC`,前面已提到,允许间接描述符。 +- `VIRTIO_F_ANY_LAYOUT` 放宽了描述符在链中如何排序的规则。 -Each device type has its own set on top of these. For a block device, `VIRTIO_BLK_F_WCE` indicates that the device has a write cache; `VIRTIO_BLK_F_FLUSH` provides a flush command. For a network device, `VIRTIO_NET_F_CSUM` advertises offloaded checksum calculation. For entropy, there are no device-specific feature bits. +每种设备类型在这些之上有自己的集合。对于块设备,`VIRTIO_BLK_F_WCE` 表示设备有写缓存;`VIRTIO_BLK_F_FLUSH` 提供刷新命令。对于网络设备,`VIRTIO_NET_F_CSUM` 通告卸载的校验和计算。对于熵设备,没有设备特定的特性位。 -The general rule is: read the feature bits the device advertises, decide which the driver can use, ignore the others. Negotiation is not about "demanding" features; it is about agreeing on an intersection. +通用规则是:读取设备通告的特性位,决定驱动程序可以使用哪些,忽略其他的。协商不是"要求"特性;而是就交集达成一致。 -### A Second Example: Structure of virtio_net +### 第二个示例:virtio_net 的结构 -It is worth a brief look at a larger VirtIO driver to see how the skeleton scales. The network driver `if_vtnet` lives in `/usr/src/sys/dev/virtio/network/if_vtnet.c`. It is roughly ten times the length of `virtio_random`, but the extra size comes from features and completeness, not from complexity in the core VirtIO interaction. Knowing how the scale-up works makes future reading more productive. +值得简要查看一个更大的 VirtIO 驱动程序,以了解骨架如何扩展。网络驱动程序 `if_vtnet` 位于 `/usr/src/sys/dev/virtio/network/if_vtnet.c`。 它大约是 `virtio_random` 的十倍長度,但额外的篇幅来自特性和完整性,而不是核心 VirtIO 交互中的复杂性。了解这种扩展方式使未来的阅读更加有效率。 -`if_vtnet` begins, like every VirtIO driver, with a module registration and a `device_method_t` table. The methods table is longer because `if_vtnet` hooks into the `ifnet(9)` framework; you will see `DEVMETHOD` entries for `device_probe`, `device_attach`, `device_detach`, `device_suspend`, `device_resume`, and `device_shutdown`, each implemented by the driver. The `VIRTIO_DRIVER_MODULE` macro at the bottom of the file registers the driver for both PCI and MMIO transports, exactly as `virtio_random` does. +`if_vtnet` 和每个 VirtIO 驱动程序一样,以模块注册和 `device_method_t` 表开始。方法表更长,因为 `if_vtnet` 挂钩到 `ifnet(9)` 框架;你会看到 `device_probe`、`device_attach`、`device_detach`、`device_suspend`、`device_resume` 和 `device_shutdown` 的 `DEVMETHOD` 条目,每个都由驱动程序实现。文件底部的 `VIRTIO_DRIVER_MODULE` 宏为 PCI 和 MMIO 传输注册驱动程序,与 `virtio_random` 完全一样。 -The softc, `struct vtnet_softc`, is much larger than `vtrnd_softc`, but its role is the same: hold the state that the driver needs to serve the device. Notable additions include a pointer to the kernel's `ifnet` structure (`vtnet_ifp`), an array of receive queues (`vtnet_rxqs`), an array of transmit queues (`vtnet_txqs`), a feature mask, a cached MAC address, and statistics counters. Each queue structure contains its own virtqueue pointer, softc back-reference, taskqueue context, and a number of bookkeeping fields. A single multi-queue virtio-net device can have tens of virtqueues; each receive/transmit pair represents one queue pair that can run in parallel with the others. +softc,即 `struct vtnet_softc`,比 `vtrnd_softc` 大得多,但它的作用相同:保存驱动程序为设备服务所需的状态。值得注意的添加包括指向内核 `ifnet` 结构的指针(`vtnet_ifp`)、接收队列数组(`vtnet_rxqs`)、发送队列数组(`vtnet_txqs`)、特性掩码、缓存的 MAC 地址和统计计数器。每个队列结构包含自己的虚拟队列指针、softc 反向引用、任务队列上下文和许多簿记字段。单个多队列 virtio-net 设备可以有数十个虚拟队列;每个接收/发送对代表一个可以与其他对并行运行的队列对。 -The probe function uses the same `VIRTIO_SIMPLE_PROBE` pattern as `virtio_random`, but matching on `VIRTIO_ID_NETWORK` (which is 1). The attach function is substantial: it reads feature bits, negotiates them, allocates the queues, reads the device's MAC address from configuration space (`virtio_read_device_config`), initialises the `ifnet`, registers with the network stack, and sets up callouts for link-status polling. Each of these steps is a small function of its own, and the flow follows the same "negotiate, allocate, register, start" rhythm that `virtio_random` illustrates. +探测函数使用与 `virtio_random` 相同的 `VIRTIO_SIMPLE_PROBE` 模式,但匹配的是 `VIRTIO_ID_NETWORK`(值为 1)。附加函数内容丰富:它读取特性位,进行协商,分配队列,从配置空间读取设备的 MAC 地址(`virtio_read_device_config`),初始化 `ifnet`,向网络协议栈注册,并设置用于链路状态轮询的 callout。这些步骤各自是一个小函数,流程遵循与 `virtio_random` 所示相同的“协商、分配、注册、启动”节奏。 -The receive path uses `virtqueue_dequeue` in a loop to drain completed packets. For each completed descriptor, the driver reads the packet header (`virtio_net_hdr`) that the device wrote to the first few bytes of the buffer, extracts metadata such as checksum-status flags and GSO segment sizes, and passes the packet up to `if_input`. If the packet is the last one in a batch, the driver re-posts fresh receive buffers to keep the queue primed for the next round. +接收路径在循环中使用 `virtqueue_dequeue` 排空已完成的包。对于每个完成的描述符,驱动程序读取设备写入缓冲区前几字节的包头(`virtio_net_hdr`),提取校验和状态标志和 GSO 段大小等元数据,然后将包向上传递给 `if_input`。如果该包是一批中的最后一个,驱动程序重新投递新的接收缓冲区,使队列保持就绪状态以迎接下一轮。 -The transmit path uses `virtqueue_enqueue` with a scatter-gather list covering both the packet header and the packet body. The cookie is the `mbuf(9)` pointer, so the transmit completion callback can free the mbuf when the device is done with it. If the queue becomes full, the driver stops accepting outbound packets until some space frees up, which is standard `ifnet` driver discipline. +发送路径使用 `virtqueue_enqueue` 配合覆盖包头和包体的分散-聚集列表。cookie 是 `mbuf(9)` 指针,这样发送完成回调可以在设备处理完毕后释放 mbuf。如果队列变满,驱动程序停止接受出站包直到有空间释放,这是标准的 `ifnet` 驱动程序规范。 -Feature negotiation in `if_vtnet` is interesting because the feature set is large. Features like `VIRTIO_NET_F_CSUM` (transmit checksum offload), `VIRTIO_NET_F_GUEST_CSUM` (receive checksum offload), `VIRTIO_NET_F_GSO` (generic segmentation offload), and `VIRTIO_NET_F_MRG_RXBUF` (merged receive buffers) each change how the driver programs the virtqueues and how it interprets incoming data. The driver's feature-negotiation function picks a set that the driver implements, offers it for negotiation, and then queries the negotiated mask to decide which code paths to enable. +`if_vtnet` 中的特性协商很有趣,因为特性集很大。像 `VIRTIO_NET_F_CSUM`(发送校验和卸载)、`VIRTIO_NET_F_GUEST_CSUM`(接收校验和卸载)、`VIRTIO_NET_F_GSO`(通用分段卸载)和 `VIRTIO_NET_F_MRG_RXBUF`(合并接收缓冲区)这样的特性各自改变了驱动程序编程虚拟队列的方式和解释传入数据的方式。驱动程序的特性协商函数选择一个驱动程序实现的集合,提供它进行协商,然后查询协商后的掩码来决定启用哪些代码路径。 -The lesson from `if_vtnet` is that a VirtIO driver scales through feature diversity and queue multiplicity, not through a fundamentally different architecture. If you understand `virtio_random`'s lifecycle, you understand `if_vtnet`'s lifecycle; the extra code is in feature-specific sub-paths and in `ifnet`-specific hooking. When the time comes to read `if_vtnet.c`, focus on `vtnet_attach` first, then walk the feature-negotiation function, then look at `vtnet_rxq_eof` (receive) and `vtnet_txq_encap` (transmit). Those four functions explain 80% of the driver. +从 `if_vtnet` 得到的教训是,VirtIO 驱动程序通过特性多样性和队列多重性来扩展,而不是通过根本不同的架构。如果你理解 `virtio_random` 的生命周期,你就理解 `if_vtnet` 的生命周期;额外的代码在于特性特定的子路径和 `ifnet` 特定的挂钩。当需要阅读 `if_vtnet.c` 时,首先关注 `vtnet_attach`,然后遍历特性协商函数,再看 `vtnet_rxq_eof`(接收)和 `vtnet_txq_encap`(发送)。这四个函数解释了驱动程序 80% 的内容。 -### A Third Example for Intuition: virtio_blk +### 第三个示例:直观理解 virtio_blk -`virtio_blk`, in `/usr/src/sys/dev/virtio/block/virtio_blk.c`, is shorter than `if_vtnet` but longer than `virtio_random`. It illustrates a third common pattern: a driver that exposes a block-oriented device rather than a stream-oriented one. +`virtio_blk`,位于 `/usr/src/sys/dev/virtio/block/virtio_blk.c`,比 `if_vtnet` 短但比 `virtio_random` 长。它演示了第三种常见模式:一个暴露面向块设备而非面向流设备的驱动程序。 -The softc of `vtblk` contains a virtqueue, a pool of request structures, statistics, and the geometry information read from the device's configuration space. The probe and attach follow the familiar pattern. The interesting part is how requests are structured. +`vtblk` 的 softc 包含一个虚拟队列、一组请求结构池、统计信息以及从设备配置空间读取的几何信息。探测和附加遵循熟悉的模式。有趣的部分是请求的结构方式。 -For every block I/O operation, the driver builds a three-segment descriptor chain: a header descriptor (containing the operation type and sector number), zero or more data descriptors (the actual payload, which is writable from the device's perspective for reads and readable from the device for writes), and a status descriptor (where the device writes a single-byte status code). The header and status are small structures; the data segments are whatever the `bio(9)` request brought in. +对于每个块 I/O 操作,驱动程序构建一个三段描述符链:一个头部描述符(包含操作类型和扇区号)、零个或多个数据描述符(实际载荷,从设备角度看读取时可写、写入时可读),以及一个状态描述符(设备在其中写入一个单字节状态码)。头部和状态是小型结构;数据段则是 `bio(9)` 请求带来的内容。 -This three-segment layout is a common VirtIO idiom. If you see a driver building a chain that starts with a header and ends with a status, you are looking at a request-response device. `virtio_scsi` uses the same layout, as does `virtio_console` (for control messages). Recognising the pattern speeds up reading. +这种三段布局是常见的 VirtIO 惯用法。如果你看到一个驱动程序构建一个以头部开始、以状态结束的链,你看到的就是一个请求-响应设备。`virtio_scsi` 使用相同的布局,`virtio_console`(用于控制消息)也是如此。识别这种模式可以加速阅读。 -### Common Mistakes When Reading VirtIO Code +### 阅读 VirtIO 代码时的常见错误 -When reading any VirtIO driver for the first time, a few patterns can confuse a reader who is not expecting them. +首次阅读任何 VirtIO 驱动程序时,一些模式可能会让没有心理准备的读者感到困惑。 -The first is the mix of probe patterns. Some drivers use `VIRTIO_SIMPLE_PROBE`; others use their own probe functions that do more complex feature checks. Both are legitimate, and the former is a shorthand for a common case. +第一个是探测模式的混合。一些驱动程序使用 `VIRTIO_SIMPLE_PROBE`;其他的使用自己的探测函数做更复杂的特性检查。两者都是合理的,前者是常见情况的简写。 -The second is the module registration style. `VIRTIO_DRIVER_MODULE` is a macro that expands to two `DRIVER_MODULE` calls, and reading the macro definition (in `/usr/src/sys/dev/virtio/virtio.h`) makes it clear. Without the macro, you might wonder why the driver is not calling `DRIVER_MODULE` explicitly; with it, you see that it is, once per transport. +第二个是模块注册风格。`VIRTIO_DRIVER_MODULE` 是一个宏,它展开为两个 `DRIVER_MODULE` 调用,阅读宏定义(在 `/usr/src/sys/dev/virtio/virtio.h` 中)就能看清。没有这个宏,你可能会想为什么驱动程序没有显式调用 `DRIVER_MODULE`;有了它,你会看到它确实调用了,每种传输一次。 -The third is the distinction between the VirtIO core functions (`virtio_*`) and the virtqueue functions (`virtqueue_*`). The core functions operate on the whole device; the virtqueue functions operate on a single queue. A driver usually uses both, and the namespace prefix is the hint. +第三个是 VirtIO 核心函数(`virtio_*`)和虚拟队列函数(`virtqueue_*`)之间的区别。核心函数操作整个设备;虚拟队列函数操作单个队列。驱动程序通常同时使用两者,命名空间前缀就是提示。 -The fourth is the polling-versus-interrupt distinction. A driver that polls (like `virtio_random`) passes `NULL` as the callback in `VQ_ALLOC_INFO_INIT` and calls `virtqueue_poll` to wait for completions. A driver that uses interrupts (like `if_vtnet`) passes a callback and lets the kernel's interrupt infrastructure schedule it. Both are legitimate; the choice depends on the workload's latency sensitivity and on whether the driver can afford to block. +第四个是轮询与中断的区别。轮询的驱动程序(如 `virtio_random`)在 `VQ_ALLOC_INFO_INIT` 中将 `NULL` 作为回调传递,并调用 `virtqueue_poll` 等待完成。使用中断的驱动程序(如 `if_vtnet`)传递一个回调,让内核的中断基础设施来调度它。两者都是合理的;选择取决于工作负载的延迟敏感性和驱动程序是否可以承受阻塞。 ### 总结 -This has been a long section, and deliberately so. VirtIO is dense, and its vocabulary is the foundation for most of the interesting work a modern guest-driver author does. You now know that a VirtIO device has a transport, a type, a feature mask, a status, a configuration space, and a set of virtqueues; that the virtqueues are shared rings with separate descriptor, available, and used components; that `virtqueue(9)` abstracts the ring mechanics behind a small API of enqueue, dequeue, notify, and poll; that feature negotiation is the mechanism for forward and backward compatibility; and that the smallest FreeBSD VirtIO driver is `virtio_random`, under four hundred lines of code that illustrate the whole skeleton. You have also seen how larger VirtIO drivers like `if_vtnet` and `virtio_blk` are structured around the same skeleton, scaled up with feature-specific code. +这是一个很长的节,而且是故意的。VirtIO 内容密集,其词汇是现代客户驱动程序作者所做大多数有趣工作的基础。你现在知道 VirtIO 设备有传输层、类型、特性掩码、状态、配置空间和一组虚拟队列;虚拟队列是共享环,有独立的描述符、可用和已用组件;`virtqueue(9)` 将环机制抽象在入队、出队、通知和轮询的小型 API 之后;特性协商是向前和向后兼容的机制;最小的 FreeBSD VirtIO 驱动程序是 `virtio_random`,不到四百行代码展示了完整的骨架。你也看到了更大的 VirtIO 驱动程序如 `if_vtnet` 和 `virtio_blk` 如何围绕相同的骨架构建,通过特性特定的代码进行扩展。 -Section 4 takes a different turn. Now that you know what a guest driver is, we consider the question: how does the driver know it is in a guest in the first place? +第4节转向不同的方向。现在你知道了什么是客户驱动程序,我们来考虑这个问题:驱动程序如何首先知道它在一个客户机中? ## 第4节:虚拟机监控程序检测与环境感知的驱动程序行为 -There are legitimate reasons for a driver to know whether it is running inside a virtual machine. A driver that is inclined to use an expensive hardware counter may skip it on a hypervisor where the counter is known to be unreliable. A driver that polls a hardware register in a tight loop may tune its polling interval differently under virtualisation, because each poll becomes a hypervisor exit. A driver that emits a warning about a suspicious interrupt rate may suppress the warning when running in a cloud where background noise is normal. A few FreeBSD drivers in the tree use this kind of adaptation. +驱动程序知道它是否在虚拟机内运行是有正当理由的。一个倾向于使用昂贵硬件计数器的驱动程序可以在已知计数器不可靠的虚拟机监控程序上跳过它。一个在紧密循环中轮询硬件寄存器的驱动程序可以在虚拟化下以不同方式调整其轮询间隔,因为每次轮询都变成一次虚拟机监控程序退出。一个发出可疑中断速率警告的驱动程序可以在云环境中运行时抑制该警告,因为云环境中的背景噪声是正常的。FreeBSD 源代码树中有一些驱动程序使用这种适应性。 -There are also illegitimate reasons. A driver that tries to behave differently to "hide" something from a hypervisor is building anti-debugging logic, which has its place in anti-tamper software but has none in a general-purpose driver. A driver that branches on the exact hypervisor brand to gain performance is building fragile code whose behaviour will drift as hypervisors evolve. We will focus on the legitimate uses. +也有不正当的理由。一个试图以不同方式行为来向虚拟机监控程序"隐藏"某些东西的驱动程序是在构建反调试逻辑,这在反篡改软件中有其位置,但在通用驱动程序中没有。一个基于确切虚拟机监控程序品牌分支以获得性能的驱动程序是在构建脆弱的代码,其行为会随着虚拟机监控程序的演进而偏移。我们将专注于正当的用途。 -### The `vm_guest` Global +### `vm_guest` 全局变量 -The FreeBSD kernel exposes a single global variable, `vm_guest`, which records the hypervisor it detected at boot. The variable is declared in `/usr/src/sys/sys/systm.h`: +FreeBSD 内核暴露一个单一的全局变量 `vm_guest`,它记录启动时检测到的虚拟机监控程序。该变量在 `/usr/src/sys/sys/systm.h` 中声明: ```c extern int vm_guest; @@ -706,35 +706,35 @@ enum VM_GUEST { }; ``` -The values are self-explanatory. `VM_GUEST_NO` means the kernel is running on bare metal; the other values identify specific hypervisors. `VM_GUEST_VM` is a fallback for "a virtual machine of unknown type," when the kernel could tell it was virtualised but could not pin down which hypervisor. +这些值是不言自明的。`VM_GUEST_NO` 表示内核运行在裸金属上;其他值标识特定的虚拟机监控程序。`VM_GUEST_VM` 是"未知类型的虚拟机"的回退值,当内核能检测到虚拟化但无法确定是哪个虚拟机监控程序时使用。 -The corresponding sysctl is `kern.vm_guest`, which yields the human-readable form of the same information. The string values mirror the enum: "none", "generic", "xen", "hv", "vmware", "kvm", "bhyve", "vbox", "parallels", "nvmm". You can query it from the shell: +相应的 sysctl 是 `kern.vm_guest`,它产生相同信息的可读形式。字符串值与枚举对应:"none"、"generic"、"xen"、"hv"、"vmware"、"kvm"、"bhyve"、"vbox"、"parallels"、"nvmm"。你可以从 shell 查询它: ```sh sysctl kern.vm_guest ``` -On a bare-metal FreeBSD machine you will see `none`. On a `bhyve(8)` guest, you will see `bhyve`. On a VirtualBox guest, `vbox`. And so on. +在裸金属 FreeBSD 机器上你会看到 `none`。在 `bhyve(8)` 客户机上你会看到 `bhyve`。在 VirtualBox 客户机上看到 `vbox`。以此类推。 -### How the Detection Works +### 检测如何工作 -The detection happens early in boot, on architectures where hypervisor presence is detectable. On amd64, the kernel examines the CPUID leaf for a hypervisor present bit and then probes specific leaves associated with each hypervisor brand. The code lives in `/usr/src/sys/x86/x86/identcpu.c`, in functions named `identify_hypervisor()` and `identify_hypervisor_cpuid_base()`. On arm64, a similar mechanism exists through firmware interfaces. +检测在启动早期进行,在可以检测虚拟机监控程序存在的架构上。在 amd64 上,内核检查 CPUID 叶的虚拟机监控程序存在位,然后探测与每个虚拟机监控程序品牌关联的特定叶。代码位于 `/usr/src/sys/x86/x86/identcpu.c`,在名为 `identify_hypervisor()` 和 `identify_hypervisor_cpuid_base()` 的函数中。在 arm64 上,通过固件接口存在类似的机制。 -The driver author does not need to care about the detection code. What matters is that by the time your driver's `attach()` runs, `vm_guest` has been set to its final value. +驱动程序作者不需要关心检测代码。重要的是,当你的驱动程序的 `attach()` 运行时,`vm_guest` 已经被设置为其最终值。 -### When to Consult `vm_guest` +### 何时查询 `vm_guest` -Consulting `vm_guest` is appropriate in a driver when the driver's correctness or performance depends on knowing the runtime environment. A few real examples from the tree illustrate the range: +当驱动程序的正确性或性能取决于了解运行时环境时,在驱动程序中查询 `vm_guest` 是合适的。源代码树中的一些实际例子说明了范围: -- Some performance counters in `/usr/src/sys/kern/kern_resource.c` adjust their behaviour when `vm_guest == VM_GUEST_NO`, because the kernel assumes a bare-metal cost model is accurate there. -- Some time-related code in the amd64 tree may not use certain timing primitives under specific hypervisors where those primitives are known to be unreliable. -- Some informational messages in driver probe paths are suppressed under virtualisation to avoid confusing users who expect the driver to behave "differently" in a VM. +- `/usr/src/sys/kern/kern_resource.c` 中的一些性能计数器在 `vm_guest == VM_GUEST_NO` 时调整其行为,因为内核假设裸金属成本模型在那里是准确的。 +- amd64 源代码树中的一些时间相关代码可能在已知某些计时原语不可靠的特定虚拟机监控程序下不使用这些原语。 +- 驱动程序探测路径中的一些信息性消息在虚拟化下被抑制,以避免让期望驱动程序在 VM 中"表现不同"的用户感到困惑。 -A driver you write should use `vm_guest` sparingly. A common anti-pattern is to test for `VM_GUEST_VM` as a blanket switch ("if virtualised, do X"), which is usually a sign that the driver has a bug on real hardware that it is papering over. Prefer to handle the underlying cause directly, and use `vm_guest` only when the dependency is genuinely on the environment rather than on a specific hardware quirk. +你编写的驱动程序应谨慎使用 `vm_guest`。一个常见的反模式是将 `VM_GUEST_VM` 作为通用开关测试("如果虚拟化了,就做 X"),这通常表明驱动程序在真实硬件上有一个它正在掩盖的 bug。更倾向于直接处理根本原因,只在依赖确实在于环境而非特定硬件怪癖时使用 `vm_guest`。 -### A Usage Example +### 使用示例 -Suppose your driver has a sysctl that controls how aggressively it polls a hardware register. The tight loop is fine on bare metal, where each poll is cheap, but under virtualisation each poll costs a hypervisor exit, which is expensive. You might want the default polling interval to be larger under virtualisation: +假设你的驱动程序有一个 sysctl 控制它轮询硬件寄存器的激进程度。紧密循环在裸金属上没问题,每次轮询很廉价,但在虚拟化下每次轮询都要付出虚拟机监控程序退出的代价,这很昂贵。你可能希望虚拟化下的默认轮询间隔更大: ```c #include @@ -749,9 +749,9 @@ my_poll_default(void) } ``` -This is a legitimate use of `vm_guest`: the driver is choosing a sensible default based on a property of the environment that genuinely affects its performance characteristics. The value remains overridable by a sysctl for users who know better than the default. +这是 `vm_guest` 的正当使用:驱动程序基于真正影响其性能特征的环境属性选择合理的默认值。该值仍然可以被 sysctl 覆盖,供比默认值更了解情况的用户使用。 -Contrast that with an illegitimate use: +与不正当使用对比: ```c /* DO NOT DO THIS */ @@ -761,11 +761,11 @@ if (vm_guest == VM_GUEST_VMWARE) { } ``` -Here the driver is branching on a specific hypervisor brand to work around a perceived bug. This is fragile for three reasons. The specific behaviour of VMware may change in a later release; the same issue may apply to KVM or Parallels without the code noticing; and the driver now has a maintenance burden tied to a third-party product. A better approach is to address the root cause (the coalescing code is fragile, so either fix it or expose a sysctl), not the symptom (VMware happens to trigger it). +这里驱动程序基于特定虚拟机监控程序品牌分支以解决一个感知到的 bug。这很脆弱,原因有三。VMware 的特定行为可能在后续版本中改变;相同的问题可能也适用于 KVM 或 Parallels 而代码没有注意到;驱动程序现在承担了与第三方产品绑定的维护负担。更好的方法是解决根本原因(合并代码很脆弱,所以要么修复它要么暴露一个 sysctl),而不是解决症状(VMware 恰好触发了它)。 -### The Sysctl Path +### Sysctl 路径 -For user-space tools and scripts, the `kern.vm_guest` sysctl is a better interface than poking at `/dev/mem` or similar. A small shell script can decide whether to run certain tests based on the environment: +对于用户空间工具和脚本,`kern.vm_guest` sysctl 是比探查 `/dev/mem` 或类似方式更好的接口。一个小型 shell 脚本可以根据环境决定是否运行某些测试: ```sh if [ "$(sysctl -n kern.vm_guest)" = "none" ]; then @@ -776,142 +776,142 @@ else fi ``` -This is how the FreeBSD test suite decides which tests to run in which environment. Reusing the same variable from inside a driver keeps the whole system consistent. +这就是 FreeBSD 测试套件决定在哪个环境中运行哪些测试的方式。从驱动程序内部重用相同的变量保持整个系统的一致性。 -### Interaction with Subsystems +### 与子系统的交互 -A few FreeBSD subsystems adapt their behaviour based on `vm_guest` automatically, and a driver author should be aware of the adaptations without having to touch them. +一些 FreeBSD 子系统基于 `vm_guest` 自动调整其行为,驱动程序作者应该意识到这些调整而不需要触碰它们。 -The timecounter selection code in `/usr/src/sys/kern/kern_tc.c` considers `vm_guest` when picking a default timecounter, because some hypervisors' TSC implementations are unreliable across guest migrations. The driver does not need to care; the kernel simply picks a safer timecounter. +`/usr/src/sys/kern/kern_tc.c` 中的时间计数器选择代码在选择默认时间计数器时考虑 `vm_guest`,因为一些虚拟机监控程序的 TSC 实现在客户机迁移之间不可靠。驱动程序不需要关心;内核只是选择一个更安全的时间计数器。 -The VirtIO transport drivers (`virtio_pci.c` and `virtio_mmio.c`) do not branch on `vm_guest` directly, because they are already guests by their own probe path. They trust that if they have a device at all, they are running in an environment that emulates VirtIO. +VirtIO 传输驱动程序(`virtio_pci.c` 和 `virtio_mmio.c`)不直接基于 `vm_guest` 分支,因为它们通过自己的探测路径已经是客户机了。它们相信如果它们有设备,就是运行在模拟 VirtIO 的环境中。 -Some network driver code handles the case where GRO (generic receive offload) is known to interact badly with certain hypervisor configurations. These adaptations are not driver-by-driver decisions; they are made in the network stack based on observed characteristics. +一些网络驱动程序代码处理 GRO(通用接收卸载)已知与某些虚拟机监控程序配置交互不良的情况。这些适应不是逐驱动程序的决策;它们是基于观察到的特征在网络栈中做出的。 -As an author of a single driver, your rule of thumb is: if you feel the urge to branch on `vm_guest`, ask yourself whether the issue belongs to the kernel's environment handling rather than to your driver. Usually it does. +作为单个驱动程序的作者,你的经验法则是:如果你感到需要基于 `vm_guest` 分支,问问自己这个问题是否属于内核的环境处理而不是你的驱动程序。通常是的。 -### Detecting Within a VirtIO Driver +### 在 VirtIO 驱动程序中检测 -A VirtIO driver, by definition, is running inside some kind of environment that speaks VirtIO. The driver does not usually need to know which specific hypervisor is backing the VirtIO device. That is one of VirtIO's virtues: it is environment-agnostic. The same `virtio_net` driver works under `bhyve`, under QEMU/KVM, under Google Cloud's backend, and under AWS Nitro, because all of them implement the same standard. +VirtIO 驱动程序,根据定义,运行在某种支持 VirtIO 的环境中。驱动程序通常不需要知道是哪个特定虚拟机监控程序在支持 VirtIO 设备。这是 VirtIO 的优点之一:它是环境无关的。相同的 `virtio_net` 驱动程序在 `bhyve`、QEMU/KVM、Google Cloud 的后端和 AWS Nitro 下都能工作,因为它们都实现了相同的标准。 -There are two exceptions. One is when the driver hits a performance cliff that is hypervisor-specific, in which case `vm_guest` tells you which workaround to apply. The other is when the driver wants to print a diagnostic message that identifies the hypervisor by name. Both are rare. +有两个例外。一个是当驱动程序遇到特定于虚拟机监控程序的性能悬崖时,在这种情况下 `vm_guest` 告诉你应用哪种变通方案。另一个是当驱动程序想要打印一条标识虚拟机监控程序名称的诊断消息时。两者都很罕见。 -### Detecting From the Host Side +### 从主机侧检测 -A host-side driver (one that runs in the host, not in a guest) usually does not care about `vm_guest` at all, because the host is not virtualised by definition. The sysctl will return `none` on bare metal, and that is the expected case. +主机侧驱动程序(运行在主机而非客户机中的驱动程序)通常完全不关心 `vm_guest`,因为根据定义主机没有虚拟化。sysctl 在裸金属上将返回 `none`,这是预期的情况。 -The one subtlety is when the host is itself a guest, as in nested virtualisation scenarios. A FreeBSD host inside a VMware ESXi VM, for example, will have `vm_guest = VM_GUEST_VMWARE`. A `bhyve(8)` running inside such a host will present guests that also see virtualisation, though they see the `bhyve` presentation rather than the VMware one. The chain of environments can go two or three levels deep in research and test setups. Do not assume a host is bare metal; if your driver has a host-versus-guest split, use the sysctl or the variable to distinguish. +一个微妙之处是当主机本身是客户机时,比如在嵌套虚拟化场景中。例如,VMware ESXi VM 内的 FreeBSD 主机将具有 `vm_guest = VM_GUEST_VMWARE`。在这样主机内运行的 `bhyve(8)` 将呈现也看到虚拟化的客户机,尽管它们看到的是 `bhyve` 的呈现而非 VMware 的。环境链在研究和测试设置中可以深入两到三层。不要假设主机是裸金属;如果你的驱动程序有主机与客户机的区分,使用 sysctl 或变量来区分。 ### 总结 -`vm_guest` is a small, quiet API that tells your driver, and user-space tools, about the environment. It is easy to use and easy to misuse. Use it to adapt sensible defaults, not to work around hypervisor-specific bugs. Use it to inform user-space decisions through the sysctl. Do not make your driver's behaviour depend on the exact hypervisor brand; doing so couples your code to a third-party product's version history, and that is a maintenance tax you do not want to pay. +`vm_guest` 是一个小型、安静的 API,告诉你的驱动程序和用户空间工具关于环境的信息。它容易使用也容易误用。用它来调整合理的默认值,而不是解决特定虚拟机监控程序的 bug。用它通过 sysctl 来告知用户空间决策。不要让你的驱动程序行为依赖于确切的虚拟机监控程序品牌;这样做会将你的代码与第三方产品的版本历史耦合,那是你不想付出的维护税。 -Section 5 looks at the other side of virtualisation for FreeBSD: the host that runs the guests, and the tools and interfaces that a driver author should understand when running or cooperating with `bhyve(8)`. +第5节审视 FreeBSD 虚拟化的另一面:运行客户机的主机,以及驱动程序作者在运行或配合 `bhyve(8)` 时应该理解的工具和接口。 ## 第5节:bhyve、PCI 直通与主机端考量 -So far we have focused on what happens inside the guest. The guest is where most of the learning happens, because the guest is where most of the driver code lives. But FreeBSD has another role in the virtualisation story: it is also a hypervisor. `bhyve(8)` runs virtual machines, and understanding how `bhyve(8)` presents devices to its guests is useful both when you are the guest author (so you know what the host is doing) and when you are the host author (so you know how to share a real device with a guest). +到目前为止我们关注的是客户机内部发生的事情。客户机是大部分学习发生的地方,因为客户机是大部分驱动程序代码所在的地方。但 FreeBSD 在虚拟化故事中还有另一个角色:它也是一个虚拟机监控程序。`bhyve(8)` 运行虚拟机,理解 `bhyve(8)` 如何向其客户机呈现设备是有用的,无论你是客户机作者(这样你知道主机在做什么)还是主机作者(这样你知道如何与客户机共享真实设备)。 -This section steps onto the host side. We will not go deep enough to write hypervisor code, because that is a topic of its own. We will go deep enough for you to understand what the host is doing, what the host-side knobs are, and what a driver author needs to know when cooperating with `bhyve(8)`. +本节踏上主机侧。我们不会深入到编写虚拟机监控程序代码的程度,因为那是自己的主题。我们会深入到足以让你理解主机在做什么、主机侧有哪些旋钮,以及驱动程序作者在配合 `bhyve(8)` 时需要知道什么。 -### bhyve From the Driver Author's Perspective +### 从驱动程序作者角度看 bhyve -`bhyve(8)` is a type-2 hypervisor that runs on a FreeBSD host and uses hardware virtualisation extensions (Intel VT-x or AMD-V) to execute guest code directly on the CPU. It is implemented as a user-space program (`/usr/sbin/bhyve`) and a kernel module (`vmm.ko`). The kernel module handles the low-level virtualisation primitives: VM entry and exit, page table management for guest memory, virtual APIC emulation, and a handful of performance-critical device backends. The user-space program handles the rest: command-line parsing, emulated device backends that do not need to live in the kernel, VirtIO backends, and the main VCPU loop. +`bhyve(8)` 是一个运行在 FreeBSD 主机上的二类虚拟机监控程序,使用硬件虚拟化扩展(Intel VT-x 或 AMD-V)直接在 CPU 上执行客户机代码。它实现为一个用户空间程序(`/usr/sbin/bhyve`)和一个内核模块(`vmm.ko`)。内核模块处理低级虚拟化原语:VM 进入和退出、客户机内存的页表管理、虚拟 APIC 模拟和少量性能关键的设备后端。用户空间程序处理其余部分:命令行解析、不需要驻留在内核中的模拟设备后端、VirtIO 后端和主 VCPU 循环。 -From a driver author's perspective, three things matter about `bhyve(8)`. +从驱动程序作者的角度来看,关于 `bhyve(8)` 有三件事很重要。 -First, `bhyve(8)` is a FreeBSD program, so the same kernel that runs your driver might also be running `bhyve(8)` in user space. That means host-side resources (memory, CPU, network interfaces) can be competing with `bhyve(8)` for allocation. If your driver is running on a host that is also a hypervisor, you may want to think about NUMA placement, IRQ affinity, and similar concerns. +首先,`bhyve(8)` 是一个 FreeBSD 程序,所以运行你的驱动程序的同一内核可能也在用户空间运行 `bhyve(8)`。这意味着主机侧资源(内存、CPU、网络接口)可能与 `bhyve(8)` 竞争分配。如果你的驱动程序运行在同时是虚拟机监控程序的主机上,你可能需要考虑 NUMA 放置、IRQ 亲和性等类似问题。 -Second, `bhyve(8)` uses a FreeBSD kernel interface called `vmm(4)` for its low-level needs. This interface is stable but niche; most driver authors never touch it directly. If you are writing a driver that needs to interact with virtual machines (for example, a driver that provides a paravirtual device to `bhyve(8)` guests from the host side), you would use `vmm(4)` or one of the higher-level libraries that wraps it. +其次,`bhyve(8)` 使用一个名为 `vmm(4)` 的 FreeBSD 内核接口来满足其低级需求。该接口稳定但小众;大多数驱动程序作者从不直接触碰它。如果你正在编写需要与虚拟机交互的驱动程序(例如,从主机侧向 `bhyve(8)` 客户机提供半虚拟化设备的驱动程序),你将使用 `vmm(4)` 或封装它的更高级库之一。 -Third, and most importantly for this chapter, `bhyve(8)` can assign a real PCI device directly to a guest. This is called PCI passthrough, and it has important implications for driver authors on both sides of the fence. +第三,也是本章最重要的,`bhyve(8)` 可以将真实 PCI 设备直接分配给客户机。这称为 PCI 直通,它对两边的驱动程序作者都有重要影响。 -### vmm(4): The Kernel Side of bhyve +### vmm(4):bhyve 的内核侧 -`vmm(4)` is a kernel module that exposes an interface for creating and managing virtual machines. It lives at `/usr/src/sys/amd64/vmm/` and related directories. The module is loaded on demand by `bhyvectl(8)` or `bhyve(8)`, and it exports a character device interface through `/dev/vmm/NAME` where `NAME` is the name of the virtual machine. +`vmm(4)` 是一个暴露创建和管理虚拟机接口的内核模块。它位于 `/usr/src/sys/amd64/vmm/` 及相关目录。该模块由 `bhyvectl(8)` 或 `bhyve(8)` 按需加载,并通过 `/dev/vmm/NAME` 导出字符设备接口,其中 `NAME` 是虚拟机的名称。 -The `vmm(4)` interface is not something a beginner driver author needs to learn in depth. It is complex, specialised, and mostly of interest to people who are extending or modifying the hypervisor itself. For our purposes, it is enough to know the following. `vmm(4)` manages the virtual CPU state, including registers, page tables, and interrupt controllers. It hands off emulation of devices that are not performance-critical to user space, via a ring buffer interface. For devices that are performance-critical, such as the in-kernel virtual APIC or the virtual IOAPIC, it handles emulation in the kernel itself. +`vmm(4)` 接口不是初学驱动程序作者需要深入学习的。它复杂、专门化,主要对正在扩展或修改虚拟机监控程序本身的人感兴趣。就我们的目的而言,了解以下内容就足够了。`vmm(4)` 管理虚拟 CPU 状态,包括寄存器、页表和中断控制器。它通过环形缓冲区接口将非性能关键设备的模拟交给用户空间。对于性能关键的设备,如内核内的虚拟 APIC 或虚拟 IOAPIC,它在内核本身中处理模拟。 -A driver author who is running inside a `bhyve(4)` guest will never interact with `vmm(4)` directly. The guest kernel sees only the virtualised devices; the mechanism by which they are emulated is invisible. The only observable trace is in `sysctl kern.vm_guest`, which will report `bhyve`. +在 `bhyve(4)` 客户机内运行的驱动程序作者永远不会直接与 `vmm(4)` 交互。客户机内核只看到虚拟化的设备;模拟它们的机制是不可见的。唯一可观察到的痕迹在 `sysctl kern.vm_guest` 中,它将报告 `bhyve`。 -A driver author who is writing host-side code for `bhyve(8)` will see `vmm(4)` only through the user-space libraries. Most tasks are handled by `libvmmapi(3)`, which wraps the raw ioctl interface. Direct `vmm(4)` work is rare outside of `bhyve(8)` development itself. +为 `bhyve(8)` 编写主机侧代码的驱动程序作者只通过用户空间库看到 `vmm(4)`。大多数任务由 `libvmmapi(3)` 处理,它封装了原始 ioctl 接口。直接的 `vmm(4)` 工作在 `bhyve(8)` 开发本身之外很少见。 -### PCI Passthrough: Giving a Guest a Real Device +### PCI 直通:将真实设备交给客户机 -The most direct way for a guest to interact with a physical device is for the host to give the guest exclusive access to that device. This is called PCI passthrough, and `bhyve(8)` supports it through the `pci_passthru(4)` facility. +客户机与物理设备交互最直接的方式是主机将设备的独占访问权交给客户机。这称为 PCI 直通,`bhyve(8)` 通过 `pci_passthru(4)` 设施支持它。 -The idea is straightforward, but the mechanics are subtle. A real PCI device is normally claimed by a driver on the host. That driver programs the device, handles its interrupts, and owns its memory-mapped registers. When we do passthrough, we want the guest's driver to do all of that instead. The host must step out of the way, and the hardware must be reconfigured so that the guest's memory addresses map to the device's memory correctly and so that the device's DMA operations go to the guest's memory rather than the host's. +想法很简单,但机制很微妙。真实 PCI 设备通常由主机上的驱动程序声明。该驱动程序编程设备、处理其中断并拥有其内存映射寄存器。当我们做直通时,我们希望客户机的驱动程序代替它做所有这些。主机必须让路,硬件必须被重新配置,使客户机的内存地址正确映射到设备的内存,使设备的 DMA 操作转到客户机的内存而不是主机的内存。 -The host steps out of the way by detaching the driver that was attached to the device and attaching a placeholder driver (`ppt(4)`) instead. `ppt` is a minimal driver whose only purpose is to claim the device so that no one else does. Its probe function matches any PCI device whose address matches a pattern specified by the user in `/boot/loader.conf`, typically using the `pptdevs` tunable. Once the placeholder driver claims the device, `bhyve(8)` can request a passthrough through the `vmm(4)` interface, and the device becomes accessible inside the guest. +主机让路的方式是分离已附加到设备的驱动程序,改为附加一个占位驱动程序(`ppt(4)`)。`ppt` 是一个最小的驱动程序,其唯一目的是声明设备以免其他人声明。其探测函数匹配任何 PCI 地址与用户在 `/boot/loader.conf` 中指定的模式匹配的设备,通常使用 `pptdevs` 可调参数。一旦占位驱动程序声明了设备,`bhyve(8)` 就可以通过 `vmm(4)` 接口请求直通,设备就可在客户机内部访问。 -The hardware reconfiguration is handled by the IOMMU. This is the part that makes passthrough both capable and dangerous. Without an IOMMU, DMA from the device would go to physical addresses on the host's memory bus, and a misbehaving guest could program the device to read or write anywhere in host memory. That is obviously unsafe. An IOMMU (Intel VT-d or AMD-Vi on the platforms FreeBSD supports) sits between the device and the host memory bus, remapping device-issued addresses so that they cannot escape the guest. From the device's perspective, it still does DMA to an address; from the host memory bus's perspective, that address is translated to somewhere inside the guest's memory and nowhere else. +硬件重新配置由 IOMMU 处理。这是使直通既强大又危险的部分。没有 IOMMU,设备的 DMA 将转到主机内存总线上的物理地址,行为不端的客户机可以编程设备来读取或写入主机内存中的任何位置。这显然是不安全的。IOMMU(FreeBSD 支持的平台上的 Intel VT-d 或 AMD-Vi)位于设备和主机内存总线之间,重新映射设备发出的地址,使它们无法逃离客户机。从设备的角度看,它仍然 DMA 到一个地址;从主机内存总线的角度看,该地址被转换到客户机内存中的某处,而不是其他任何地方。 -If your host has no IOMMU, `bhyve(8)` will refuse to set up passthrough. This is an intentional safety check. Enabling passthrough without IOMMU protection would be like handing a stranger a signed blank cheque on the host kernel: one bug in the device firmware or one malicious guest, and the host is compromised. +如果你的主机没有 IOMMU,`bhyve(8)` 将拒绝设置直通。这是一个有意为之的安全检查。在没有 IOMMU 保护的情况下启用直通就像给陌生人一张签好名的主机内核空白支票:设备固件中的一个 bug 或一个恶意客户机,主机就被入侵了。 -### How Passthrough Looks to the Guest Driver +### 直通在客户驱动程序眼中的样子 -From the guest's perspective, a PCI passthrough device looks exactly like the real hardware. The guest's PCI enumeration finds the device, with its real vendor and device IDs, its real capabilities, and its real BARs. The guest's driver attaches just as it would on bare metal. The read and write operations hit the real hardware (with some address translation in between). Interrupts are delivered to the guest through the hypervisor's virtual interrupt controller. DMA works, though the addresses the guest programs into the device are guest-physical addresses, not host-physical addresses, with the IOMMU taking care of the translation. +从客户机的角度看,PCI 直通设备看起来与真实硬件完全一样。客户机的 PCI 枚举找到设备,具有真实的厂商和设备 ID、真实的能力和真实的 BAR。客户机的驱动程序像在裸金属上一样附加。读写操作命中真实硬件(中间有一些地址转换)。中断通过虚拟机监控程序的虚拟中断控制器投递到客户机。DMA 正常工作,尽管客户机编程到设备中的地址是客户机物理地址,不是主机物理地址,IOMMU 负责转换。 -This has three practical consequences for a driver author. +这对驱动程序作者有三个实际后果。 -First, your driver does not need to know it is running under passthrough. The same driver binary works on bare metal and in a passthrough guest. This is a major design goal of the whole scheme. +首先,你的驱动程序不需要知道它在直通下运行。相同的驱动程序二进制文件在裸金属和直通客户机中都能工作。这是整个方案的一个主要设计目标。 -Second, if your driver uses DMA, make sure you are using `bus_dma(9)` properly. The bus-DMA framework handles the guest-physical versus host-physical translation transparently if you use it correctly. If you are doing clever things with physical addresses directly (which you should not be), passthrough will break those things. +其次,如果你的驱动程序使用 DMA,确保你正确使用了 `bus_dma(9)`。如果你正确使用,总线 DMA 框架透明地处理客户机物理地址与主机物理地址的转换。如果你直接对物理地址做了巧妙的事情(你不应该这样做),直通将破坏这些事情。 -Third, if your driver relies on platform-specific features (for example, special firmware on the PCI device itself, or a particular BIOS table), those features must be present in the guest too. Passthrough gives the guest the device, but it does not give it the firmware or the BIOS tables. Some passthrough setups fail because the driver assumes the presence of an ACPI table that exists on the host but not inside the guest's virtual BIOS. +第三,如果你的驱动程序依赖于平台特定的特性(例如,PCI 设备本身的特殊固件或特定的 BIOS 表),这些特性在客户机中也必须存在。直通给了客户机设备,但没有给它固件或 BIOS 表。一些直通设置失败是因为驱动程序假设存在一个只在主机上存在而不在客户机虚拟 BIOS 中的 ACPI 表。 -The last point matters especially for devices that expect strict ordering or uncached memory access. The bus-DMA and bus-space interfaces, used correctly, handle these cases. Direct pointer manipulation to mapped memory usually does not survive passthrough. +最后一点对于期望严格排序或非缓存内存访问的设备尤其重要。如果正确使用总线 DMA 和总线空间接口,它们能处理这些情况。直接指针操作映射内存在直通下通常不能存活。 -### Host-Side Driver Attach Under bhyve +### bhyve 下的主机侧驱动程序附加 -When `bhyve(8)` is running on a FreeBSD host, two categories of device exist. Some devices are claimed by host drivers and shared with guests through emulation or VirtIO. Others are claimed by `ppt(4)` and passed through entirely. +当 `bhyve(8)` 在 FreeBSD 主机上运行时,存在两类设备。一些设备由主机驱动程序声明并通过模拟或 VirtIO 与客户机共享。其他设备由 `ppt(4)` 声明并完全直通。 -If you are writing a driver for a device that might be used under passthrough, there are a few things to consider. +如果你正在编写一个可能用于直通的设备驱动程序,有几件事需要考虑。 -The first is whether the device should even allow passthrough. Some devices are fundamental to the host's operation (for example, the SATA controller that the host boots from, or the network interface the host is reachable on). These devices should not be marked as candidates for passthrough, because taking them away from the host would break the host. The mechanism for marking candidates is administrative, through `pptdevs` in `loader.conf`, and the host administrator is responsible. There is no per-driver lockout, but a driver author can document clearly whether passthrough is recommended for the device. +首先是设备是否应该允许直通。一些设备对主机的运行是基础性的(例如,主机启动的 SATA 控制器或主机可达的网络接口)。这些设备不应该被标记为直通候选,因为从主机拿走它们会破坏主机。标记候选的机制是管理性的,通过 `loader.conf` 中的 `pptdevs`,主机管理员负责。没有逐驱动程序的锁定,但驱动程序作者可以清楚地记录是否推荐该设备的直通。 -The second is whether the driver releases the device cleanly at detach time. Passthrough requires the original driver to detach, and then `ppt(4)` to attach. If your driver's `DEVICE_DETACH` method is sloppy, passthrough setup will be unstable. The detach code must stop the hardware cleanly, release IRQs, unmap resources, and free any memory that the hardware might touch. Anything that persists after detach is a risk. +其次是驱动程序在分离时是否干净地释放设备。直通要求原始驱动程序分离,然后 `ppt(4)` 附加。如果你的驱动程序的 `DEVICE_DETACH` 方法草率,直通设置将不稳定。分离代码必须干净地停止硬件、释放 IRQ、取消映射资源并释放硬件可能接触的任何内存。分离后仍然存在的任何东西都是风险。 -The third is whether the driver tolerates being re-attached after a passthrough use. When the guest shuts down and releases the device, the host administrator might want to rebind the device to the original driver for use on the host. The driver should be able to attach to a device that was previously owned by `ppt(4)`, even though the device may have been reset and reconfigured by the guest. This means the driver's `DEVICE_ATTACH` method should not assume anything about the device's initial state; it should program the device from scratch, just as it does on first boot. +第三是驱动程序是否容忍在直通使用后重新附加。当客户机关闭并释放设备时,主机管理员可能希望将设备重新绑定到原始驱动程序以在主机上使用。驱动程序应该能够附加到之前由 `ppt(4)` 拥有的设备,即使设备可能已被客户机重置和重新配置。这意味着驱动程序的 `DEVICE_ATTACH` 方法不应该假设关于设备初始状态的任何事情;它应该从头编程设备,就像首次启动一样。 -None of these are new requirements. They are all things a well-written driver does anyway. Passthrough just makes the habits more important, because the cost of getting them wrong shows up immediately. +这些都不是新的要求。它们都是编写良好的驱动程序本就应该做的事情。直通只是使这些习惯更加重要,因为犯错的成本会立即显现。 -### IOMMU Groups and the Reality of Partial Isolation +### IOMMU 组与部分隔离的现实 -A brief word on IOMMU groups, which come up sometimes in passthrough discussions. An IOMMU cannot always isolate a single device from another device on the same PCI bus. When two devices share a bus or a bridge without ACS (Access Control Services), the IOMMU treats them as a single group, because it cannot guarantee that one cannot see the other's DMA. FreeBSD's `dmar(4)` (Intel) and `amdvi(4)` (AMD) drivers handle this grouping internally, but the administrator sometimes has to pass through a whole group rather than a single device. +简要提及 IOMMU 组,这在直通讨论中有时会出现。IOMMU 不能总是将单个设备与同一 PCI 总线上的另一个设备隔离。当两个设备在没有 ACS(访问控制服务)的总线或桥上共享时,IOMMU 将它们视为单个组,因为它不能保证一个设备看不到另一个设备的 DMA。FreeBSD 的 `dmar(4)`(Intel)和 `amdvi(4)`(AMD)驱动程序在内部处理这种分组,但管理员有时必须直通整个组而不是单个设备。 -For a driver author, the practical implication is that passthrough sometimes grabs more than the device you expected. If your device sits behind a bridge shared with another device, turning on passthrough for your device may pull the other one into the guest too. The solution is usually to place devices on separate bridges in the firmware configuration, but that is an administrator concern, not a driver concern. Knowing it exists helps when diagnosing unexpected behaviour. +对于驱动程序作者来说,实际的影响是直通有时会抓取比你预期更多的设备。如果你的设备位于与另一个设备共享的桥后面,为你的设备启用直通可能会将另一个设备也拉入客户机。解决方案通常是在固件配置中将设备放在单独的桥上,但这是管理员的事,不是驱动程序的事。知道它的存在有助于诊断意外行为。 -### Host-Only Considerations: Memory, CPU, and the Hypervisor +### 仅主机考量:内存、CPU 与虚拟机监控程序 -A FreeBSD host that runs `bhyve(8)` guests has a few extra responsibilities beyond the usual. Memory for the guest's RAM is allocated from the host's physical memory, so a host running many guests needs correspondingly more memory. Guest VCPUs are backed by host threads, so a host running many guests needs to provision CPU capacity. And the hypervisor itself uses a small amount of memory and CPU for its bookkeeping. +运行 `bhyve(8)` 客户机的 FreeBSD 主机除了常规职责外还有一些额外的责任。客户机 RAM 的内存从主机的物理内存分配,因此运行许多客户机的主机需要相应更多的内存。客户机的 VCPU 由主机线程支持,因此运行许多客户机的主机需要配置足够的 CPU 容量。虚拟机监控程序本身也使用少量内存和 CPU 进行簿记。 -A driver author on the host side does not need to manage these resources directly. They are managed by `bhyve(8)` and the host administrator. But there are two ways in which a host-side driver can interact with them. +主机侧的驱动程序作者不需要直接管理这些资源。它们由 `bhyve(8)` 和主机管理员管理。但主机侧驱动程序有两种方式可以与之交互。 -The first is when a driver offers a device backend that `bhyve(8)` consumes. An example would be a storage driver that provides the backing store for a guest's virtual disk. If the host-side driver is slow, the guest feels it as slow disk. If the host-side driver consumes too much memory, the host runs out of memory for guests. This is a classic shared-resource problem, and it is usually solved by provisioning rather than by clever code. +第一种是当驱动程序提供 `bhyve(8)` 消费的设备后端时。例如,一个为客户机虚拟磁盘提供后端存储的存储驱动程序。如果主机侧驱动程序慢,客户机会感觉磁盘慢。如果主机侧驱动程序消耗太多内存,主机会没有足够内存给客户机。这是一个经典的共享资源问题,通常通过合理配置而不是巧妙的代码来解决。 -The second is when a driver interacts with the hypervisor through `vmm(4)` or similar. Paravirtual device backends sometimes use kernel-side hooks to deliver notifications to guests more efficiently than going through user space. These are rare and advanced, and outside the scope of this chapter. They are mentioned here so you are not surprised if you see them referenced later. +第二种是当驱动程序通过 `vmm(4)` 或类似接口与虚拟机监控程序交互时。半虚拟化设备后端有时使用内核侧钩子来比通过用户空间更高效地向客户机传递通知。这些很少见且属于高级主题,超出了本章的范围。这里提及是为了让你在后续看到相关引用时不至于感到意外。 -### Cross-Platform Notes: bhyve on arm64 +### 跨平台说明:arm64 上的 bhyve -`bhyve(8)` runs on amd64 and, increasingly, on arm64. The arm64 port uses the ARMv8 virtualisation extensions (EL2) rather than Intel VT-x or AMD-V. The SMMU (System Memory Management Unit) takes the role of the IOMMU. The user-space interface is the same, the guest's VirtIO experience is the same, and from a driver author's perspective, the two architectures are interchangeable. The distinction matters only for the low-level hypervisor code inside `vmm(4)`. +`bhyve(8)` 在 amd64 上运行,并且越来越多地在 arm64 上运行。arm64 移植使用 ARMv8 虚拟化扩展(EL2)而不是 Intel VT-x 或 AMD-V。SMMU(系统内存管理单元)承担 IOMMU 的角色。用户空间接口相同,客户机的 VirtIO 体验相同,从驱动程序作者的角度看,两个架构是可互换的。区别只对 `vmm(4)` 内部的低级虚拟机监控程序代码有意义。 -For a book about driver authorship, the lesson is the one we have already learned in Chapter 29: write clean, bus-dma-using, endian-correct code, and you will not notice which architecture you are running on. The hypervisor story is another good reason to follow those habits. +对于一本关于驱动程序编写的书来说,教训就是我们在第 29 章已经学到的:编写干净的、使用 bus-dma 的、字节序正确的代码,你就不会注意到自己在哪个架构上运行。虚拟机监控程序的故事是遵循这些习惯的另一个好理由。 -### Inspecting bhyve From the Host +### 从主机侧检查 bhyve -A driver author can inspect `bhyve(8)` state in a few useful ways without getting into `vmm(4)` internals. +驱动程序作者可以通过几种有用的方式检查 `bhyve(8)` 状态,而不需要进入 `vmm(4)` 内部。 -`bhyvectl(8)` is the command-line tool for querying and controlling virtual machines. `bhyvectl --vm=NAME --get-stats` shows counters maintained by `vmm(4)` for a running guest, including VM exit counts, emulation counts, and similar diagnostics. This is useful when you suspect that a guest driver is generating unnecessary VM exits (a common performance pitfall). +`bhyvectl(8)` 是查询和控制虚拟机的命令行工具。`bhyvectl --vm=NAME --get-stats` 显示 `vmm(4)` 为运行中的客户机维护的计数器,包括 VM 退出计数、模拟计数和类似的诊断信息。当你怀疑客户驱动程序正在产生不必要的 VM 退出(一个常见的性能陷阱)时,这很有用。 -`pciconf -lvBb` on the host shows the PCI devices and their current driver bindings. A device bound to `ppt(4)` is visible in passthrough mode; a device bound to its native driver is available to the host. This is a quick way to see what is passed through and what is not. +主机上的 `pciconf -lvBb` 显示 PCI 设备及其当前驱动程序绑定。绑定到 `ppt(4)` 的设备处于直通模式;绑定到其原生驱动程序的设备可供主机使用。这是快速查看哪些设备已直通、哪些未直通的方法。 -`vmstat -i` on the host shows interrupt counts per device. If a device is passed through to a guest, its interrupts are delivered to the guest's virtual interrupt controller, not to the host. On the host side, you will see the hypervisor's posted-interrupt or interrupt-remapping counts increase instead. This is a subtle but useful diagnostic. +主机上的 `vmstat -i` 显示每个设备的中断计数。如果设备被直通给客户机,其中断会传递给客户机的虚拟中断控制器,而不是主机。在主机侧,你会看到虚拟机监控程序的通知中断或中断重映射计数增加。这是一个微妙但有用的诊断手段。 -None of this is required reading for driver authorship. It is mentioned here so that when you encounter `bhyve(8)` on a host while debugging a driver, you know where to look first. +这些都不是驱动程序编写的必读内容。这里提及是为了当你在主机上调试驱动程序时遇到 `bhyve(8)`,知道首先该去哪里查看。 -### A Typical bhyve Command Line +### 典型的 bhyve 命令行 -For readers who want to see what `bhyve(8)` actually looks like when invoked without a wrapper tool, here is a representative command line. It starts a guest named `guest0` with two VCPUs, two gigabytes of memory, a virtio-blk disk backed by a file, and a virtio-net network interface bridged to the host: +对于想了解 `bhyve(8)` 在不使用封装工具时实际样子的读者,这里有一个代表性的命令行。它启动一个名为 `guest0` 的客户机,配备两个 VCPU、2 GB 内存、一个由文件支持的 virtio-blk 磁盘和一个桥接到主机的 virtio-net 网络接口: ```sh bhyve -c 2 -m 2G \ @@ -923,90 +923,90 @@ bhyve -c 2 -m 2G \ guest0 ``` -Each `-s` flag defines a PCI slot. Slot zero is the host bridge; slot two is a virtio-blk device backed by a disk image file; slot three is a virtio-net device backed by a `tap(4)` interface the host has configured; slot thirty-one is the LPC bridge used for legacy devices like the serial console. The `-l com1,stdio` redirects the guest's first serial port to the host's standard I/O, which is convenient for console access. +每个 `-s` 标志定义一个 PCI 插槽。插槽零是主桥;插槽二是由磁盘映像文件支持的 virtio-blk 设备;插槽三是由主机配置的 `tap(4)` 接口支持的 virtio-net 设备;插槽三十一是用于串行控制台等传统设备的 LPC 桥。`-l com1,stdio` 将客户机的第一个串口重定向到主机的标准 I/O,这对于控制台访问很方便。 -When this command runs, the host kernel creates a new VM through `vmm(4)`, allocates memory for the guest's RAM, and hands off VCPU execution to the guest's kernel. The virtio-blk backend in `bhyve(8)` (user-space code) services the guest's block requests by reading and writing the disk image file. The virtio-net backend sends and receives packets through the `tap0` interface, which the host's network stack handles as an ordinary interface. +当此命令运行时,主机内核通过 `vmm(4)` 创建一个新的 VM,为客户机的 RAM 分配内存,并将 VCPU 执行移交给客户机内核。`bhyve(8)` 中的 virtio-blk 后端(用户空间代码)通过读写磁盘映像文件来服务客户机的块请求。virtio-net 后端通过 `tap0` 接口发送和接收数据包,主机的网络协议栈将其作为普通接口处理。 -A driver running inside this guest sees a PCI virtio-blk device, a PCI virtio-net device, and the usual assortment of emulated LPC devices. From the driver's perspective, there is no clue that the "hardware" is implemented by a user-space program running a few milliseconds away on the same host. The abstraction is, by design, complete. +在此客户机内运行的驱动程序看到一个 PCI virtio-blk 设备、一个 PCI virtio-net 设备和通常的一组模拟 LPC 设备。从驱动程序的角度看,没有任何线索表明"硬件"是由运行在同一主机上几毫秒之外的用户空间程序实现的。这种抽象在设计上是完整的。 -### Inside the vmm(4) Module +### vmm(4) 模块内部 -`vmm(4)` is the kernel-side infrastructure for `bhyve(8)`. In FreeBSD 14.3, its main source files live in `/usr/src/sys/amd64/vmm/`; an arm64 port is under active development and is expected to ship in a later release, so if you are on FreeBSD 14.3 the amd64 tree is the one to read. The module exports a small control interface through `/dev/vmmctl` and a per-VM interface through `/dev/vmm/NAME`. +`vmm(4)` 是 `bhyve(8)` 的内核侧基础设施。在 FreeBSD 14.3 中,其主要源文件位于 `/usr/src/sys/amd64/vmm/`;arm64 移植正在积极开发中,预计在后续版本中发布,所以如果你使用 FreeBSD 14.3,amd64 代码树就是你应该阅读的。该模块通过 `/dev/vmmctl` 导出一个小的控制接口,通过 `/dev/vmm/NAME` 导出每个 VM 的接口。 -The control interface is used by `bhyvectl(8)` and `bhyve(8)` to create, destroy, and enumerate virtual machines. The per-VM interface is used to read and write VCPU state, map guest memory, inject interrupts, and receive VM-exit events from the guest. +控制接口被 `bhyvectl(8)` 和 `bhyve(8)` 用于创建、销毁和枚举虚拟机。每个 VM 的接口用于读写 VCPU 状态、映射客户机内存、注入中断以及从客户机接收 VM 退出事件。 -When a guest's VCPU executes code that requires emulation (reading from an I/O port, accessing a memory-mapped device register, executing a hypercall), the hardware traps the execution and the control returns to `vmm(4)`. The module either handles the exit in the kernel (for a small set of performance-critical cases, like reading the local APIC) or forwards it to `bhyve(8)` in user space (for most cases, including all VirtIO device emulation). +当客户机的 VCPU 执行需要模拟的代码(从 I/O 端口读取、访问内存映射设备寄存器、执行超级调用)时,硬件捕获执行并将控制权返回给 `vmm(4)`。该模块要么在内核中处理退出(对于少量性能关键的情况,如读取本地 APIC),要么将其转发给用户空间中的 `bhyve(8)`(对于大多数情况,包括所有 VirtIO 设备模拟)。 -The kernel/user-space split is a deliberate design choice. Keeping the code in user space makes it easier to develop, debug, and audit. Keeping performance-critical paths in the kernel keeps the overhead low. For FreeBSD, the split has worked well, and `bhyve(8)` has grown from a small academic prototype to a production-quality hypervisor. +内核/用户空间的分离是一个刻意的设计选择。将代码保留在用户空间使其更容易开发、调试和审计。将性能关键路径保留在内核中保持了低开销。对于 FreeBSD 来说,这种分离效果良好,`bhyve(8)` 已从一个小型学术原型成长为生产质量的虚拟机监控程序。 -For a driver author who is not extending `bhyve(8)` itself, none of this matters in detail. What matters is the observable behaviour: a guest executes code, some operations trap, the hypervisor emulates them, and the guest continues. The driver in the guest sees consistent behaviour regardless of where the emulation happens. +对于不扩展 `bhyve(8)` 本身的驱动程序作者来说,这些细节无关紧要。重要的是可观察的行为:客户机执行代码,一些操作触发捕获,虚拟机监控程序模拟它们,客户机继续执行。无论模拟在哪里发生,客户机中的驱动程序看到的是一致的行为。 -### Nested Virtualisation +### 嵌套虚拟化 -A brief mention of nested virtualisation, since it comes up. FreeBSD's `bhyve(8)` on amd64 currently does not support running hardware-virtualised guests inside hardware-virtualised guests (no `VIRTUAL_VMX` or `VIRTUAL_SVM` extensions yet). If you try to run `bhyve(8)` inside a `bhyve(8)` guest, the inner hypervisor will fail to initialise. Intel and AMD both support nested virtualisation in hardware, but the FreeBSD implementation has not yet enabled it. +简要提及嵌套虚拟化,因为它会出现。FreeBSD 在 amd64 上的 `bhyve(8)` 目前不支持在硬件虚拟化客户机内运行硬件虚拟化客户机(还没有 `VIRTUAL_VMX` 或 `VIRTUAL_SVM` 扩展)。如果你尝试在 `bhyve(8)` 客户机内运行 `bhyve(8)`,内部虚拟机监控程序将无法初始化。Intel 和 AMD 都在硬件中支持嵌套虚拟化,但 FreeBSD 实现尚未启用它。 -This matters for labs only in the sense that you must run `bhyve(8)` on bare metal (or on a host that provides nested virtualisation, which some cloud platforms do). If your lab machine is itself a VM, you may find that `bhyve(8)` either fails to load `vmm.ko` or loads it but refuses to start guests. +这对实验的影响仅在于你必须在裸金属上运行 `bhyve(8)`(或提供嵌套虚拟化的主机上,一些云平台提供此功能)。如果你的实验机器本身就是一个 VM,你可能会发现 `bhyve(8)` 要么无法加载 `vmm.ko`,要么加载了但拒绝启动客户机。 -On arm64, nested virtualisation is a different story; the ARM architecture has cleaner support, and the FreeBSD arm64 port is moving toward enabling it. For up-to-date information, consult the `bhyve(8)` and `vmm(4)` manual pages on the version of FreeBSD you are running. +在 arm64 上,嵌套虚拟化是另一回事;ARM 架构有更干净的支持,FreeBSD arm64 移植正在朝着启用它的方向发展。获取最新信息,请查阅你运行的 FreeBSD 版本上的 `bhyve(8)` 和 `vmm(4)` 手册页。 -### An Example: Debugging a PCI Passthrough Driver +### 一个示例:调试 PCI 直通驱动程序 -To make the host-side discussion concrete, consider a scenario that combines several of the ideas above. You have a PCI network card that your host's driver knows how to drive. You want to pass it through to a `bhyve(8)` guest and test that the same driver works unchanged in the guest. +为了使主机侧的讨论具体化,考虑一个结合上述几个想法的场景。你有一张主机驱动程序知道如何驱动的 PCI 网卡。你想把它直通给一个 `bhyve(8)` 客户机并测试相同的驱动程序在客户机中无需更改即可工作。 -Step 1: Identify the device. `pciconf -lvBb` shows `em0@pci0:2:0:0` with the driver `em` attached. The device is an Intel Gigabit Ethernet controller. +步骤 1:识别设备。`pciconf -lvBb` 显示 `em0@pci0:2:0:0`,驱动程序 `em` 已附加。该设备是 Intel 千兆以太网控制器。 -Step 2: Mark it for passthrough. Edit `/boot/loader.conf` and add `pptdevs="2/0/0"`. Reboot. +步骤 2:标记为直通。编辑 `/boot/loader.conf` 并添加 `pptdevs="2/0/0"`。重启。 -Step 3: Verify. After reboot, `pciconf -l` shows `ppt0@pci0:2:0:0`, with `ppt` (the placeholder driver) attached instead of `em`. The device is no longer available to the host's network stack. +步骤 3:验证。重启后,`pciconf -l` 显示 `ppt0@pci0:2:0:0`,`ppt`(占位驱动程序)替代 `em` 附加。该设备不再对主机的网络协议栈可用。 -Step 4: Configure the guest. In the guest's `bhyve` configuration, add `-s 4,passthru,2/0/0`. This tells `bhyve(8)` to pass through the device to the guest at PCI slot 4. +步骤 4:配置客户机。在客户机的 `bhyve` 配置中,添加 `-s 4,passthru,2/0/0`。这告诉 `bhyve(8)` 将设备直通给客户机的 PCI 插槽 4。 -Step 5: Start the guest. Inside the guest, run `pciconf -lvBb`. The device appears, with its real Intel vendor and device IDs, attached to `em`. Check `dmesg`. The guest's `em` driver has attached to the passthrough device exactly as it would on bare metal. +步骤 5:启动客户机。在客户机内部,运行 `pciconf -lvBb`。设备出现,带有真实的 Intel 供应商和设备 ID,附加到 `em`。检查 `dmesg`。客户机的 `em` 驱动程序已附加到直通设备,就像在裸金属上一样。 -Step 6: Exercise the device. Configure the interface (`ifconfig em0 10.0.0.1/24 up`), send traffic, verify it works. +步骤 6:操作设备。配置接口(`ifconfig em0 10.0.0.1/24 up`),发送流量,验证其工作正常。 -Step 7: Shut down the guest. Back on the host, decide whether to keep the device in passthrough mode or return it to the host. If you want it back, edit `/boot/loader.conf` to remove `pptdevs`, reboot, and verify that `em` is attached again. +步骤 7:关闭客户机。回到主机,决定是保持设备的直通模式还是将其返回给主机。如果要取回,编辑 `/boot/loader.conf` 移除 `pptdevs`,重启,并验证 `em` 再次附加。 -Every step in this workflow is something the administrator does; the driver itself is untouched. That is the point. If the driver is written correctly (with `bus_dma`, clean detach, no hidden platform assumptions), it works in both environments without changes. +这个工作流程中的每一步都是管理员做的;驱动程序本身未被触及。这就是要点。如果驱动程序编写正确(使用 `bus_dma`、干净的分离、没有隐藏的平台假设),它在两种环境中无需更改即可工作。 ### 总结 -The host side of virtualisation is where FreeBSD plays a slightly different role. Instead of writing a driver that consumes a hypervisor-provided device, you may find yourself writing (or at least interacting with) the infrastructure that provides devices to a hypervisor. `bhyve(8)`, `vmm(4)`, and `pci_passthru(4)` are the main interfaces to know about. PCI passthrough is the most relevant of these for a driver author, because it exercises the detach-and-reattach lifecycle that a well-written driver already supports. +虚拟化的主机侧是 FreeBSD 扮演略有不同角色的地方。你可能发现自己不是在编写消费虚拟机监控程序提供设备的驱动程序,而是在编写(或至少与之交互)向虚拟机监控程序提供设备的基础设施。`bhyve(8)`、`vmm(4)` 和 `pci_passthru(4)` 是需要了解的主要接口。PCI 直通是其中与驱动程序作者最相关的,因为它锻炼了编写良好的驱动程序已经支持的分离和重新附加生命周期。 -With guests and hosts both covered, the next major environment in FreeBSD's virtualisation story is the one that does not use a separate kernel at all: jails. Section 6 turns to them, to devfs, and to the VNET framework that extends the jail model into the network stack. +客户机和主机都已涵盖,FreeBSD 虚拟化故事中的下一个主要环境是完全不使用单独内核的那个:jail。第6节转向它们、devfs,以及将 jail 模型扩展到网络栈的 VNET 框架。 ## 第6节:Jail、devfs、VNET 与设备可见性 -Virtualisation and containerization share a goal: they both let one physical machine host several workloads that appear, to their users, to be running on separate machines. The mechanisms they use are dramatically different. A virtual machine runs a complete guest kernel on top of a hypervisor; it has its own memory map, its own device tree, its own everything. A container, in the FreeBSD sense, shares the host's kernel entirely. What it has of its own is a filesystem view, a process table, and (if the administrator sets it up that way) a network stack. FreeBSD's answer to the container question is the jail, and jails have existed in some form since FreeBSD 4.0. For driver authors, jails matter because they change what a process can see and do with respect to devices, without changing the driver code at all. +虚拟化和容器化共享一个目标:它们都让一台物理机器托管多个工作负载,对用户来说这些工作负载看起来运行在独立的机器上。它们使用的机制截然不同。虚拟机在虚拟机监控程序之上运行完整的客户内核;它有自己的内存映射、自己的设备树、自己的一切。容器,在 FreeBSD 的意义上,完全共享主机的内核。它拥有的是自己的文件系统视图、进程表,以及(如果管理员这样设置的话)网络栈。FreeBSD 对容器问题的回答是 jail,jail 从 FreeBSD 4.0 开始就以某种形式存在。对于驱动程序作者来说,jail 很重要,因为它们改变了进程在设备方面能看到什么和能做什么,而完全不改变驱动程序代码。 -This section explains how jails interact with devices. It focuses on four topics: the jail model itself, the devfs ruleset system that controls device visibility, the VNET framework that gives jails their own network stacks, and the question every container system eventually has to answer: which processes can reach which drivers. +本节解释 jail 如何与设备交互。它关注四个主题:jail 模型本身、控制设备可见性的 devfs 规则集系统、给 jail 自己的网络栈的 VNET 框架,以及每个容器系统最终都必须回答的问题:哪些进程可以访问哪些驱动程序。 -### What a Jail Is, and What It Is Not +### Jail 是什么,不是什么 -A jail is a subdivision of the host kernel's resources. A process running inside a jail sees a subset of the filesystem (rooted at the jail's root directory), a subset of the process table (only processes in the same jail), a subset of the network (depending on whether the jail has its own VNET), and a subset of the devices (depending on the jail's devfs ruleset). The host kernel is a single, shared kernel; there is no separate guest kernel inside the jail. System calls made inside the jail are executed by the same kernel that executes calls from outside the jail, with jail-specific checks inserted at the right places. +jail 是主机内核资源的子划分。在 jail 内运行的进程看到文件系统的一个子集(以 jail 的根目录为根)、进程表的一个子集(只有同一 jail 中的进程)、网络的一个子集(取决于 jail 是否有自己的 VNET)和设备的一个子集(取决于 jail 的 devfs 规则集)。主机内核是单个共享内核;jail 内部没有独立的客户内核。jail 内发出的系统调用由执行 jail 外调用的同一内核执行,在正确的位置插入了 jail 特定的检查。 -Because the kernel is shared, drivers are shared too. There is no separate copy of a driver inside each jail; there is only the one driver that the kernel loaded at boot time. The jail just controls which of the driver's devices are visible to the jail's processes. A jail that has not been configured to see `/dev/null` will see no `/dev/null`; a jail that has been configured to see `/dev/null` will see the same `/dev/null` that the host sees. No new driver instance; no new softc; just a visibility rule. +因为内核是共享的,驱动程序也是共享的。每个 jail 内没有单独的驱动程序副本;只有内核在启动时加载的那个驱动程序。jail 只是控制驱动程序的哪些设备对 jail 的进程可见。一个没有被配置为看到 `/dev/null` 的 jail 将看不到 `/dev/null`;一个被配置为看到 `/dev/null` 的 jail 将看到与主机相同的 `/dev/null`。没有新的驱动程序实例;没有新的 softc;只是一个可见性规则。 -This simplicity is both jails' great strength and their great limitation. It means jails are extremely cheap: starting a jail is roughly the cost of running a few system calls, whereas starting a VM is the cost of booting a whole kernel. It also means jails cannot isolate kernel-level failures: a driver bug that panics the host kernel panics every jail running on it. A jail is a policy boundary, not a crash boundary. For many workloads that trade-off is excellent; for others, a VM is the right answer. +这种简单性既是 jail 的巨大优势也是其巨大局限。这意味着 jail 非常廉价:启动 jail 的成本大约是运行几个系统调用的成本,而启动 VM 是启动整个内核的成本。这也意味着 jail 无法隔离内核级别的故障:一个导致主机内核 panic 的驱动程序 bug 会导致运行在上面的每个 jail 都 panic。jail 是一个策略边界,不是崩溃边界。对于许多工作负载来说,这种权衡是出色的;对于其他工作负载,VM 是正确的答案。 -### The Kernel's View of Jails +### 内核眼中的 Jail -Inside the kernel, a jail is represented by a `struct prison`, defined in `/usr/src/sys/sys/jail.h`. Each process has a pointer to the prison it belongs to, via `td->td_ucred->cr_prison`. Code that wants to check whether a process is inside a jail can compare this pointer against the global `prison0`, which is the root jail (the host itself). If the pointer is `prison0`, the process is on the host; otherwise, it is in some jail. +在内核内部,jail 由 `struct prison` 表示,定义在 `/usr/src/sys/sys/jail.h` 中。每个进程通过 `td->td_ucred->cr_prison` 指向它所属的 prison。想要检查进程是否在 jail 内的代码可以将此指针与全局 `prison0`(根 jail,即主机本身)进行比较。如果指针是 `prison0`,进程在主机上;否则,它在某个 jail 中。 -Several helper functions exist for the common checks a driver might want to do. `jailed(cred)` returns true if the credential belongs to a jail other than `prison0`. `prison_check(cred1, cred2)` returns zero if two credentials are in the same jail (or one is the parent of the other); it returns an error otherwise. `prison_priv_check(cred, priv)` is how privilege checks are extended for jails: a root user inside a jail does not have all privileges that root has on the host, and `prison_priv_check` implements the reduction. +存在几个辅助函数用于驱动程序可能想要做的常见检查。`jailed(cred)` 如果凭证属于 `prison0` 以外的 jail 则返回 true。`prison_check(cred1, cred2)` 如果两个凭证在同一个 jail 中(或一个是另一个的父级)则返回零;否则返回错误。`prison_priv_check(cred, priv)` 是权限检查如何为 jail 扩展的:jail 内的 root 用户不具有主机上 root 拥有的所有权限,`prison_priv_check` 实现了这种缩减。 -A driver author will usually not need to call any of these directly. The framework calls them on your behalf. When a process opens a `devfs` node, for example, the devfs layer consults the jail's devfs ruleset before handing the file descriptor over. When a process tries to use a privilege-gated feature (like `bpf(4)` or `kldload(2)`), the privilege check goes through `prison_priv_check`. A driver only needs to be aware that these checks exist, and to call the framework helpers correctly when it defines its own access rules. +驱动程序作者通常不需要直接调用其中任何一个。框架代表你调用它们。例如,当进程打开 `devfs` 节点时,devfs 层在交出文件描述符之前查询 jail 的 devfs 规则集。当进程尝试使用权限门控的特性(如 `bpf(4)` 或 `kldload(2)`)时,权限检查通过 `prison_priv_check` 进行。驱动程序只需要意识到这些检查存在,并在定义自己的访问规则时正确调用框架辅助函数。 -### devfs: The Filesystem Through Which Devices Are Exposed +### devfs:暴露设备的文件系统 -In FreeBSD, devices are exposed through a filesystem called `devfs(5)`. Every entry under `/dev` is a `devfs` node. A driver that calls `make_dev(9)` or `make_dev_s(9)` creates a `devfs` node; the name, permissions, and uid/gid are attributes of that node. The node is visible in every `devfs` instance that the kernel mounts, and FreeBSD mounts one `devfs` instance per filesystem view: one for the host's `/dev`, one for each jail's `/dev` (if the jail has its own `/dev`), and one per chroot that mounts its own `devfs`. +在 FreeBSD 中,设备通过一个名为 `devfs(5)` 的文件系统暴露。`/dev` 下的每个条目都是一个 `devfs` 节点。调用 `make_dev(9)` 或 `make_dev_s(9)` 的驱动程序创建一个 `devfs` 节点;名称、权限和 uid/gid 是该节点的属性。该节点在内核挂载的每个 `devfs` 实例中都可见,FreeBSD 为每个文件系统视图挂载一个 `devfs` 实例:一个用于主机的 `/dev`,每个 jail 的 `/dev` 一个(如果 jail 有自己的 `/dev`),每个挂载自己 `devfs` 的 chroot 一个。 -This is the first part of the visibility story. Each jail (more precisely, each filesystem view) has its own `devfs` mount, and the kernel can apply different rules to different mounts. The rules are called devfs rulesets, and they are the main tool for controlling which devices a jail can see. +这是可见性故事的第一部分。每个 jail(更准确地说,每个文件系统视图)都有自己的 `devfs` 挂载,内核可以对不同的挂载应用不同的规则。这些规则称为 devfs 规则集,它们是控制 jail 可以看到哪些设备的主要工具。 -### devfs Rulesets: Declaring What a Jail Can See +### devfs 规则集:声明监狱可以看到什么 -A devfs ruleset is a numbered set of rules stored in the kernel. Rules can hide nodes, reveal nodes, change their permissions, or change their ownership. The ruleset is applied to a mounted `devfs` instance; every time a lookup happens in that instance, the kernel walks the ruleset and applies the matching rule to each node. +devfs 规则集是存储在内核中的编号规则集合。规则可以隐藏节点、显示节点、更改其权限或更改其所有权。规则集应用于已挂载的 `devfs` 实例;每次在该实例中进行查找时,内核遍历规则集并对每个节点应用匹配的规则。 -On a fresh FreeBSD system, four rulesets are predefined in `/etc/defaults/devfs.rules` (which is processed when the kernel starts). The file uses `devfs(8)` syntax, a small declarative language for ruleset construction. Let us look at a representative slice. +在新的 FreeBSD 系统上,`/etc/defaults/devfs.rules` 中预定义了四个规则集(在内核启动时处理)。该文件使用 `devfs(8)` 语法,一种用于规则集构建的小型声明式语言。让我们看看一个代表性的片段。 ```text [devfsrules_hide_all=1] @@ -1034,21 +1034,21 @@ add path zfs unhide add path 'bpf*' unhide ``` -Rule 1, `devfsrules_hide_all`, hides everything. On its own it is useless, because a `devfs` mount with nothing visible is not helpful. It is the starting point for other rulesets. +规则 1 `devfsrules_hide_all` 隐藏一切。它本身是无用的,因为一个什么都看不见的 `devfs` 挂载没有帮助。它是其他规则集的起点。 -Rule 2, `devfsrules_unhide_basic`, unhides a small set of essential devices: `log`, `null`, `zero`, `crypto`, `random`, `urandom`. These are the devices that essentially every program needs; without them, even basic tools fail. +规则 2 `devfsrules_unhide_basic` 显示一小组基本设备:`log`、`null`、`zero`、`crypto`、`random`、`urandom`。这些是几乎所有程序都需要的设备;没有它们,即使是基本工具也会失败。 -Rule 4, `devfsrules_jail`, is the ruleset intended for non-VNET jails. It starts by including `devfsrules_hide_all` (so everything is hidden), then layers `devfsrules_unhide_basic` on top (so the essentials are visible), and adds ZFS devices. The result is a jail that sees a small, safe set of devices and nothing else. +规则 4 `devfsrules_jail` 是为非 VNET jail 设计的规则集。它首先包含 `devfsrules_hide_all`(所以一切都被隐藏),然后在上面叠加 `devfsrules_unhide_basic`(所以基本设备可见),并添加 ZFS 设备。结果是一个 jail 只看到一小组安全的设备,其他什么都看不到。 -Rule 5, `devfsrules_jail_vnet`, is the equivalent for VNET jails. It is the same as rule 4 with the addition that `bpf*` devices are unhidden, because a VNET jail might legitimately need `bpf(4)` (for tools like `tcpdump(8)` or `dhclient(8)`). +规则 5 `devfsrules_jail_vnet` 是 VNET jail 的等效规则集。它与规则 4 相同,只是增加了 `bpf*` 设备的显示,因为 VNET jail 可能合理地需要 `bpf(4)`(用于 `tcpdump(8)` 或 `dhclient(8)` 等工具)。 -When creating a jail, the administrator specifies which ruleset to apply to the jail's `/dev` mount, either through `jail.conf(5)` (`devfs_ruleset = 4`) or on the command line (`jail -c ... devfs_ruleset=4`). The kernel applies the ruleset to the mount, and the jail sees only what the ruleset allows. +创建 jail 时,管理员指定将哪个规则集应用于 jail 的 `/dev` 挂载,可以通过 `jail.conf(5)`(`devfs_ruleset = 4`)或命令行(`jail -c ... devfs_ruleset=4`)。内核将规则集应用于挂载,jail 只看到规则集允许的内容。 -### Creating a Custom devfs Ruleset +### 创建自定义 devfs 规则集 -For most jails, the default rulesets are enough. When they are not, an administrator can define new ones. A new ruleset must have a unique number (other than the reserved defaults) and can be constructed by inclusion, addition, and override. +对于大多数 jail,默认规则集就够了。当它们不够时,管理员可以定义新的规则集。新规则集必须具有唯一的编号(除了保留的默认值),可以通过包含、添加和覆盖来构建。 -A classical example is a jail that needs one specific device that the default rules hide. Suppose we have a jail that runs a service that needs `/dev/tun0`, and we want to expose it without opening the whole `/dev/tun*` family. We would create a ruleset like: +一个典型的例子是 jail 需要一个默认规则隐藏的特定设备。假设我们有一个运行服务的 jail 需要 `/dev/tun0`,我们想暴露它但不打开整个 `/dev/tun*` 系列。我们可以创建这样的规则集: ```text [devfsrules_myjail=100] @@ -1056,7 +1056,7 @@ add include $devfsrules_jail add path 'tun0' unhide ``` -And apply it in `jail.conf(5)`: +然后在 `jail.conf(5)` 中应用它: ```text myjail { @@ -1066,58 +1066,58 @@ myjail { } ``` -The `devfs(8)` tool can load this ruleset into the running kernel with `devfs rule -s 100 add ...`, or the administrator can edit `/etc/devfs.rules` and restart `devfs`. For persistent configuration, the file is the right place. +`devfs(8)` 工具可以通过 `devfs rule -s 100 add ...` 将此规则集加载到运行中的内核,或者管理员可以编辑 `/etc/devfs.rules` 并重启 `devfs`。对于持久配置,文件是正确的位置。 -### What devfs Rulesets Do Not Do +### devfs 规则集不能做什么 -It is worth noting what devfs rulesets are not. They are not a capability system. Hiding a device from a jail means the jail cannot open that specific path, but a jail that has the `allow.raw_sockets` privilege can still send arbitrary raw packets, ruleset or no ruleset. Hiding `/dev/kmem` does not prevent a determined attacker with the right privileges from reading kernel memory via other means; it just removes one obvious path. +值得注意的是 devfs 规则集不是什么。它们不是能力系统。对 jail 隐藏设备意味着 jail 无法打开该特定路径,但具有 `allow.raw_sockets` 权限的 jail 仍然可以发送任意原始数据包,无论有没有规则集。隐藏 `/dev/kmem` 不会阻止具有正确权限的攻击者通过其他方式读取内核内存;它只是移除了一条明显的路径。 -Rulesets are a visibility policy, layered on top of the standard UNIX permissions model. The UNIX permissions still apply: a file hidden by the ruleset is not openable, but a file visible to the ruleset still respects its own permissions. A jail's `root` user can open `/dev/null` because the ruleset says so and the permissions say so, not because the ruleset alone grants access. +规则集是一种可见性策略,叠加在标准 UNIX 权限模型之上。UNIX 权限仍然适用:被规则集隐藏的文件无法打开,但对规则集可见的文件仍然遵循其自身权限。jail 的 `root` 用户可以打开 `/dev/null`,是因为规则集允许且权限允许,而不是仅凭规则集就授予了访问权。 -For strong isolation, combine rulesets with privilege restrictions (`allow.*` parameters in `jail.conf(5)`) and, if the workload warrants it, with a VM. Rulesets alone are one layer of defence, not the only one. +要实现强隔离,请将规则集与权限限制(`jail.conf(5)` 中的 `allow.*` 参数)结合使用,如果工作负载需要,还应与 VM 结合。规则集只是防御的一层,而不是唯一的一层。 -### A Driver Author's View of devfs Rulesets +### 驱动程序作者眼中的 devfs 规则集 -For a driver author, devfs rulesets matter for two reasons. +对于驱动程序作者来说,devfs 规则集之所以重要有两个原因。 -First, when you create a `devfs` node with `make_dev(9)`, you pick a default owner, group, and permission. These apply to every `devfs` view that the node appears in. If your device is something that jails should generally not see (for example, a low-level hardware-management interface), consider whether the name should be obvious (so administrators can easily write a rule that hides it) or whether it should be under a subdirectory (so a single rule can hide the whole subdirectory). +首先,当你用 `make_dev(9)` 创建 `devfs` 节点时,你选择默认的所有者、组和权限。这些适用于节点出现的每个 `devfs` 视图。如果你的设备是 jail 通常不应该看到的东西(例如,低级硬件管理接口),考虑名称是否应该明显(以便管理员可以轻松编写隐藏它的规则)或者是否应该放在子目录下(以便单条规则可以隐藏整个子目录)。 -Second, if your driver's device is something that jails commonly need, document that fact in your driver's manual page. The administrator who writes a jail's ruleset is usually not the person who wrote the driver, and they need to know whether to unhide your node. A line like "This device is typically used inside jails; unhide it with `add path mydev unhide` in the jail's ruleset" is very helpful. +其次,如果你的驱动程序的设备是 jail 通常需要的东西,请在驱动程序的手册页中文档说明这一点。编写 jail 规则集的管理员通常不是编写驱动程序的人,他们需要知道是否要取消隐藏你的节点。像"此设备通常在 jail 内使用;在 jail 的规则集中使用 `add path mydev unhide` 取消隐藏"这样的一行说明非常有帮助。 -Neither of these is a code change. Both are decisions about naming and documentation. Driver authorship is not just about code; it is also about making the code usable by the administrators who will deploy it. +这些都不是代码更改。两者都是关于命名和文档的决定。驱动程序编写不仅仅是关于代码;它还关于使代码对将部署它的管理员可用。 -### 总结 the Jail and devfs Side +### 总结:Jail 与 devfs 侧 -Jails are the lightweight containerization mechanism in FreeBSD. They share the host kernel, and thus share drivers, but they control which devices are visible through the devfs ruleset mechanism. For a driver author, the relevant design decisions are at the naming and documentation level: pick names that make it easy to write rules, and document which jails should see the device. +jail 是 FreeBSD 中的轻量级容器化机制。它们共享主机内核,因此共享驱动程序,但通过 devfs 规则集机制控制哪些设备可见。对于驱动程序作者,相关的设计决定在命名和文档层面:选择使编写规则容易的名称,并记录哪些 jail 应该看到该设备。 -The network side of jails is a story of its own, because FreeBSD has two models: single-stack jails that share the host's network, and VNET jails that have their own network stacks. The VNET model is the more interesting one for driver authors, because it has direct consequences for how network drivers are assigned and moved. We turn to that next. +jail 的网络侧是一个独立的故事,因为 FreeBSD 有两种模型:共享主机网络的单一栈 jail,以及拥有自己网络栈的 VNET jail。VNET 模型对驱动程序作者来说更有趣,因为它对网络驱动程序如何分配和移动有直接影响。我们接下来讨论它。 -### The VNET Framework: One Kernel, Many Network Stacks +### VNET 框架:一个内核,多个网络栈 -The default jail model has one network stack: the host's. Every jail sees the same routing table, the same interfaces, the same sockets. A jail can be restricted to particular IPv4 or IPv6 addresses (via `ip4.addr` and `ip6.addr` in `jail.conf(5)`), but it cannot have a genuinely independent network configuration. That is often enough for simple workloads, but it is not enough for any jail that wants to run its own firewall, use its own default gateway, or be reached by the outside world through a unique set of addresses on its own interfaces. +默认的 jail 模型有一个网络栈:主机的。每个 jail 看到相同的路由表、相同的接口、相同的套接字。jail 可以被限制到特定的 IPv4 或 IPv6 地址(通过 `jail.conf(5)` 中的 `ip4.addr` 和 `ip6.addr`),但它不能拥有真正独立的网络配置。这对于简单工作负载通常够了,但对于任何想要运行自己的防火墙、使用自己的默认网关或通过自己接口上的唯一地址集被外部世界访问的 jail 来说是不够的。 -VNET (short for "virtual network stack") solves this. It is a kernel feature that replicates the parts of the network stack per jail, so each VNET jail sees its own routing table, its own interface list, its own firewall state, and its own socket namespace. The stack code still belongs to the same kernel, but many of its global variables are now per-VNET instead of truly global. A network driver's per-interface state belongs to whichever VNET it is currently assigned to, and interfaces can be moved from one VNET to another. +VNET("虚拟网络栈"的缩写)解决了这个问题。它是一个内核特性,按 jail 复制网络栈的各个部分,所以每个 VNET jail 看到自己的路由表、自己的接口列表、自己的防火墙状态和自己的套接字命名空间。协议栈代码仍然属于同一个内核,但它的许多全局变量现在是 per-VNET 的而非真正全局的。网络驱动程序的逐接口状态属于它当前被分配到的 VNET,接口可以从一个 VNET 移动到另一个。 -For driver authors, VNET is interesting in three respects. It changes how global state in network subsystems is declared. It adds a lifecycle to interfaces: interfaces can be moved, and drivers must support the move cleanly. And it interacts with jail creation and destruction through VNET-specific hooks. +对于驱动程序作者,VNET 在三个方面很有趣。它改变了网络子系统中全局状态的声明方式。它为接口添加了生命周期:接口可以被移动,驱动程序必须干净地支持移动。它还通过 VNET 特定的钩子与 jail 的创建和销毁交互。 -### Declaring VNET State: VNET_DEFINE and CURVNET_SET +### 声明 VNET 状态:VNET_DEFINE 与 CURVNET_SET -VNET's design puts the work on whoever declares global state in a VNET-aware subsystem. Instead of a plain `static int mysubsys_count;`, a VNET-aware declaration looks like: +VNET 的设计将工作放在在 VNET 感知子系统中声明全局状态的人身上。不是一个普通的 `static int mysubsys_count;`,一个 VNET 感知的声明看起来像这样: ```c VNET_DEFINE(int, mysubsys_count); #define V_mysubsys_count VNET(mysubsys_count) ``` -The `VNET_DEFINE` macro expands to a storage declaration that places the variable in a special section of the kernel. At VNET creation time, the kernel allocates a new per-VNET region of memory and initialises it from the section. The `VNET(...)` macro, used via a short alias like `V_mysubsys_count`, resolves to the correct copy for the current VNET. +`VNET_DEFINE` 宏展开为一个存储声明,将变量放在内核的特殊段中。在 VNET 创建时,内核分配一个新的 per-VNET 内存区域并从该段初始化。`VNET(...)` 宏通过像 `V_mysubsys_count` 这样的短别名使用,解析为当前 VNET 的正确副本。 -"The current VNET" is thread-local context. When a thread enters code that operates on a VNET, it calls `CURVNET_SET(vnet)` to establish the context, and `CURVNET_RESTORE()` to tear it down. Inside the context, `V_mysubsys_count` resolves to the right instance. Outside the context, accessing `V_mysubsys_count` is a bug; the macro depends on the thread-local current-VNET pointer, and without that pointer set the result is undefined. +"当前 VNET" 是线程局部上下文。当线程进入操作 VNET 的代码时,它调用 `CURVNET_SET(vnet)` 来建立上下文,调用 `CURVNET_RESTORE()` 来拆除它。在上下文内部,`V_mysubsys_count` 解析到正确的实例。在上下文外部,访问 `V_mysubsys_count` 是一个 bug;该宏依赖于线程局部的当前 VNET 指针,没有该指针集,结果是未定义的。 -Most driver authors do not need to write `VNET_DEFINE` declarations themselves. The network stack and the ifnet framework declare their own VNET state. Driver-level state (per-interface softcs, per-hardware private data) is not usually VNET-scoped, because it is tied to the hardware, not to the network stack. The driver's state lives wherever the driver put it, and the framework takes care of moving the right bits between VNETs when interfaces move. +大多数驱动程序作者不需要自己编写 `VNET_DEFINE` 声明。网络栈和 ifnet 框架声明自己的 VNET 状态。驱动程序级别的状态(逐接口 softc、逐硬件私有数据)通常不是 VNET 作用域的,因为它绑定到硬件而不是网络栈。驱动程序的状态存放在驱动程序放置的地方,框架负责在接口移动时在 VNET 之间移动正确的位。 -What driver authors do need to do is wrap any code that touches network-stack objects in a `CURVNET_SET` / `CURVNET_RESTORE` pair if that code is called from outside a network-stack entry point. Most driver code is called from the network stack already, so the VNET context is already set. The exception is callouts and taskqueues: a callback fired from a callout does not inherit a VNET context, and the driver must establish one before touching any `V_` variable. +驱动程序作者需要做的是将任何接触网络栈对象的代码包裹在 `CURVNET_SET` / `CURVNET_RESTORE` 对中,如果该代码从网络栈入口点之外调用。大多数驱动程序代码已经从网络栈调用,所以 VNET 上下文已经设置。例外是 callout 和 taskqueue:从 callout 触发的回调不继承 VNET 上下文,驱动程序必须在接触任何 `V_` 变量之前建立一个。 -A typical pattern inside a callout handler: +callout 处理程序中的典型模式: ```c static void @@ -1131,31 +1131,31 @@ mydev_callout(void *arg) } ``` -The driver stored a reference to the interface's VNET on attach (`sc->ifp->if_vnet` is filled in by the framework when the ifnet is created). On every callout, it establishes the context, does its work, and restores. This is one of the few places where driver authors encounter VNET directly. +驱动程序在附加时存储了对接口 VNET 的引用(`sc->ifp->if_vnet` 在 ifnet 创建时由框架填充)。每次 callout 时,它建立上下文、执行工作并恢复。这是驱动程序作者直接遇到 VNET 的少数地方之一。 -### if_vmove: Moving an Interface Between VNETs +### if_vmove:在 VNET 之间移动接口 -When a VNET jail starts, it typically is given one or more network interfaces to use. There are two common mechanisms. The first is that the administrator creates a virtual interface (an `epair(4)` or `vlan(4)`) and moves one end into the jail. The second is that the administrator moves a physical interface into the jail outright, so that the jail has exclusive access to it while it runs. +当 VNET jail 启动时,通常会获得一个或多个网络接口来使用。有两种常见机制。第一种是管理员创建一个虚拟接口(`epair(4)` 或 `vlan(4)`)并将一端移入 jail。第二种是管理员将物理接口整体移入 jail,使 jail 在运行时拥有独占访问权。 -The move is implemented by the kernel function `if_vmove()`. It takes an interface and a destination VNET, detaches the interface from the source VNET's network stack (without destroying it), and reattaches it to the destination VNET's network stack. The interface retains its driver, its softc, its hardware state, and its configured MAC address. What changes is which VNET's routing table, firewall, and socket namespace it is attached to. +移动由内核函数 `if_vmove()` 实现。它接受一个接口和一个目标 VNET,将接口从源 VNET 的网络栈分离(不销毁它),并重新附加到目标 VNET 的网络栈。接口保留其驱动程序、softc、硬件状态和配置的 MAC 地址。改变的是它附加到哪个 VNET 的路由表、防火墙和套接字命名空间。 -For a driver author, the move imposes a lifecycle requirement. The interface must be able to survive being detached from one VNET and attached to another. The driver's `if_init` function may be called again in the new context. The driver's `if_transmit` function may receive packets from the new VNET's sockets. Any state the driver caches about the "current" network stack (for example, routing-table lookups) must be invalidated or re-established. +对于驱动程序作者,移动施加了生命周期要求。接口必须能够在从一个 VNET 分离并附加到另一个 VNET 后存活。驱动程序的 `if_init` 函数可能在新的上下文中再次被调用。驱动程序的 `if_transmit` 函数可能从新 VNET 的套接字接收数据包。驱动程序缓存的关于"当前"网络栈的任何状态(例如,路由表查找)必须被失效或重新建立。 -For a network driver written to the standard `ifnet(9)` interface, the move usually works without special handling. The ifnet framework does the heavy lifting, and the driver is largely unaware. What the driver must avoid is holding references to VNET-scoped state across entry points. Code like "grab a pointer to the current routing table at attach and cache it" does not survive an interface move, because the interface may later belong to a different VNET with a different table. +对于按照标准 `ifnet(9)` 接口编写的网络驱动程序,移动通常不需要特殊处理即可工作。ifnet 框架做了大部分工作,驱动程序在很大程度上不知情。驱动程序必须避免的是在入口点之间持有对 VNET 作用域状态的引用。像"在附加时获取当前路由表的指针并缓存它"这样的代码在接口移动后无法存活,因为接口可能后来属于具有不同表的另一个 VNET。 -A related primitive, `if_vmove_loan()`, is used for interfaces that should return to the host when the jail shuts down. The jail gets the interface on a loan basis, and on jail destruction the interface is moved back. This is common for `epair(4)` setups where the physical connection (if any) belongs to the host and only the logical presence belongs to the jail. +一个相关的原语 `if_vmove_loan()` 用于在 jail 关闭时应该返回主机的接口。jail 以借用方式获得接口,在 jail 销毁时接口被移回。这在 `epair(4)` 设置中很常见,其中物理连接(如果有)属于主机,只有逻辑存在属于 jail。 -### VNET Lifecycle Hooks +### VNET 生命周期钩子 -When a VNET is created or destroyed, subsystems that keep VNET state need to initialise it or release it. The `VNET_SYSINIT` and `VNET_SYSUNINIT` macros register functions to be called at those moments. A network protocol might register an init function that creates per-VNET hash tables, and an uninit function that destroys them. +当 VNET 被创建或销毁时,保持 VNET 状态的子系统需要初始化或释放它。`VNET_SYSINIT` 和 `VNET_SYSUNINIT` 宏注册在这些时刻调用的函数。网络协议可能注册一个创建 per-VNET 哈希表的初始化函数,以及一个销毁它们的反初始化函数。 -Driver authors rarely need these hooks. They are relevant to protocols and stack features, not to device drivers. They are mentioned here because you will see them scattered across the network stack code, and knowing that they are VNET lifecycle hooks helps you read the source. +驱动程序作者很少需要这些钩子。它们与协议和栈特性相关,不与设备驱动程序相关。这里提到它们是因为你会看到它们散布在网络栈代码中,知道它们是 VNET 生命周期钩子有助于你阅读源代码。 -### A Concrete VNET Pattern +### 一个具体的 VNET 模式 -To make the VNET abstractions concrete, consider a simplified pseudo-driver that keeps a counter of packets received per VNET. The counter must be per-VNET because the same pseudo-driver might be cloned into several VNETs simultaneously, and each clone should have its own count. +为了使 VNET 抽象具体化,考虑一个简化的伪驱动程序,它保持一个每个 VNET 接收数据包的计数器。计数器必须是 per-VNET 的,因为同一个伪驱动程序可能被克隆到多个 VNET 中同时存在,每个克隆应该有自己的计数。 -The declaration looks like: +声明看起来像这样: ```c #include @@ -1173,9 +1173,9 @@ VNET_SYSINIT(pseudo_vnet_init, SI_SUB_PSEUDO, SI_ORDER_ANY, pseudo_vnet_init, NULL); ``` -The `VNET_DEFINE_STATIC` places the counter in a per-VNET section of the kernel image. When a new VNET is created, the kernel copies the per-VNET section into fresh memory, so each VNET starts with its own zero-initialised copy of the counter. The `V_pseudo_rx_count` shorthand is a macro that expands to `VNET(pseudo_rx_count)`, which in turn dereferences the current VNET's storage. +`VNET_DEFINE_STATIC` 将计数器放在内核映像的 per-VNET 段中。当新的 VNET 被创建时,内核将 per-VNET 段复制到新内存中,所以每个 VNET 都从自己的零初始化计数器副本开始。`V_pseudo_rx_count` 简写是一个展开为 `VNET(pseudo_rx_count)` 的宏,后者解引用当前 VNET 的存储。 -When a packet arrives, the receive path increments the counter: +当一个数据包到达时,接收路径递增计数器: ```c static void @@ -1187,9 +1187,9 @@ pseudo_receive_one(struct mbuf *m) } ``` -This looks like ordinary code, because the macro hides the per-VNET indirection. The condition for it to be correct is that the thread is already in the right VNET context when `pseudo_receive_one` is called. In a network driver's receive path that condition is automatic: the network stack calls the driver's entry point with the right context already established. +这看起来像普通代码,因为宏隐藏了 per-VNET 间接引用。使其正确的条件是当调用 `pseudo_receive_one` 时线程已经在正确的 VNET 上下文中。在网络驱动程序的接收路径中,这个条件是自动的:网络栈在调用驱动程序的入口点时已经建立了正确的上下文。 -When the counter is accessed from an unusual context, the context must be established explicitly: +当计数器从不寻常的上下文被访问时,必须显式建立上下文: ```c static void @@ -1204,60 +1204,60 @@ pseudo_print_counter(struct vnet *vnet) } ``` -Here the function is called from some administrative path that does not know the current VNET, so it sets the context manually, reads the counter, restores the context, and prints the result. This is the pattern you will see repeated in VNET-aware code. +这里函数从某个不知道当前 VNET 的管理路径被调用,所以它手动设置上下文、读取计数器、恢复上下文并打印结果。这是你会在 VNET 感知代码中看到的重复模式。 -### Reading Real VNET Code +### 阅读真实的 VNET 代码 -If you want to see the pattern in a real driver, `/usr/src/sys/net/if_tuntap.c` is a good starting point. The `tun` and `tap` cloning drivers are VNET-aware: each clone belongs to one VNET, and creating or destroying clones respects the VNET boundaries. The code is well-commented and small enough to read in a couple of evenings. +如果你想在一个真实驱动程序中看到这种模式,`/usr/src/sys/net/if_tuntap.c` 是一个好的起点。`tun` 和 `tap` 克隆驱动程序是 VNET 感知的:每个克隆属于一个 VNET,创建或销毁克隆遵守 VNET 边界。代码注释良好,足够小,可以在几个晚上读完。 -Two patterns in `if_tuntap.c` are worth noticing. The first is the use of `V_tun_cdevsw` and `V_tap_cdevsw`, per-VNET character device switch structures. Each VNET has its own copy of the switch, so `/dev/tun0` in one VNET can map to a different underlying clone than `/dev/tun0` in another VNET. This is the kind of fine-grained per-VNET duplication that the framework enables. +`if_tuntap.c` 中有两个模式值得注意。第一个是 `V_tun_cdevsw` 和 `V_tap_cdevsw` 的使用,per-VNET 字符设备开关结构。每个 VNET 都有自己的开关副本,所以一个 VNET 中的 `/dev/tun0` 可以映射到与另一个 VNET 中 `/dev/tun0` 不同的底层克隆。这是框架启用的细粒度 per-VNET 复制的类型。 -The second is the use of `if_clone(9)` with VNET. The `if_clone_attach` and `if_clone_detach` functions take VNET into account automatically, so a clone created in a VNET lives in that VNET until it is explicitly moved or destroyed. The cloner does not need to carry VNET state in its softc; the framework handles it. +第二个是 `if_clone(9)` 与 VNET 的使用。`if_clone_attach` 和 `if_clone_detach` 函数自动考虑 VNET,所以在 VNET 中创建的克隆存活在该 VNET 中,直到被显式移动或销毁。克隆器不需要在其 softc 中携带 VNET 状态;框架处理它。 -Studying these patterns makes the text in this chapter concrete. Read, take notes, and come back to the text if anything is unclear. +研究这些模式使本章的文字变得具体。阅读、做笔记,如果有什么不清楚的就回来重读。 -### Hierarchical Jails +### 分层监狱 -A brief mention of hierarchical jails, which are a feature some readers will encounter. FreeBSD supports nesting jails: a jail can create child jails, and the child jails are bounded by the parent jail's restrictions. This is useful for services that want to further subdivide their environment. +简要提及分层 jail,这是一些读者会遇到的功能。FreeBSD 支持嵌套 jail:一个 jail 可以创建子 jail,子 jail 受父 jail 的限制约束。这对于想要进一步细分其环境的服务很有用。 -From a driver author's perspective, hierarchical jails do not introduce new APIs. The `prison_priv_check` helper walks the hierarchy automatically: a privilege is granted only if every level of the hierarchy allows it. A driver that uses the framework correctly works in hierarchical jails without additional code. +从驱动程序作者的角度来看,分层 jail 不引入新的 API。`prison_priv_check` 辅助函数自动遍历层次结构:只有当层次结构的每一级都允许时,权限才被授予。正确使用框架的驱动程序在分层 jail 中无需额外代码即可工作。 -The administrative side is more complex (the parent jail must allow child-jail creation, the children inherit a restricted set of privileges), but the driver-side does not need to care. Knowing that the feature exists helps when you see nested jails in a deployment. +管理侧更复杂(父 jail 必须允许子 jail 创建,子 jail 继承受限的权限集合),但驱动程序侧不需要关心。知道这个功能的存在有助于在部署中看到嵌套 jail 时不感到困惑。 -### Putting It All Together +### 综合应用 -A FreeBSD system with jails and VNET is a system where a single kernel serves many isolated environments. Each environment sees its own filesystem view, its own process table, its own devices (filtered by devfs ruleset), and possibly its own network stack (under VNET). The driver serving all of them is a single shared binary, but it respects the isolation because it calls the framework APIs correctly. +一个带有 jail 和 VNET 的 FreeBSD 系统是单个内核服务多个隔离环境的系统。每个环境看到自己的文件系统视图、自己的进程表、自己的设备(由 devfs 规则集过滤),可能还有自己的网络栈(在 VNET 下)。服务于所有这些的驱动程序是单个共享二进制文件,但它尊重隔离,因为它正确调用了框架 API。 -The framework APIs for this isolation, `priv_check`, `prison_priv_check`, `CURVNET_SET`, `VNET_DEFINE`, and the cloning helpers, are small and self-contained. A driver author who learns them once can write drivers that work correctly in every jail configuration the administrator can dream up. There is no need to special-case specific jail setups; the framework does that work. +实现这种隔离的框架 API——`priv_check`、`prison_priv_check`、`CURVNET_SET`、`VNET_DEFINE` 和克隆辅助函数——小巧且自包含。学过一次的驱动程序作者就能编写在管理员能想到的每种 jail 配置中正确工作的驱动程序。不需要针对特定 jail 设置编写特殊代码;框架处理了这些工作。 -### Single-Stack Jails and the In-Between +### 单栈监狱与中间情况 -Not every jail needs VNET. A jail that is running a web server that talks through a reverse proxy on the host may do perfectly well with a single-stack jail bound to a specific IPv4 address. The main cost of VNET is complexity in the stack (every protocol must be VNET-aware) and some memory overhead (each VNET has its own hash tables, caches, and counters). For lightweight jails, the single-stack model is often the better choice. +不是每个 jail 都需要 VNET。一个通过主机上的反向代理通信的 web 服务器可能在一个绑定到特定 IPv4 地址的单一栈 jail 中运行得很好。VNET 的主要代价是栈的复杂性(每个协议都必须是 VNET 感知的)和一些内存开销(每个 VNET 有自己的哈希表、缓存和计数器)。对于轻量级 jail,单一栈模型通常是更好的选择。 -The trade-off for driver authors is worth knowing. A network driver that works correctly in a host-stack jail may still need attention for VNET jails, because the interface can be moved under VNET but not under the single-stack model. Writing the driver with VNET in mind from the start is the right approach; the additional discipline is small, and it future-proofs the driver. +驱动程序作者值得了解这个权衡。一个在主机栈 jail 中正确工作的网络驱动程序可能仍需要对 VNET jail 给予关注,因为接口可以在 VNET 下移动但不在单一栈模型下移动。从一开始就考虑到 VNET 来编写驱动程序是正确的做法;额外的规范很小,而且它使驱动程序面向未来。 ### 总结 -Jails share the host's kernel and thus the host's drivers. What they do not share is visibility: devfs rulesets control which device nodes a jail can open, and VNET controls which network interfaces a jail can use. Driver authors benefit from understanding both mechanisms, because the design choices they make (how to name `devfs` nodes, how to handle VNET context in callouts, how to support interface moves) affect how their driver behaves in jailed environments. +jail 共享主机的内核,因此共享主机的驱动程序。它们不共享的是可见性:devfs 规则集控制 jail 可以打开哪些设备节点,VNET 控制 jail 可以使用哪些网络接口。驱动程序作者受益于理解这两种机制,因为他们的设计选择(如何命名 `devfs` 节点、如何在 callout 中处理 VNET 上下文、如何支持接口移动)影响驱动程序在 jail 环境中的行为。 -With the jail picture complete, we can now think about the companion question: once a jail has access to a device, what privileges does it have to use that device? Section 7 takes up resource limits and security boundaries, and looks at the other side of the jail policy story. +jail 的全景已完成,我们现在可以思考伴随的问题:一旦 jail 有权访问设备,它有什么权限来使用该设备?第7节讨论资源限制和安全边界,并审视 jail 策略故事的另一面。 ## 第7节:资源限制、安全边界与主机与 Jail 的访问 -A driver is not an isolated object. It is a consumer of kernel resources and a provider of services to processes, and both relationships are mediated by the kernel's security and accounting frameworks. When a driver runs on a FreeBSD host that contains jails, the security boundary shifts: some privileges that are unconditional on the host are restricted for jail processes, and some resources that are unmetered on a traditional system are now subject to per-jail limits. A good driver author knows where those boundaries are, because their driver's behaviour on a host is not always its behaviour inside a jail. +驱动程序不是一个孤立的对象。它是内核资源的消费者和向进程提供服务的提供者,这两种关系都由内核的安全和记账框架中介。当驱动程序运行在包含 jail 的 FreeBSD 主机上时,安全边界发生转移:一些在主机上无条件的权限对 jail 进程受到限制,一些在传统系统上未计量的资源现在受到逐 jail 的限制。一个好的驱动程序作者知道这些边界在哪里,因为他们的驱动程序在主机上的行为不总是它在 jail 内的行为。 -This section covers three topics. First, the privilege framework and how `prison_priv_check` reshapes it for jails. Second, `rctl(8)` and how resource limits apply to kernel resources a driver might care about. Third, the practical distinction between attaching a driver from inside a jail (which is usually impossible) and making a driver's services available to a jail (which is the usual case). +本节涵盖三个主题。首先是权限框架以及 `prison_priv_check` 如何为 jail 重塑它。其次是 `rctl(8)` 以及资源限制如何应用于驱动程序可能关心的内核资源。第三是从 jail 内部附加驱动程序(通常不可能)与使驱动程序的服务对 jail 可用(通常情况)之间的实际区别。 -### The Privilege Framework and prison_priv_check +### 权限框架与 prison_priv_check -FreeBSD uses a privilege system to make fine-grained decisions about what a process can and cannot do. Traditional UNIX has a single privilege bit (root versus not-root), and that bit determines everything. FreeBSD refines this with the `priv(9)` framework, which defines a long list of named privileges. Each privilege covers a specific kind of operation. Loading a kernel module is `PRIV_KLD_LOAD`. Setting a process's root directory is `PRIV_VFS_CHROOT`. Opening a raw socket is `PRIV_NETINET_RAW`. Configuring an interface's MAC address is `PRIV_NET_SETLLADDR`. Using a BPF device for packet capture is `PRIV_NET_BPF`. +FreeBSD 使用权限系统来对进程能做什么和不能做什么做出细粒度决策。传统 UNIX 有一个单一的权限位(root 与非 root),该位决定一切。FreeBSD 通过 `priv(9)` 框架对此进行了细化,该框架定义了一长列命名权限。每个权限涵盖一种特定操作。加载内核模块是 `PRIV_KLD_LOAD`。设置进程的根目录是 `PRIV_VFS_CHROOT`。打开原始套接字是 `PRIV_NETINET_RAW`。配置接口的 MAC 地址是 `PRIV_NET_SETLLADDR`。使用 BPF 设备进行数据包捕获是 `PRIV_NET_BPF`。 -A process that is root (uid 0) has all of these privileges on the host. A process that is a jail's root has some of them, but not all. The restriction is handled by `prison_priv_check(cred, priv)`: it takes the credential and the privilege name, and returns zero if the privilege is granted and an error (usually `EPERM`) if it is denied. The kernel's privilege-checking path is structured so that for a jailed credential, `prison_priv_check` is called first; if it denies the privilege, the caller returns `EPERM` without further ado. +主机上的 root(uid 0)进程拥有所有这些权限。jail 的 root 进程拥有其中一些,但不是全部。限制由 `prison_priv_check(cred, priv)` 处理:它接受凭证和权限名称,如果权限被授予则返回零,如果被拒绝则返回错误(通常是 `EPERM`)。内核的权限检查路径的结构使得对于 jail 内的凭证,首先调用 `prison_priv_check`;如果它拒绝了权限,调用者直接返回 `EPERM`。 -Which privileges a jail is allowed to exercise is determined by two things. The first is a hardcoded list inside `prison_priv_check`: some privileges are simply never granted to jails, regardless of configuration. Examples include `PRIV_KLD_LOAD` (loading kernel modules) and `PRIV_IO` (I/O port access). The second is the `allow.*` parameters in `jail.conf(5)`, which turn on or off specific categories. `allow.raw_sockets` (off by default) controls `PRIV_NETINET_RAW`. `allow.mount` (off by default) controls filesystem mounting privileges. `allow.vmm` (off by default) controls access to `vmm(4)` for running nested hypervisors. The defaults err on the side of denial: if you do not explicitly allow it, the jail does not get it. +jail 被允许行使哪些权限由两件事决定。第一是 `prison_priv_check` 内部的硬编码列表:一些权限无论配置如何都不会授予 jail,例如 `PRIV_KLD_LOAD`(加载内核模块)和 `PRIV_IO`(I/O 端口访问)。第二是 `jail.conf(5)` 中的 `allow.*` 参数,它们开启或关闭特定类别。`allow.raw_sockets`(默认关闭)控制 `PRIV_NETINET_RAW`。`allow.mount`(默认关闭)控制文件系统挂载权限。`allow.vmm`(默认关闭)控制对 `vmm(4)` 的访问以运行嵌套虚拟机监控程序。默认偏向拒绝:如果你不明确允许,jail 就不会获得。 -For a driver author, the privilege framework matters whenever the driver does something that a process might or might not be allowed to do. A driver that implements a low-level hardware interface might require `PRIV_DRIVER` (the catch-all for driver-specific privilege checks) or a more specific privilege. A driver that exposes a character device whose `ioctl`s can reconfigure the hardware will call `priv_check(td, PRIV_DRIVER)` (or a more specific name) to decide whether the caller is allowed to do the reconfiguration. +对于驱动程序作者来说,权限框架在驱动程序执行进程可能被允许或可能不被允许做的事情时很重要。实现低级硬件接口的驱动程序可能需要 `PRIV_DRIVER`(驱动程序特定权限检查的通用选项)或更具体的权限。暴露字符设备且其 `ioctl` 可以重新配置硬件的驱动程序会调用 `priv_check(td, PRIV_DRIVER)`(或更具体的名称)来决定调用者是否被允许进行重新配置。 -The standard pattern in driver code looks like this: +驱动程序代码中的标准模式如下: ```c static int @@ -1278,123 +1278,123 @@ mydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, } ``` -`priv_check(td, PRIV_DRIVER)` does the right thing for both host and jail callers. On a host, a root process passes; on a host, a non-root process is denied (unless the driver grants permission by other means). Inside a jail, `prison_priv_check` is consulted, and by default `PRIV_DRIVER` is denied inside jails. If the administrator has configured the jail to allow driver access (a very unusual setting), the privilege is granted and the call proceeds. +`priv_check(td, PRIV_DRIVER)` 对主机和 jail 调用者都做正确的事情。在主机上,root 进程通过;在主机上,非 root 进程被拒绝(除非驱动程序通过其他方式授予权限)。在 jail 内,查询 `prison_priv_check`,默认情况下 `PRIV_DRIVER` 在 jail 内被拒绝。如果管理员配置了 jail 允许驱动程序访问(一个非常不寻常的设置),权限被授予,调用继续。 -The result is that a driver that uses `priv_check` correctly gets jail safety for free. The driver does not need to know whether the caller is in a jail; it just asks whether the caller has the right privilege, and the framework takes care of the rest. +结果是正确使用 `priv_check` 的驱动程序免费获得了 jail 安全性。驱动程序不需要知道调用者是否在 jail 中;它只是询问调用者是否拥有正确的权限,框架处理其余的。 -### Named Privileges Most Relevant to Drivers +### 与驱动程序最相关的命名权限 -A short reference for some of the privileges a driver author will encounter. +驱动程序作者将遇到的一些权限的简要参考。 -`PRIV_IO` is for direct I/O port access on x86. It is defined in `/usr/src/sys/sys/priv.h` and is denied to jails unconditionally. Drivers that offer raw I/O port access to user space are rare (usually limited to legacy hardware like `/dev/io`), but when they exist, they use this privilege. +`PRIV_IO` 用于 x86 上的直接 I/O 端口访问。它在 `/usr/src/sys/sys/priv.h` 中定义,对 jail 无条件拒绝。向用户空间提供原始 I/O 端口访问的驱动程序很少见(通常限于像 `/dev/io` 这样的遗留硬件),但当它们存在时,使用此权限。 -`PRIV_DRIVER` is the catch-all for driver-specific privileges. If a driver needs to gate an `ioctl` that only an administrator should call, `PRIV_DRIVER` is the default choice. +`PRIV_DRIVER` 是驱动程序特定权限的通用选项。如果驱动程序需要门控一个只有管理员才应该调用的 `ioctl`,`PRIV_DRIVER` 是默认选择。 -`PRIV_KMEM_WRITE` gates write access to `/dev/kmem`. Like `PRIV_IO`, it is denied to jails. Writing to kernel memory is the ultimate privileged operation; no reasonable container policy allows it. +`PRIV_KMEM_WRITE` 门控对 `/dev/kmem` 的写访问。与 `PRIV_IO` 一样,它对 jail 被拒绝。写入内核内存是终极特权操作;没有合理的容器策略允许它。 -`PRIV_NET_*` is a family of network-related privileges. `PRIV_NET_IFCREATE` is for creating network interfaces; `PRIV_NET_SETLLADDR` is for changing MAC addresses; `PRIV_NET_BPF` is for opening a BPF device. Each has its own jail policy, and the combinations are how a VNET jail can (for example) run `dhclient(8)` (which needs `PRIV_NET_BPF`) without also being able to arbitrarily reconfigure interfaces. +`PRIV_NET_*` 是一系列网络相关权限。`PRIV_NET_IFCREATE` 用于创建网络接口;`PRIV_NET_SETLLADDR` 用于更改 MAC 地址;`PRIV_NET_BPF` 用于打开 BPF 设备。每个权限有自己的 jail 策略,这些组合使得 VNET jail 可以(例如)运行 `dhclient(8)`(需要 `PRIV_NET_BPF`)而不能任意重新配置接口。 -`PRIV_VFS_MOUNT` gates filesystem mounting. Jails have a very restricted version of this by default: they can mount `nullfs` and `tmpfs` if `allow.mount` is set, but not arbitrary filesystems. +`PRIV_VFS_MOUNT` 控制文件系统挂载。jail 默认有非常受限的版本:如果设置了 `allow.mount`,它们可以挂载 `nullfs` 和 `tmpfs`,但不能挂载任意文件系统。 -A complete list is in `/usr/src/sys/sys/priv.h`. For driver authorship, you will rarely invent new privilege categories; you will pick the existing one that fits. +完整列表在 `/usr/src/sys/sys/priv.h` 中。对于驱动程序编写,你很少需要发明新的权限类别;你会选择适合的现有权限。 -### rctl(8): Per-Jail and Per-Process Resource Limits +### rctl(8):逐监狱与逐进程的资源限制 -Jails (and, indeed, processes) can be subject to resource limits beyond the traditional UNIX `ulimit(1)` model. FreeBSD's `rctl(8)` (the runtime resource control framework) lets an administrator set limits on a wide variety of resources, and enforce them with specified actions when the limits are hit. +jail(以及进程)可以受到超出传统 UNIX `ulimit(1)` 模型的资源限制。FreeBSD 的 `rctl(8)`(运行时资源控制框架)让管理员可以设置各种资源的限制,并在达到限制时以指定操作强制执行。 -The limits cover things like memory use, CPU time, number of processes, number of open files, I/O bandwidth, and so on. They can be applied per user, per process, per login class, or per jail. The typical use in a jail setup is to cap a jail's total memory and CPU so that a misbehaving application inside the jail cannot affect other jails on the same host. +限制涵盖内存使用、CPU 时间、进程数、打开文件数、I/O 带宽等。它们可以按用户、按进程、按登录类或按 jail 应用。在 jail 设置中的典型用途是封顶 jail 的总内存和 CPU,使 jail 内行为异常的应用程序不能影响同一主机上的其他 jail。 -For a driver author, `rctl(8)` matters for a subtle reason. Drivers allocate resources on behalf of processes. When a driver calls `malloc(9)` to allocate a buffer, the memory goes somewhere. When a driver creates a file descriptor by opening a file internally, the descriptor goes somewhere. When a driver spawns a kernel thread, the thread runs as part of somebody's accounting. If the "somebody" is a process inside a jail, the accounting might hit the jail's `rctl` limits. +对于驱动程序作者,`rctl(8)` 之所以重要有一个微妙的原因。驱动程序代表进程分配资源。当驱动程序调用 `malloc(9)` 分配缓冲区时,内存去了某个地方。当驱动程序通过内部打开文件创建文件描述符时,描述符去了某个地方。当驱动程序产生内核线程时,线程作为某个人的记账的一部分运行。如果"某个人"是 jail 内的进程,记账可能会触及 jail 的 `rctl` 限制。 -Usually this is exactly what you want. If a jail is supposed to be limited to 100 MB of memory, and an allocation on behalf of a jail process should count against that limit, and `rctl` hits the limit, the allocation should fail with `ENOMEM`. Your driver then propagates the failure back to user space, and the well-behaved application inside the jail handles it. +通常这正是你想要的。如果 jail 应该被限制为 100 MB 内存,而代表 jail 进程的分配应该计入该限制,`rctl` 触及了限制,分配应该以 `ENOMEM` 失败。你的驱动程序然后将失败传播回用户空间,jail 内行为良好的应用程序处理它。 -Occasionally the accounting is less obvious. A driver that maintains a pool of buffers shared across all callers will, by default, charge the pool to the kernel rather than to any single process. That is fine, but it means the pool is unmetered: a very active jail can consume a larger share of the pool than it "should" under the resource limits. For most drivers this is acceptable, but for drivers whose resources are expensive (large DMA buffers, for instance) it may be worth considering whether the resource should be tracked per-process through `racct(9)`, the underlying accounting layer that `rctl` sits on top of. +偶尔记账不太明显。维护跨所有调用者共享的缓冲池的驱动程序,默认会将缓冲池计入内核而不是任何单个进程。这没问题,但这意味着缓冲池是不计量的:一个非常活跃的 jail 可以在资源限制下消耗比它"应该"消耗的更大份额。对于大多数驱动程序这是可以接受的,但对于资源昂贵的驱动程序(例如大型 DMA 缓冲区),可能值得考虑资源是否应该通过 `racct(9)`(`rctl` 所依赖的底层记账层)按进程跟踪。 -The `racct(9)` framework exposes `racct_add(9)` and `racct_sub(9)` functions for drivers that want to participate in accounting. Most drivers never call these directly. Adding `racct` support is a deliberate design choice, usually made when a driver's resource consumption is large enough to matter in aggregate. For everyday character-device drivers or network drivers, the default accounting done by the kernel (per-socket buffer memory, per-process file descriptor counts, and so on) is sufficient. +`racct(9)` 框架暴露了 `racct_add(9)` 和 `racct_sub(9)` 函数供想要参与记账的驱动程序使用。大多数驱动程序从不直接调用这些函数。添加 `racct` 支持是一个有意的设计选择,通常在驱动程序的资源消耗大到需要关注时才会做。对于日常的字符设备驱动程序或网络驱动程序,内核完成的默认记账(每套接字缓冲内存、每进程文件描述符计数等)就足够了。 -### Enforcement Actions and What They Mean for Drivers +### 强制执行操作及其对驱动程序的意义 -When a resource limit is hit, `rctl(8)` can do one of several things: deny the operation, send a signal to the offending process, log the event, or throttle (for rate-based resources). The enforcement is handled by the kernel's accounting layer, not by drivers. What drivers see is the result: an allocation fails, a signal delivers, a rate-limited operation takes longer. +当资源限制被触及时,`rctl(8)` 可以执行以下操作之一:拒绝操作、向违规进程发送信号、记录事件或限制速率(对于基于速率的资源)。强制执行由内核的记账层处理,而不是驱动程序。驱动程序看到的是结果:分配失败、信号送达、限速操作花费更长时间。 -For a driver, the practical implication is that every allocation and every resource acquisition must be written to handle failure. This is not specific to jails or `rctl`; it is good defensive coding anyway. A `malloc(9)` with `M_WAITOK` can wait for memory indefinitely, but in a jail with a memory limit, it may still fail (if `M_WAITOK` is not set) or it may block a long time waiting for memory that will never be freed (because no other process in the jail has any to free). +对于驱动程序来说,实际的影响是每次分配和每次资源获取都必须编写为能处理失败。这不是特定于 jail 或 `rctl` 的;无论如何这都是良好的防御性编码。带有 `M_WAITOK` 的 `malloc(9)` 可以无限期等待内存,但在有内存限制的 jail 中,它仍然可能失败(如果未设置 `M_WAITOK`)或可能长时间阻塞等待永远不会被释放的内存(因为 jail 中没有其他进程有内存可释放)。 -The rule of thumb: if your driver is doing allocations on behalf of a user process, consider whether `M_NOWAIT` is more appropriate than `M_WAITOK`, and whether the caller can tolerate a delayed or failed allocation. Jails (and the resource limits around them) make the consideration more than theoretical. +经验法则:如果你的驱动程序代表用户进程进行分配,考虑 `M_NOWAIT` 是否比 `M_WAITOK` 更合适,以及调用者是否能容忍延迟或失败的分配。jail(及其周围的资源限制)使这种考虑不仅是理论上的。 -### Host-Side Drivers versus Jail-Side Processes +### 主机侧驱动程序与监狱侧进程 -A recurring question for driver authors is: can my driver be loaded or attached from inside a jail? The short answer is almost always no. Loading kernel modules (`kldload(2)`) requires `PRIV_KLD_LOAD`, which is never granted to jails. A jail that needs access to a driver's services must have that driver already loaded and attached on the host, and then the jail can use the driver through the usual user-space interfaces. +驱动程序作者反复出现的一个问题是:我的驱动程序能从 jail 内部加载或附加吗?简短的回答几乎总是不能。加载内核模块(`kldload(2)`)需要 `PRIV_KLD_LOAD`,它从不授予 jail。需要访问驱动程序服务的 jail 必须已经在主机上加载和附加了该驱动程序,然后 jail 可以通过通常的用户空间接口使用驱动程序。 -This is a consequence of the single-kernel model. A jail does not have its own kernel, so it cannot load drivers of its own. What it has is access (subject to the devfs ruleset) to the drivers that the host has loaded. In practice this means: +这是单内核模型的结果。jail 没有自己的内核,所以它不能加载自己的驱动程序。它拥有的是(受 devfs 规则集约束的)对主机已加载驱动程序的访问权。实际上这意味着: -- Driver loading and unloading happen on the host. The host administrator is responsible for `kldload` and `kldunload`. -- Device attachment to devices happens on the host. The driver's `DEVICE_ATTACH` runs in host context, not in jail context. -- Device access from user space happens inside the jail, through `/dev` (if the ruleset allows) and through the driver's `open`/`read`/`write`/`ioctl` methods. +- 驱动程序的加载和卸载在主机上发生。主机管理员负责 `kldload` 和 `kldunload`。 +- 设备附加在主机上发生。驱动程序的 `DEVICE_ATTACH` 在主机上下文中运行,而不是在 jail 上下文中。 +- 从用户空间对设备的访问在 jail 内发生,通过 `/dev`(如果规则集允许)和驱动程序的 `open`/`read`/`write`/`ioctl` 方法。 -The separation is usually clean. The driver does not need to know whether its caller is in a jail; the kernel handles the context. Where it sometimes matters is in `ioctl` handlers that want to distinguish host and jail callers, or in drivers that allocate resources per-open whose release policy differs. +分离通常是干净的。驱动程序不需要知道其调用者是否在 jail 中;内核处理上下文。有时重要的是在想要区分主机和 jail 调用者的 `ioctl` 处理程序中,或者在分配每次打开资源的驱动程序中,这些资源的释放策略不同。 -A specific caveat: when a driver creates state on open, that state survives until close. If the jail that held the open file descriptor goes away before the descriptor is closed (because the jail was destroyed while processes still had the device open), the kernel will close the descriptor on the jail's behalf. The driver's `close` method will run in a safe context. But the driver should not assume that the jail still exists during close; it may not, and if the driver tries to reach into the jail's state, it will encounter a freed `struct prison`. The clean rule is that `close` should only touch driver state, not jail state. +一个具体的注意事项:当驱动程序在打开时创建状态时,该状态一直存活到关闭。如果持有打开文件描述符的 jail 在描述符关闭之前消失了(因为 jail 在进程仍然打开设备时被销毁),内核将代表 jail 关闭描述符。驱动程序的 `close` 方法将在安全的上下文中运行。但驱动程序不应该假设 jail 在关闭期间仍然存在;它可能不存在了,如果驱动程序试图访问 jail 的状态,它将遇到已释放的 `struct prison`。干净的规则是 `close` 只应触碰驱动程序状态,而不是 jail 状态。 -### How Drivers Cooperate with Jails in Practice +### 驱动程序如何在实际中与监狱协作 -Putting the pieces together, a typical FreeBSD setup with a driver and a jail looks like this. +将各部分放在一起,一个带有驱动程序和 jail 的典型 FreeBSD 设置看起来像这样。 -1. The administrator loads the driver on the host, either at boot through `/boot/loader.conf` or at runtime through `kldload(8)`. -2. The driver's probe and attach functions run on the host, create whatever `devfs` nodes are appropriate, and register their `cdev_methods`. -3. The administrator creates a jail, possibly with a specific devfs ruleset and possibly with VNET. -4. The jail's processes open the driver's devices (if they are visible through the ruleset) and make `ioctl` or `read`/`write` calls. -5. The driver's methods execute on behalf of the jail process, with the jail's credential attached to the thread, and the driver's `priv_check` calls correctly return `EPERM` for privileges the jail does not hold. -6. When the jail is destroyed, open file descriptors are closed, the driver's `close` methods run cleanly, and the driver's state returns to its normal host-only view. +1. 管理员在主机上加载驱动程序,要么在启动时通过 `/boot/loader.conf`,要么在运行时通过 `kldload(8)`。 +2. 驱动程序的探测和附加函数在主机上运行,创建适当的 `devfs` 节点并注册其 `cdev_methods`。 +3. 管理员创建一个 jail,可能带有特定的 devfs 规则集,也可能带有 VNET。 +4. jail 的进程打开驱动程序的设备(如果它们通过规则集可见)并进行 `ioctl` 或 `read`/`write` 调用。 +5. 驱动程序的方法代表 jail 进程执行,jail 的凭证附加到线程上,驱动程序的 `priv_check` 调用正确地为 jail 不持有的权限返回 `EPERM`。 +6. 当 jail 被销毁时,打开的文件描述符被关闭,驱动程序的 `close` 方法干净地运行,驱动程序的状态返回到其正常的主机视图。 -Nothing in this flow requires the driver to know about jails explicitly. The driver is a passive participant that calls the right framework functions, and the framework handles the rest. This is the cleanest possible design, and it is what you should aim for. +这个流程中没有任何东西要求驱动程序显式地了解 jail。驱动程序是一个被动参与者,调用正确的框架函数,框架处理其余的。这是最干净的设计,也是你应该追求的。 -### The Container Frameworks: ocijail and pot +### 容器框架:ocijail 与 pot -FreeBSD's jail infrastructure is a kernel mechanism; the user-space tooling around it has multiple forms. The base system provides `jail(8)`, `jail.conf(5)`, `jls(8)`, and related tools. These are enough to manage jails by hand or with shell scripts. +FreeBSD 的 jail 基础设施是一个内核机制;围绕它的用户空间工具有多种形式。基本系统提供 `jail(8)`、`jail.conf(5)`、`jls(8)` 和相关工具。这些足以手动或通过 shell 脚本管理 jail。 -Higher-level container frameworks have emerged on top. `ocijail` aims to provide an OCI (Open Container Initiative) runtime that uses jails as the isolation mechanism, letting FreeBSD participate in container ecosystems that use OCI-compliant images. `pot` (available from ports) is a more FreeBSD-native container manager that bundles a jail with a filesystem layer, a network configuration, and a lifecycle. Both are external to the base system and are installed through the ports collection or packages. +更高级的容器框架已经在其之上出现。`ocijail` 旨在提供一个使用 jail 作为隔离机制的 OCI(开放容器倡议)运行时,让 FreeBSD 参与使用 OCI 兼容镜像的容器生态系统。`pot`(可从 ports 获取)是一个更加 FreeBSD 原生的容器管理器,它将 jail 与文件系统层、网络配置和生命周期捆绑在一起。两者都不在基本系统中,通过 ports 集合或包安装。 -For a driver author, these frameworks do not change the fundamentals. They still use jails underneath; they still rely on devfs rulesets and VNET for isolation; they still respect the same privilege framework. What they change is how administrators describe and deploy the containers, not how the drivers interact with them. A driver that works with a hand-crafted `jail.conf(5)` will work with `ocijail` and `pot` as well. +对于驱动程序作者来说,这些框架不改变基本面。它们仍然在底层使用 jail;它们仍然依赖 devfs 规则集和 VNET 进行隔离;它们仍然遵守相同的权限框架。它们改变的是管理员如何描述和部署容器,而不是驱动程序如何与它们交互。一个与手工编写的 `jail.conf(5)` 一起工作的驱动程序也能与 `ocijail` 和 `pot` 一起工作。 -The most a driver author usually needs to know is that these frameworks exist and are becoming common. If your driver's documentation mentions jails, mention that the recommendations apply equally to container frameworks built on top. That single sentence saves administrators a lot of guesswork. +驱动程序作者通常最需要知道的就是这些框架存在并且变得越来越普遍。如果你的驱动程序文档提到了 jail,也提及这些建议同样适用于建立在其上的容器框架。这一句话可以为管理员省去很多猜测。 ### 总结 -Jails are a policy boundary around a shared kernel. The policy extends into three dimensions: which devices are visible (devfs rulesets), which privileges are granted (`prison_priv_check` and `allow.*` parameters), and which resources can be consumed (`rctl(8)`). Driver authors encounter each of these in small, local ways: `priv_check` for privileged operations, sensible naming of `devfs` nodes, graceful handling of allocation failures. There is no large new API to learn; there are small new habits to pick up. +jail 是围绕共享内核的策略边界。策略延伸到三个维度:哪些设备可见(devfs 规则集)、哪些权限被授予(`prison_priv_check` 和 `allow.*` 参数),以及哪些资源可以被消耗(`rctl(8)`)。驱动程序作者以小型、局部的方式遇到这些:`priv_check` 用于特权操作、合理的 `devfs` 节点命名、优雅地处理分配失败。没有大型新 API 需要学习;只有一些小的新习惯需要养成。 -With the security and resource picture covered, the final conceptual topic is how to actually test and develop drivers in virtualised and containerised environments. Section 8 pulls the chapter's ideas together into a development workflow. +安全和资源的全貌已经覆盖,最后一个概念性主题是如何在虚拟化和容器化环境中实际测试和开发驱动程序。第8节将本章的想法整合为一个开发工作流。 ## 第8节:为虚拟化与容器化环境测试和重构驱动程序 -A driver that runs on bare metal is a driver that works on one configuration. A driver that runs across virtualisation and containerisation has been exercised under varied conditions: different bus presentations, different interrupt delivery mechanisms, different memory-mapping behaviours, different privilege contexts. The driver that makes it through all of those without changes is the driver that will survive the next new environment too. This section describes the development and testing workflow that gets you there. +一个只在裸金属上运行的驱动程序是一个只在一个配置上工作的驱动程序。一个跨虚拟化和容器化运行的驱动程序已经在多种条件下被测试:不同的总线呈现、不同的中断投递机制、不同的内存映射行为、不同的权限上下文。通过了所有这些而不需要更改的驱动程序也能在下一个新环境中存活。本节描述实现这一目标的开发和测试工作流程。 -The workflow has three layers. The development layer uses a VM as a disposable kernel host, so that panics and hangs cost you nothing. The integration layer uses VirtIO devices, passthrough, and jails to exercise the driver in realistic environments. The regression layer uses automation to run the whole suite repeatedly as the driver evolves. +工作流程有三层。开发层使用 VM 作为一次性内核主机,所以 panic 和挂起的代价为零。集成层使用 VirtIO 设备、直通和 jail 在现实环境中测试驱动程序。回归层使用自动化随着驱动程序的演进重复运行整个套件。 -### Using a VM as Your Development Host +### 使用虚拟机作为开发主机 -When you are writing a kernel module, the cost of a panic is your session. On a bare-metal development machine, a panic interrupts your work, possibly forces a filesystem check, and may require a reboot with manual recovery steps. On a VM, a panic is a detail: the VM stops, you restart it, and the host is untouched. +当你编写内核模块时,panic 的代价是你的会话。在裸金属开发机器上,panic 会中断你的工作,可能强制文件系统检查,并可能需要手动恢复步骤的重启。在 VM 上,panic 是一个细节:VM 停止,你重新启动它,主机不受影响。 -For this reason, experienced driver authors do almost all of their new-driver development inside a `bhyve(8)` or QEMU-based VM, not on bare metal. The workflow looks like this: +因此,经验丰富的驱动程序作者几乎所有新驱动程序开发都在 `bhyve(8)` 或基于 QEMU 的 VM 中进行,而不是在裸金属上。工作流程如下: -1. A FreeBSD 14.3 VM is installed in `bhyve(8)` with a standard disk image. -2. The source tree is either on the VM's own disk or mounted via NFS from a host-side build machine. -3. The driver is built inside the VM (`make clean && make`) or on the host and copied in. -4. `kldload(8)` loads the module. If the module panics the kernel, the VM crashes, and the VM is restarted. -5. Once the module loads cleanly, it is exercised against whatever test fixture you have: a VirtIO device, a loopback mode, or a passthrough target. +1. 在 `bhyve(8)` 中安装一个使用标准磁盘映像的 FreeBSD 14.3 VM。 +2. 源代码树或者在 VM 自己的磁盘上,或者通过 NFS 从主机侧的构建机器挂载。 +3. 驱动程序在 VM 内构建(`make clean && make`)或在主机上构建后复制进来。 +4. `kldload(8)` 加载模块。如果模块导致内核 panic,VM 崩溃,重启 VM 即可。 +5. 模块干净加载后,对你拥有的测试装置进行测试:VirtIO 设备、回环模式或直通目标。 -The key point is that iteration is fast. A broken module that would make a bare-metal machine unbootable is a minor inconvenience in a VM. You can try things that you would never try on a machine you rely on. +关键点是迭代速度很快。一个会使裸金属机器无法启动的损坏模块在 VM 中只是一个小小的不便。你可以尝试在你依赖的机器上永远不会尝试的事情。 -For VirtIO driver development specifically, the VM is not just convenient; it is the only sensible platform. VirtIO devices only exist inside VMs (or under qemu emulation), so the VM is where the devices are. Starting a VM with a virtio-rnd device, or a virtio-net device, or a virtio-console device, gives you a target to develop against. The hypervisor provides everything a real device would provide, including interrupts, DMA, and register access, so the driver you write inside the VM is the same driver that will run anywhere else. +对于 VirtIO 驱动程序开发来说,VM 不仅方便;它是唯一合理的平台。VirtIO 设备只存在于 VM 内(或在 qemu 模拟下),所以 VM 就是设备所在的地方。启动一个带有 virtio-rnd 设备、virtio-net 设备或 virtio-console 设备的 VM 给你一个开发目标。虚拟机监控程序提供了真实设备会提供的一切,包括中断、DMA 和寄存器访问,所以你在 VM 内编写的驱动程序与在其他任何地方运行的驱动程序相同。 -### Using VirtIO as a Test Substrate +### 使用 VirtIO 作为测试基底 -VirtIO has a second role beyond being the target for VirtIO drivers: it is a test substrate. Because VirtIO devices are easy to define, easy to emulate, and well-documented, they are useful for building controlled test scenarios even for drivers that are not VirtIO drivers. +VirtIO 除了作为 VirtIO 驱动程序的目标之外还有第二个角色:它是一个测试基底。因为 VirtIO 设备易于定义、易于模拟且有良好文档,它们对于为非 VirtIO 驱动程序构建受控测试场景也很有用。 -For example, suppose you are writing a driver for a physical PCI device, and you want to test how your driver handles a specific error condition. On the real hardware, reproducing the error may require a specific physical fault, which is hard to arrange. On a VirtIO-based proxy, you can implement a device that always returns the error, and test your driver's error path without touching the physical hardware. The caveat is that your driver must be loosely coupled to the specific hardware (the techniques from Chapter 29 matter here); the more the driver is split along the accessor/backend lines described there, the easier it is to test the upper layers against a synthetic backend. +例如,假设你正在为一个物理 PCI 设备编写驱动程序,你想测试驱动程序如何处理特定的错误条件。在真实硬件上,重现错误可能需要特定的物理故障,这很难安排。在基于 VirtIO 的代理上,你可以实现一个总是返回错误的设备,在不触碰物理硬件的情况下测试驱动程序的错误路径。需要注意的是,你的驱动程序必须与特定硬件松耦合(第 29 章的技术在这里很重要);驱动程序越是按照该章描述的访问器/后端方式拆分,就越容易针对合成后端测试上层代码。 -The mechanism for synthesizing VirtIO devices in user space is `bhyve`'s own pluggable emulated devices. Writing a new `bhyve` device emulator is beyond the scope of this chapter, but the relevant code lives in `/usr/src/usr.sbin/bhyve/` and is approachable if you have basic C skills. For simpler cases, using a pre-existing virtio-blk, virtio-net, or virtio-console device configured with specific parameters is often enough. +在用户空间合成 VirtIO 设备的机制是 `bhyve` 自己的可插拔模拟设备。编写新的 `bhyve` 设备模拟器超出了本章范围,但相关代码位于 `/usr/src/usr.sbin/bhyve/`,如果你有基本的 C 技能是可以入门的。对于更简单的情况,使用带有特定参数的预存 virtio-blk、virtio-net 或 virtio-console 设备通常就足够了。 -### Using Jails for Integration Testing +### 使用监狱进行集成测试 -When your driver is working and you want to verify it under container-style isolation, jails are the obvious next step. The setup is simple: create a jail with an appropriate devfs ruleset that exposes your device, and run your user-space test harness inside the jail. +当你的驱动程序可以工作并且想在容器式隔离下验证它时,jail 是显而易见的下一步。设置很简单:创建一个带有适当 devfs 规则集(暴露你的设备)的 jail,并在 jail 内运行你的用户空间测试工具。 A typical test shape: @@ -1411,128 +1411,128 @@ myjail { } ``` -Inside the jail, you run your test harness. It opens `/dev/mydev`, exercises the `ioctl`s or the `read`/`write` methods, and records results. On the host, you run the same harness and compare. If the jail-side test passes and the host-side test passes, your driver tolerates the jail environment. +在 jail 内部,你运行测试工具。它打开 `/dev/mydev`,测试 `ioctl` 或 `read`/`write` 方法,并记录结果。在主机上,你运行相同的测试工具进行比较。如果 jail 侧的测试通过且主机侧的测试也通过,你的驱动程序就能容忍 jail 环境。 -If one passes and the other does not, you have a diagnostic opportunity. Possible reasons for a divergence include: a privilege check that denies the jail call (look for `priv_check` in your driver), a device node permission the ruleset does not account for, a resource limit the host happens to avoid, or a jail-specific code path in your driver that exists by mistake. Each of these is fixable once identified. +如果一个通过而另一个没有,你就获得了一个诊断机会。产生差异的可能原因包括:一个拒绝 jail 调用的权限检查(在驱动程序中查找 `priv_check`)、规则集未考虑的设备节点权限、主机恰好避免的资源限制,或者驱动程序中错误存在的 jail 特定代码路径。每一个问题一旦识别就可以修复。 -### Using VNET Jails for Network Driver Testing +### 使用 VNET 监狱进行网络驱动程序测试 -For network drivers, the test is similar but uses VNET. Create a jail with `vnet = 1` in `jail.conf(5)`, move one end of an `epair(4)` into the jail, and run traffic between the jail and the host. If your driver is a physical network driver, you can also move the physical interface into the jail for a full-isolation test. +对于网络驱动程序,测试类似但使用 VNET。在 `jail.conf(5)` 中创建一个 `vnet = 1` 的 jail,将 `epair(4)` 的一端移入 jail,在 jail 和主机之间运行流量。如果你的驱动程序是物理网络驱动程序,也可以将物理接口移入 jail 进行完全隔离测试。 -The VNET test exercises the `if_vmove()` lifecycle: the interface is detached from the host's VNET, reattached to the jail's VNET, and eventually returned. A driver that survives this without losing state is a driver that tolerates VNET. A driver that panics, hangs, or stops delivering packets after a move has work to do. +VNET 测试锻炼 `if_vmove()` 生命周期:接口从主机的 VNET 分离,重新附加到 jail 的 VNET,最终返回。在不丢失状态的情况下存活下来的驱动程序就是能容忍 VNET 的驱动程序。在移动后 panic、挂起或停止传递数据包的驱动程序还有工作要做。 -The common failure modes in VNET testing are: +VNET 测试中常见的故障模式有: -- The driver holds a pointer to the host's ifnet or VNET across the move, and uses it from a callout after the move has happened. -- The driver's `if_init` assumes it is called in the original VNET and fails when called in the new one. -- The driver cleans up incorrectly at `if_detach`, because it does not distinguish "detach to move" from "detach to destroy". +- 驱动程序在移动过程中持有指向主机 ifnet 或 VNET 的指针,并在移动发生后从 callout 中使用它。 +- 驱动程序的 `if_init` 假设它在原始 VNET 中被调用,在新 VNET 中被调用时失败。 +- 驱动程序在 `if_detach` 时清理不正确,因为它没有区分"为移动而分离"和"为销毁而分离"。 -Each of these is diagnosable with `dtrace(1)` or kernel printfs at the right place. The first time you see a VNET-related crash, find the point in the driver where the move happens and work backward from there. +这些问题中的每一个都可以通过 `dtrace(1)` 或在正确位置的内核 printf 来诊断。第一次看到 VNET 相关崩溃时,找到驱动程序中发生移动的位置,然后从那里往回追踪。 -### Passthrough Testing +### 直通测试 -PCI passthrough is the exercise that validates your driver's detach path. Create a `bhyve(8)` guest with your device passed through, install FreeBSD inside, and load your driver there. If the driver attaches cleanly in the guest, your device setup and DMA code handle IOMMU remapping correctly. If the driver loads, the test is simple: run the driver's normal workload inside the guest. +PCI 直通是验证驱动程序分离路径的练习。创建一个直通了你的设备的 `bhyve(8)` 客户机,在其中安装 FreeBSD,并在那里加载驱动程序。如果驱动程序在客户机中干净地附加,你的设备设置和 DMA 代码能正确处理 IOMMU 重映射。如果驱动程序加载了,测试就很简单:在客户机内运行驱动程序的正常工作负载。 -The detach test is the harder one. Shut down the guest, rebind the device to its native driver on the host (by unloading `ppt(4)` from that device, if necessary, and letting the host's driver re-attach), and exercise the driver on the host. If the driver attaches cleanly after the guest has used the device and put it through whatever state changes, the driver's `DEVICE_ATTACH` is properly defensive. If it fails, look for assumptions about the device's initial state that should not be assumptions. +分离测试更难。关闭客户机,将设备重新绑定到主机上的原生驱动程序(如有必要,从该设备卸载 `ppt(4)`,让主机的驱动程序重新附加),并在主机上操作驱动程序。如果驱动程序在客户机使用过设备并将其置于各种状态后仍能干净地附加,说明驱动程序的 `DEVICE_ATTACH` 是充分防御性的。如果失败,寻找关于设备初始状态的假设,这些假设不应该存在。 -The full round-trip (host, guest, host) is the gold standard for passthrough compatibility. A driver that passes it can be handed to any administrator with confidence. +完整的往返(主机、客户机、主机)是直通兼容性的黄金标准。通过它的驱动程序可以放心地交给任何管理员。 -### Hypervisor Detection in Tests +### 测试中的虚拟机监控程序检测 -If your driver uses `vm_guest` to adjust defaults, test the adjustment. Run the driver on bare metal (if available), inside `bhyve(8)`, inside QEMU/KVM, and observe whether the defaults it picks make sense. The `kern.vm_guest` sysctl is your quick check: +如果你的驱动程序使用 `vm_guest` 调整默认值,测试这种调整。在裸金属上(如果可用)、在 `bhyve(8)` 内、在 QEMU/KVM 内运行驱动程序,观察它选择的默认值是否合理。`kern.vm_guest` sysctl 是你的快速检查: ```sh sysctl kern.vm_guest ``` -If your driver logs its environment at attach time ("attaching on bhyve host, defaulting to X"), the log makes the detection visible, which helps with debugging. Do not over-log: once at attach is usually enough. +如果你的驱动程序在附加时记录其环境("在 bhyve 主机上附加,默认为 X"),日志使检测可见,有助于调试。不要过度记录:附加时一次通常就足够了。 -### Automating the Test Suite +### 自动化测试套件 -Once the individual tests are known, the next step is to run them repeatedly as the driver evolves. FreeBSD's `kyua(1)` test runner, combined with the `atf(7)` test framework, is the standard mechanism. A test suite that includes a "bare-metal test", a "VirtIO guest test", a "VNET jail test", and a "passthrough test" covers most of what you want to verify. +一旦各个测试已知,下一步是在驱动程序演进过程中重复运行它们。FreeBSD 的 `kyua(1)` 测试运行器配合 `atf(7)` 测试框架是标准机制。包含"裸金属测试"、"VirtIO 客户机测试"、"VNET jail 测试"和"直通测试"的测试套件覆盖了你想要验证的大部分内容。 -The details of writing tests in `atf(7)` are outside this chapter; they are treated more fully in Chapter 32 (Debugging Drivers) and Chapter 33 (Testing and Validation). The point for now is that the test suite should exercise the driver across the environments it is expected to run in. A single test on bare metal proves very little about virtualisation; a suite of tests across environments proves something about portability. +在 `atf(7)` 中编写测试的细节超出了本章范围;它们在第 32 章(调试驱动程序)和第 33 章(测试与验证)中有更详细的讨论。现在的重点是测试套件应该在驱动程序预期运行的各个环境中进行测试。在裸金属上的单个测试对虚拟化几乎没有证明力;跨环境的测试套件才对可移植性有所证明。 -### Refactoring Tips Revisited +### 重温重构技巧 -In Chapter 29 we introduced a discipline for portability: accessor layers, backend abstractions, endian helpers, no hidden hardware assumptions. Virtualisation and containerisation put that discipline to the test. A driver written with clean abstractions will survive the variety of environments described in this chapter; a driver with hidden assumptions will hit them as soon as the environment changes. +在第 29 章中,我们介绍了一种可移植性的规范:访问器层、后端抽象、字节序辅助函数、没有隐藏的硬件假设。虚拟化和容器化检验了这种规范。用干净抽象编写的驱动程序能在本章描述的各种环境中存活;带有隐藏假设的驱动程序会在环境改变时立即碰到问题。 -The refactoring tips most relevant to this chapter are: +与本章最相关的重构技巧有: -- Put all register access through accessors, so the access path can be simulated or redirected in tests. -- Handle the full lifecycle: attach, detach, suspend, resume. Passthrough exercises attach and detach repeatedly; VNET exercises detach in a way the driver might not see on bare metal. -- Use `bus_dma(9)` and `bus_space(9)` correctly, never physical addresses directly. The guest-versus-host address translation under passthrough depends on correct use of these APIs. -- Use `priv_check` for privilege gating, not hardcoded uid 0 checks. Jail restrictions work correctly only if the framework is called. -- Use `CURVNET_SET` around any callout or taskqueue code that touches network-stack state. This is the one VNET-specific discipline that catches most driver authors off guard. +- 将所有寄存器访问通过访问器进行,这样访问路径可以在测试中被模拟或重定向。 +- 处理完整的生命周期:附加、分离、挂起、恢复。直通反复锻炼附加和分离;VNET 以驱动程序在裸金属上可能看不到的方式锻炼分离。 +- 正确使用 `bus_dma(9)` 和 `bus_space(9)`,永远不要直接使用物理地址。直通下的客户机与主机地址转换依赖于这些 API 的正确使用。 +- 使用 `priv_check` 进行权限门控,而不是硬编码 uid 0 检查。jail 限制只有在框架被调用时才能正确工作。 +- 在任何接触网络协议栈状态的 callout 或 taskqueue 代码周围使用 `CURVNET_SET`。这是让大多数驱动程序作者措手不及的 VNET 特定规范。 -None of these are new concepts. They are all standard FreeBSD driver practice. What this chapter adds is the context in which each one matters: which environments exercise which disciplines. Knowing that lets you prioritise when deciding what to refactor first. +这些都不是新概念。它们都是标准的 FreeBSD 驱动程序实践。本章增加的是每个规范在什么上下文中重要的背景:哪些环境锻炼哪些规范。知道这些可以让你在决定先重构什么时排列优先级。 -### A Development Order That Works +### 行之有效的开发顺序 -Putting the pieces together, here is a development order that has proven effective. +将各部分放在一起,以下是已被证明有效的开发顺序。 -1. Start in a `bhyve(8)` VM. Write the driver's basic skeleton (module hooks, probe and attach, simple I/O path). Exercise it with `kldload` and a minimal test. -2. Add the accessor layer and the backend abstraction from Chapter 29. Test that the simulation backend runs, even if the real hardware is not yet plugged in. -3. If VirtIO is the target, develop against `virtio_pci.c` in the VM. You have a real device to talk to, and you can iterate quickly. -4. If real hardware is the target, begin PCI passthrough testing when the driver reaches a stable point. The round-trip (host, guest, host) becomes part of the regular test cycle. -5. Add jail-based tests when the driver exposes user-space interfaces. Start with a single-stack jail; move to VNET if the driver is a network driver. -6. Add automation with `kyua(1)` and `atf(7)` as the test count grows. -7. When a bug is found, reproduce it in the smallest environment that shows the bug, fix it, and add a regression test at that level. +1. 在 `bhyve(8)` VM 中开始。编写驱动程序的基本骨架(模块钩子、探测和附加、简单 I/O 路径)。用 `kldload` 和最小测试来验证它。 +2. 添加第 29 章的访问器层和后端抽象。测试模拟后端能运行,即使真实硬件尚未插入。 +3. 如果 VirtIO 是目标,在 VM 中针对 `virtio_pci.c` 开发。你有一个真实的设备可以对话,可以快速迭代。 +4. 如果真实硬件是目标,当驱动程序达到稳定点时开始 PCI 直通测试。往返(主机、客户机、主机)成为常规测试周期的一部分。 +5. 当驱动程序暴露用户空间接口时添加基于 jail 的测试。从单栈 jail 开始;如果驱动程序是网络驱动程序则转向 VNET。 +6. 随着测试数量增长,用 `kyua(1)` 和 `atf(7)` 添加自动化。 +7. 发现 bug 时,在能显示 bug 的最小环境中重现它,修复它,并在该级别添加回归测试。 -This order keeps the iteration fast at the beginning (where it matters most) and adds environmental complexity only as the driver stabilises. Trying to test everything at once is a common beginner mistake; it is how projects stall. The incremental path is slower per step but much faster in aggregate. +这个顺序在开始时保持快速迭代(在最重要的地方),只在驱动程序稳定时才增加环境复杂性。试图一次测试所有东西是初学者的常见错误;这就是项目停滞的原因。增量路径每步较慢,但总体上快得多。 -### An End-to-End Example: From Bare Metal to Passthrough +### 端到端示例:从裸金属到直通 -To illustrate the workflow, here is a complete example walkthrough for a hypothetical driver called `mydev`. The driver is a PCI-based character device; it has a small register interface, uses MSI-X interrupts, and performs DMA. The development order below is condensed into a single narrative so you can see how the steps connect. +为了说明工作流程,这里有一个名为 `mydev` 的假设驱动程序的完整示例演练。该驱动程序是一个基于 PCI 的字符设备;它有一个小型寄存器接口,使用 MSI-X 中断,并执行 DMA。下面的开发顺序被浓缩为一个单一的叙述,以便你可以看到各步骤如何连接。 -Day 1: skeleton in a VM. You install a FreeBSD 14.3 guest in `bhyve(8)`, set up NFS so the source tree on your host is visible in the guest, and write the module skeleton. It is a `KMOD=mydev, SRCS=mydev.c` Makefile and a `mydev.c` with `DECLARE_MODULE`, a stub probe, a stub attach, and a stub detach. It loads and unloads cleanly. `dmesg` shows "mydev: hello" on load. +第 1 天:VM 中的骨架。你在 `bhyve(8)` 中安装 FreeBSD 14.3 客户机,设置 NFS 使主机上的源代码树在客户机中可见,并编写模块骨架。它是一个 `KMOD=mydev, SRCS=mydev.c` 的 Makefile 和一个包含 `DECLARE_MODULE`、桩探测、桩附加和桩分离的 `mydev.c`。它能干净地加载和卸载。`dmesg` 在加载时显示 "mydev: hello"。 -Day 2: accessor layer. You add the Chapter 29 accessor pattern: all register access goes through `mydev_reg_read32` and `mydev_reg_write32`, with the real backend calling `bus_read_4` and `bus_write_4`. You also add a simulation backend that stores register values in a small in-memory array. The simulation backend is selected by a module parameter. The accessor layer means the same driver can run against a real device or against the simulated backend without changes to the upper code. +第 2 天:访问器层。你添加第 29 章的访问器模式:所有寄存器访问通过 `mydev_reg_read32` 和 `mydev_reg_write32` 进行,真实后端调用 `bus_read_4` 和 `bus_write_4`。你还添加了一个在小型内存数组中存储寄存器值的模拟后端。模拟后端通过模块参数选择。访问器层意味着同一个驱动程序可以针对真实设备或模拟后端运行,而无需更改上层代码。 -Day 3: upper-layer code. You add the driver's core logic: initialisation, the character-device interface (`open`, `close`, `read`, `write`), the `ioctl` surface, and the DMA setup. The simulation backend does not model DMA, but the upper layer is structured to treat DMA through `bus_dma(9)` handles, so the code is written correctly from the start. You exercise the code through the simulation backend in a simple test program: open the device, issue `ioctl`s, verify the responses. +第 3 天:上层代码。你添加驱动程序的核心逻辑:初始化、字符设备接口(`open`、`close`、`read`、`write`)、`ioctl` 接口和 DMA 设置。模拟后端不模拟 DMA,但上层结构化地通过 `bus_dma(9)` 句柄处理 DMA,所以代码从一开始就是正确编写的。你通过模拟后端在一个简单测试程序中验证代码:打开设备、发出 `ioctl`、验证响应。 -Day 4: real hardware, passthrough setup. You have the target hardware in a workstation. You add `pptdevs` to `/boot/loader.conf`, reboot, and confirm that `ppt(4)` has claimed the device. You add `passthru` to the `bhyve(8)` guest configuration and boot the guest. Inside the guest, you load your driver. The driver attaches to the passed-through device. You have now demonstrated that the real hardware path works. +第 4 天:真实硬件、直通设置。你将目标硬件放在工作站中。你在 `/boot/loader.conf` 中添加 `pptdevs`,重启,确认 `ppt(4)` 已占用了该设备。你向 `bhyve(8)` 客户机配置添加 `passthru` 并启动客户机。在客户机内部,你加载驱动程序。驱动程序附加到直通设备。你现在已证明真实硬件路径可以工作。 -Day 5: interrupts and DMA testing. The driver receives interrupts; the MSI-X setup code works. You test DMA: a short DMA read works, a long DMA read works, a simultaneous read and write works. You find one bug: the driver programs a physical address computed incorrectly, but only for DMA regions crossing a page boundary. You fix it. Total time spent debugging: two hours, all in a VM that would have required a hard reboot of the workstation on bare metal. +第 5 天:中断和 DMA 测试。驱动程序接收中断;MSI-X 设置代码工作正常。你测试 DMA:短 DMA 读取成功,长 DMA 读取成功,同时读写成功。你发现一个 bug:驱动程序计算的物理地址不正确,但只在 DMA 区域跨越页面边界时才出现。你修复了它。总调试时间:两小时,全部在 VM 中完成,在裸金属上这会需要工作站硬重启。 -Day 6: jail test. You exit the guest, return to the host, and configure a jail that sees `/dev/mydev0`. Your test program runs inside the jail and exercises the driver exactly as it did on the host. One `ioctl` fails with `EPERM`; you look at the driver and find that you forgot to add a `priv_check` for an operation that should require privilege. You add the check, and now the jail behaves correctly (the ioctl is denied for non-privileged callers; the host's root can still run it). +第 6 天:jail 测试。你退出客户机,返回主机,配置一个能看到 `/dev/mydev0` 的 jail。你的测试程序在 jail 内运行,像在主机上一样测试驱动程序。一个 `ioctl` 以 `EPERM` 失败;你查看驱动程序发现忘记为一个需要权限的操作添加 `priv_check`。你添加了检查,现在 jail 行为正确(非特权调用者的 ioctl 被拒绝;主机的 root 仍然可以运行它)。 -Day 7: VNET test (if the driver has a network interface). You create a VNET jail and move a cloned interface into it. The interface works. You notice that one of your callouts does not set `CURVNET_SET` before accessing a per-VNET counter; you fix it. The callout now works in both the host VNET and the jail VNET without interference. +第 7 天:VNET 测试(如果驱动程序有网络接口)。你创建一个 VNET jail 并将克隆的接口移入其中。接口工作正常。你注意到一个 callout 在访问 per-VNET 计数器之前没有设置 `CURVNET_SET`;你修复了它。callout 现在在主机 VNET 和 jail VNET 中都能正常工作而没有干扰。 -Day 8: full round-trip. You destroy the jail, shut down the guest, unload `ppt(4)` from the device (or reboot without `pptdevs`), and wait for the host's driver to re-attach. The attach works cleanly. You exercise the device on the host. It works. The round trip host-guest-host is complete. +第 8 天:完整往返。你销毁 jail,关闭客户机,从设备卸载 `ppt(4)`(或不带 `pptdevs` 重启),等待主机驱动程序重新附加。附加干净完成。你在主机上操作设备。它工作正常。主机-客户机-主机的往返完成。 -This eight-day cycle is a stylised version of real development; your mileage will vary. The important point is that each day's work builds on the previous one, and the test environments become more exacting as the driver stabilises. By day eight, you have exercised the driver under every environment it will see in production, and you have fixed the bugs that each environment exposes. What remains is soak testing and user-facing polish, which are topics for Chapters 33 and 34. +这个八天周期是真实开发的一个风格化版本;你的情况会有所不同。重要的点是每天的工作建立在前一天的基础之上,测试环境随着驱动程序的稳定而变得更加严格。到第八天,你已经在驱动程序将在生产中看到的每个环境中测试了它,并修复了每个环境暴露的 bug。剩下的是浸泡测试和面向用户的打磨,这些是第 33 章和第 34 章的主题。 -### Measuring Virtualisation Overhead +### 测量虚拟化开销 -A quick note on performance. Drivers running under virtualisation sometimes show measurable overhead compared to bare metal. The sources of overhead include VM exits on I/O, interrupt delivery through the hypervisor, and DMA address translation through the IOMMU. +简单提一下性能。在虚拟化下运行的驱动程序有时会显示出相对于裸金属可测量的开销。开销来源包括 I/O 上的 VM 退出、通过虚拟机监控程序的中断投递以及通过 IOMMU 的 DMA 地址转换。 -For most drivers most of the time, the overhead is not significant. Modern hardware accelerates almost every part of the virtualisation path (posted interrupts, EPT page tables, SR-IOV), and the fraction of CPU time spent in hypervisor code is typically in the low single digits. For performance-sensitive drivers, though, measuring and understanding the overhead is essential. +对于大多数驱动程序在大多数情况下,开销并不显著。现代硬件加速了虚拟化路径的几乎每个部分(通知中断、EPT 页表、SR-IOV),虚拟机监控程序代码消耗的 CPU 时间比例通常在低个位数。但对于性能敏感的驱动程序,测量和理解开销是必不可少的。 -The tools for measurement are the same ones you use in other performance work. `pmcstat(8)` samples hardware counters, including counters for VM exits and for translation-lookaside-buffer misses that the IOMMU may cause. `dtrace(1)` can trace specific kernel paths, and with the `fbt` provider you can measure how often each path is entered and how long it takes. `vmstat -i` shows interrupt rates. +测量工具与你在其他性能工作中使用的相同。`pmcstat(8)` 采样硬件计数器,包括 VM 退出计数器和 IOMMU 可能导致的 TLB 未命中计数器。`dtrace(1)` 可以追踪特定内核路径,使用 `fbt` 提供者可以测量每个路径被进入的频率和耗时。`vmstat -i` 显示中断速率。 -For VirtIO drivers, the most common source of overhead is excessive notifications. Every `virtqueue_notify` potentially causes a VM exit, and a driver that notifies on every packet rather than coalescing can generate hundreds of thousands of exits per second. The `VIRTIO_F_RING_EVENT_IDX` feature, if negotiated, lets the guest and host cooperate to reduce notification frequency. Check that your driver negotiates this feature if it runs in a high-packet-rate path. +对于 VirtIO 驱动程序,最常见的开销来源是过多的通知。每次 `virtqueue_notify` 可能导致一次 VM 退出,在每个包都通知而不是合并的驱动程序可以产生每秒数十万次退出。如果协商了 `VIRTIO_F_RING_EVENT_IDX` 特性,客户机和主机可以合作减少通知频率。如果你的驱动程序运行在高包率路径中,请检查它是否协商了此特性。 -For passthrough drivers, the most common source of overhead is IOMMU translation misses. Each DMA buffer must be walked through the IOMMU's page tables, and a driver that maps and unmaps buffers many times per second spends a lot of CPU on that. The fix is usually to keep DMA mappings alive for longer (using `bus_dma(9)`'s mapping-retention features) rather than map-and-unmap every transaction. +对于直通驱动程序,最常见的开销来源是 IOMMU 转换未命中。每个 DMA 缓冲区必须遍历 IOMMU 的页表,每秒多次映射和取消映射缓冲区的驱动程序会在上面花费大量 CPU。修复通常是让 DMA 映射存活更长时间(使用 `bus_dma(9)` 的映射保留功能),而不是每个事务都映射和取消映射。 -Performance tuning is a whole chapter of its own (Chapter 34). For now, the takeaway is that virtualisation has measurable costs, those costs are usually small, and the standard FreeBSD tooling applies without modification. +性能调优本身就可以写成完整的一章(第 34 章)。目前,要点是虚拟化有可测量的成本,这些成本通常很小,标准的 FreeBSD 工具无需修改即可使用。 ### 总结 -A driver that runs correctly under virtualisation and containerisation is not the result of special virtualisation code. It is the result of standard FreeBSD driver discipline, exercised in environments that expose hidden assumptions. The test and development workflow in this section is the practical side of that discipline: a VM for fast iteration, VirtIO for a controlled test substrate, jails for privilege and visibility checks, VNET for network-stack testing, passthrough for hardware round-trips, and automation to keep the whole thing honest. +在虚拟化和容器化下正确运行的驱动程序不是特殊虚拟化代码的结果。它是标准 FreeBSD 驱动程序规范在暴露隐藏假设的环境中实践的结果。本节中的测试和开发工作流是这种规范的实践面:用于快速迭代的 VM、用于受控测试基底的 VirtIO、用于权限和可见性检查的 jail、用于网络协议栈测试的 VNET、用于硬件往返的直通,以及用于保持一切诚实的自动化。 -With the conceptual and practical material in place, the rest of the chapter turns to hands-on labs that let you try these techniques yourself. Before we get there, two more sections complete the picture. Section 9 covers the quieter but equally important topics of time, memory, and interrupt handling under virtualisation, the areas where beginner drivers often fail in subtle ways that only manifest in a VM. Section 10 widens the lens to architectures beyond amd64, because FreeBSD on arm64 and riscv64 is increasingly common and the virtualisation story there has its own shape. After those two sections, we move into the labs. +概念性和实践性材料都已就位,本章的其余部分转向让你自己尝试这些技术的动手实验。在此之前,还有两节来完成全景。第 9 节涵盖虚拟化下更安静但同样重要的话题——时间、内存和中断处理,这是初学者驱动程序经常以微妙方式失败、只在 VM 中表现出来的领域。第 10 节将视角扩大到 amd64 之外的架构,因为 FreeBSD 在 arm64 和 riscv64 上越来越普遍,那里的虚拟化故事有它自己的形态。在这两节之后,我们进入实验部分。 ## 第9节:虚拟化下的时间管理、内存与中断处理 -So far the chapter has concentrated on devices, the visible artefacts that a driver binds to and talks to. But a driver also depends on three ambient services that the kernel provides transparently: time, memory, and interrupts. Under virtualisation, all three change in subtle ways that rarely break a driver outright but often make it behave strangely. A driver that ignores these differences will usually pass functional tests and then fail in production when a user notices that timeouts are wrong, throughput is lower than expected, or interrupts are being lost. This section gathers what every driver author should know. +到目前为止,本章集中在设备上——驱动程序绑定并与之通信的可见制品。但驱动程序还依赖于内核透明提供的三个环境服务:时间、内存和中断。在虚拟化下,这三者都发生了微妙的变化,这些变化很少直接破坏驱动程序,但经常使其行为变得奇怪。忽略这些差异的驱动程序通常会通过功能测试,然后当用户注意到超时不正确、吞吐量低于预期或中断丢失时在生产环境中失败。本节汇集了每个驱动程序作者应该知道的内容。 -### Why Time Is Different Inside a VM +### 为什么虚拟机内的时间不同 -On bare metal, the kernel has direct access to several hardware time sources. The TSC (time-stamp counter) reads a per-CPU cycle counter; the HPET (high-precision event timer) provides a system-wide counter; the ACPI PM timer provides a lower-frequency fallback. The kernel chooses one as the current `timecounter(9)` source, wraps it in a small API, and uses it to derive `getbintime`, `getnanotime`, and friends. +在裸金属上,内核可以直接访问几个硬件时间源。TSC(时间戳计数器)读取每 CPU 周期计数器;HPET(高精度事件定时器)提供系统范围的计数器;ACPI PM 定时器提供较低频率的后备。内核选择一个作为当前 `timecounter(9)` 源,将其包装在一个小型 API 中,并使用它来派生 `getbintime`、`getnanotime` 等。 -Inside a VM, those same sources exist, but they are emulated or passed through, and each has its own quirks. The TSC, which is normally the best source, can become unreliable when the VM migrates between physical hosts, when the host's TSCs are unsynchronised, or when the hypervisor rate-limits the guest in ways that cause TSC skew. The HPET is emulated and costs a VM exit on every read, which is cheap for occasional use but expensive if a driver reads it in a tight loop. The ACPI PM timer is generally reliable but slow. +在 VM 内,这些相同的源也存在,但它们是被模拟或直通的,每个都有自己的怪癖。TSC 通常是最佳源,但当 VM 在物理主机之间迁移时、当主机的 TSC 不同步时或当虚拟机监控程序以导致 TSC 偏移的方式限制客户机时,它可能变得不可靠。HPET 是模拟的,每次读取都会产生 VM 退出,偶尔使用很廉价,但如果驱动程序在紧密循环中读取它就很昂贵。ACPI PM 定时器通常可靠但很慢。 -To address this, major hypervisors expose *paravirtual* clock interfaces. Linux popularised the term `kvm-clock` for the KVM paravirtual clock; Xen has `xen-clock`; VMware has `vmware-clock`; Microsoft's Hyper-V has `hyperv_tsc`. Each of these is a small protocol by which the hypervisor publishes time information in a shared memory page that the guest can read without a VM exit. FreeBSD supports several of them. You can see which the kernel has chosen as follows. +为了解决这个问题,主要虚拟机监控程序暴露了*半虚拟化*时钟接口。Linux 推广了 `kvm-clock` 这个术语用于 KVM 半虚拟时钟;Xen 有 `xen-clock`;VMware 有 `vmware-clock`;微软的 Hyper-V 有 `hyperv_tsc`。每一个都是一个小型协议,虚拟机监控程序在共享内存页中发布时间信息,客户机无需 VM 退出即可读取。FreeBSD 支持其中几个。你可以看到内核选择了哪个。 ```sh % sysctl kern.timecounter.choice @@ -1542,17 +1542,17 @@ kern.timecounter.choice: ACPI-fast(900) i8254(0) TSC-low(1000) dummy(-1000000) kern.timecounter.hardware: TSC-low ``` -On a guest under bhyve, the kernel may select `TSC-low` or one of the paravirtual options depending on the CPU flags the hypervisor advertises. The important point is that the choice is automatic and the `timecounter(9)` API is the same regardless. +在 bhyve 下的客户机中,内核可能选择 `TSC-low` 或一个半虚拟化选项,取决于虚拟机监控程序播发的 CPU 标志。重要的点是选择是自动的,无论选择什么,`timecounter(9)` API 都是相同的。 -### What This Means for Drivers +### 这对驱动程序意味着什么 -For a driver that only uses the high-level time APIs (`getbintime`, `ticks`, `callout`), nothing needs to change. The `timecounter(9)` abstraction shields you from the underlying details. The driver asks "what time is it" or "how many ticks have elapsed" and the kernel answers correctly, whether on bare metal or in a VM. +对于只使用高级时间 API(`getbintime`、`ticks`、`callout`)的驱动程序,不需要改变任何东西。`timecounter(9)` 抽象使你免受底层细节的影响。驱动程序询问"现在几点"或"经过了多少 tick",内核无论是裸金属还是 VM 都正确回答。 -Problems arise when a driver bypasses the abstraction and reads time sources directly. A driver that does `rdtsc()` inline and uses the result for timing will be wrong under virtualisation whenever the host's TSC changes (for example, during a live migration). A driver that spins on a device register with a timeout measured in CPU cycles will consume excessive CPU inside a VM where one "CPU cycle" is not a predictable unit. +当驱动程序绕过抽象直接读取时间源时会出现问题。一个内联执行 `rdtsc()` 并使用结果进行计时的驱动程序在虚拟化下每当主机 TSC 改变时(例如在实时迁移期间)都会出错。一个以 CPU 周期为超时单位在设备寄存器上自旋的驱动程序在 VM 内会消耗过多的 CPU,因为一个"CPU 周期"不是一个可预测的单位。 -The cure is simple: use the kernel's time primitives. `DELAY(9)` for short, bounded waits. `pause(9)` for yields that can sleep. `callout(9)` for deferred work. `getbintime(9)` or `getsbinuptime(9)` for clock readings. Each of these is correct under virtualisation because the kernel has already adapted to the environment. +解决方案很简单:使用内核的时间原语。`DELAY(9)` 用于短暂的、有界的等待。`pause(9)` 用于可以睡眠的让步。`callout(9)` 用于延迟工作。`getbintime(9)` 或 `getsbinuptime(9)` 用于时钟读取。这些中的每一个在虚拟化下都是正确的,因为内核已经适应了环境。 -A concrete pattern that breaks in VMs and is surprisingly common is the "reset and wait" sequence. +在 VM 中会出问题的一个具体模式是"复位并等待"序列,这个模式出奇地常见。 ```c /* Broken pattern: busy-wait without yielding. */ @@ -1563,9 +1563,9 @@ for (i = 0; i < 1000000; i++) { } ``` -On bare metal, this loop might complete in a few microseconds because the device clears the status bit quickly. In a VM, the bus read and write each cost a VM exit, and the loop body runs much slower because every iteration makes a round trip through the hypervisor. The 1,000,000 iteration bound, which is instant on bare metal, can become a multi-second hang inside a VM. Worse, during a VM pause (a live migration), the guest does not execute at all, and the timeout loses its meaning. +在裸金属上,这个循环可能在几微秒内完成,因为设备快速清除状态位。在 VM 中,每次总线读写都会产生一次 VM 退出,循环体运行慢得多,因为每次迭代都要经过虚拟机监控程序往返。1,000,000 次迭代上限在裸金属上是瞬时的,在 VM 内可能变成持续数秒的挂起。更糟的是,在 VM 暂停期间(实时迁移),客户机根本不执行,超时就失去了意义。 -The corrected pattern uses `DELAY(9)` and a bounded real-time wait. +修正后的模式使用 `DELAY(9)` 和有界的实时等待。 ```c /* Correct pattern: bounded wait with DELAY and a wallclock timeout. */ @@ -1579,15 +1579,15 @@ if (i == RESET_TIMEOUT_MS) return (ETIMEDOUT); ``` -`DELAY(9)` is calibrated against the kernel's time source, so it sleeps for the intended number of microseconds regardless of how fast or slow the CPU is executing at that moment. The loop's bound is now expressed in milliseconds, which is meaningful in both bare-metal and virtualised environments. +`DELAY(9)` 根据内核的时间源校准,所以无论当时 CPU 执行快慢,它都会休眠预期的微秒数。循环的上限现在以毫秒表示,这在裸金属和虚拟化环境中都有意义。 -### Callouts and Timers Across Migration +### 迁移期间的 Callout 与定时器 -A more subtle concern is what happens to a driver's callouts when the VM pauses. If a callout was scheduled to fire in 100 ms and the VM is paused for 5 seconds (during a live migration, for example), does the callout fire 5.1 seconds after it was scheduled, or 100 ms after the VM resumes? +一个更微妙的问题是当 VM 暂停时驱动程序的 callout 会发生什么。如果一个 callout 被调度在 100 ms 后触发,而 VM 暂停了 5 秒(例如在实时迁移期间),callout 是在调度后 5.1 秒触发,还是在 VM 恢复后 100 ms 触发? -The answer is that it depends on the clock source the `callout(9)` subsystem uses. `callout` uses `sbt` (signed binary time), which under normal circumstances is derived from the selected `timecounter`. For hypervisors that pause the guest's virtual TSC during migration, the callout behaves as if no time had passed during the pause; the 100 ms wait is 100 ms of guest-observed time, which may be 5.1 seconds of wallclock time. For hypervisors that do not pause the virtual TSC, the callout fires at the scheduled wallclock time, which may be "immediately" after the VM resumes. +答案取决于 `callout(9)` 子系统使用的时钟源。`callout` 使用 `sbt`(有符号二进制时间),在正常情况下从选定的 `timecounter` 派生。对于在迁移期间暂停客户机虚拟 TSC 的虚拟机监控程序,callout 的行为就像暂停期间没有时间过去一样;100 ms 的等待是客户机观察到的 100 ms 时间,实际可能是 5.1 秒的挂钟时间。对于不暂停虚拟 TSC 的虚拟机监控程序,callout 在调度的挂钟时间触发,可能在 VM 恢复后"立即"触发。 -For most drivers, either behaviour is acceptable. The callout eventually fires and the code it triggers runs. But a driver that measures real-world time (for example, a driver that talks to a hardware device whose state depends on wallclock time) may need to re-sync after a resume. FreeBSD's suspend-and-resume infrastructure provides `DEVMETHOD(device_resume, ...)`, and a driver can detect a resume and take corrective action. +对于大多数驱动程序,两种行为都是可接受的。callout 最终会触发,它触发的代码会运行。但是测量现实世界时间的驱动程序(例如,与硬件设备对话的驱动程序,其状态取决于挂钟时间)可能需要在恢复后重新同步。FreeBSD 的挂起和恢复基础设施提供 `DEVMETHOD(device_resume, ...)`,驱动程序可以检测恢复并采取纠正措施。 ```c static int @@ -1608,43 +1608,43 @@ mydrv_resume(device_t dev) } ``` -`bhyve(8)` supports guest suspend through its own suspend interface (on hypervisors that implement it); the kernel delivers a normal `device_resume` method call on wake-up. A driver that writes `device_resume` correctly works in both cases. +`bhyve(8)` 通过自己的挂起接口(在实现它的虚拟机监控程序上)支持客户机挂起;内核在唤醒时传递正常的 `device_resume` 方法调用。正确编写 `device_resume` 的驱动程序在两种情况下都能工作。 -### Memory Pressure, Ballooning, and Pinned Buffers +### 内存压力、气球与固定缓冲区 -Drivers that own DMA buffers or pinned memory have a relationship with the memory subsystem that changes under virtualisation. On bare metal, the physical memory the kernel sees is the memory actually installed in the machine. Inside a VM, the guest's "physical" memory is virtual from the host's point of view: it is backed by host RAM plus possibly swap, and its extent can change during the guest's lifetime. +拥有 DMA 缓冲区或固定内存的驱动程序与内存子系统的关系在虚拟化下会发生变化。在裸金属上,内核看到的物理内存是实际安装在机器中的内存。在 VM 内,客户机的"物理"内存从主机的角度看是虚拟的:它由主机 RAM 加上可能的交换空间支持,其范围可以在客户机的生命周期内改变。 -The `virtio-balloon` device is the mechanism hypervisors use to reclaim memory from a guest that is not using it. When the host needs memory, it asks the guest to "inflate" its balloon, which allocates pages from the guest kernel's free pool and declares them unusable. Those pages can then be unmapped from the guest and reused by the host. Conversely, when the host has memory to spare, it can "deflate" the balloon and return pages to the guest. +`virtio-balloon` 设备是虚拟机监控程序用来从未使用内存的客户机回收内存的机制。当主机需要内存时,它要求客户机"膨胀"其气球,这会从客户机内核的空闲池中分配页面并声明它们不可用。这些页面然后可以从客户机取消映射并被主机重用。相反,当主机有富余内存时,它可以"缩小"气球并将页面返回给客户机。 -FreeBSD has a `virtio_balloon` driver (in `/usr/src/sys/dev/virtio/balloon/virtio_balloon.c`) that participates in this protocol. For most drivers, this is invisible: the balloon takes from the general free pool, so only drivers that pin significant amounts of memory can be affected. If your driver allocates a 256 MB DMA buffer and pins it (for a frame buffer, for example), the balloon cannot reclaim that memory. This is the correct behaviour for a pinned buffer, but it does mean that a VM running your driver cannot shrink its memory footprint as much as a VM with only non-pinning drivers. +FreeBSD 有一个 `virtio_balloon` 驱动程序(在 `/usr/src/sys/dev/virtio/balloon/virtio_balloon.c` 中)参与此协议。对于大多数驱动程序,这是不可见的:气球从通用空闲池中获取,所以只有固定大量内存的驱动程序才会受到影响。如果你的驱动程序分配了 256 MB 的 DMA 缓冲区并固定它(例如作为帧缓冲区),气球无法回收该内存。这对固定缓冲区来说是正确的行为,但这确实意味着运行你的驱动程序的 VM 不能像只运行非固定驱动程序的 VM 那样大幅缩减其内存占用。 -A pragmatic guideline: avoid allocating more pinned memory than you absolutely need. For buffers that can be allocated on demand, allocate them on demand. For buffers that must be resident, size them to a reasonable working-set bound rather than a pessimistic maximum. The balloon driver will return the rest to the host when it needs to. +一个实用指南:避免分配超过你绝对需要的固定内存。对于可以按需分配的缓冲区,按需分配。对于必须驻留的缓冲区,将其大小调整为合理的工作集边界而不是悲观的最大值。气球驱动程序会在需要时将其余内存返回给主机。 -### Memory Hotplug +### 内存热插拔 -Some hypervisors (including bhyve with appropriate support) can hot-add memory to a running guest. FreeBSD handles this through ACPI events and the generic hotplug machinery. Drivers that cache memory information at attach time must be prepared for that cache to become stale when hotplug occurs; the robust pattern is to re-read the information when needed rather than caching it indefinitely. +一些虚拟机监控程序(包括适当支持的 bhyve)可以向运行中的客户机热添加内存。FreeBSD 通过 ACPI 事件和通用热插拔机制处理此操作。在附加时缓存内存信息的驱动程序必须准备好当热插拔发生时缓存会过期;健壮的模式是在需要时重新读取信息,而不是无限期缓存。 -Hot-removal of memory is rarer and more delicate. For driver authors, it is usually enough to note that if a driver owns pinned memory, the hypervisor cannot remove it; if the driver owns unpinned memory, the kernel's memory management handles relocation. Drivers that violate this (by expecting that physical addresses they have read from the kernel remain valid forever) will break under memory hot-removal. The fix is to go through `bus_dma(9)` for every physical address that gets programmed into hardware, not to cache physical addresses outside of a DMA map. +内存热移除更罕见也更微妙。对于驱动程序作者来说,通常只需注意:如果驱动程序拥有固定内存,虚拟机监控程序无法移除它;如果驱动程序拥有未固定内存,内核的内存管理处理重定位。违反此规则的驱动程序(期望从内核读取的物理地址永远有效)会在内存热移除下出错。修复方法是通过 `bus_dma(9)` 处理每个被编程到硬件中的物理地址,而不是在 DMA 映射之外缓存物理地址。 -### DMA and the IOMMU Path +### DMA 与 IOMMU 路径 -We covered IOMMU in Section 5 from the host's perspective. Here, from the driver's perspective, there are two practical consequences. +我们在第 5 节从主机角度讨论了 IOMMU。这里从驱动程序的角度看,有两个实际后果。 -First, every address programmed into hardware must come from a `bus_dma(9)` load operation. Under bare metal without an IOMMU, a driver that programs a physical address obtained from `vmem_alloc` or a similar interface usually works, because physical-equals-bus in that environment. Under passthrough with an IOMMU, the bus address the device needs is not the physical address; it is the IOMMU-mapped address, which `bus_dma_load` computes. A driver that programs physical addresses directly will transfer data to or from the wrong memory, sometimes corrupting unrelated data. +首先,每个编程到硬件中的地址必须来自 `bus_dma(9)` 的加载操作。在没有 IOMMU 的裸金属上,编程从 `vmem_alloc` 或类似接口获得的物理地址的驱动程序通常可以工作,因为在那个环境中物理地址等于总线地址。在带 IOMMU 的直通下,设备需要的总线地址不是物理地址;而是 IOMMU 映射的地址,由 `bus_dma_load` 计算。直接编程物理地址的驱动程序会将数据传输到或来自错误的内存,有时会损坏无关数据。 -Second, `bus_dma` mappings have lifetimes. A typical pattern is to allocate a DMA tag at attach, allocate a DMA map per buffer, load the buffer, program the device, wait for completion, and then unload the buffer. The load and unload each cost a small amount of CPU, and under the IOMMU they also cost an IOMMU invalidation. For drivers that cycle through many small buffers per second, the invalidation cost can become significant. +其次,`bus_dma` 映射有生命周期。典型模式是在附加时分配 DMA 标签,为每个缓冲区分配 DMA 映射,加载缓冲区,编程设备,等待完成,然后卸载缓冲区。每次加载和卸载都消耗少量 CPU,在 IOMMU 下还需要一次 IOMMU 失效操作。对于每秒循环使用许多小缓冲区的驱动程序,失效成本可能变得显著。 -The fix, when it applies, is to keep DMA mappings alive for longer. `bus_dma` supports pre-allocated maps that can be reused; a driver that needs to DMA into the same physical region repeatedly can load it once and reuse the bus address until the region is no longer needed. This is a standard optimisation and is entirely orthogonal to virtualisation, but it matters more under passthrough because the IOMMU work is bigger than the host-to-bus work on bare metal. +当适用时,修复方法是让 DMA 映射存活更长时间。`bus_dma` 支持可重用的预分配映射;需要重复 DMA 到同一物理区域的驱动程序可以加载一次并重用总线地址,直到该区域不再需要。这是一种标准优化,与虚拟化完全正交,但在直通下更重要,因为 IOMMU 工作比裸金属上的主机到总线工作更大。 -### Interrupt Delivery in Virtualised Environments +### 虚拟化环境中的中断投递 -Interrupts have always been the sharp edge of driver design, and under virtualisation they become sharper. The two interrupt styles a driver encounters are *INTx* (pin-based) and *MSI/MSI-X* (message-signalled). +中断一直是驱动程序设计中最尖锐的边缘,在虚拟化下它们变得更尖锐。驱动程序遇到的两种中断风格是 *INTx*(基于引脚)和 *MSI/MSI-X*(消息信号)。 -INTx is the old-style interrupt pin. In a real machine, the pin connects through the PCI bus and an interrupt controller (APIC, IOAPIC) to the CPU. In a VM, each INTx delivery requires the hypervisor to intercept the device's pin assertion, map it to an internal interrupt, and inject it into the guest. The intercept and injection both cost VM exits. For low-rate interrupts (the classic "something happened" signal) this is fine. For high-rate interrupts, it can be a bottleneck. +INTx 是旧式的中断引脚。在真实机器中,引脚通过 PCI 总线和中断控制器(APIC、IOAPIC)连接到 CPU。在 VM 中,每次 INTx 投递需要虚拟机监控程序拦截设备的引脚断言、将其映射到内部中断并注入到客户机。拦截和注入都消耗 VM 退出。对于低速率中断(经典的"发生了某事"信号),这没问题。对于高速率中断,它可能成为瓶颈。 -MSI (Message-Signalled Interrupts) and its successor MSI-X avoid the pin entirely. The device writes a small message to a well-known memory-mapped address, and the interrupt controller delivers the corresponding interrupt vector. Under virtualisation, MSI-X works much better than INTx because the hypervisor can map the message write directly to a guest interrupt without needing to intercept every edge transition on a virtual pin. Modern hardware supports *posted interrupts*, which let the hypervisor deliver MSI-X interrupts to a running vCPU without any VM exit at all. +MSI(消息信号中断)及其后继者 MSI-X 完全避免了引脚。设备向一个已知的内存映射地址写入一个小消息,中断控制器投递相应的中断向量。在虚拟化下,MSI-X 比 INTx 工作得更好,因为虚拟机监控程序可以将消息写入直接映射到客户机中断,而不需要拦截虚拟引脚上的每个边沿转换。现代硬件支持*投递中断*,让虚拟机监控程序可以将 MSI-X 中断投递到正在运行的 vCPU 而完全不需要 VM 退出。 -The driver-side implication is clear: prefer MSI-X. FreeBSD's `pci_alloc_msix` API lets a driver request MSI-X interrupts. Most modern drivers already use it. If you are writing a new driver or updating an old one, use MSI-X unless you have a specific reason not to. +驱动程序侧的暗示很清楚:优先使用 MSI-X。FreeBSD 的 `pci_alloc_msix` API 让驱动程序请求 MSI-X 中断。大多数现代驱动程序已经使用它。如果你正在编写新的驱动程序或更新旧的,除非有特定原因,否则使用 MSI-X。 ```c static int @@ -1679,19 +1679,19 @@ mydrv_setup_msix(struct mydrv_softc *sc) } ``` -This is the standard MSI-X setup sequence. The `pci_alloc_msix` call negotiates with the kernel's PCI layer to allocate one MSI-X vector. The resource and interrupt handler are set up as usual. The cleanup path releases the MSI-X vector along with the other resources. +这是标准的 MSI-X 设置序列。`pci_alloc_msix` 调用与内核的 PCI 层协商分配一个 MSI-X 向量。资源和中断处理程序照常设置。清理路径与其他资源一起释放 MSI-X 向量。 -For drivers with multiple queues or multiple event sources, MSI-X supports up to 2048 vectors per device, and a driver can allocate one per queue to avoid lock contention. The `pci_alloc_msix` API supports requesting multiple vectors; `count` is an in-out parameter. Under virtualisation, each vector maps to a separate guest interrupt, and posted interrupts deliver them with no VM exit on modern hardware. +对于具有多个队列或多个事件源的驱动程序,MSI-X 支持每个设备最多 2048 个向量,驱动程序可以为每个队列分配一个以避免锁竞争。`pci_alloc_msix` API 支持请求多个向量;`count` 是一个输入输出参数。在虚拟化下,每个向量映射到一个独立的客户机中断,通知中断在现代硬件上无需 VM 退出即可投递。 ### Interrupt Coalescing and Notification Suppression -Even with MSI-X, an interrupt-per-transaction model can be too expensive under virtualisation. A high-rate device that fires an interrupt for every received packet can generate hundreds of thousands of interrupts per second, and although each is cheap individually, the aggregate cost is noticeable. +即使使用 MSI-X,每个事务一次中断的模型在虚拟化下也可能过于昂贵。对每个接收的包都触发中断的高速率设备可以产生每秒数十万次中断,虽然每次中断单独来看很廉价,但总成本是明显的。 -Hardware interrupt coalescing addresses this on real devices: the device can be configured to deliver one interrupt for a batch of events rather than one per event. Under VirtIO, the equivalent mechanism is *notification suppression*, exposed through the `VIRTIO_F_RING_EVENT_IDX` feature. +硬件中断合并在真实设备上解决了这个问题:设备可以配置为对一批事件传递一次中断而不是每个事件一次。在 VirtIO 中,等价的机制是*通知抑制*,通过 `VIRTIO_F_RING_EVENT_IDX` 特性暴露。 -With event indexes, the guest tells the device "do not interrupt me until you have processed up to descriptor N", and the device honours this by checking the guest's used_event field before raising an interrupt. A guest that is already polling the ring does not need an interrupt at all; a guest that wants to be interrupted only after a batch can set the event index to the batch size. +使用事件索引时,客户机告诉设备"在处理到描述符 N 之前不要中断我",设备通过在引发中断前检查客户机的 used_event 字段来遵守这一点。已经在轮询环的客户机根本不需要中断;只想在一批完成后被中断的客户机可以将事件索引设置为批量大小。 -FreeBSD's `virtqueue(9)` framework supports event indexes when negotiated. A driver that knows it may process multiple buffers per interrupt can enable event indexes to reduce interrupt rate. The classic pattern is: +FreeBSD 的 `virtqueue(9)` 框架在协商后支持事件索引。知道自己可能每次中断处理多个缓冲区的驱动程序可以启用事件索引来降低中断率。经典模式是: ```c static void @@ -1713,148 +1713,148 @@ mydrv_intr(void *arg) } ``` -The `virtqueue_disable_intr` call tells the device not to interrupt again until re-enabled. The driver then drains the ring. The `virtqueue_enable_intr` call arms interrupts, but only if no new buffer has arrived in the meantime; if one has, it returns nonzero and the loop continues. This is a standard pattern that minimises interrupt rate without ever missing a completion. +`virtqueue_disable_intr` 调用告诉设备在重新启用前不要再次中断。驱动程序然后排空环。`virtqueue_enable_intr` 调用启用中断,但仅在此期间没有新缓冲区到达时;如果有,它返回非零值,循环继续。这是一种最小化中断率而不遗漏任何完成的标准模式。 ### Putting the Pieces Together -Time, memory, and interrupts are not glamorous topics, but they are where the rubber meets the road for drivers that want to be correct under virtualisation. The guidelines distil to a small set of disciplines: +时间、内存和中断不是引人注目的话题,但它们是希望在虚拟化下正确工作的驱动程序真正面对挑战的地方。这些指南浓缩为一小组规范: -- Use the kernel's time APIs rather than rolling your own. -- Treat the device's state as a thing that can disappear on resume; write `device_resume` correctly. -- Do not pin more memory than necessary, and go through `bus_dma(9)` for every DMA address. -- Prefer MSI-X over INTx. -- Use the virtqueue event-index mechanism where appropriate to reduce interrupt rate. +- 使用内核的时间 API 而不是自己实现。 +- 将设备状态视为可能在恢复时消失的东西;正确编写 `device_resume`。 +- 不要固定超过必要的内存,每个 DMA 地址都通过 `bus_dma(9)` 处理。 +- 优先使用 MSI-X 而非 INTx。 +- 在适当的地方使用虚拟队列事件索引机制来降低中断率。 -These are the disciplines of any well-written driver; under virtualisation they are not optional. A driver that follows them will work in a VM. A driver that violates them will work on bare metal and fail in the field on a customer's VM, sometimes in ways that are difficult to reproduce. +这些是任何编写良好的驱动程序的规范;在虚拟化下它们不是可选的。遵循它们的驱动程序会在 VM 中工作。违反它们的驱动程序会在裸金属上工作但在客户的 VM 上失败,有时以难以重现的方式失败。 -With that grounding in place, we can zoom out one more time and look at how these ideas travel to architectures other than amd64. +有了这些基础,我们可以再一次放大视角,看看这些想法如何适用于 amd64 之外的架构。 ## 第10节:其他架构上的虚拟化 -FreeBSD runs well on amd64, arm64, and riscv64. The virtualisation story on amd64 is the one we have been telling: `bhyve(8)` uses Intel VT-x or AMD-V, guests see PCI-based VirtIO devices, the IOMMU is VT-d or AMD-Vi, and the general flow is familiar. On the other architectures, the pieces are similar but the specifics differ. For a driver author, most of this is invisible, because FreeBSD's virtualisation APIs are architecture-independent. But a few practical points are worth knowing, and a few drivers have architecture-specific behaviour that only surfaces under virtualisation. +FreeBSD 在 amd64、arm64 和 riscv64 上运行良好。amd64 上的虚拟化方案是我们一直在讲述的:`bhyve(8)` 使用 Intel VT-x 或 AMD-V,客户机看到基于 PCI 的 VirtIO 设备,IOMMU 是 VT-d 或 AMD-Vi,总体流程是熟悉的。在其他架构上,各个部分类似但具体细节不同。对于驱动程序作者来说,大部分是不可见的,因为 FreeBSD 的虚拟化 API 是架构无关的。但一些实用要点值得了解,一些驱动程序具有只在虚拟化下才会显现的架构特定行为。 -### arm64 Virtualisation +### arm64 虚拟化 -On arm64, the hypervisor mode is called *EL2* (Exception Level 2), and the virtualisation extensions are part of the architecture's standard specification (ARMv8-A virtualisation). A guest runs in EL1 under the hypervisor in EL2. There is no direct amd64-style INTx; the interrupt controller is the *GICv3* (Generic Interrupt Controller version 3), and interrupt virtualisation is provided by the GIC's *virtual CPU interface*. +在 arm64 上,虚拟机监控程序模式称为 *EL2*(异常级别 2),虚拟化扩展是架构标准规范的一部分(ARMv8-A 虚拟化)。客户机在虚拟机监控程序的 EL2 下的 EL1 中运行。没有直接的 amd64 风格 INTx;中断控制器是 *GICv3*(通用中断控制器版本 3),中断虚拟化由 GIC 的*虚拟 CPU 接口*提供。 -FreeBSD has an arm64 `bhyve(8)` host-side port under development that targets a future release; as of FreeBSD 14.3 the vmm implementation ships only for amd64, so arm64 hosts do not yet run guests natively. The guest side of FreeBSD, however, already uses the same `virtio_mmio` and `virtio_pci` transports that amd64 does, so a FreeBSD guest running on an arm64 hypervisor (for example, KVM or a future arm64 `bhyve`) does not know or care that the host is arm64. +FreeBSD 有一个 arm64 `bhyve(8)` 主机侧移植正在开发中,目标是一个未来版本;截至 FreeBSD 14.3,vmm 实现仅随 amd64 提供,因此 arm64 主机还不能原生运行客户机。然而,FreeBSD 的客户机侧已经使用了与 amd64 相同的 `virtio_mmio` 和 `virtio_pci` 传输,所以在 arm64 虚拟机监控程序(例如 KVM 或未来的 arm64 `bhyve`)上运行的 FreeBSD 客户机不知道也不关心主机是 arm64。 -For VirtIO specifically, arm64 guests more often use the MMIO transport. This is a practical consequence of how the virtual platforms are typically configured: arm64 hypervisors often expose VirtIO devices as MMIO regions rather than as emulated PCI buses. FreeBSD's `virtio_mmio.c` (in `/usr/src/sys/dev/virtio/mmio/`) provides the transport. A driver that uses `VIRTIO_DRIVER_MODULE` is automatically compatible with both transports, because the macro registers the driver with both `virtio_mmio` and `virtio_pci`. +对于 VirtIO 来说,arm64 客户机更常使用 MMIO 传输。这是虚拟平台通常配置方式的实际结果:arm64 虚拟机监控程序通常将 VirtIO 设备暴露为 MMIO 区域而不是模拟 PCI 总线。FreeBSD 的 `virtio_mmio.c`(在 `/usr/src/sys/dev/virtio/mmio/` 中)提供了传输层。使用 `VIRTIO_DRIVER_MODULE` 的驱动程序自动兼容两种传输,因为该宏同时在 `virtio_mmio` 和 `virtio_pci` 上注册驱动程序。 -This is one of the quiet wins of the `virtio_bus` design. A VirtIO driver written once runs across every VirtIO transport on every architecture that FreeBSD supports. No `#ifdef __amd64__` clauses, no per-architecture translation layer. The `virtio_bus` abstracts the transport; the driver talks to the abstraction. +这是 `virtio_bus` 设计的一个安静胜利。编写一次的 VirtIO 驱动程序可以在 FreeBSD 支持的每个架构上的每个 VirtIO 传输上运行。没有 `#ifdef __amd64__` 子句,没有逐架构的转换层。`virtio_bus` 抽象了传输;驱动程序与抽象对话。 -### riscv64 Virtualisation +### riscv64 虚拟化 -On riscv64, virtualisation is provided by the *H extension* (Hypervisor extension). FreeBSD has a `bhyve` port for riscv64 as well, though it is less mature than the amd64 and arm64 ports as of FreeBSD 14.3. The VirtIO transports work the same way: drivers use `VIRTIO_DRIVER_MODULE` and the kernel's `virtio_bus` handles the transport specifics. +在 riscv64 上,虚拟化由 *H 扩展*(虚拟机监控程序扩展)提供。FreeBSD 也有一个 riscv64 的 `bhyve` 移植,尽管截至 FreeBSD 14.3 它不如 amd64 和 arm64 移植成熟。VirtIO 传输的工作方式相同:驱动程序使用 `VIRTIO_DRIVER_MODULE`,内核的 `virtio_bus` 处理传输细节。 -For driver authors working on riscv64, the most important thing to know is that the architecture-independent APIs all apply. `bus_dma(9)`, `callout(9)`, `mtx(9)`, `sx(9)`, and the VirtIO framework all work on riscv64. Code that is correct on amd64 usually runs unchanged on riscv64. The differences are in lower-level details (memory ordering, cache flushing, interrupt routing) that the kernel handles under the hood. +对于在 riscv64 上工作的驱动程序作者来说,最重要的是知道架构无关的 API 都适用。`bus_dma(9)`、`callout(9)`、`mtx(9)`、`sx(9)` 和 VirtIO 框架在 riscv64 上都能工作。在 amd64 上正确的代码通常在 riscv64 上无需更改即可运行。差异在于底层细节(内存排序、缓存刷新、中断路由),由内核在底层处理。 -### Cross-Architecture Considerations for Driver Authors +### 驱动程序作者的跨架构考量 -If you are writing a driver that should work on multiple architectures, the guidelines from Chapter 29 apply directly. Use the architecture-independent APIs. Avoid inline assembly except where strictly necessary (and then isolate it behind a portable wrapper). Do not assume a specific cache-line size or a specific page size. Do not assume an architecture's endianness unless you have explicitly used a conversion macro. +如果你正在编写应该在多个架构上工作的驱动程序,第29章的指南直接适用。使用架构无关的 API。避免内联汇编,除非严格必要(然后将其隔离在可移植包装器后面)。不要假设特定的缓存行大小或特定的页大小。不要假设架构的字节序,除非你已显式使用了转换宏。 -For virtualisation specifically, the main cross-architecture concern is *which VirtIO transports are present*. On amd64, VirtIO is almost always PCI. On arm64 with QEMU or Ampere hypervisors, VirtIO is often MMIO. On riscv64 with QEMU, VirtIO is often MMIO. A driver that only handles PCI VirtIO will not work in MMIO environments. The fix is to use `VIRTIO_DRIVER_MODULE`, which registers the driver with both transports, and to avoid assuming that the device's parent bus is PCI. +对于虚拟化来说,主要的跨架构关注点是*存在哪些 VirtIO 传输*。在 amd64 上,VirtIO 几乎总是 PCI。在使用 QEMU 或 Ampere 虚拟机监控程序的 arm64 上,VirtIO 通常是 MMIO。在使用 QEMU 的 riscv64 上,VirtIO 通常是 MMIO。只处理 PCI VirtIO 的驱动程序在 MMIO 环境中不工作。修复方法是使用 `VIRTIO_DRIVER_MODULE`,它在两种传输上注册驱动程序,并避免假设设备的父总线是 PCI。 -A concrete test: on your target architecture, run `pciconf -l` inside a guest and see whether VirtIO devices appear. If they do, the transport is PCI. If they do not (but the devices work), the transport is MMIO. On arm64 guests, you can also check `sysctl dev.virtio_mmio` to see MMIO VirtIO devices. A driver that works with both transports will not produce different output in these checks, because the `virtio_bus` API is what it interacts with. +一个具体的测试:在你的目标架构上,在客户机内运行 `pciconf -l` 查看 VirtIO 设备是否出现。如果出现了,传输是 PCI。如果没有出现(但设备工作),传输是 MMIO。在 arm64 客户机上,你也可以检查 `sysctl dev.virtio_mmio` 来查看 MMIO VirtIO 设备。与两种传输都工作的驱动程序在这些检查中不会产生不同的输出,因为它与 `virtio_bus` API 交互。 -### When Architecture Matters for Real +### 架构何时真正重要 -Most drivers are architecture-independent if written in the FreeBSD idiom. The exceptions are: +如果按照 FreeBSD 的惯用法编写,大多数驱动程序是架构无关的。例外有: -- Drivers that deal with hardware-specific features: for example, ARM's SMMU is architecturally different from Intel's VT-d, and a driver that manipulates the IOMMU directly (rare) must handle both. -- Drivers that perform byte-order conversion: network drivers do this routinely, but they use portable helpers (`htonl`, `ntohs`, etc.) rather than architecture-specific code. -- Drivers that need specific CPU instructions: for example, cryptographic drivers that use AES-NI on amd64 or the AES extensions on arm64 need per-architecture code paths. These are rare and are already isolated by the kernel's crypto framework. +- 处理硬件特定功能的驱动程序:例如,ARM 的 SMMU 在架构上不同于 Intel 的 VT-d,直接操作 IOMMU 的驱动程序(罕见)必须处理两者。 +- 执行字节序转换的驱动程序:网络驱动程序经常这样做,但它们使用可移植的辅助函数(`htonl`、`ntohs` 等)而不是架构特定的代码。 +- 需要特定 CPU 指令的驱动程序:例如,在 amd64 上使用 AES-NI 或在 arm64 上使用 AES 扩展的加密驱动程序需要逐架构的代码路径。这些很少见,已被内核的加密框架隔离。 -For most driver work on most architectures, the right mental model is "FreeBSD is FreeBSD". The APIs are the same. The idioms are the same. The virtualisation framework is the same. The architecture is a detail the kernel manages for you. +对于大多数架构上的大多数驱动程序工作,正确的思维模型是"FreeBSD 就是 FreeBSD"。API 是相同的。惯用法是相同的。虚拟化框架是相同的。架构是内核为你管理的细节。 -With architecture considerations covered, we have the complete picture of virtualisation and containerisation as it affects a FreeBSD driver author. The remaining sections of the chapter turn to hands-on practice. +架构考虑已经覆盖,我们现在有了虚拟化和容器化影响 FreeBSD 驱动程序作者的完整图景。本章的其余部分转向动手实践。 ## 实践实验 -The labs below walk you through four small exercises that put the chapter's ideas into practice. Each lab has a clear goal, a set of prerequisites, and a series of steps. Companion files are available under `examples/part-07/ch30-virtualisation/` for the ones that need more than a handful of lines of code. +下面的实验引导你完成四个小练习,将本章的想法付诸实践。每个实验都有明确的目标、先决条件和一系列步骤。对于需要不止几行代码的实验,配套文件可在 `examples/part-07/ch30-virtualisation/` 下找到。 -Work through them in order. The first lab gets you comfortable inspecting a VirtIO guest from inside a VM. The second gets you writing a tiny VirtIO-adjacent driver. The third and fourth move into jails and VNET. Allow a couple of hours of hands-on time for the whole set; longer if the `bhyve(8)` or QEMU setup is new to you. +按顺序完成它们。第一个实验让你熟悉在 VM 内检查 VirtIO 客户机。第二个实验让你编写一个微型 VirtIO 相关驱动程序。第三个和第四个实验进入 jail 和 VNET。整个集合需要两到三个小时的动手时间;如果 `bhyve(8)` 或 QEMU 设置对你来说是新的,时间会更长。 -### 实验1:Exploring a VirtIO Guest -**Goal**: Confirm that you can start a FreeBSD 14.3 guest under `bhyve(8)`, log in, and observe the VirtIO devices it has attached. This establishes the development environment you will use for later labs. +### 实验1:探索 VirtIO 客户机 +**目标**:确认你能在 `bhyve(8)` 下启动 FreeBSD 14.3 客户机、登录并观察它附加的 VirtIO 设备。这建立了你在后续实验中使用的开发环境。 -**Prerequisites**: A FreeBSD 14.3 host (bare metal or nested in another hypervisor, provided the outer hypervisor supports nested virtualisation). Enough memory for a small guest (2 GB is plenty). The `vmm.ko` module loadable on the host, which it is on any standard FreeBSD 14.3 kernel. +**先决条件**:一台 FreeBSD 14.3 主机(裸金属或嵌套在另一个虚拟机监控程序中,前提是外层虚拟机监控程序支持嵌套虚拟化)。足够用于小型客户机的内存(2 GB 即可)。主机上可加载 `vmm.ko` 模块,这在任何标准 FreeBSD 14.3 内核上都可用。 **Steps**: -1. Fetch a FreeBSD 14.3 VM image. The base project provides prebuilt VM images at `https://download.freebsd.org/`. Choose a `bhyve`-friendly image (typically the "BASIC-CI" or "VM-IMAGE" variants in the `amd64` directory). -2. Install the `vm-bhyve` port or package: `pkg install vm-bhyve`. This wraps `bhyve(8)` in a friendlier management interface. -3. Configure a VM directory: `zfs create -o mountpoint=/vm zroot/vm` (or `mkdir /vm` if you are not using ZFS). In `/etc/rc.conf`, add `vm_enable="YES"` and `vm_dir="zfs:zroot/vm"` (or `vm_dir="/vm"`). -4. Initialise the directory: `vm init`. Copy a default template: `cp /usr/local/share/examples/vm-bhyve/default.conf /vm/.templates/default.conf`. -5. Create a VM: `vm create -t default -s 10G guest0`. Attach the downloaded image: `vm install guest0 /path/to/FreeBSD-14.3-RELEASE-amd64.iso`. -6. Log in once the installer finishes and reboots. The login prompt comes up on `vm console guest0`. -7. Inside the guest, run `pciconf -lvBb | head -40`. You will see virtio-blk, virtio-net, and possibly virtio-random devices, depending on the template. Note the driver each device is bound to. -8. Run `sysctl kern.vm_guest`. The output should be `bhyve`. -9. Run `dmesg | grep -i virtio`. Observe the attach messages for each VirtIO device. -10. Record your observations in a text file. You will refer to them in Labs 2 and 4. +1. 获取 FreeBSD 14.3 VM 映像。基础项目在 `https://download.freebsd.org/` 提供预构建的 VM 映像。选择一个 `bhyve` 友好的映像(通常是 `amd64` 目录中的"BASIC-CI"或"VM-IMAGE"变体)。 +2. 安装 `vm-bhyve` port 或软件包:`pkg install vm-bhyve`。它将 `bhyve(8)` 包装在更友好的管理界面中。 +3. 配置 VM 目录:`zfs create -o mountpoint=/vm zroot/vm`(如果不使用 ZFS 则用 `mkdir /vm`)。在 `/etc/rc.conf` 中添加 `vm_enable="YES"` 和 `vm_dir="zfs:zroot/vm"`(或 `vm_dir="/vm"`)。 +4. 初始化目录:`vm init`。复制默认模板:`cp /usr/local/share/examples/vm-bhyve/default.conf /vm/.templates/default.conf`。 +5. 创建 VM:`vm create -t default -s 10G guest0`。附加下载的映像:`vm install guest0 /path/to/FreeBSD-14.3-RELEASE-amd64.iso`。 +6. 安装程序完成并重启后登录。登录提示在 `vm console guest0` 上出现。 +7. 在客户机内,运行 `pciconf -lvBb | head -40`。你将看到 virtio-blk、virtio-net,可能还有 virtio-random 设备,具体取决于模板。注意每个设备绑定的驱动程序。 +8. 运行 `sysctl kern.vm_guest`。输出应该是 `bhyve`。 +9. 运行 `dmesg | grep -i virtio`。观察每个 VirtIO 设备的附加消息。 +10. 将你的观察记录到文本文件中。你将在实验 2 和 4 中引用它们。 -**Expected outcome**: A running VM, a clear listing of attached VirtIO devices, and a confirmed `kern.vm_guest = bhyve` reading. +**预期结果**:一个运行中的 VM、清晰的已附加 VirtIO 设备列表,以及确认的 `kern.vm_guest = bhyve` 读数。 -**Common pitfalls**: Not enabling VT-x or AMD-V in the host's BIOS. Not having enough memory for the guest. Misconfigured network bridge preventing the guest from reaching the network (which is harmless for this lab but will matter later). +**常见陷阱**:未在主机 BIOS 中启用 VT-x 或 AMD-V。客户机内存不足。网络桥配置错误导致客户机无法访问网络(对此实验无害但后续会有影响)。 -### 实验2:Using Hypervisor Detection in a Kernel Module -**Goal**: Write a small kernel module that reads `vm_guest` and logs the environment at load time. This is the smallest possible example of environment-aware driver behaviour. +### 实验2:在内核模块中使用虚拟机监控程序检测 +**目标**:编写一个读取 `vm_guest` 并在加载时记录环境的小型内核模块。这是环境感知驱动程序行为的最小示例。 -**Prerequisites**: A working FreeBSD 14.3 guest from Lab 1. Kernel build tools installed (they come with the base system on the development kit). The `bsd.kmod.mk` build system, accessed via a simple `Makefile`. +**先决条件**:实验 1 中可工作的 FreeBSD 14.3 客户机。已安装内核构建工具(开发套件的基础系统附带)。通过简单 `Makefile` 访问的 `bsd.kmod.mk` 构建系统。 **Steps**: -1. Under `/home/ebrandi/FDD-book/examples/part-07/ch30-virtualisation/lab02-detect/` in the companion examples tree, you will find a starter `detectmod.c` and `Makefile`. If you are not using the companion tree, create these files by hand. -2. The source file should define a kernel module that, on load, prints which environment it is in based on `vm_guest`. -3. Build the module: `make clean && make`. -4. Load it: `sudo kldload ./detectmod.ko`. -5. Check the dmesg output: `dmesg | tail`. You should see a line like `detectmod: running on bhyve`. -6. Unload: `sudo kldunload detectmod`. -7. Reboot the guest on a different hypervisor if possible (QEMU/KVM, for example) and re-run. The output should now reflect the new environment. +1. 在配套示例树的 `/home/ebrandi/FDD-book/examples/part-07/ch30-virtualisation/lab02-detect/` 下,你会找到起始的 `detectmod.c` 和 `Makefile`。如果你不使用配套代码树,请手动创建这些文件。 +2. 源文件应定义一个内核模块,在加载时根据 `vm_guest` 打印它所处的环境。 +3. 构建模块:`make clean && make`。 +4. 加载它:`sudo kldload ./detectmod.ko`。 +5. 检查 dmesg 输出:`dmesg | tail`。你应该看到类似 `detectmod: running on bhyve` 的一行。 +6. 卸载:`sudo kldunload detectmod`。 +7. 如果可能,在不同虚拟机监控程序上重启客户机(例如 QEMU/KVM)并重新运行。输出现在应该反映新环境。 -**Expected outcome**: A module that correctly identifies the hypervisor it is running on, using `vm_guest`. +**预期结果**:一个使用 `vm_guest` 正确识别其运行虚拟机监控程序的模块。 -**Common pitfalls**: Forgetting to include `` for the `vm_guest` declaration. Linking errors from mistyped macros. Forgetting to set `KMOD=` and `SRCS=` in the Makefile. +**常见陷阱**:忘记包含 `` 来获取 `vm_guest` 声明。宏拼写错误导致的链接错误。忘记在 Makefile 中设置 `KMOD=` 和 `SRCS=`。 -### 实验3:A Minimal Character Device Driver Inside a Jail -**Goal**: Write a small character device driver, expose it from the host, create a jail with a custom devfs ruleset that makes the device visible inside, and verify that the jail's processes can use it while the host's privilege checks are still enforced. +### 实验3:监狱内的最小字符设备驱动程序 +**目标**:编写一个小型字符设备驱动程序,从主机暴露它,创建一个带有自定义 devfs 规则集的 jail 使设备在其中可见,并验证 jail 的进程可以使用它,同时主机的权限检查仍然被执行。 -**Prerequisites**: A FreeBSD 14.3 host. A working jail setup directory (typically `/jails/`). Basic familiarity with `make_dev(9)`, `d_read`, and `d_write`. +**先决条件**:一台 FreeBSD 14.3 主机。一个可工作的 jail 设置目录(通常是 `/jails/`)。对 `make_dev(9)`、`d_read` 和 `d_write` 的基本了解。 **Steps**: -1. Under `examples/part-07/ch30-virtualisation/lab03-jaildev/`, you will find `jaildev.c` and `Makefile`. The driver creates a `/dev/jaildev` character device whose `read` returns a fixed greeting. -2. Build and load the module on the host: `make && sudo kldload ./jaildev.ko`. -3. Verify `/dev/jaildev` exists and is readable: `cat /dev/jaildev`. -4. Create a jail root: `mkdir -p /jails/test && cp /bin/sh /jails/test/` (this is a minimal jail; for a real setup, use a proper filesystem layout). -5. Add a devfs ruleset to `/etc/devfs.rules`: +1. 在 `examples/part-07/ch30-virtualisation/lab03-jaildev/` 下,你会找到 `jaildev.c` 和 `Makefile`。驱动程序创建一个 `/dev/jaildev` 字符设备,其 `read` 返回一个固定问候。 +2. 在主机上构建并加载模块:`make && sudo kldload ./jaildev.ko`。 +3. 验证 `/dev/jaildev` 存在且可读:`cat /dev/jaildev`。 +4. 创建 jail 根目录:`mkdir -p /jails/test && cp /bin/sh /jails/test/`(这是一个最小 jail;对于真实设置,使用适当的文件系统布局)。 +5. 在 `/etc/devfs.rules` 中添加 devfs 规则集: ```text [devfsrules_jaildev=100] add include $devfsrules_hide_all add include $devfsrules_unhide_basic add path 'jaildev' unhide ``` -6. Reload the rules: `sudo service devfs restart`. -7. Start the jail: `sudo jail -c path=/jails/test devfs_ruleset=100 persist command=/bin/sh`. -8. In another terminal, enter the jail: `sudo jexec test /bin/sh`. -9. Inside the jail, run `cat /dev/jaildev`. The greeting should appear. Try `ls /dev/`: only the allowed devices (including `jaildev`) are visible. -10. Test the privilege boundary: modify the driver to require `PRIV_DRIVER` for an ioctl, rebuild, reload, and verify that the jail's root cannot run the ioctl while the host's root can. +6. 重新加载规则:`sudo service devfs restart`。 +7. 启动 jail:`sudo jail -c path=/jails/test devfs_ruleset=100 persist command=/bin/sh`。 +8. 在另一个终端中,进入 jail:`sudo jexec test /bin/sh`。 +9. 在 jail 内,运行 `cat /dev/jaildev`。问候应该出现。尝试 `ls /dev/`:只有允许的设备(包括 `jaildev`)可见。 +10. 测试权限边界:修改驱动程序以要求 `PRIV_DRIVER` 才能执行 ioctl,重新构建、重新加载,并验证 jail 的 root 无法运行 ioctl 而主机的 root 可以。 -**Expected outcome**: A driver visible in the jail only because the ruleset allows it, with privilege checks that behave differently for host root and jail root. +**预期结果**:驱动程序仅在规则集允许时在 jail 中可见,权限检查对主机 root 和 jail root 的行为不同。 -**Common pitfalls**: Forgetting to restart `devfs` after editing the rules. Not setting `persist` on the jail (without it, the jail dies as soon as the initial process exits). Misreading the ruleset syntax (whitespace is significant). +**常见陷阱**:编辑规则后忘记重启 `devfs`。未在 jail 上设置 `persist`(没有它,jail 在初始进程退出时即死亡)。误读规则集语法(空格是有意义的)。 -### 实验4:A Network Driver Inside a VNET Jail -**Goal**: Create a VNET jail, move one end of an `epair(4)` into it, and verify that network traffic flows between the host and the jail using only the jail's VNET. This exercises `if_vmove()` and the VNET lifecycle. +### 实验4:VNET 监狱内的网络驱动程序 +**目标**:创建一个 VNET jail,将 `epair(4)` 的一端移入其中,并验证网络流量仅使用 jail 的 VNET 在主机和 jail 之间流动。这锻炼了 `if_vmove()` 和 VNET 生命周期。 -**Prerequisites**: A FreeBSD 14.3 host with `if_epair.ko` loadable. Root privileges. +**先决条件**:一台可加载 `if_epair.ko` 的 FreeBSD 14.3 主机。Root 权限。 **Steps**: -1. Load the `if_epair` module: `sudo kldload if_epair`. -2. Create an `epair`: `sudo ifconfig epair create`. You will get a device pair `epair0a` and `epair0b`. -3. Assign an IP to `epair0a` on the host: `sudo ifconfig epair0a 10.100.0.1/24 up`. -4. Create a jail root directory: `mkdir -p /jails/vnet-test`. Place a minimal shell and `ifconfig` binary inside (or bind-mount `/bin`, `/sbin`, `/usr/bin` for testing). -5. Create the jail with VNET enabled: +1. 加载 `if_epair` 模块:`sudo kldload if_epair`。 +2. 创建一个 `epair`:`sudo ifconfig epair create`。你将获得一个设备对 `epair0a` 和 `epair0b`。 +3. 在主机上为 `epair0a` 分配 IP:`sudo ifconfig epair0a 10.100.0.1/24 up`。 +4. 创建 jail 根目录:`mkdir -p /jails/vnet-test`。在其中放置最小的 shell 和 `ifconfig` 二进制文件(或绑定挂载 `/bin`、`/sbin`、`/usr/bin` 用于测试)。 +5. 创建启用 VNET 的 jail: ```sh sudo jail -c \ name=vnet-test \ @@ -1865,485 +1865,485 @@ Work through them in order. The first lab gets you comfortable inspecting a Virt persist \ command=/bin/sh ``` - The `vnet.interface=epair0b` parameter triggers the `if_vmove()` that moves the interface into the jail. -6. Enter the jail: `sudo jexec vnet-test /bin/sh`. -7. Inside the jail, configure the interface: `ifconfig epair0b 10.100.0.2/24 up`. -8. Still inside the jail, ping the host: `ping -c 3 10.100.0.1`. It should succeed. -9. From the host, ping the jail: `ping -c 3 10.100.0.2`. It should succeed. -10. Stop the jail: `sudo jail -r vnet-test`. The `epair0b` interface is moved back to the host (because it was moved with `vnet.interface`, which uses `if_vmove_loan()` under the hood in recent FreeBSD releases). -11. Verify the interface is back on the host: `ifconfig epair0b`. It should still exist but belong to the host's VNET again. + `vnet.interface=epair0b` 参数触发 `if_vmove()` 将接口移入 jail。 +6. 进入 jail:`sudo jexec vnet-test /bin/sh`。 +7. 在 jail 内,配置接口:`ifconfig epair0b 10.100.0.2/24 up`。 +8. 仍在 jail 内,ping 主机:`ping -c 3 10.100.0.1`。应该成功。 +9. 从主机 ping jail:`ping -c 3 10.100.0.2`。应该成功。 +10. 停止 jail:`sudo jail -r vnet-test`。`epair0b` 接口被移回主机(因为它通过 `vnet.interface` 移动,后者在最近的 FreeBSD 版本中底层使用 `if_vmove_loan()`)。 +11. 验证接口已回到主机:`ifconfig epair0b`。它应该仍然存在但再次属于主机的 VNET。 -**Expected outcome**: A jail with its own network stack, moving an interface cleanly in and out. +**预期结果**:一个拥有自己网络栈的 jail,干净地将接口移入和移出。 -**Common pitfalls**: Forgetting to enable VNET in the kernel (`options VIMAGE` is enabled in `GENERIC`, so this should be fine, but custom kernels might not have it). Trying to use a physical interface instead of `epair(4)` for the first attempt (this works but causes the host to lose that interface while the jail has it). Not giving the jail enough binaries to run a shell (the simplest workaround is a `nullfs` mount of the host's `/rescue` or a minimal bind-mount setup). +**常见陷阱**:忘记在内核中启用 VNET(`options VIMAGE` 在 `GENERIC` 中已启用,所以应该没问题,但自定义内核可能没有)。首次尝试使用物理接口而不是 `epair(4)`(这可以工作但会导致主机在 jail 占用接口期间失去该接口)。没有给 jail 足够的二进制文件来运行 shell(最简单的解决方法是 `nullfs` 挂载主机的 `/rescue` 或最小绑定挂载设置)。 -### 实验5:PCI Passthrough Simulation (Optional) -**Goal**: Observe how PCI passthrough changes a device's ownership, using a non-critical device as the target. This lab is marked optional because it requires a spare PCI device and an IOMMU-capable host. If those are not available, read through the steps; they illustrate the workflow even without running them. +### 实验5:PCI 直通模拟(可选) +**目标**:使用非关键设备作为目标,观察 PCI 直通如何改变设备的所有权。此实验标记为可选,因为它需要一个空闲 PCI 设备和支持 IOMMU 的主机。如果这些不可用,请通读步骤;即使不运行,它们也说明了工作流程。 -**Prerequisites**: A FreeBSD 14.3 host with VT-d or AMD-Vi enabled in firmware. A spare PCI device that is safe to remove from the host (an unused NIC is a common choice). A `bhyve(8)` guest configuration. +**先决条件**:一台在固件中启用 VT-d 或 AMD-Vi 的 FreeBSD 14.3 主机。一个可以安全从主机移除的空闲 PCI 设备(常见选择是未使用的网卡)。一个 `bhyve(8)` 客户机配置。 **Steps**: -1. Identify the target device: `pciconf -lvBb | grep -B 1 -A 10 'Ethernet'` (or whatever type the spare device is). Note its bus, slot, and function (e.g., `pci0:5:0:0`). -2. Edit `/boot/loader.conf` and add the device to the passthrough list: +1. 识别目标设备:`pciconf -lvBb | grep -B 1 -A 10 'Ethernet'`(或空闲设备的任何类型)。记下它的总线、插槽和功能号(例如 `pci0:5:0:0`)。 +2. 编辑 `/boot/loader.conf` 并将设备添加到直通列表: ```text pptdevs="5/0/0" ``` -3. Reboot the host. The device should now be bound to `ppt(4)` rather than its native driver. Confirm with `pciconf -l` (look for `ppt0`). -4. Configure a guest to pass the device through: +3. 重启主机。设备现在应该绑定到 `ppt(4)` 而不是其原生驱动程序。用 `pciconf -l` 确认(查找 `ppt0`)。 +4. 配置客户机以直通设备: ```text passthru0="5/0/0" ``` - (Using the `vm-bhyve` configuration; the raw `bhyve` command is more verbose.) -5. Boot the guest. Inside the guest, run `pciconf -lvBb`. The device now appears in the guest with its real vendor and device IDs, attached to its native driver. -6. Exercise the device inside the guest: configure the NIC, send traffic, verify it works. -7. Shut down the guest. Edit `/boot/loader.conf` to remove the `pptdevs` line, reboot, and verify that the device returns to the host with its native driver attached. + (使用 `vm-bhyve` 配置;原始 `bhyve` 命令更冗长。) +5. 启动客户机。在客户机内,运行 `pciconf -lvBb`。设备现在以真实的供应商和设备 ID 出现在客户机中,附加到其原生驱动程序。 +6. 在客户机内操作设备:配置 NIC,发送流量,验证其工作。 +7. 关闭客户机。编辑 `/boot/loader.conf` 移除 `pptdevs` 行,重启,验证设备以其原生驱动程序返回主机。 -**Expected outcome**: A clean round trip of a PCI device from host to guest and back, exercising the detach and reattach paths of the native driver. +**预期结果**:PCI 设备从主机到客户机再回来的干净往返,锻炼原生驱动程序的分离和重新附加路径。 -**Common pitfalls**: The host firmware does not have VT-d or AMD-Vi enabled (look for it in the BIOS/UEFI setup). The chosen device is in the same IOMMU group as a device the host needs, forcing a multi-device passthrough. The device is attached to its native driver at boot before `ppt(4)` can claim it (usually this is fine if `pptdevs` is set early enough). +**常见陷阱**:主机固件未启用 VT-d 或 AMD-Vi(在 BIOS/UEFI 设置中查找)。所选设备与主机需要的设备在同一 IOMMU 组中,迫使进行多设备直通。设备在启动时已附加到其原生驱动程序,`ppt(4)` 无法声明它(如果 `pptdevs` 设置得足够早,通常没问题)。 -### 实验6:Building and Loading the vtedu Driver -**Goal**: Build the pedagogical `vtedu` driver from the case study, load it under a FreeBSD 14.3 guest, and observe its behaviour even without a matching backend. This lab exercises the kernel module build process in the VirtIO context and verifies the module structure. +### 实验6:构建并加载 vtedu 驱动程序 +**目标**:从案例研究构建教学用的 `vtedu` 驱动程序,在 FreeBSD 14.3 客户机下加载它,并观察其行为(即使没有匹配的后端)。此实验锻炼 VirtIO 上下文中的内核模块构建过程并验证模块结构。 -**Prerequisites**: A FreeBSD 14.3 guest (the one from Lab 1 is fine). The FreeBSD source tree under `/usr/src` or the kernel headers installed (`pkg install kernel-14.3-RELEASE` works on stock systems). Root privileges inside the guest. +**先决条件**:一台 FreeBSD 14.3 客户机(实验 1 的即可)。`/usr/src` 下的 FreeBSD 源代码树或已安装的内核头文件(`pkg install kernel-14.3-RELEASE` 在标准系统上可用)。客户机内的 root 权限。 **Steps**: -1. Copy the companion files to the guest. From the book's examples tree, `examples/part-07/ch30-virtualisation/vtedu/` contains `vtedu.c`, `Makefile`, and `README.md`. Transfer them to the guest (via `scp`, `9p` share, or a shared volume). -2. Inside the guest, change into the `vtedu` directory: `cd /tmp/vtedu`. -3. Build the module: `make clean && make`. If the build fails because `/usr/src` is not installed, install it with `pkg install kernel-14.3-RELEASE` or point `SYSDIR` at an alternative kernel source tree: `make SYSDIR=/path/to/sys`. -4. A successful build produces `virtio_edu.ko` in the current directory. -5. Load the module: `sudo kldload ./virtio_edu.ko`. The load succeeds regardless of whether a matching device is present. -6. Check module status: `kldstat -v | grep -A 5 virtio_edu`. You will see the module is loaded, but no device is bound. This is expected without a backend. -7. Unload the module: `sudo kldunload virtio_edu`. -8. Inspect the module's PNP information: `kldxref -d /boot/modules` lists modules and their PNP entries. If you moved the module into `/boot/modules`, you will see the `VirtIO simple` PNP entry advertising device ID 0xfff0. -9. Look at `dmesg` output during load and unload. There should be no errors. The absence of an attach message confirms that no device is bound, which is the expected behaviour. +1. 将配套文件复制到客户机。从本书的示例树中,`examples/part-07/ch30-virtualisation/vtedu/` 包含 `vtedu.c`、`Makefile` 和 `README.md`。将它们传输到客户机(通过 `scp`、`9p` 共享或共享卷)。 +2. 在客户机内,进入 `vtedu` 目录:`cd /tmp/vtedu`。 +3. 构建模块:`make clean && make`。如果构建因 `/usr/src` 未安装而失败,用 `pkg install kernel-14.3-RELEASE` 安装,或将 `SYSDIR` 指向替代的内核源代码树:`make SYSDIR=/path/to/sys`。 +4. 成功的构建会在当前目录产生 `virtio_edu.ko`。 +5. 加载模块:`sudo kldload ./virtio_edu.ko`。无论是否存在匹配的设备,加载都会成功。 +6. 检查模块状态:`kldstat -v | grep -A 5 virtio_edu`。你会看到模块已加载,但没有设备被绑定。没有后端这是预期的。 +7. 卸载模块:`sudo kldunload virtio_edu`。 +8. 检查模块的 PNP 信息:`kldxref -d /boot/modules` 列出模块及其 PNP 条目。如果你将模块移入了 `/boot/modules`,你会看到播发设备 ID 0xfff0 的 `VirtIO simple` PNP 条目。 +9. 查看加载和卸载期间的 `dmesg` 输出。不应该有错误。缺少附加消息确认没有设备被绑定,这是预期行为。 -**Expected outcome**: A successful build and load cycle that demonstrates the module is well-formed. Without a backend, the module is inert; this is a useful confirmation that the build and load plumbing work independently of the device side. +**预期结果**:一个成功的构建和加载循环,证明模块是格式良好的。没有后端时,模块是惰性的;这是一个有用的确认,表明构建和加载管道独立于设备侧工作。 -**Common pitfalls**: Missing kernel sources (install the `src` package). Missing `virtio.ko` dependency (load `virtio` first if it was somehow absent, though it is built into `GENERIC`). Confusion when no device attaches (re-read Section 1 of the vtedu README; this is by design). +**常见陷阱**:缺少内核源代码(安装 `src` 包)。缺少 `virtio.ko` 依赖(如果它因为某种原因不存在,先加载 `virtio`,虽然它已内置于 `GENERIC`)。没有设备附加时的困惑(重读 vtedu README 的第 1 节;这是设计如此)。 -**What to do next**: The real learning comes from pairing this module with a backend. Challenge 5 in the Challenge Exercises describes writing a matching backend in `bhyve(8)`. If you complete that, the driver will attach to the backend-provided device, a `/dev/vtedu0` node will appear, and you will be able to `echo hello > /dev/vtedu0 && cat /dev/vtedu0` to exercise the full VirtIO round-trip you studied in the case study. +**下一步**:真正的学习来自将此模块与后端配对。挑战练习中的挑战 5 描述了在 `bhyve(8)` 中编写匹配的后端。如果你完成了它,驱动程序将附加到后端提供的设备,一个 `/dev/vtedu0` 节点将出现,你将能够 `echo hello > /dev/vtedu0 && cat /dev/vtedu0` 来锻炼你在案例研究中学习的完整 VirtIO 往返。 -### 实验7:Measuring VirtIO Overhead -**Goal**: Quantify the performance characteristics of VirtIO by running a simple workload under emulated, paravirtualised, and passthrough device configurations. This lab is about building intuition for what virtualisation costs, not about optimising a specific driver. +### 实验7:测量 VirtIO 开销 +**目标**:通过在模拟、半虚拟化和直通设备配置下运行简单工作负载来量化 VirtIO 的性能特征。此实验是为了建立虚拟化成本的直觉,而不是优化特定驱动程序。 -**Prerequisites**: A FreeBSD 14.3 host with bhyve, at least 8 GB of RAM, and the `vm-bhyve` tool installed. A NVMe drive is ideal but not required. The `fio(1)` benchmarking tool (available from ports as `benchmarks/fio`). Optional: a spare NIC for passthrough comparison. +**先决条件**:一台装有 bhyve 的 FreeBSD 14.3 主机,至少 8 GB RAM,以及 `vm-bhyve` 工具。NVMe 驱动器最理想但不是必需的。`fio(1)` 基准测试工具(可通过 ports 获取,为 `benchmarks/fio`)。可选:用于直通比较的空闲 NIC。 **Steps**: -1. Create a baseline guest with VirtIO block and network devices (this is the default in `vm-bhyve`). -2. Inside the guest, install `fio`: `pkg install fio`. -3. Run a baseline disk benchmark: `fio --name=baseline --rw=randread --bs=4k --size=1G --numjobs=4 --iodepth=32 --runtime=30s --group_reporting`. Record the IOPS and latency. -4. On the host, measure the same workload directly (not inside the guest) using the backing storage as the target. Compare. -5. Run a baseline network benchmark: `iperf3 -c 10.0.0.1 -t 30` (server on the host, client in the guest). Record the throughput. -6. If you have a spare NIC, reconfigure the guest to use passthrough for the NIC (see Lab 5). Re-run the iperf3 benchmark. Compare. -7. On the host, observe interrupt and VM exit counts while the benchmarks run: `vmstat -i`, `pmcstat -S instructions -l 10`. The most interesting counters are VM exit rates, which correlate with overhead. -8. For the disk benchmark, try varying the VirtIO features. Modify the guest configuration to disable `VIRTIO_F_RING_EVENT_IDX` (if the backend supports disabling it) and observe the change in interrupt rate. +1. 创建一个带有 VirtIO 块和网络设备的基线客户机(这是 `vm-bhyve` 的默认配置)。 +2. 在客户机内,安装 `fio`:`pkg install fio`。 +3. 运行基线磁盘基准测试:`fio --name=baseline --rw=randread --bs=4k --size=1G --numjobs=4 --iodepth=32 --runtime=30s --group_reporting`。记录 IOPS 和延迟。 +4. 在主机上,直接(不在客户机内)使用后备存储作为目标测量相同的工作负载。进行比较。 +5. 运行基线网络基准测试:`iperf3 -c 10.0.0.1 -t 30`(服务器在主机上,客户端在客户机内)。记录吞吐量。 +6. 如果你有空闲的 NIC,重新配置客户机使用 NIC 直通(参见实验 5)。重新运行 iperf3 基准测试。进行比较。 +7. 在主机上,观察基准测试运行期间的中断和 VM 退出计数:`vmstat -i`、`pmcstat -S instructions -l 10`。最有趣的计数器是 VM 退出率,它与开销相关。 +8. 对于磁盘基准测试,尝试改变 VirtIO 特性。修改客户机配置以禁用 `VIRTIO_F_RING_EVENT_IDX`(如果后端支持禁用它)并观察中断率的变化。 -**Expected outcome**: A small set of numbers that quantify the cost of virtualisation for your particular setup. Typically, VirtIO paravirtualised I/O is within 10-20% of bare metal for sustained workloads and within 30-40% for latency-sensitive random workloads; passthrough is within a few percent of bare metal but forfeits flexibility; pure emulation (for example, emulated E1000 instead of virtio-net) is 5-10x slower than VirtIO and should be avoided for any serious workload. +**预期结果**:一组量化你的特定设置虚拟化成本的数据。通常,VirtIO 半虚拟化 I/O 在持续工作负载下与裸金属差距在 10-20% 以内,在延迟敏感的随机工作负载下差距在 30-40% 以内;直通与裸金属差距在几个百分点以内但丧失灵活性;纯模拟(例如模拟 E1000 而不是 virtio-net)比 VirtIO 慢 5-10 倍,应避免用于任何严肃的工作负载。 -**Common pitfalls**: Benchmarks can be noisy; run each multiple times and take medians rather than single samples. The host's cache state affects disk benchmarks; run a warmup pass before the measured runs. CPU frequency scaling can skew results; pin the guest to specific cores and disable scaling on the host for reproducibility. +**常见陷阱**:基准测试可能有噪声;每次运行多次并取中位数而不是单次采样。主机的缓存状态影响磁盘基准测试;在测量运行之前运行预热。CPU 频率缩放可能偏斜结果;将客户机固定到特定核心并在主机上禁用缩放以确保可重现性。 -**What this teaches**: The numbers are secondary; the method is primary. Being able to measure overhead and attribute it to a specific layer (emulation vs. paravirtualisation vs. passthrough, interrupt rate vs. throughput, guest CPU vs. host CPU) is the foundation of performance work in virtualised environments. The same technique applies to any driver you write: if it has a performance requirement, you need to measure, and the measurement techniques are the ones in this lab. +**这教会什么**:数字是次要的;方法是主要的。能够测量开销并将其归因于特定层(模拟 vs. 半虚拟化 vs. 直通,中断率 vs. 吞吐量,客户机 CPU vs. 主机 CPU)是虚拟化环境中性能工作的基础。相同的技术适用于你编写的任何驱动程序:如果它有性能要求,你需要测量,而测量技术就是本实验中的那些。 -### A Note on Labs You Cannot Complete Today +### 关于今天无法完成的实验的说明 -Not every reader will have the hardware for every lab. Labs 1 through 4 are doable on essentially any FreeBSD 14.3 machine with enough memory and the `vmm` module. Lab 5 requires specific hardware that many readers will not have. Treat Lab 5 as a read-along walkthrough if you cannot run it; the concepts translate to any passthrough scenario, and the exact commands are documented in `pci_passthru(4)` and the `bhyve(8)` manual page. +不是每个读者都有完成每个实验的硬件。实验 1 到 4 基本上可以在任何有足够内存和 `vmm` 模块的 FreeBSD 14.3 机器上完成。实验 5 需要许多读者没有的特定硬件。如果你无法运行实验 5,请将其作为阅读演练;概念适用于任何直通场景,确切的命令记录在 `pci_passthru(4)` 和 `bhyve(8)` 手册页中。 -If you are blocked on a lab, write down exactly what went wrong and come back to it. Virtualisation and containerization are areas where small environmental details can derail a whole setup, and the diagnostic skill of narrowing down the failure is as important as completing the lab. +如果你在某个实验上受阻,准确记录出了什么问题,然后再回来。虚拟化和容器化是小型环境细节可能破坏整个设置的领域,缩小失败范围的诊断技能与完成实验同样重要。 ## 挑战练习 -The labs above guide you through the standard paths. The challenges below ask you to extend the work. They are harder, less prescriptive, and designed to reward experimentation. Pick whichever one interests you most; all of them stretch different muscles. +上面的实验引导你通过标准路径。下面的挑战要求你扩展这些工作。它们更难、更不规定性,旨在奖励实验精神。选择你最感兴趣的一个;它们都锻炼不同的能力。 -### 挑战1:Extend the Detect Module -The Lab 2 module reads `vm_guest` and prints an environment label. Extend it so that it also reads the CPU vendor string (using `cpu_vendor` and `cpu_vendor_id`), the total physical memory (`realmem`), and the hypervisor signature where applicable. Produce a single structured log line that a test script can parse. +### 挑战1:扩展检测模块 +实验 2 的模块读取 `vm_guest` 并打印环境标签。扩展它使其也读取 CPU 供应商字符串(使用 `cpu_vendor` 和 `cpu_vendor_id`)、总物理内存(`realmem`)以及适用的虚拟机监控程序签名。生成一条测试脚本可以解析的结构化日志行。 -The CPU vendor string is a well-known part of CPU identification; look at `/usr/src/sys/x86/x86/identcpu.c` to see how the kernel reads it. The physical memory total is exposed through the `realmem` global and through the `hw.physmem` sysctl. The hypervisor signature lives in CPUID leaf 0x40000000 on most hypervisors; reading it requires a small piece of assembly or an intrinsic. +CPU 供应商字符串是 CPU 识别的知名部分;查看 `/usr/src/sys/x86/x86/identcpu.c` 了解内核如何读取它。物理内存总量通过 `realmem` 全局变量和 `hw.physmem` sysctl 暴露。虚拟机监控程序签名在大多数虚拟机监控程序上位于 CPUID 叶 0x40000000;读取它需要一小段汇编或内联函数。 -The interesting design question is how to expose this information to user space. You could log it at module load, add a sysctl, or create a `/dev/envinfo` device. Each has trade-offs. Think about which is most appropriate for a real production driver. +有趣的设计问题是如何将这些信息暴露给用户空间。你可以在模块加载时记录它、添加 sysctl,或创建一个 `/dev/envinfo` 设备。每种方法都有权衡。思考哪种对真正的生产驱动程序最合适。 -### 挑战2:A Simulation Backend for a Real VirtIO Driver -Chapter 29's techniques encourage splitting a driver into accessors, backends, and a thin upper layer. Apply this to `virtio_random`. The real driver (in `/usr/src/sys/dev/virtio/random/virtio_random.c`) is small and tightly written. Can you refactor it so that the virtqueue operations go through an accessor layer, and a simulation backend that does not need a real VirtIO device can be selected for tests? +### 挑战2:为真实 VirtIO 驱动程序构建模拟后端 +第 29 章的技术鼓励将驱动程序拆分为访问器、后端和薄上层。将此应用于 `virtio_random`。真实驱动程序(在 `/usr/src/sys/dev/virtio/random/virtio_random.c` 中)小而紧凑。你能重构它使虚拟队列操作通过访问器层进行,并且可以选择一个不需要真实 VirtIO 设备的模拟后端进行测试吗? -The refactor is subtle because the VirtIO framework provides most of the accessor layer for you: `virtqueue_enqueue`, `virtqueue_dequeue`, `virtio_notify` are already abstractions. The challenge is to find a layer above them that can be swapped out. One possibility is to move the harvest loop into a function that takes a callback for "get one buffer's worth of data", and implement that callback either as "call the virtqueue" (real) or as "read from `/dev/urandom` on the host" (simulation). +重构是微妙的,因为 VirtIO 框架为你提供了大部分访问器层:`virtqueue_enqueue`、`virtqueue_dequeue`、`virtio_notify` 已经是抽象。挑战在于找到一个可以在它们之上交换的层。一种可能性是将收获循环移入一个接受回调的函数,并将该回调实现为“调用虚拟队列”(真实)或“从主机上的 `/dev/urandom` 读取”(模拟)。 -This is a design exercise more than a coding exercise. The goal is to understand how far Chapter 29's advice can be stretched in a real driver that already has good abstractions. +这与其说是编码练习,不如说是设计练习。目标是了解第 29 章的建议在已经有良好抽象的真实驱动程序中能延伸多远。 -### 挑战3:A VNET-Aware Driver Skeleton -Write a skeleton kernel module that creates a pseudo-network interface (using the `if_clone(9)` framework), supports being moved between VNETs, and reports its VNET identity in a sysctl. Verify with a VNET jail that the interface can be moved into the jail, used, and moved back. +### 挑战3:VNET 感知的驱动程序骨架 +编写一个骨架内核模块,创建一个伪网络接口(使用 `if_clone(9)` 框架),支持在 VNET 之间移动,并在 sysctl 中报告其 VNET 身份。用 VNET jail 验证接口可以被移入 jail、使用并移回。 -The key subtlety is handling the VNET context correctly. Read the code in `/usr/src/sys/net/if_tuntap.c` for a reference. The `if_vmove` lifecycle requires the driver to clean up per-VNET state when the interface leaves and re-create it when the interface arrives. Pay attention to `VNET_SYSINIT` and `VNET_SYSUNINIT` if your driver needs per-VNET state. +关键的微妙之处在于正确处理 VNET 上下文。阅读 `/usr/src/sys/net/if_tuntap.c` 中的代码作为参考。`if_vmove` 生命周期要求驱动程序在接口离开时清理 per-VNET 状态,在接口到达时重新创建。如果你的驱动程序需要 per-VNET 状态,请注意 `VNET_SYSINIT` 和 `VNET_SYSUNINIT`。 -This is a deep challenge that will take you into the VNET internals. Do not expect to complete it in a single sitting. Treat it as a multi-day project. +这是一个深度挑战,会带你进入 VNET 内部。不要期望一次完成。把它当作一个多天项目。 -### 挑战4:A Jail-Visible Status Device -Write a driver that exposes a `/dev/status` character device. The device's `read` returns different information depending on whether the caller is in a jail. If the caller is on the host, it returns system-wide status. If the caller is in a jail, it returns jail-specific status (number of processes, current memory use, and so on). +### 挑战4:监狱可见的状态设备 +编写一个暴露 `/dev/status` 字符设备的驱动程序。设备的 `read` 根据调用者是否在 jail 中返回不同信息。如果调用者在主机上,返回系统范围的状态。如果调用者在 jail 中,返回 jail 特定的状态(进程数、当前内存使用等)。 -The interesting part is how to distinguish the caller's jail. The `struct thread` passed to the `read` method has `td->td_ucred->cr_prison`, and `prison0` is the host. From the prison pointer you can read the jail's name, its process count (`pr_nprocs`), and so on. Be careful about locking: the prison's fields are mostly read under a mutex that the driver must acquire. +有趣的部分是如何区分调用者的 jail。传递给 `read` 方法的 `struct thread` 有 `td->td_ucred->cr_prison`,`prison0` 是主机。从 prison 指针你可以读取 jail 的名称、进程计数(`pr_nprocs`)等。注意加锁:prison 的字段大多需要在驱动程序获取互斥锁后读取。 -This challenge is a good way to learn about the jail API without writing anything hypervisor-related. It also teaches you about `struct thread` and `struct ucred`, which are central to FreeBSD's privilege model. +这个挑战是学习 jail API 的好方法,不需要编写任何虚拟机监控程序相关的东西。它还教你关于 `struct thread` 和 `struct ucred`,这些是 FreeBSD 权限模型的核心。 -### 挑战5:A bhyve Emulated Device in User Space -If you are ready for a bigger project, study how `bhyve(8)` emulates a simple VirtIO device (for example, virtio-rnd) in user space, and write a new emulated device of your own. The easiest target is a "hello" device that returns a fixed string through a VirtIO interface. The guest-side driver is your Chapter 29 or Chapter 30 work; the host-side emulator lives in `/usr/src/usr.sbin/bhyve/`. +### 挑战5:用户空间的 bhyve 模拟设备 +如果你准备好做更大的项目,研究 `bhyve(8)` 如何在用户空间模拟一个简单的 VirtIO 设备(例如 virtio-rnd),并编写你自己的新模拟设备。最简单的目标是返回固定字符串的 hello 设备。客户机侧的驱动程序是你第 29 章或第 30 章的工作;主机侧的模拟器位于 `/usr/src/usr.sbin/bhyve/`。 -This exercise ties together everything in the chapter: you write a VirtIO device in user space on the host, your driver inside the guest reads from it, the virtqueue transport between them is what you have been studying, and the whole thing exercises the full guest-host loop. +这个练习将本章的所有内容联系在一起:你在主机上的用户空间编写 VirtIO 设备,你的驱动程序在客户机内从中读取,它们之间的虚拟队列传输就是你一直在学习的内容,整个事情锻炼了完整的客户机-主机循环。 -It is a substantial project, and it requires some familiarity with `bhyve(8)`'s code structure. Consider it a reach goal. If you finish it, you have genuinely learned both sides of the VirtIO story. +这是一个实质性的项目,需要对 `bhyve(8)` 的代码结构有一定了解。把它当作一个远大目标。如果你完成了它,你真正学会了 VirtIO 故事的双方。 -### 挑战6:Container Orchestration for Driver Testing -Write a shell script (or a more elaborate tool) that automates the Lab 3 and Lab 4 workflows. Given a driver and a test harness, the script should: +### 挑战6:用于驱动程序测试的容器编排 +编写一个 shell 脚本(或更复杂的工具)来自动化实验 3 和实验 4 的工作流程。给定驱动程序和测试工具,脚本应该: -1. Build the driver. -2. Load it on the host. -3. Create a jail (or a VNET jail) with an appropriate ruleset. -4. Run the harness inside the jail. -5. Collect results. -6. Destroy the jail. -7. Unload the driver. -8. Report pass/fail with diagnostics. +1. 构建驱动程序。 +2. 在主机上加载它。 +3. 创建一个带有适当规则集的 jail(或 VNET jail)。 +4. 在 jail 内运行测试工具。 +5. 收集结果。 +6. 销毁 jail。 +7. 卸载驱动程序。 +8. 报告通过/失败及诊断信息。 -The script should be idempotent (running it twice should not leave residue) and it should handle common failures gracefully. The end result is a tool you can run in CI to verify that your driver continues to work under jails as it evolves. +脚本应该是幂等的(运行两次不应该留下残留),并且应该优雅地处理常见故障。最终结果是一个你可以在 CI 中运行的工具,以验证你的驱动程序在演进过程中继续在 jail 下工作。 -This is not a deep technical challenge but a practical one. Building this kind of automation is a significant fraction of real-world driver work, and building it yourself once teaches you what is involved. +这不是一个深度技术挑战,而是一个实践挑战。构建这种自动化是真实驱动程序工作的重要部分,自己构建一次会教你涉及什么。 -### How to Approach These Challenges +### 如何对待这些挑战 -Each challenge could be a weekend project. Pick one that seems interesting and set aside time for it. Do not try to do all of them at once; your energy for unfamiliar work is limited, and you learn more from one challenge finished than from three challenges half-done. +每个挑战都可以是一个周末项目。选择一个看起来有趣的并为它留出时间。不要试图一次完成所有;你对不熟悉工作的精力是有限的,从一个完成的挑战中学到的东西比从三个半途而废的挑战中学到的更多。 -If you get stuck, do two things. First, re-read the relevant section of the chapter; the hints are there. Second, look at real FreeBSD drivers that do something similar. The source tree is your best teacher for the idiomatic way to solve problems that have been solved before. +如果你卡住了,做两件事。首先,重新阅读本章的相关节次;提示就在那里。其次,看看做了类似事情的真实 FreeBSD 驱动程序。源代码树是你解决之前已被解决过的问题的最佳老师。 -## 故障排除 and Common Mistakes +## 故障排除与常见错误 -This section collects the problems that driver authors most often hit when working with virtualised and containerised environments. Each entry describes the symptom, the likely cause, and the way to verify and fix it. Keep this as a reference; the first time you see a symptom, it will be new, and the next time it will be familiar. +本节汇集了驱动程序作者在使用虚拟化和容器化环境时最常遇到的问题。每个条目描述症状、可能的原因以及验证和修复的方法。把它当作参考保留;第一次看到症状时它是新的,下次就会熟悉了。 -### VirtIO Device Not Detected in the Guest +### 客户机中未检测到 VirtIO 设备 -**Symptom**: The guest boots, but `pciconf -l` does not show the VirtIO device, and `dmesg` contains no `virtio` attach messages. +**症状**:客户机启动了,但 `pciconf -l` 不显示 VirtIO 设备,`dmesg` 中没有 `virtio` 附加消息。 -**Cause**: Either the host did not configure the device (wrong `bhyve` command line, wrong `vm-bhyve` template), or the guest kernel is missing the VirtIO module. On FreeBSD 14.3, VirtIO drivers are built into `GENERIC` and auto-load; the guest side should almost never be the cause. +**原因**:要么是主机没有配置设备(错误的 `bhyve` 命令行、错误的 `vm-bhyve` 模板),要么是客户机内核缺少 VirtIO 模块。在 FreeBSD 14.3 上,VirtIO 驱动程序内置于 `GENERIC` 并自动加载;客户机侧几乎不应该是原因。 -**Fix**: On the host, verify that the `bhyve` command line includes the device. For `vm-bhyve`, look at the VM's configuration file and check for lines like `disk0_type="virtio-blk"` or `network0_type="virtio-net"`. If the device is listed but still missing, check that the hypervisor has permission to access the backing resource (the disk image, the tap device). +**修复**:在主机上,验证 `bhyve` 命令行包含该设备。对于 `vm-bhyve`,查看 VM 的配置文件,检查是否有 `disk0_type="virtio-blk"` 或 `network0_type="virtio-net"` 这样的行。如果设备已列出但仍然缺失,检查虚拟机监控程序是否有权访问后备资源(磁盘映像、tap 设备)。 -Inside the guest, confirm the kernel has VirtIO: `kldstat -m virtio` or `kldstat | grep -i virtio`. If the module is not loaded, try `kldload virtio`. +在客户机内,确认内核有 VirtIO:`kldstat -m virtio` 或 `kldstat | grep -i virtio`。如果模块未加载,尝试 `kldload virtio`。 -### virtqueue_enqueue Fails With ENOBUFS +### virtqueue_enqueue 返回 ENOBUFS -**Symptom**: A VirtIO driver tries to enqueue a buffer and gets `ENOBUFS`. +**症状**:VirtIO 驱动程序尝试入队缓冲区时得到 `ENOBUFS`。 -**Cause**: The virtqueue is full. Either the driver has not been draining completed buffers through `virtqueue_dequeue`, or the ring size is smaller than expected and the driver is enqueueing more than it can hold. +**原因**:虚拟队列已满。要么是驱动程序没有通过 `virtqueue_dequeue` 排空已完成的缓冲区,要么是环形大小比预期的小,驱动程序入队的内容超过了它能容纳的。 -**Fix**: Call `virtqueue_dequeue` in the interrupt handler to drain completed buffers and free their associated state. If the ring is genuinely too small, negotiate a larger ring size at feature-negotiation time, if the device supports `VIRTIO_F_RING_INDIRECT_DESC` or similar features. +**修复**:在中断处理程序中调用 `virtqueue_dequeue` 排空已完成的缓冲区并释放其关联状态。如果环形确实太小,在特性协商时协商更大的环形大小,前提是设备支持 `VIRTIO_F_RING_INDIRECT_DESC` 或类似特性。 -A common beginner error is to forget that enqueue produces a descriptor that must be matched by a dequeue. Every successful enqueue must eventually produce a dequeue; otherwise the ring fills up. +一个常见的初学者错误是忘记入队产生一个必须与出队匹配的描述符。每次成功的入队最终必须产生一次出队;否则环形会被填满。 -### Passthrough Device Not Available in the Guest +### 客户机中直通设备不可用 -**Symptom**: The host has marked a device as passthrough-capable, the guest is configured to use it, but the guest does not see the device. +**症状**:主机已将设备标记为可直通,客户机已配置使用它,但客户机看不到该设备。 -**Cause**: Several possible. The host did not actually bind the device to `ppt(4)` at boot (check `pciconf -l` for `pptN`). The host's firmware does not have the IOMMU enabled (check `dmesg | grep -i dmar` or `grep -i iommu`). The device is in an IOMMU group that cannot be split (so you need to pass through the whole group). +**原因**:有几种可能。主机实际上没有在启动时将设备绑定到 `ppt(4)`(检查 `pciconf -l` 中的 `pptN`)。主机固件没有启用 IOMMU(检查 `dmesg | grep -i dmar` 或 `grep -i iommu`)。设备在一个无法拆分的 IOMMU 组中(所以需要直通整个组)。 -**Fix**: Verify each of the above in turn. `dmesg | grep -i dmar` should show initialisation messages from `dmar(4)` on Intel hosts or `amdvi(4)` on AMD hosts. If those are missing, enable VT-d or AMD-Vi in the firmware. If the device is in a shared IOMMU group, either pass through the whole group or move the device to a different PCI slot that is better isolated (an administrator task requiring chassis access). +**修复**:依次验证上述各项。`dmesg | grep -i dmar` 应该显示 Intel 主机上 `dmar(4)` 或 AMD 主机上 `amdvi(4)` 的初始化消息。如果缺失,在固件中启用 VT-d 或 AMD-Vi。如果设备在共享的 IOMMU 组中,要么直通整个组,要么将设备移到隔离更好的不同 PCI 插槽(需要物理机箱访问的管理员任务)。 -### Kernel Panic at Module Load Inside a Guest +### 客户机内加载模块时内核崩溃 -**Symptom**: `kldload` of a new driver inside a guest causes a kernel panic. +**症状**:在客户机内 `kldload` 新驱动程序导致内核 panic。 -**Cause**: Usually a bug in the driver, but sometimes a VirtIO-specific one: the driver assumes a device feature that the backend does not provide, or it accesses config space using the wrong layout (legacy versus modern). +**原因**:通常是驱动程序的 bug,但有时是 VirtIO 特有的:驱动程序假设了后端不提供的设备特性,或者它使用错误的布局(传统与现代)访问配置空间。 -**Fix**: Use the guest as your development platform precisely to make panics cheap. Capture the panic output (either from the serial console or from a `bhyve` log), narrow down the faulting function with `ddb(4)` if you have it configured, and iterate. The combination of a VM (so panics are cheap) and `printf` debugging (so you can see what happens before the panic) is usually enough to fix a VirtIO driver bug quickly. +**修复**:使用客户机作为你的开发平台正是为了让 panic 的代价低廉。捕获 panic 输出(从串行控制台或 `bhyve` 日志),如果你配置了 `ddb(4)` 就用它缩小故障函数范围,然后迭代。VM(所以 panic 代价低)和 `printf` 调试(所以你可以看到 panic 之前发生了什么)的组合通常足以快速修复 VirtIO 驱动程序 bug。 -For VirtIO-specific bugs, double-check the feature bits your driver negotiates. A driver that claims a feature but then does not implement it correctly (for example, claims `VIRTIO_F_VERSION_1` but uses legacy config space) will break in surprising ways. +对于 VirtIO 特有的 bug,仔细检查驱动程序协商的特性位。声明了特性但没有正确实现的驱动程序(例如,声明 `VIRTIO_F_VERSION_1` 但使用传统配置空间)会以令人惊讶的方式出错。 -### Jail Cannot See a Device Even After Unhiding +### 取消隐藏后监狱仍看不到设备 -**Symptom**: A devfs ruleset includes the device, the ruleset is applied to the jail, but the jail's `ls /dev` does not show it. +**症状**:devfs 规则集包含该设备,规则集已应用到 jail,但 jail 的 `ls /dev` 不显示它。 -**Cause**: The `devfs` mount inside the jail was not re-mounted or re-ruled after the ruleset change. devfs caches the visibility decision at mount time, so later changes do not propagate until the mount is refreshed. +**原因**:jail 内的 `devfs` 挂载在规则集更改后没有被重新挂载或重新应用规则。devfs 在挂载时缓存可见性决定,所以后续更改不会传播,直到挂载被刷新。 -**Fix**: Run `devfs -m /jails/myjail/dev rule -s 100 applyset` (replace the path and ruleset number as appropriate) to force a reapply. Alternatively, stop the jail, restart `devfs`, and start the jail again. The `service devfs restart` command applies the rules in `/etc/devfs.rules` to the host's `/dev`; for jails, you generally need to restart the jail. +**修复**:运行 `devfs -m /jails/myjail/dev rule -s 100 applyset`(替换路径和规则集编号)来强制重新应用。或者,停止 jail,重启 `devfs`,再启动 jail。`service devfs restart` 命令将 `/etc/devfs.rules` 中的规则应用到主机的 `/dev`;对于 jail,通常需要重启 jail。 -### Privilege Denied Inside a Jail That Should Work +### 监狱内权限被拒绝但应能工作 -**Symptom**: A driver operation works on the host as root but fails with `EPERM` inside a jail's root. +**症状**:驱动程序操作在主机上以 root 身份可以工作,但在 jail 的 root 内以 `EPERM` 失败。 -**Cause**: The operation requires a privilege that `prison_priv_check` denies by default. This is the intended behaviour. The fix is either to use a less-privileged operation, to configure the jail with `allow.*` to grant the privilege, or (if appropriate) to change the driver to use a different privilege. +**原因**:操作需要 `prison_priv_check` 默认拒绝的权限。这是预期行为。修复方法是使用较低权限的操作,用 `allow.*` 配置 jail 以授予权限,或(如果适当)更改驱动程序以使用不同的权限。 -**Fix**: Look at the driver's `priv_check` call and identify which privilege is being checked. Consult `/usr/src/sys/sys/priv.h` and `prison_priv_check` in `/usr/src/sys/kern/kern_jail.c` to see whether the privilege is allowed inside jails. If it is not, consider whether the restriction is appropriate (usually yes) and adjust the jail's configuration accordingly (`allow.raw_sockets`, `allow.mount`, etc.). +**修复**:查看驱动程序的 `priv_check` 调用并识别正在检查的权限。查阅 `/usr/src/sys/sys/priv.h` 和 `/usr/src/sys/kern/kern_jail.c` 中的 `prison_priv_check` 以了解该权限是否在 jail 内被允许。如果不被允许,考虑该限制是否适当(通常是)并相应调整 jail 的配置(`allow.raw_sockets`、`allow.mount` 等)。 -Do not be tempted to remove the `priv_check` call just to make the jail work. The check is there for a reason; work with the framework, not against it. +不要为了使 jail 工作而删除 `priv_check` 调用。检查是有原因的;与框架合作,而不是对抗它。 -### VNET Jail Cannot Send or Receive Packets +### VNET 监狱无法发送或接收数据包 -**Symptom**: A VNET jail is created, an interface is moved in, but network traffic does not flow. +**症状**:创建了 VNET jail,接口已移入,但网络流量不流动。 -**Cause**: Several possibilities. The interface was not configured inside the jail (each VNET has its own ifconfig state). The default route was not set inside the jail. The host's firewall is blocking traffic between the jail's interface and the rest of the network. The interface is not in an `UP` state. +**原因**:有几种可能。接口没有在 jail 内配置(每个 VNET 有自己的 ifconfig 状态)。jail 内没有设置默认路由。主机的防火墙阻止了 jail 接口和其余网络之间的流量。接口不在 `UP` 状态。 -**Fix**: Inside the jail, run `ifconfig` and confirm the interface has an address and is `UP`. Run `netstat -rn` and confirm the routing table has the entries you expect. If you are using `pf(4)` or `ipfw(8)` on the host, check the rules: filter rules apply to the host's VNET, and the jail's packets may be rejected if the host's filter blocks them (depending on how the topology is set up). +**修复**:在 jail 内,运行 `ifconfig` 确认接口有地址且为 `UP`。运行 `netstat -rn` 确认路由表有你期望的条目。如果在主机上使用 `pf(4)` 或 `ipfw(8)`,检查规则:过滤规则应用于主机的 VNET,jail 的数据包可能被主机的过滤器拒绝(取决于拓扑的设置方式)。 -For `epair(4)` setups specifically, remember that both ends need configuration, and that the host side stays on the host. The jail configures the end that was moved in; the host configures the end that stayed. +对于 `epair(4)` 设置,记住两端都需要配置,主机侧留在主机上。jail 配置移入的那端;主机配置留下的那端。 -### PCI Passthrough Driver Fails to Attach in the Guest +### PCI 直通驱动程序在客户机中附加失败 -**Symptom**: The guest sees the passed-through device in `pciconf -l`, but the driver fails to attach, or the attach succeeds but `read`/`write` fails. +**症状**:客户机在 `pciconf -l` 中看到直通设备,但驱动程序附加失败,或附加成功但 `read`/`write` 失败。 -**Cause**: Usually one of two things. Either the driver assumes a platform-specific feature that is not present in the guest (an ACPI table, a BIOS entry), or the driver is programming physical addresses directly rather than going through `bus_dma(9)`, and the IOMMU is redirecting DMA in a way the driver does not expect. +**原因**:通常是以下两种之一。要么是驱动程序假设了客户机中不存在的平台特定功能(ACPI 表、BIOS 条目),要么是驱动程序直接编程物理地址而不是通过 `bus_dma(9)`,IOMMU 正在以驱动程序不期望的方式重定向 DMA。 -**Fix**: For the first case, look at the driver's attach code for calls that read platform tables (ACPI, FDT, etc.). If the guest's firmware does not expose the expected tables, the driver must either provide defaults or refuse gracefully. +**修复**:对于第一种情况,查看驱动程序的附加代码中读取平台表(ACPI、FDT 等)的调用。如果客户机的固件没有暴露预期的表,驱动程序必须提供默认值或优雅地拒绝。 -For the second case, audit the driver's DMA code. Every address programmed into the device must come from a `bus_dma(9)` load operation, not from a `vtophys` call or similar. This is standard practice anyway, but it becomes mandatory under passthrough. +对于第二种情况,审计驱动程序的 DMA 代码。编程到设备中的每个地址必须来自 `bus_dma(9)` 的加载操作,而不是 `vtophys` 调用或类似方法。这本身就是标准实践,但在直通下是强制性的。 -### Host Becomes Unresponsive When a Guest Starts +### 客户机启动时主机变得无响应 -**Symptom**: Running `bhyve(8)` makes the host sluggish or unresponsive. +**症状**:运行 `bhyve(8)` 使主机变得迟钝或无响应。 -**Cause**: Resource contention. The guest is allocated more memory or more VCPUs than the host can afford to share. The host is swapping or spinning on a shared lock. +**原因**:资源争用。客户机被分配了比主机能够承受分享的更多内存或更多 VCPU。主机在交换或在共享锁上自旋。 -**Fix**: Check the guest's resource allocation. A guest with all the host's memory will starve the host; a guest with more VCPUs than the host has cores will cause thrashing. A common rule of thumb is to give guests no more than half the host's memory and no more VCPUs than (host cores - 1), to leave room for the host itself. +**修复**:检查客户机的资源分配。占用主机全部内存的客户机会使主机内存不足;VCPU 超过主机核心数的客户机会导致抖动。常用的经验法则是给客户机不超过主机一半的内存,VCPU 不超过(主机核心数 - 1),为主机本身留出空间。 -If the sluggishness persists after sensible allocation, check `top -H` on the host for the `bhyve(8)` process and its threads. Heavy CPU use by `bhyve(8)` suggests the guest is doing something CPU-intensive; heavy CPU use by `vmm` kernel threads suggests excessive VM exits, which may indicate a guest driver that is polling too aggressively. +如果在合理分配后仍然迟钝,检查主机上的 `top -H` 查看 `bhyve(8)` 进程及其线程。`bhyve(8)` 的 CPU 使用率高表明客户机在做 CPU 密集型操作;`vmm` 内核线程的 CPU 使用率高表明 VM 退出过多,可能表示客户机驱动程序轮询过于激进。 -### `kldunload` Hangs +### `kldunload` 挂起 -**Symptom**: Unloading a driver module hangs the process and cannot be interrupted. +**症状**:卸载驱动程序模块时进程挂起且无法中断。 -**Cause**: Some resource the driver owns is still in use. A file descriptor is still open on the driver's device, a callout is still scheduled, a taskqueue still has pending tasks, or a kernel thread the driver spawned has not exited. +**原因**:驱动程序拥有的某些资源仍在使用。驱动程序设备上的文件描述符仍然打开、callout 仍在调度、taskqueue 仍有待处理任务,或驱动程序生成的内核线程尚未退出。 -**Fix**: Find and release the holder. `fstat` or `lsof` lists open file descriptors; `procstat -kk` shows kernel threads. The driver's module unload handler must drain every async mechanism it starts: cancel callouts, drain taskqueues, wait for kernel threads to exit, close any held file descriptors. If any of these is missing, unload hangs. +**修复**:找到并释放持有者。`fstat` 或 `lsof` 列出打开的文件描述符;`procstat -kk` 显示内核线程。驱动程序的模块卸载处理程序必须排空它启动的每个异步机制:取消 callout、排空 taskqueue、等待内核线程退出、关闭任何持有的文件描述符。如果缺少其中任何一个,卸载就会挂起。 -For VNET-aware drivers, the unload must correctly clean up per-VNET state. A common mistake is to clean up in `mod_event(MOD_UNLOAD)` but forget that one of the VNETs the module is attached to is not the current one; accessing its state without `CURVNET_SET` leads to either a wrong-context access (fast) or a hang (slow). The correct pattern is to iterate over VNETs and clean up each explicitly. +对于 VNET 感知的驱动程序,卸载必须正确清理 per-VNET 状态。一个常见错误是在 `mod_event(MOD_UNLOAD)` 中清理但忘记模块附加的某个 VNET 不是当前的;不使用 `CURVNET_SET` 就访问其状态会导致错误的上下文访问(快)或挂起(慢)。正确的模式是遍历 VNET 并显式清理每个。 -### Timing-Related Bugs Only in VMs +### 仅在虚拟机中出现的时序相关错误 -**Symptom**: The driver works on bare metal but hangs or loses interrupts inside a VM. +**症状**:驱动程序在裸金属上工作但在 VM 内挂起或丢失中断。 -**Cause**: Timing assumptions that fail under virtualisation. Guest execution is sometimes paused for milliseconds at a time (during VM exits), and a driver that polls a status register in a tight loop without yielding may fail to make progress or may consume excessive CPU. +**原因**:在虚拟化下失效的时序假设。客户机执行有时会被暂停数毫秒(在 VM 退出期间),在紧密循环中轮询状态寄存器而不让步的驱动程序可能无法取得进展或消耗过多 CPU。 -**Fix**: Replace tight polling with `DELAY(9)` for microsecond-scale waits, `pause(9)` for short waits, or proper sleep with `tsleep(9)` for longer waits. Use interrupt-driven designs instead of polling wherever possible. Test with virtio-blk's performance counters to see whether the driver is generating an unreasonable number of VM exits. +**修复**:将紧密轮询替换为 `DELAY(9)`(微秒级等待)、`pause(9)`(短等待)或 `tsleep(9)`(更长的适当睡眠)。尽可能使用中断驱动设计而不是轮询。用 virtio-blk 的性能计数器测试驱动程序是否产生了不合理的 VM 退出数量。 -A driver that works correctly on bare metal but fails on a VM is almost always making a timing assumption. The solution is to use the kernel's time primitives correctly; they work on both. +在裸金属上正确工作但在 VM 上失败的驱动程序几乎总是在做时序假设。解决方案是正确使用内核的时间原语;它们在两种环境中都能工作。 -### VirtIO Negotiation Fails or Returns Unexpected Features +### VirtIO 协商失败或返回意外特性 -**Symptom**: The driver logs that feature negotiation produced a feature set that is missing bits you expected, or the probe-and-attach path succeeds but the device behaves unexpectedly. +**症状**:驱动程序记录特性协商产生的特性集缺少你期望的位,或者探测和附加路径成功但设备行为异常。 -**Cause**: Two classes of issue. The first is that the device (or its backend) advertises a feature set that does not include the bit you requested. This is normal when the hypervisor's backend is older or intentionally minimal. The second is that the guest-side code is requesting a feature bit that the framework does not know about, in which case the framework may strip it silently. +**原因**:两类问题。第一类是设备(或其后端)播发的特性集不包含你请求的位。当虚拟机监控程序的后端较旧或有意的最小时,这是正常的。第二类是客户机侧代码请求了框架不知道的特性位,框架可能会静默地剥离它。 -**Fix**: Log `sc->features` immediately after `virtio_negotiate_features` returns. Compare it to the set you requested. If the device is missing a bit you thought was mandatory, your driver needs to fall back gracefully or refuse to attach with a clear error message. Never assume a bit is present without checking the post-negotiation value. +**修复**:在 `virtio_negotiate_features` 返回后立即记录 `sc->features`。将它与你请求的集合进行比较。如果设备缺少你认为必需的位,驱动程序需要优雅地回退或以明确的错误消息拒绝附加。永远不要在不检查协商后值的情况下假设位存在。 -For backend-side investigation (if you are using a hypervisor whose source you can read, such as `bhyve(8)` or QEMU), look at the device emulator's feature advertisement. The backend holds the truth: the guest sees only what the backend advertises. A mismatch between what you expect and what you see almost always traces back to the backend. +对于后端侧的调查(如果你使用的是可以阅读源代码的虚拟机监控程序,如 `bhyve(8)` 或 QEMU),查看设备模拟器的特性播发。后端掌握真相:客户机只看到后端播发的内容。你期望的和看到的之间的不匹配几乎总是追溯到后端。 -### `bus_alloc_resource` Fails Inside a Guest +### 客户机内 `bus_alloc_resource` 失败 -**Symptom**: The attach path calls `bus_alloc_resource_any` or `bus_alloc_resource` and receives `NULL`, causing the driver to fail attach. +**症状**:附加路径调用 `bus_alloc_resource_any` 或 `bus_alloc_resource` 并收到 `NULL`,导致驱动程序附加失败。 -**Cause**: Under a hypervisor, the device's resources (BARs, IRQ lines, MMIO windows) may differ from their bare-metal layout. A driver that hard-codes resource IDs or assumes specific BAR numbers can fail if the hypervisor presents a different layout. +**原因**:在虚拟机监控程序下,设备的资源(BAR、IRQ 线、MMIO 窗口)可能与其裸金属布局不同。硬编码资源 ID 或假设特定 BAR 编号的驱动程序在虚拟机监控程序呈现不同布局时可能失败。 -**Fix**: Always use `pci_read_config(dev, PCIR_...)` to read actual BAR contents rather than assuming. Use `bus_alloc_resource_any` with the rid obtained from the resource list, not a hard-coded number. If the resource allocation still fails, compare `pciconf -lvBb` output from bare metal and from the guest to see what has changed. +**修复**:始终使用 `pci_read_config(dev, PCIR_...)` 读取实际 BAR 内容而不是假设。使用从资源列表获取的 rid 配合 `bus_alloc_resource_any`,而不是硬编码的数字。如果资源分配仍然失败,比较裸金属和客户机的 `pciconf -lvBb` 输出以查看变化。 -A concrete example: a device that uses BAR 0 for MMIO and BAR 2 for I/O on bare metal may be configured differently by the hypervisor. Always read the BARs at runtime and allocate resources based on what is actually present. +一个具体的例子:在裸金属上使用 BAR 0 作为 MMIO、BAR 2 作为 I/O 的设备可能被虚拟机监控程序以不同方式配置。始终在运行时读取 BAR 内容并根据实际存在的资源进行分配。 -### `kldload` Succeeds but No Device Attaches +### `kldload` 成功但无设备附加 -**Symptom**: `kldload` of a VirtIO driver returns success, but `kldstat -v` shows no device bound to the module, and no dmesg messages are produced. +**症状**:VirtIO 驱动程序的 `kldload` 返回成功,但 `kldstat -v` 显示没有设备绑定到该模块,且没有产生 dmesg 消息。 -**Cause**: The driver's PNP table does not match any device advertised by the hypervisor. This is normal when a backend is not providing the expected device. For `vtedu` in the case study, this is the expected behaviour without a matching `bhyve(8)` backend. +**原因**:驱动程序的 PNP 表与虚拟机监控程序播发的任何设备都不匹配。当后端未提供预期设备时,这是正常的。对于案例研究中的 `vtedu`,在没有匹配的 `bhyve(8)` 后端时,这是预期行为。 -**Fix**: Run `devctl list` (or `devinfo -v`) on the host or in the guest to see which devices are present but unbound. If the device is not listed at all, the backend is not running or is misconfigured. If the device is listed but unbound, check its PNP identifiers (`vendor`, `device` for PCI, or the VirtIO type ID for VirtIO) and compare against the driver's PNP table. Mismatch is the most common cause. +**修复**:在主机或客户机上运行 `devctl list`(或 `devinfo -v`)查看哪些设备存在但未绑定。如果设备根本未列出,则后端未运行或配置错误。如果设备已列出但未绑定,检查其 PNP 标识符(PCI 的 `vendor`、`device`,或 VirtIO 的类型 ID)并与驱动程序的 PNP 表进行比较。不匹配是最常见的原因。 -A common beginner error is to believe that `kldload` success means the driver is working. It only means the module loaded. Use `kldstat -v | grep yourdriver` to see whether any device has been claimed. +一个常见的初学者错误是认为 `kldload` 成功意味着驱动程序正在工作。它仅表示模块已加载。使用 `kldstat -v | grep yourdriver` 查看是否有任何设备已被声明。 -### Module Is Loaded but `/dev` Node Does Not Appear +### 模块已加载但 `/dev` 节点未出现 -**Symptom**: The driver has loaded, `kldstat -v` shows it attached to a device, but the expected `/dev` node does not appear. +**症状**:驱动程序已加载,`kldstat -v` 显示它已附加到设备,但预期的 `/dev` 节点未出现。 -**Cause**: Either the driver did not call `make_dev(9)`, or the `devfs` mount inside the current jail is filtered by a ruleset that hides the node, or the `make_dev` call failed silently because the device unit number clashed with an existing one. +**原因**:要么驱动程序未调用 `make_dev(9)`,要么当前 jail 内的 `devfs` 挂载被隐藏该节点的规则集过滤,要么 `make_dev` 调用因设备单元号与现有单元号冲突而静默失败。 -**Fix**: On the host, check `ls /dev/yourdev*`. If it is missing there too, the driver did not create the node. Check the attach path for the `make_dev` call, and verify its return value. If the node is present on the host but missing inside a jail, the devfs ruleset is the cause. Run `devfs -m /path/to/jail/dev rule show` to see the active ruleset inside the jail. +**修复**:在主机上,检查 `ls /dev/yourdev*`。如果那里也缺失,则驱动程序未创建该节点。检查附加路径中的 `make_dev` 调用并验证其返回值。如果节点在主机上存在但在 jail 内缺失,则 devfs 规则集是原因。运行 `devfs -m /path/to/jail/dev rule show` 查看 jail 内的活动规则集。 -For a driver that is intended to be visible inside jails, the correct practice is to document which devfs ruleset exposes the node and to provide an example ruleset in the driver's README. Do not assume the administrator will figure it out. +对于预期在 jail 内可见的驱动程序,正确的做法是记录哪个 devfs 规则集暴露了该节点,并在驱动程序的 README 中提供示例规则集。不要假设管理员会自己弄明白。 -### Virtqueue Interrupts Never Fire +### 虚拟队列中断从未触发 -**Symptom**: The driver's interrupt handler is never called, even though the driver has submitted work to the virtqueue. +**症状**:驱动程序的中断处理程序从未被调用,尽管驱动程序已向虚拟队列提交了工作。 -**Cause**: One of several possibilities. The backend never processes the work (bug in the backend). The driver did not register the interrupt handler correctly. The driver did not call `virtio_setup_intr`, so no interrupt plumbing exists. The driver disabled interrupts via `virtqueue_disable_intr` and never re-enabled them. +**原因**:以下几种可能性之一。后端从未处理该工作(后端中的 bug)。驱动程序未正确注册中断处理程序。驱动程序未调用 `virtio_setup_intr`,因此不存在中断管道。驱动程序通过 `virtqueue_disable_intr` 禁用了中断且从未重新启用。 -**Fix**: Systematically check each step. In the attach path, verify that `virtio_setup_intr` was called and returned 0. In the interrupt handler, verify that you are re-enabling interrupts when appropriate. Add a `printf` at the top of the handler to confirm it is never called. If the handler is genuinely never called, run `vmstat -i | grep yourdriver` to see the interrupt count; a count of zero confirms the interrupt is not arriving. +**修复**:系统地检查每一步。在附加路径中,验证 `virtio_setup_intr` 已被调用并返回 0。在中断处理程序中,验证您正在适当地重新启用中断。在处理程序顶部添加 `printf` 以确认它从未被调用。如果处理程序确实从未被调用,运行 `vmstat -i | grep yourdriver` 查看中断计数;计数为零确认中断未到达。 -If the count is nonzero but the handler does no work, the handler is running but finding nothing in the virtqueue. This suggests the backend is acknowledging but not producing real completions; look at the backend. +如果计数非零但处理程序不做任何工作,则处理程序正在运行但在虚拟队列中找不到任何内容。这表明后端正在确认但未产生真正的完成;检查后端。 -### Interrupt Storm Under Virtualisation +### 虚拟化下的中断风暴 -**Symptom**: Inside a VM, `vmstat -i` shows interrupt rates in the hundreds of thousands per second, and CPU utilisation is high even without real work. +**症状**:在虚拟机内部,`vmstat -i` 显示每秒数十万次的中断速率,即使没有实际工作,CPU 利用率也很高。 -**Cause**: An interrupt that is not being cleared, or a driver that interrupts on every event without coalescing. Under INTx specifically, a level-triggered interrupt that remains asserted causes the handler to be called in a loop. +**原因**:未被清除的中断,或驱动程序在每个事件上触发中断而不进行合并。特别是在 INTx 下,保持断言状态的电平触发中断会导致处理程序在循环中被调用。 -**Fix**: For MSI-X, confirm that the handler acknowledges completions and that the virtqueue ring is being drained. For INTx, confirm that the handler clears the device's interrupt status register. For VirtIO specifically, negotiate `VIRTIO_F_RING_EVENT_IDX` if the backend supports it; this lets the device suppress unnecessary interrupts. +**修复**:对于 MSI-X,确认处理程序确认了完成并且虚拟队列环正在被排空。对于 INTx,确认处理程序清除了设备的中断状态寄存器。对于 VirtIO 特别地,如果后端支持,协商 `VIRTIO_F_RING_EVENT_IDX`;这使设备可以抑制不必要的中断。 -Look at the Section 9 pattern with `virtqueue_disable_intr` / `virtqueue_enable_intr`. A correct driver disables interrupts on entry, drains the ring, and only re-enables interrupts when the ring is empty. Missing this structure is a common cause of interrupt storms. +查看第9节中使用 `virtqueue_disable_intr` / `virtqueue_enable_intr` 的模式。正确的驱动程序在进入时禁用中断,排空环,并且仅在环为空时重新启用中断。缺少这种结构是中断风暴的常见原因。 -### DMA Failures Only Under Passthrough +### 仅在直通下出现的 DMA 故障 -**Symptom**: The driver works correctly with an emulated device, but when the same hardware is passed through via `ppt(4)`, DMA transfers fail silently or corrupt memory. +**症状**:驱动程序在使用模拟设备时正常工作,但当同一硬件通过 `ppt(4)` 直通时,DMA 传输静默失败或破坏内存。 -**Cause**: Most often, the driver is programming physical addresses directly rather than going through `bus_dma(9)`. Under emulation, the hypervisor intercepts all I/O and translates addresses on the fly, hiding the bug. Under passthrough, the device DMA's directly through the IOMMU, and the physical address the driver programmed is not the bus address the IOMMU expects. +**原因**:最常见的是,驱动程序直接编程物理地址而非通过 `bus_dma(9)`。在模拟下,虚拟机监控程序拦截所有 I/O 并即时转换地址,隐藏了该 bug。在直通下,设备直接通过 IOMMU 进行 DMA,驱动程序编程的物理地址不是 IOMMU 期望的总线地址。 -**Fix**: Audit every place the driver computes an address to program into the device. Each must come from `bus_dma_load` or `bus_dma_load_mbuf` or similar, not from `vtophys` or a raw physical address. This is a mandatory discipline for passthrough and is strongly recommended for all drivers. +**修复**:审计驱动程序计算要编程到设备中的地址的每个位置。每个地址必须来自 `bus_dma_load` 或 `bus_dma_load_mbuf` 或类似的 API,而不是来自 `vtophys` 或原始物理地址。这是直通的强制性规范,强烈建议所有驱动程序遵守。 -A useful diagnostic: enable IOMMU verbose logging (`sysctl hw.dmar.debug=1` on Intel, or the equivalent on AMD) and watch the kernel log for IOMMU page faults while the driver runs. A page fault reveals exactly which bus address the device attempted to access; if it does not match a mapped region, the driver's address calculation is wrong. +一个有用的诊断方法:启用 IOMMU 详细日志记录(Intel 上为 `sysctl hw.dmar.debug=1`,或 AMD 上的等效设置),并在驱动程序运行时观察内核日志中的 IOMMU 页错误。页错误会精确揭示设备尝试访问的总线地址;如果与映射区域不匹配,则驱动程序的地址计算错误。 -### A VirtIO Device Appears but Has the Wrong Type +### VirtIO 设备出现但类型错误 -**Symptom**: The guest sees a VirtIO device at the expected PCI address, but `pciconf -lv` or `devinfo` reports a different VirtIO device type than expected. +**症状**:客户机在预期的 PCI 地址看到 VirtIO 设备,但 `pciconf -lv` 或 `devinfo` 报告了与预期不同的 VirtIO 设备类型。 -**Cause**: Device-ID confusion. The PCI vendor ID for VirtIO is always 0x1af4, but the device ID encodes the VirtIO type, and different VirtIO versions use different device-ID ranges. Legacy VirtIO uses 0x1000 + VIRTIO_ID. Modern VirtIO uses 0x1040 + VIRTIO_ID. A hypervisor that exposes a mix of modern and legacy devices can confuse a driver that only probes one range. +**原因**:设备 ID 混淆。VirtIO 的 PCI 厂商 ID 始终为 0x1af4,但设备 ID 编码了 VirtIO 类型,不同的 VirtIO 版本使用不同的设备 ID 范围。传统 VirtIO 使用 0x1000 + VIRTIO_ID。现代 VirtIO 使用 0x1040 + VIRTIO_ID。一个暴露了现代和传统设备混合的虚拟机监控程序可能混淆仅探测一个范围的驱动程序。 -**Fix**: FreeBSD's `virtio_pci` transport handles both ranges transparently, so most drivers are immune. For driver authors who inspect `pciconf -lv` directly, be aware that both 0x1000-0x103f (legacy) and 0x1040-0x107f (modern) are VirtIO. The `VIRTIO_DRIVER_MODULE` macro registers the driver with both transports and does the right thing for both device-ID ranges. +**修复**:FreeBSD 的 `virtio_pci` 传输透明地处理两个范围,因此大多数驱动程序不受影响。对于直接检查 `pciconf -lv` 的驱动程序作者,请注意 0x1000-0x103f(传统)和 0x1040-0x107f(现代)都是 VirtIO。`VIRTIO_DRIVER_MODULE` 宏在两种传输上注册驱动程序,并为两种设备 ID 范围做正确的事情。 -### Jail-Specific Ioctl Fails With ENOTTY +### 监狱特定的 Ioctl 返回 ENOTTY -**Symptom**: An ioctl that works on the host returns `ENOTTY` when issued from inside a jail, even though the ioctl number is recognised by the driver. +**症状**:在主机上正常工作的 ioctl 在 jail 内发出时返回 `ENOTTY`,即使驱动程序识别该 ioctl 编号。 -**Cause**: The driver's ioctl handler checks jail visibility and returns `ENOTTY` to hide the ioctl's existence from jailed callers. This is a security-by-obscurity pattern used by some drivers that expose host-only administrative operations through otherwise jail-visible devices. +**原因**:驱动程序的 ioctl 处理程序检查 jail 可见性并返回 `ENOTTY` 以对 jail 调用者隐藏该 ioctl 的存在。这是一种通过模糊实现安全性的模式,被一些通过原本 jail 可见的设备暴露仅限主机的管理操作的驱动程序使用。 -**Fix**: If the jail should be able to use the ioctl, review the driver's visibility check. The idiomatic approach is to return `EPERM` (permission denied) rather than `ENOTTY` when an operation exists but is not permitted; `ENOTTY` implies the ioctl does not exist, which can confuse callers. Consider whether the jailed caller should see the ioctl; if so, remove the hiding logic and use `priv_check` for access control instead. +**修复**:如果 jail 应该能够使用该 ioctl,请复查驱动程序的可见性检查。惯用的做法是在操作存在但不被允许时返回 `EPERM`(权限被拒绝)而不是 `ENOTTY`;`ENOTTY` 暗示该 ioctl 不存在,这可能混淆调用者。考虑 jail 调用者是否应该看到该 ioctl;如果是,移除隐藏逻辑并使用 `priv_check` 进行访问控制。 -### VNET Move Leaks Per-VNET State +### VNET 移动泄漏逐 VNET 状态 -**Symptom**: After moving an interface in and out of a VNET multiple times, the kernel's memory usage grows, eventually triggering a memory pressure event. +**症状**:将接口移入和移出 VNET 多次后,内核的内存使用量增长,最终触发内存压力事件。 -**Cause**: The driver allocates per-VNET state when an interface enters a VNET but does not free it when the interface leaves. Each VNET move leaks a fixed amount of memory. +**原因**:当接口进入 VNET 时驱动程序分配逐 VNET 状态,但接口离开时不释放它。每次 VNET 移动泄漏固定数量的内存。 -**Fix**: Implement the VNET-move lifecycle correctly. When an interface enters a VNET (`if_vmove` into the new VNET), allocate per-VNET state. When it leaves (`if_vmove` out), free it. The `CURVNET_SET` and `CURVNET_RESTORE` pair delineates the VNET context; use them when allocating or freeing. +**修复**:正确实现 VNET 移动生命周期。当接口进入 VNET(`if_vmove` 进入新的 VNET)时,分配逐 VNET 状态。当它离开(`if_vmove` 移出)时,释放它。`CURVNET_SET` 和 `CURVNET_RESTORE` 对界定了 VNET 上下文;在分配或释放时使用它们。 -Look at `/usr/src/sys/net/if_tuntap.c` for a correct VNET-move implementation. The lifecycle is subtle and easy to get wrong; a reference implementation is the best teacher. +查看 `/usr/src/sys/net/if_tuntap.c` 了解正确的 VNET 移动实现。生命周期很微妙且容易出错;参考实现是最好的老师。 -### Guest Kernel Panics with "Fatal Trap 12" on First I/O +### 客户机内核在首次 I/O 时出现"Fatal Trap 12"崩溃 -**Symptom**: The guest boots, the driver attaches, the first user-space I/O to the driver's device causes a "Fatal Trap 12: page fault while in kernel mode" panic. +**症状**:客户机启动,驱动程序附加,对驱动程序设备的首次用户空间 I/O 导致"Fatal Trap 12: page fault while in kernel mode"崩溃。 -**Cause**: Almost always a NULL pointer dereference in the driver's `read`, `write`, or `ioctl` path. Under virtualisation, the fault is immediate rather than merely corrupt-then-continue, because the guest's memory protection is exact. +**原因**:几乎总是驱动程序 `read`、`write` 或 `ioctl` 路径中的空指针解引用。在虚拟化下,故障是立即发生的,而不仅仅是破坏后继续执行,因为客户机的内存保护是精确的。 -**Fix**: Use the kernel's debugger (`ddb(4)` or `dtrace(1)`) to find the faulting instruction. A typical cause is a `dev->si_drv1 = sc` that was forgotten in attach, so when user space opens `/dev/yourdriver` and calls `read`, `dev->si_drv1` is NULL. The fix is to always set `si_drv1` in attach, right after creating the cdev. +**修复**:使用内核调试器(`ddb(4)` 或 `dtrace(1)`)找到故障指令。典型的原因是在附加时忘记了 `dev->si_drv1 = sc`,因此当用户空间打开 `/dev/yourdriver` 并调用 `read` 时,`dev->si_drv1` 为 NULL。修复方法是在附加时紧接在创建 cdev 之后始终设置 `si_drv1`。 -Under VMs, these panics are cheap: fix the code, rebuild, reload. On bare metal, each panic costs a reboot. One more reason to develop under virtualisation. +在虚拟机中,这些崩溃代价低廉:修复代码、重新构建、重新加载。在裸金属上,每次崩溃都需要重启。这是在虚拟化下开发的又一个理由。 -### Live Migration Fails or Causes Guest Hang +### 实时迁移失败或导致客户机挂起 -**Symptom**: A guest under a hypervisor that supports live migration (currently limited in `bhyve(8)`, more common in Linux KVM and VMware) is migrated to a different host, and the guest hangs or corrupts after migration. +**症状**:在支持实时迁移的虚拟机监控程序下(目前在 `bhyve(8)` 中有限支持,在 Linux KVM 和 VMware 中更常见)的客户机被迁移到不同主机后,客户机挂起或损坏。 -**Cause**: The guest driver holds state that is tied to the source host (a specific physical TSC, a specific IOMMU mapping, a specific passed-through device). Migration transfers the guest's memory and CPU state but cannot transfer physical hardware state. +**原因**:客户机驱动程序持有与源主机绑定的状态(特定的物理 TSC、特定的 IOMMU 映射、特定的直通设备)。迁移传输客户机的内存和 CPU 状态,但无法传输物理硬件状态。 -**Fix**: For driver authors, the advice is simple: do not cache values that are tied to the physical host. Re-read TSC frequency from `timecounter(9)` rather than storing a local copy. Do not pass through PCI devices that you need to migrate. For VirtIO devices, live migration is supported by the standard, and the guest driver needs no special code. +**修复**:对于驱动程序作者,建议很简单:不要缓存与物理主机绑定的值。从 `timecounter(9)` 重新读取 TSC 频率,而不是存储本地副本。不要直通您需要迁移的 PCI 设备。对于 VirtIO 设备,标准支持实时迁移,客户机驱动程序不需要特殊代码。 -If you are writing a driver for a live-migration-supporting environment, the main design rule is: all state should be in the guest's memory; anything on the host side should be recreatable after migration. Standard VirtIO drivers meet this bar because the virtqueue state is in guest memory. +如果您正在为支持实时迁移的环境编写驱动程序,主要设计规则是:所有状态应在客户机的内存中;主机侧的任何内容都应在迁移后可重新创建。标准 VirtIO 驱动程序满足这一要求,因为虚拟队列状态在客户机内存中。 -### Unexpected devfs Entries Appear Inside a Jail +### 监狱内出现意外的 devfs 条目 -**Symptom**: A jail has a minimal devfs ruleset, but entries appear that the administrator did not expect. +**症状**:jail 拥有最小的 devfs 规则集,但出现了管理员未预期的条目。 -**Cause**: Either the ruleset was not applied correctly, or the jail inherited the default ruleset before the custom one was applied, or a new device appeared after the ruleset was set. +**原因**:要么规则集未正确应用,要么 jail 在自定义规则集应用之前继承了默认规则集,要么在规则集设置后出现了新设备。 -**Fix**: Run `devfs -m /jail/path/dev rule show` to see what rules are active. Compare with `/etc/devfs.rules`. If a later rule is adding visibility the earlier rule denied, the order is wrong. If the jail was started before the ruleset was finalised, restart the jail. +**修复**:运行 `devfs -m /jail/path/dev rule show` 查看哪些规则处于活动状态。与 `/etc/devfs.rules` 进行比较。如果后一条规则添加了前一条规则拒绝的可见性,则顺序错误。如果 jail 在规则集最终确定之前已启动,请重启 jail。 -A robust practice is to always start a jail with a known ruleset specified in `/etc/jail.conf` rather than relying on the devfs default. The `devfs_ruleset = NNN` directive in the jail configuration ensures the jail's devfs mount uses the expected ruleset from the moment the jail starts. +一个健壮的做法是始终使用 `/etc/jail.conf` 中指定的已知规则集启动 jail,而不是依赖 devfs 默认值。jail 配置中的 `devfs_ruleset = NNN` 指令确保 jail 的 devfs 挂载从 jail 启动之时起就使用预期的规则集。 -### Two Drivers Fight Over the Same Device +### 两个驱动程序争夺同一设备 -**Symptom**: Loading driver A works, but loading driver B after A (or vice versa) causes one of them to fail attach with a cryptic message about resource conflicts. +**症状**:加载驱动程序 A 正常工作,但在 A 之后加载驱动程序 B(反之亦然)导致其中一个因资源冲突的隐晦消息而附加失败。 -**Cause**: Two drivers are trying to claim the same device. This can happen if the device has multiple valid drivers (for example, a generic driver and a specific driver for a particular chipset variant) and the load order determines which one wins. +**原因**:两个驱动程序试图声明同一设备。当设备有多个有效驱动程序(例如通用驱动程序和特定芯片组变体的专用驱动程序)时可能发生这种情况,加载顺序决定哪个获胜。 -**Fix**: FreeBSD's Newbus arbitrates driver priority through `DRIVER_MODULE`'s ordering, but the exact semantics depend on which driver attached first. The general rule is that once a device is attached, another driver cannot steal it. If you need to switch drivers, detach the first one (`devctl detach yourdev0`) before loading the second. +**修复**:FreeBSD 的 Newbus 通过 `DRIVER_MODULE` 的顺序仲裁驱动程序优先级,但确切的语义取决于哪个驱动程序先附加。一般规则是,一旦设备被附加,另一个驱动程序无法抢夺它。如果您需要切换驱动程序,在加载第二个之前先分离第一个(`devctl detach yourdev0`)。 -Under virtualisation this can show up when you load a test driver after the VirtIO framework has already attached a production driver to the device. The test driver must either use a different PNP entry or explicitly detach the existing one. +在虚拟化下,当您在 VirtIO 框架已将生产驱动程序附加到设备后加载测试驱动程序时,可能出现这种情况。测试驱动程序必须使用不同的 PNP 条目或显式分离现有驱动程序。 -### `vm_guest` Shows "no" Inside an Obvious VM +### 在明显是虚拟机的环境中 `vm_guest` 显示"no" -**Symptom**: `sysctl kern.vm_guest` returns "no" inside a guest that is definitely running under a hypervisor. +**症状**:在确定运行在虚拟机监控程序下的客户机内部,`sysctl kern.vm_guest` 返回"no"。 -**Cause**: The hypervisor is not setting the CPUID hypervisor-present bit, or is setting a vendor string that the FreeBSD kernel does not recognise. This can happen with exotic or customised hypervisors. +**原因**:虚拟机监控程序未设置 CPUID 虚拟机监控程序存在位,或设置了 FreeBSD 内核无法识别的供应商字符串。这可能在特殊或自定义的虚拟机监控程序上发生。 -**Fix**: This is informational, not a fix. If your driver needs to detect virtualisation but `vm_guest` does not cooperate, use alternative signals: the presence of VirtIO devices, the absence of physical hardware that would be present on bare metal, specific CPUID leaves that expose hypervisor-specific information. But recognise that accurate hypervisor detection is hard to guarantee; design your driver to work correctly regardless of the environment, and use `vm_guest` only for non-critical defaults. +**修复**:这是信息性的,而非修复方案。如果您的驱动程序需要检测虚拟化但 `vm_guest` 不配合,请使用替代信号:VirtIO 设备的存在、裸金属上应存在但缺失的物理硬件、暴露虚拟机监控程序特定信息的特定 CPUID 叶。但请认识到精确的虚拟机监控程序检测难以保证;设计您的驱动程序使其无论环境如何都能正确工作,并且仅将 `vm_guest` 用于非关键的默认值。 -### General Diagnostic Approach +### 通用诊断方法 -When something breaks in a virtualised or containerised environment, the pattern for diagnosis is consistent. First, reduce the environment to the simplest setup that shows the problem: strip the VM down to a single VirtIO device, remove extra jails, disable VNET if it is not needed. Second, try the same operation at the next layer up: if the problem shows in a jail, try it on the host; if on the host, try it on a guest; if in a guest, try it on bare metal. The layer where the problem disappears is usually the layer where the problem lives. +当虚拟化或容器化环境中出现问题时,诊断模式是一致的。首先,将环境简化到显示问题的最简单设置:将 VM 剥离到单个 VirtIO 设备、移除额外的 jail、如果不需要则禁用 VNET。其次,在上一层尝试相同的操作:如果问题出现在 jail 中,在主机上尝试;如果在主机上,在客户机上尝试;如果在客户机中,在裸金属上尝试。问题消失的层通常是问题所在的层。 -Third, once you have localised the layer, add logging. `printf` in the kernel is still a valid debugging tool; combined with `dmesg`, it gives you a timestamped trace of what the driver does. `dtrace(1)` is more capable but has a higher setup cost. For a first diagnosis, `printf` is usually enough. +第三,一旦你定位了层,添加日志。内核中的 `printf` 仍然是一个有效的调试工具;结合 `dmesg`,它给你一个带时间戳的驱动程序行为跟踪。`dtrace(1)` 更强大但设置成本更高。对于首次诊断,`printf` 通常就够了。 -Fourth, if the problem is a race or a timing issue, simplify before you complicate. A race that happens once in ten thousand iterations can be investigated with a test loop that runs ten thousand iterations. A timing issue under VM execution can be made reproducible by pinning the VM to specific host CPUs and disabling frequency scaling. +第四,如果问题是竞态或时序问题,先简化再复杂化。每万次迭代发生一次的竞态可以通过运行万次迭代的测试循环来调查。虚拟机执行下的时序问题可以通过将虚拟机固定到特定主机 CPU 并禁用频率缩放来使其可重现。 -None of this is specific to virtualisation. It is good general debugging discipline. Virtualisation just happens to be an environment where the discipline pays off quickly, because the layers are clearly separated and the layers can be swapped in and out easily. +这些都不是虚拟化特定的。这是良好的通用调试规范。虚拟化恰好是一个规范回报很快的环境,因为各层清晰分离,各层可以轻松替换。 -## Wrapping Up +## 总结 -Virtualisation and containerization are two names for what they are in FreeBSD: two different answers to the same broad question. Virtualisation multiplies kernels; containerization subdivides one. A driver lives inside a kernel, and the way it interacts with its environment depends on which of these is in use. +虚拟化和容器化在 FreeBSD 中是两个不同的名称,代表对同一个广泛问题的两种不同回答。虚拟化使内核倍增;容器化使一个内核细分。驱动程序存在于内核内部,它与环境的交互方式取决于正在使用哪种方式。 -The virtualisation side is where the VirtIO story lives. VirtIO is the mature, standardised, high-performance paravirtual interface between a guest driver and a hypervisor-provided device. FreeBSD's VirtIO framework (in `/usr/src/sys/dev/virtio/`) implements the standard cleanly, and the `virtio_random` driver you studied in Section 3 is a minimal example of how a VirtIO driver is structured. The key concepts, feature negotiation, virtqueue management, notification, are the same whether the device is a random-number generator, a network card, or a block device. Learn them once, and every VirtIO driver becomes more approachable. +虚拟化方面是 VirtIO 故事所在的位置。VirtIO 是客户机驱动程序与虚拟机监控程序提供的设备之间成熟、标准化、高性能的半虚拟化接口。FreeBSD 的 VirtIO 框架(在 `/usr/src/sys/dev/virtio/` 中)干净地实现了该标准,你在第3节中学习的 `virtio_random` 驱动程序是 VirtIO 驱动程序的极小示例。关键概念——特性协商、虚拟队列管理、通知——无论设备是随机数生成器、网卡还是块设备都是相同的。只需学习一次,每个 VirtIO 驱动程序都变得更容易理解。 -The hypervisor detection mechanism, `vm_guest`, gives a driver a small window into the environment. It is useful for adjusting defaults but dangerous when used to work around bugs. The right mindset is "this is informational"; the wrong mindset is "this is a branch target". +虚拟机监控程序检测机制 `vm_guest` 为驱动程序提供了一个窥视环境的小窗口。它在调整默认值时很有用,但用于绕过 bug 时很危险。正确的心态是"这是信息性的";错误的心态是"这是一个分支目标"。 -The host side, where FreeBSD runs `bhyve(8)` and provides devices to guests, is where driver authorship meets hypervisor authorship. Most driver authors never touch `vmm(4)` directly, but the PCI passthrough facility is worth understanding, because it exercises the detach and reattach paths that a well-written driver already supports. A driver that survives a round trip through `ppt(4)` is a driver whose lifecycle is honest. +主机侧是 FreeBSD 运行 `bhyve(8)` 并向客户机提供设备的地方,也是驱动程序编写与虚拟机监控程序编写相遇的地方。大多数驱动程序作者从不直接接触 `vmm(4)`,但 PCI 直通设施值得理解,因为它锻炼了编写良好的驱动程序早已支持的分离和重新附加路径。一个通过 `ppt(4)` 完整往返的驱动程序是一个生命周期诚实的驱动程序。 -The containerization side is where jails, devfs rulesets, and VNET come together. Jails share the kernel, so drivers are not multiplied; they are filtered. The filter operates on three axes: which devices the jail can see (devfs rulesets), which privileges it can exercise (`prison_priv_check` and `allow.*`), and how much it can consume (`rctl(8)` and `racct(9)`). For a driver author, the design decisions are small and local: pick sensible `devfs` names, call `priv_check` correctly, handle allocation failures gracefully. +容器化方面是 jail、devfs 规则集和 VNET 汇聚的地方。Jail 共享内核,因此驱动程序不会被复制;它们被过滤。过滤在三个轴向上运行:jail 可以看到哪些设备(devfs 规则集)、它可以行使哪些权限(`prison_priv_check` 和 `allow.*`),以及它可以消耗多少资源(`rctl(8)` 和 `racct(9)`)。对于驱动程序作者来说,设计决策是小而局部的:选择合理的 `devfs` 名称、正确调用 `priv_check`、优雅地处理分配失败。 -The VNET framework extends the jail model into the network stack. It is the part of jails that comes closest to requiring explicit driver cooperation. Drivers that write to per-VNET state from outside a network-stack entry point (for example, from callouts) must establish the VNET context with `CURVNET_SET`. Drivers that survive `if_vmove` cleanly are drivers that will work in VNET jails. +VNET 框架将 jail 模型扩展到网络栈。它是 jail 中最接近需要显式驱动程序协作的部分。从网络栈入口点之外(例如从 callout 中)写入逐 VNET 状态的驱动程序必须使用 `CURVNET_SET` 建立 VNET 上下文。能够干净地通过 `if_vmove` 存活的驱动程序就是将在 VNET jail 中工作的驱动程序。 -Together, these mechanisms shape FreeBSD as a platform for both hypervisor workloads and container workloads. A single kernel, a single driver set, several different ways for that driver to appear to its users. Understanding the mechanisms is what lets you write drivers that work correctly across all of them, without special-casing any of them. +这些机制共同将 FreeBSD 塑造为一个既能运行虚拟机监控程序工作负载又能运行容器工作负载的平台。一个内核、一个驱动程序集、几种不同的方式让驱动程序呈现给其用户。理解这些机制使你能够编写在所有这些环境中正确工作的驱动程序,而不需要为任何环境特殊处理。 -The discipline the chapter has advocated, sometimes explicitly, sometimes by example, is a continuation of Chapter 29's theme. Write clean abstractions. Use the framework APIs. Do not reach around them. Do not invent your own DMA or privilege or visibility mechanisms; FreeBSD already has well-tested ones. If you do all of this, your driver will work in environments you did not have in mind when you wrote it, and that is the best definition of portable a driver can have. +本章倡导的规范——有时明确,有时通过示例——是第29章主题的延续。编写干净的抽象。使用框架 API。不要绕过它们。不要发明自己的 DMA、权限或可见性机制;FreeBSD 已经有了经过良好测试的。如果你做到了所有这些,你的驱动程序将能在你编写时没有想到的环境中工作,这就是驱动程序可移植性的最佳定义。 -If you worked through the labs, you now have hands-on experience with starting a `bhyve` guest, writing a small module that uses `vm_guest`, putting a character device behind a devfs ruleset in a jail, and moving a network interface through VNET. Those four skills are all you need to start doing real work on driver code that runs in virtualised and containerised environments. Everything else in the chapter is supporting context. +如果你完成了实验,你现在就有了启动 `bhyve` 客户机、编写使用 `vm_guest` 的小型模块、将字符设备放在 jail 的 devfs 规则集后,以及通过 VNET 移动网络接口的实践经验。这四个技能是你在虚拟化和容器化环境中对驱动程序代码进行实际工作所需的全部。本章中的其他一切都是辅助背景。 -If you tackled one or more of the challenges, you have stretched further: into simulation backends, into VNET-aware interfaces, into the bhyve emulator itself, or into test automation. Any of these is a genuine piece of FreeBSD driver craft, and the work compounds. Every hour you spend on these topics comes back in every driver you write afterwards. +如果你完成了一个或多个挑战,你已经走得更远:深入到模拟后端、VNET 感知的接口、bhyve 模拟器本身或测试自动化。这些中的每一个都是真正的 FreeBSD 驱动程序技艺,并且这些工作会不断积累。你在这些主题上花费的每一个小时都会在你之后编写的每个驱动程序中得到回报。 -A final note on attitude. Virtualisation and containerization can feel overwhelming because they introduce so many new pieces at once: hypervisors, paravirtual devices, jails, VNET, rulesets, privileges. But every piece has a clear purpose and a small, well-designed API. The sense of overwhelm goes away once you have seen each one in isolation, and this chapter's pacing was chosen to let you do that. If you are still feeling overwhelmed, go back to Section 3 (VirtIO) or Section 6 (jails and devfs) and re-read with a specific small question in mind. The answers are there. +最后关于态度的一句话。虚拟化和容器化可能会让人感到不知所措,因为它们一次引入了太多新部分:虚拟机监控程序、半虚拟化设备、jail、VNET、规则集、权限。但每个部分都有明确的目的和一个小巧、设计良好的 API。一旦你单独看过每个部分,不知所措的感觉就会消失,本章的节奏选择正是为了让你做到这一点。如果你仍然感到不知所措,回到第3节(VirtIO)或第6节(jail 和 devfs),带着一个具体的小问题重新阅读。答案就在那里。 -## Looking Ahead: Security and Privilege +## 展望:安全与权限 -Chapter 31, "Security and Privilege in Device Drivers," builds directly on the foundations laid in this chapter. Jails and virtual machines are one kind of security boundary; drivers have many others. A driver that exposes an `ioctl` is a driver that has created a new interface into the kernel, and that interface must be checked, validated, and restricted. +第31章"设备驱动程序中的安全与权限"直接建立在本章所奠定的基础之上。jail 和虚拟机是一种安全边界;驱动程序还有许多其他安全边界。暴露 `ioctl` 的驱动程序是一个创建了进入内核的新接口的驱动程序,该接口必须被检查、验证和限制。 -Chapter 31 will cover the privilege framework in depth (you saw `priv_check` here; Chapter 31 goes through the whole list), the `ucred(9)` structure and how credentials flow through the kernel, the `capsicum(4)` capability framework for finer-grained restrictions, and the MAC (Mandatory Access Control) framework for policy-based security. It will also revisit jails from a security-first perspective, complementing the container-first perspective of this chapter. +第31章将深入介绍权限框架(你在这里看到了 `priv_check`;第31章会覆盖整个列表)、`ucred(9)` 结构以及凭证如何在内核中流动、用于更细粒度限制的 `capsicum(4)` 能力框架,以及用于基于策略的安全性的 MAC(强制访问控制)框架。它还将从安全优先的角度重新审视 jail,补充本章的容器优先视角。 -The thread that runs through Chapters 29, 30, and 31 is environment. Chapter 29 was about architectural environment: running on the same kernel with different buses or bit-widths. Chapter 30 was about operational environment: running inside a VM, a container, or on a host. Chapter 31 is about policy environment: running under the constraints a security-conscious administrator chooses to apply. A driver that handles all three kinds of environment well is a driver that can be deployed anywhere FreeBSD runs. +贯穿第29、30和31章的线索是环境。第29章是关于架构环境:在具有不同总线或位宽的同一内核上运行。第30章是关于运行环境:在 VM、容器或主机内运行。第31章是关于策略环境:在安全意识强的管理员选择应用的约束下运行。能良好处理这三种环境的驱动程序是一个可以在 FreeBSD 运行的任何地方部署的驱动程序。 -With Chapter 31, Part 7 approaches its midpoint. The remaining chapters of the part turn to debugging (Chapter 32), testing (Chapter 33), performance tuning (Chapter 34), and specialised driver topics in later chapters. Each builds on what you have learned so far. Take the time to let this chapter settle; the concepts will keep paying off as you continue. +随着第31章的到来,第7部分已接近其中点。本部分接下来的章节转向调试(第32章)、测试(第33章)、性能调优(第34章)以及后续章节中的专业驱动程序主题。每一章都建立在你已学内容的基础上。花时间让本章沉淀;这些概念将在你继续前进时持续产生回报。 -## Case Study: Designing a Pedagogical VirtIO Driver +## 案例研究:设计一个教学用 VirtIO 驱动程序 -This closing case study pulls together the threads of the chapter into a single design walkthrough. It does not present a complete implementation. Instead, it walks through the decisions you would make if you sat down today to design a pedagogical VirtIO driver called `vtedu`. The driver does nothing useful in production, but it exercises enough of the VirtIO surface to be a valuable teaching tool for future readers. +这个结束案例研究将本章的线索汇集到一个单一的设计演练中。它不提供一个完整的实现。相反,它遍历你如果今天坐下来设计一个名为 `vtedu` 的教学 VirtIO 驱动程序时会做出的决策。该驱动程序在生产中不做有用的事情,但它演练了足够的 VirtIO 表面,成为未来读者有价值的教学工具。 -### What vtedu Is For +### vtedu 的用途 -Imagine that `vtedu` is meant to serve as the example driver for a future FreeBSD workshop on paravirtualised devices. Its job is to expose a single virtqueue, accept write requests from user space, pass them through the virtqueue to a backend in `bhyve(8)` (which does something simple like echoing bytes back), and deliver the echoed bytes back to user space. It must be small enough to read in an afternoon and complete enough to demonstrate the full VirtIO lifecycle. +设想 `vtedu` 是作为未来 FreeBSD 半虚拟化设备研讨会的示例驱动程序。它的任务是暴露一个单一的虚拟队列,接受来自用户空间的写入请求,通过虚拟队列将其传递给 `bhyve(8)` 中的后端(该后端做一些简单的事情,比如回声返回字节),并将回声返回的字节送回用户空间。它必须足够小,可以在一个下午读完,又足够完整,能够演示完整的 VirtIO 生命周期。 -The design choices below explain each step. A reader who finishes this section should be able to reason about any similar VirtIO driver in the same terms. +下面的设计选择解释了每个步骤。完成本节的读者应该能够用相同的术语推理任何类似的 VirtIO 驱动程序。 -### Choosing the Device Identifier +### 选择设备标识符 -VirtIO defines a set of well-known device IDs in `/usr/src/sys/dev/virtio/virtio_ids.h`. For a pedagogical driver, a reserved or experimental ID is appropriate. The VirtIO specification reserves some ranges for "vendor-specific" devices, and a workshop driver would pick one of those. +VirtIO 在 `/usr/src/sys/dev/virtio/virtio_ids.h` 中定义了一组众所周知的设备 ID。对于教学驱动程序,保留或实验性的 ID 是合适的。VirtIO 规范为“厂商特定”设备保留了一些范围,研讨会驱动程序会选择其中之一。 -For `vtedu`, we pick a hypothetical `VIRTIO_ID_EDU = 0xfff0` (chosen so it does not collide with real device IDs). The corresponding backend in `bhyve(8)` would register the same ID. A real project would coordinate with the `bhyve(8)` maintainers on the ID assignment. +对于 `vtedu`,我们选择一个假设的 `VIRTIO_ID_EDU = 0xfff0`(选择它以免与真实设备 ID 冲突)。`bhyve(8)` 中相应的后端将注册相同的 ID。一个真实的项目会与 `bhyve(8)` 维护者协调 ID 分配。 -### Defining the Features +### 定义特性 -A teaching driver should negotiate a meaningful feature bit so that the reader sees feature negotiation in action. `vtedu` defines one feature: +教学驱动程序应该协商一个有意义的特性位,以便读者看到特性协商的实际情况。`vtedu` 定义一个特性: ```c #define VTEDU_F_UPPERCASE (1ULL << 0) ``` -When negotiated, the backend returns the input bytes uppercased. When not negotiated, it returns them unchanged. The driver advertises the feature, the backend may or may not support it, and the negotiation produces whichever outcome both sides can support. +当协商成功时,后端返回大写的输入字节。当未协商时,它原样返回。驱动程序播发该特性,后端可能支持也可能不支持,协商产生双方都能支持的结果。 -This kind of trivial feature is a teaching device. In a real driver, features correspond to real capabilities; in `vtedu`, the feature exists just to show how negotiation works. +这种简单的特性是一种教学手段。在真实驱动程序中,特性对应真实的能力;在 `vtedu` 中,该特性存在只是为了展示协商是如何工作的。 -### Softc Layout +### Softc 布局 -The softc is the per-instance state: +softc 是每个实例的状态: ```c struct vtedu_softc { @@ -2358,11 +2358,11 @@ struct vtedu_softc { }; ``` -The device handle, the virtqueue pointer, the negotiated feature mask, a mutex protecting the driver's serialised access, a `cdev` for the user-space interface, a pre-allocated scatter-gather list, a buffer for the data, and its current length. +设备句柄、虚拟队列指针、协商后的特性掩码、保护驱动程序串行化访问的互斥锁、用于用户空间接口的 `cdev`、预分配的分散-聚集列表、用于数据的缓冲区及其当前长度。 -### Transport Registration +### 传输层注册 -The module uses `VIRTIO_DRIVER_MODULE` as always: +模块一如既往地使用 `VIRTIO_DRIVER_MODULE`: ```c static device_method_t vtedu_methods[] = { @@ -2383,11 +2383,11 @@ MODULE_VERSION(vtedu, 1); MODULE_DEPEND(vtedu, virtio, 1, 1, 1); ``` -The PNP info for `vtedu` advertises `VIRTIO_ID_EDU`, so the framework binds the driver to any VirtIO device of that type, under either PCI or MMIO transport. +`vtedu` 的 PNP 信息播发 `VIRTIO_ID_EDU`,因此框架将驱动程序绑定到该类型的任何 VirtIO 设备,无论是在 PCI 还是 MMIO 传输下。 -### Probe and Attach +### 探测与附加 -The probe is a one-liner using `VIRTIO_SIMPLE_PROBE`. The attach sets up the device in the standard order: +探测函数使用 `VIRTIO_SIMPLE_PROBE` 一行完成。附加函数按标准顺序设置设备: ```c static int @@ -2432,11 +2432,11 @@ fail: } ``` -This follows the standard rhythm: negotiate, allocate queue, setup interrupts, set up user-space interface. It is structurally identical to `virtio_random`'s attach, with a `cdev` creation added because `vtedu` exposes a character device. +这遵循标准节奏:协商、分配队列、设置中断、设置用户空间接口。它在结构上与 `virtio_random` 的附加相同,只是添加了 `cdev` 创建,因为 `vtedu` 暴露了字符设备。 -### Feature Negotiation +### 特性协商 -Negotiation is straightforward: +协商很直接: ```c static int @@ -2449,11 +2449,11 @@ vtedu_negotiate_features(struct vtedu_softc *sc) } ``` -The driver advertises the two features, gets back an intersection, and finalises. The intersection tells the driver whether `VTEDU_F_UPPERCASE` is in play. Subsequent code uses `virtio_with_feature(sc->dev, VTEDU_F_UPPERCASE)` to check. +驱动程序通告两个特性,获取一个交集,然后终结。交集告诉驱动程序 `VTEDU_F_UPPERCASE` 是否在起作用。后续代码使用 `virtio_with_feature(sc->dev, VTEDU_F_UPPERCASE)` 来检查。 -### Queue Allocation +### 队列分配 -A single virtqueue is allocated with an interrupt callback: +分配一个带有中断回调的单个虚拟队列: ```c static int @@ -2468,11 +2468,11 @@ vtedu_alloc_virtqueue(struct vtedu_softc *sc) } ``` -The maximum indirect-descriptor size is zero (no indirects), the interrupt callback is `vtedu_vq_intr`, and the virtqueue pointer is stored in `sc->vq`. A single queue is enough for a request-response pattern where the same queue is used for both directions. +最大间接描述符大小为 0(无间接描述符),中断回调为 `vtedu_vq_intr`,虚拟队列指针存储在 `sc->vq` 中。对于同一队列用于双向的请求-响应模式,单个队列就足够了。 -### The Character Device Interface +### 字符设备接口 -User space opens `/dev/vtedu0` and writes bytes to it. The driver accepts them, issues a VirtIO request, waits for the response, and exposes the response back to user space through read. +用户空间打开 `/dev/vtedu0` 并向其写入字节。驱动程序接受它们,发出 VirtIO 请求,等待响应,并通过 read 将响应暴露回用户空间。 ```c static int @@ -2497,7 +2497,7 @@ vtedu_write(struct cdev *dev, struct uio *uio, int flags __unused) } ``` -The write copies bytes into the softc buffer, sets `buf_len`, and calls `vtedu_submit`, which does the VirtIO enqueue and notify. +写入函数将字节复制到 softc 缓冲区中,设置 `buf_len`,并调用 `vtedu_submit`,后者执行 VirtIO 入队和通知。 ```c static int @@ -2519,11 +2519,11 @@ vtedu_submit(struct vtedu_softc *sc) } ``` -One readable segment (the driver's write into the buffer) and one writable segment (the device's write of the result). The cookie is `sc` itself; the interrupt handler will receive it back when the completion arrives. +一个可读段(驱动程序写入缓冲区)和一个可写段(设备写入结果)。cookie 是 `sc` 本身;当完成到达时,中断处理程序将收到它。 -### The Interrupt Handler +### 中断处理程序 -Completions are processed in a taskqueue-deferred or immediate fashion. For pedagogical simplicity, `vtedu` processes them immediately in the interrupt callback: +完成以 taskqueue 延迟或即时方式处理。为了教学简单性,`vtedu` 在中断回调中立即处理它们: ```c static void @@ -2543,11 +2543,11 @@ vtedu_vq_intr(void *arg) } ``` -The handler drains all completions, updates the softc, and wakes any sleeper waiting on the buffer. For a real driver, this would be richer; for `vtedu`, it is all we need. +处理程序排空所有完成,更新 softc,并唤醒任何在缓冲区上等待的休眠者。对于真实驱动程序,这将更丰富;对于 `vtedu`,这就是我们所需要的。 -### The Read Path +### 读取路径 -User space then reads the result: +用户空间然后读取结果: ```c static int @@ -2571,11 +2571,11 @@ vtedu_read(struct cdev *dev, struct uio *uio, int flags __unused) } ``` -If no result is available, the read sleeps on `sc`, which the interrupt handler will wake. This is the standard "block until ready" pattern for character devices with slow underlying I/O. +如果没有结果可用,读取操作会在 `sc` 上休眠,中断处理程序会将其唤醒。这是底层 I/O 较慢的字符设备的标准"阻塞直到就绪"模式。 -### Detach +### 分离 -The detach reverses the attach, cleanly: +分离干净地逆转附加过程: ```c static int @@ -2594,85 +2594,82 @@ vtedu_detach(device_t dev) } ``` -`virtio_stop` resets the device status so it no longer generates interrupts. The `cdev` is destroyed, the scatter-gather list freed, and the mutex destroyed. +`virtio_stop` 重置设备状态使其不再生成中断。`cdev` 被销毁,分散-聚集列表被释放,互斥锁被销毁。 -### Putting vtedu Together +### 整合 vtedu -This walkthrough has touched on every major element of a VirtIO driver: +本演练涉及了 VirtIO 驱动程序的每个主要元素: 1. Device ID selection and PNP info. 2. Feature definition and negotiation. 3. Softc layout and locking. -4. Virtqueue allocation with interrupt callback. -5. User-space interface through `cdev`. -6. Request submission through enqueue + notify. -7. Completion handling through the interrupt callback. +4. 带中断回调的虚拟队列分配。 +5. 通过 `cdev` 的用户空间接口。 +6. 通过入队 + 通知的请求提交。 +7. 通过中断回调的完成处理。 8. Clean detach. -The whole driver, fully implemented, fits in around 300 lines of C. That is less than `virtio_random` once you add in the backend plumbing. Because the user-space interface is richer than `virtio_random`'s (which hides in the `random(4)` framework), the code is slightly larger in total, but the VirtIO-specific part is no bigger. +完全实现的整个驱动程序大约有 300 行 C 代码。加上后端管道后,这比 `virtio_random` 还要少。由于用户空间接口比 `virtio_random`(它隐藏在 `random(4)` 框架中)更丰富,代码总量略大,但 VirtIO 特定部分并不更大。 -### Using vtedu for Teaching +### 使用 vtedu 进行教学 -A `vtedu` driver would be used in a workshop something like this: +`vtedu` 驱动程序在研讨会中的使用方式大致如下: -1. The instructor starts by demonstrating the driver loading, attaching, and processing a write-then-read round trip. -2. Students follow along, typing the key sections from a cheat sheet. -3. The instructor introduces feature negotiation by showing what happens when `VTEDU_F_UPPERCASE` is negotiated (outputs arrive uppercased) versus when it is not. -4. Students modify the driver to add a second feature: "reverse the bytes". They learn how features compose. -5. Finally, the instructor shows how to run the driver in a jail (it just works, as long as `vtedu0` is in the devfs ruleset), illustrating the containerisation side of the chapter. +1. 讲师首先演示驱动程序加载、附加以及处理先写后读的完整往返。 +2. 学生跟着操作,从速查表输入关键部分。 +3. 讲师通过展示协商 `VTEDU_F_UPPERCASE`(输出以大写形式到达)与未协商时的对比,介绍特性协商。 +4. 学生修改驱动程序以添加第二个特性:“反转字节”。他们学习特性如何组合。 +5. 最后,讲师展示如何在 jail 中运行驱动程序(只要 `vtedu0` 在 devfs 规则集中就可正常工作),阐明本章的容器化方面。 -This is a pedagogical design, not a production one. Its purpose is to show how the pieces fit. A reader who has followed this case study should be able to write a similar driver of their own, starting from scratch or starting from `virtio_random.c` as a template. +这是一个教学设计,而非生产设计。其目的是展示各个部分如何配合。跟随此案例研究的读者应该能够编写自己的类似驱动程序,可以从头开始或以 `virtio_random.c` 为模板开始。 -### What vtedu Does Not Do +### vtedu 不做的事情 -For honesty: `vtedu` as sketched here omits several things a production driver would include. It does not support multiple in-flight requests (the lock serialises everything). It does not handle queue-full situations gracefully (it assumes one request at a time). It does not support module-wide module-event cleanup (just per-device). It does not demonstrate indirect descriptors (because the feature is irrelevant for 256-byte messages). +诚实地说:此处勾勒的 `vtedu` 省略了生产驱动程序应包含的几个方面。它不支持多个进行中的请求(锁串行化了所有操作)。它不能优雅地处理队列已满的情况(假设一次一个请求)。它不支持模块级的事件清理(仅逐设备)。它不演示间接描述符(因为该特性对于 256 字节的消息无关紧要)。 -Each of these is an exercise the reader could undertake after understanding the base design. The chapter's challenge exercises hint at some of them; a dedicated workshop would develop them further. +这些都是读者在理解基本设计后可以承担的练习。本章的挑战练习暗示了其中一些;专门的研讨会将进一步发展它们。 -### A Teaching Driver Versus a Real Driver +### 教学驱动程序与真实驱动程序 -Before leaving `vtedu`, a note about the difference between a teaching driver and a real one. A teaching driver is designed for readability. Its code makes every concept visible, often at the cost of clever optimisations. A real driver is designed for reliability and performance. It compresses the common-case paths, adds error handling for every edge case, and optimises for the actual workload. +在离开 `vtedu` 之前,有一个关于教学驱动程序和真实驱动程序之间差异的说明。教学驱动程序是为可读性而设计的。其代码使每个概念可见,通常以牺牲巧妙优化为代价。真实驱动程序是为可靠性和性能而设计的。它压缩常见路径,为每个边缘情况添加错误处理,并针对实际工作负载进行优化。 -The temptation when moving from learning to production is to start with the teaching driver and add features. That usually produces worse code than starting with an architectural sketch and filling it in. A teaching driver is a reference; a real driver is a system. The two are not on the same continuum. +从学习过渡到生产时的诱惑是以教学驱动程序为基础并添加特性。这通常会产生比从架构草图开始并填充它更糟糕的代码。教学驱动程序是一个参考;真实驱动程序是一个系统。两者不在同一个连续体上。 -As a driver author, your job is to understand the teaching driver well enough that the real-driver design decisions become clear. This chapter's treatment of VirtIO is meant to get you to that understanding. The next step is yours. +作为驱动程序作者,你的工作是充分理解教学驱动程序,使真实驱动程序的设计决策变得清晰。本章对 VirtIO 的处理旨在让你达到那种理解。下一步取决于你。 -## Appendix: Quick Reference +## 附录:快速参考 -The reference tables below condense the chapter's key facts into a form -you can return to during driver work. They are not a substitute for the -explanatory text; think of them as the one-page cheat sheet for the day -you are actually writing code and need a specific detail. +下面的参考表将本章的关键事实浓缩成你在驱动程序工作中可以随时查阅的形式。它们不能替代解释性文本;把它们当作你在实际编写代码并需要特定细节那天的单页备忘录。 -### VirtIO Core API Functions +### VirtIO 核心 API 函数 -| Function | Purpose | +| 函数 | 用途 | |----------|---------| -| `virtio_negotiate_features(dev, mask)` | Advertise and negotiate feature bits. | -| `virtio_finalize_features(dev)` | Seal the feature negotiation. | -| `virtio_with_feature(dev, feature)` | Test whether a feature is negotiated. | -| `virtio_alloc_virtqueues(dev, flags, nvqs, info)` | Allocate a set of virtqueues. | -| `virtio_setup_intr(dev, type)` | Install the negotiated interrupt handlers. | -| `virtio_read_device_config(dev, offset, dst, size)` | Read device-specific configuration. | -| `virtio_write_device_config(dev, offset, src, size)` | Write device-specific configuration. | +| `virtio_negotiate_features(dev, mask)` | 播发并协商特性位。 | +| `virtio_finalize_features(dev)` | 锁定特性协商。 | +| `virtio_with_feature(dev, feature)` | 测试特性是否已协商。 | +| `virtio_alloc_virtqueues(dev, flags, nvqs, info)` | 分配一组虚拟队列。 | +| `virtio_setup_intr(dev, type)` | 安装已协商的中断处理程序。 | +| `virtio_read_device_config(dev, offset, dst, size)` | 读取设备特定配置。 | +| `virtio_write_device_config(dev, offset, src, size)` | 写入设备特定配置。 | -### virtqueue(9) Functions +### virtqueue(9) 函数 -| Function | Purpose | +| 函数 | 用途 | |----------|---------| -| `virtqueue_enqueue(vq, cookie, sg, readable, writable)` | Push a scatter-gather chain onto the available ring. | -| `virtqueue_dequeue(vq, &len)` | Pop one completed chain from the used ring. | -| `virtqueue_notify(vq)` | Tell the host new work is available. | -| `virtqueue_poll(vq, &len)` | Wait for a completion and return it. | -| `virtqueue_empty(vq)` | Check whether the queue has any pending work. | -| `virtqueue_full(vq)` | Check whether the queue has space for another enqueue. | +| `virtqueue_enqueue(vq, cookie, sg, readable, writable)` | 将分散-聚集链推入可用环。 | +| `virtqueue_dequeue(vq, &len)` | 从已用环弹出一个完成的链。 | +| `virtqueue_notify(vq)` | 通知主机有新工作可用。 | +| `virtqueue_poll(vq, &len)` | 等待完成并返回。 | +| `virtqueue_empty(vq)` | 检查队列是否有待处理的工作。 | +| `virtqueue_full(vq)` | 检查队列是否有空间进行另一次入队。 | -### vm_guest Values +### vm_guest 值 -| Constant | String via `kern.vm_guest` | Meaning | +| 常量 | 通过 `kern.vm_guest` 获取的字符串 | 含义 | |----------|---------------------------|---------| -| `VM_GUEST_NO` | `none` | Bare metal | -| `VM_GUEST_VM` | `generic` | Unknown hypervisor | +| `VM_GUEST_NO` | `none` | 裸金属 | +| `VM_GUEST_VM` | `generic` | 未知虚拟机监控程序 | | `VM_GUEST_XEN` | `xen` | Xen | | `VM_GUEST_HV` | `hv` | Microsoft Hyper-V | | `VM_GUEST_VMWARE` | `vmware` | VMware ESXi / Workstation | @@ -2682,94 +2679,90 @@ you are actually writing code and need a specific detail. | `VM_GUEST_PARALLELS` | `parallels` | Parallels | | `VM_GUEST_NVMM` | `nvmm` | NetBSD NVMM | -### Default devfs Rulesets +### 默认 devfs 规则集 -| Number | Name | Purpose | +| 编号 | 名称 | 用途 | |--------|------|---------| -| 1 | `devfsrules_hide_all` | Start with everything hidden. | -| 2 | `devfsrules_unhide_basic` | Essential devices (`null`, `zero`, `random`, etc.). | -| 3 | `devfsrules_unhide_login` | Login-related devices (`pts`, `ttyv*`). | -| 4 | `devfsrules_jail` | Standard non-VNET jail ruleset. | -| 5 | `devfsrules_jail_vnet` | Standard VNET jail ruleset. | +| 1 | `devfsrules_hide_all` | 以隐藏所有内容开始。 | +| 2 | `devfsrules_unhide_basic` | 基础设备(`null`、`zero`、`random` 等)。 | +| 3 | `devfsrules_unhide_login` | 登录相关设备(`pts`、`ttyv*`)。 | +| 4 | `devfsrules_jail` | 标准非 VNET jail 规则集。 | +| 5 | `devfsrules_jail_vnet` | 标准 VNET jail 规则集。 | -### Common Privilege Constants +### 常用权限常量 -| Constant | Typical jail policy | +| 常量 | 典型监狱策略 | |----------|--------------------| -| `PRIV_DRIVER` | Denied (driver-private ioctls). | -| `PRIV_IO` | Denied (raw I/O port access). | -| `PRIV_KMEM_WRITE` | Denied (kernel memory writes). | -| `PRIV_KLD_LOAD` | Denied (module loading). | -| `PRIV_NET_SETLLADDR` | Denied (MAC address changes). | -| `PRIV_NETINET_RAW` | Denied unless `allow.raw_sockets`. | -| `PRIV_NET_BPF` | Allowed via `allow.raw_sockets` for BPF-needing tools. | +| `PRIV_DRIVER` | 拒绝(驱动程序私有的 ioctl)。 | +| `PRIV_IO` | 拒绝(原始 I/O 端口访问)。 | +| `PRIV_KMEM_WRITE` | 拒绝(内核内存写入)。 | +| `PRIV_KLD_LOAD` | 拒绝(模块加载)。 | +| `PRIV_NET_SETLLADDR` | 拒绝(MAC 地址更改)。 | +| `PRIV_NETINET_RAW` | 拒绝,除非设置了 `allow.raw_sockets`。 | +| `PRIV_NET_BPF` | 通过 `allow.raw_sockets` 允许给需要 BPF 的工具。 | -### VNET Macros +### VNET 宏 -| Macro | Purpose | +| 宏 | 用途 | |-------|---------| -| `VNET_DEFINE(type, name)` | Declare a per-VNET variable. | -| `VNET(name)` | Access the per-VNET variable for the current VNET. | -| `V_name` | Conventional shorthand for `VNET(name)`. | -| `CURVNET_SET(vnet)` | Establish a VNET context on the current thread. | -| `CURVNET_RESTORE()` | Tear down the context. | -| `VNET_SYSINIT(name, ...)` | Register a per-VNET init function. | -| `VNET_SYSUNINIT(name, ...)` | Register a per-VNET uninit function. | +| `VNET_DEFINE(type, name)` | 声明逐 VNET 变量。 | +| `VNET(name)` | 访问当前 VNET 的逐 VNET 变量。 | +| `V_name` | `VNET(name)` 的常规简写。 | +| `CURVNET_SET(vnet)` | 在当前线程上建立 VNET 上下文。 | +| `CURVNET_RESTORE()` | 拆除上下文。 | +| `VNET_SYSINIT(name, ...)` | 注册逐 VNET 初始化函数。 | +| `VNET_SYSUNINIT(name, ...)` | 注册逐 VNET 反初始化函数。 | -### bhyve and Passthrough Tools +### bhyve 与直通工具 -| Tool | Purpose | +| 工具 | 用途 | |------|---------| -| `bhyve(8)` | Run a virtual machine. | -| `bhyvectl(8)` | Query and control running VMs. | -| `vm(8)` | High-level management (via `vm-bhyve` port). | -| `pciconf(8)` | Show PCI devices and their driver bindings. | -| `devctl(8)` | Explicit control of driver attach/detach. | -| `pptdevs` in `/boot/loader.conf` | Bind devices to the passthrough placeholder. | +| `bhyve(8)` | 运行虚拟机。 | +| `bhyvectl(8)` | 查询和控制运行中的虚拟机。 | +| `vm(8)` | 高级管理(通过 `vm-bhyve` 包)。 | +| `pciconf(8)` | 显示 PCI 设备及其驱动程序绑定。 | +| `devctl(8)` | 显式控制驱动程序附加/分离。 | +| `/boot/loader.conf` 中的 `pptdevs` | 将设备绑定到直通占位符。 | -### Manual Pages Worth Bookmarking +### 值得收藏的手册页 -- `virtio(4)` - VirtIO framework overview. -- `vtnet(4)`, `virtio_blk(4)` - Specific VirtIO drivers. -- `bhyve(8)`, `bhyvectl(8)`, `vmm(4)` - Hypervisor user and kernel interfaces. -- `pci_passthru(4)` - PCI passthrough mechanism. -- `jail(8)`, `jail.conf(5)`, `jls(8)`, `jexec(8)` - Jail management. -- `devfs(5)`, `devfs(8)`, `devfs.rules(5)` - devfs and rulesets. -- `if_epair(4)`, `vlan(4)`, `if_tap(4)` - Pseudo-interfaces useful for jails. -- `rctl(8)`, `racct(9)` - Resource control. -- `priv(9)` - Privilege framework. +- `virtio(4)` - VirtIO 框架概述。 +- `vtnet(4)`、`virtio_blk(4)` - 特定 VirtIO 驱动程序。 +- `bhyve(8)`、`bhyvectl(8)`、`vmm(4)` - 虚拟机监控程序用户和内核接口。 +- `pci_passthru(4)` - PCI 直通机制。 +- `jail(8)`、`jail.conf(5)`、`jls(8)`、`jexec(8)` - Jail 管理。 +- `devfs(5)`、`devfs(8)`、`devfs.rules(5)` - devfs 与规则集。 +- `if_epair(4)`、`vlan(4)`、`if_tap(4)` - 对 jail 有用的伪接口。 +- `rctl(8)`、`racct(9)` - 资源控制。 +- `priv(9)` - 权限框架。 -### Top Five Things a Driver Author Should Do +### 驱动程序作者应做的五件事 -If you remember nothing else from this chapter, remember these five habits: +如果你不记得本章的其他内容,请记住这五个习惯: -1. Use `bus_dma(9)` for every DMA buffer. Never pass physical addresses - directly to the hardware. This is the single most important habit for - passthrough and IOMMU-protected environments. -2. Use `priv_check(9)` for privileged operations. Do not hardcode - `cred->cr_uid == 0` checks. The framework extends your code to jails - for free. -3. Keep device node names predictable. Administrators who write devfs - rulesets need to know what to unhide. Document the name in your driver's - manual page. -4. Handle detach cleanly. Release every resource, cancel every callout, - drain every taskqueue, and never assume the softc will be re-used. - Passthrough and VNET both exercise detach heavily. -5. Establish VNET context around callout and taskqueue code that touches - per-VNET state. `CURVNET_SET` / `CURVNET_RESTORE` is the boilerplate, - and missing it is the most common VNET-related bug. +1. 对每个 DMA 缓冲区使用 `bus_dma(9)`。切勿将物理地址 + 直接传递给硬件。这是直通和 IOMMU 保护环境中 + 最重要的一项习惯。 +2. 对特权操作使用 `priv_check(9)`。不要硬编码 + `cred->cr_uid == 0` 检查。框架将您的代码免费扩展到 jail。 +3. 保持设备节点名称可预测。编写 devfs + 规则集的管理员需要知道要取消隐藏什么。在您的驱动程序手册页中 + 记录该名称。 +4. 干净地处理分离。释放每个资源,取消每个 callout, + 排空每个 taskqueue,并且永远不要假设 softc 会被重用。 + 直通和 VNET 都会大量调用分离路径。 +5. 在访问逐 VNET 状态的 callout 和 taskqueue 代码周围 + 建立 VNET 上下文。`CURVNET_SET` / `CURVNET_RESTORE` 是样板代码, + 遗漏它是最常见的 VNET 相关错误。 -These five habits between them cover nearly all of the "works under -virtualisation and containerization" work a driver author needs to do. -Everything else is refinement. +这五个习惯几乎涵盖了驱动程序作者需要做的「在虚拟化和容器化下工作」的所有工作。 +其他一切都是优化细节。 -## Appendix: Common Code Patterns +## 附录:常见代码模式 -A small catalogue of patterns that appear repeatedly in FreeBSD drivers -that run in virtualised or containerised environments. Each one is a -snippet you can adapt to your own code. +在虚拟化或容器化环境中运行的 FreeBSD 驱动程序中反复出现的模式的小目录。每一个都是你可以适应自己代码的片段。 -### Pattern: Environment-aware default +### 模式:环境感知的默认值 ```c static int @@ -2785,11 +2778,10 @@ mydev_default_interrupt_moderation(void) } ``` -Use this pattern to seed a default that the user can override via sysctl. -Do not branch on the specific hypervisor brand unless there is a real -reason. +使用此模式设置一个用户可以通过 sysctl 覆盖的默认值。 +除非有真正的原因,否则不要针对特定虚拟机监控程序品牌进行分支。 -### Pattern: Privilege-gated ioctl +### 模式:权限门控的 ioctl ```c case MYDEV_IOC_DANGEROUS: @@ -2800,11 +2792,9 @@ case MYDEV_IOC_DANGEROUS: return (0); ``` -The default position for driver-specific privileges is to require -`PRIV_DRIVER`. Consult `priv(9)` if a more specific privilege fits -better. +驱动程序特定权限的默认立场是要求 `PRIV_DRIVER`。如果有更合适的特定权限,请查阅 `priv(9)`。 -### Pattern: VNET-aware callout +### 模式:VNET 感知的 callout ```c static void @@ -2820,11 +2810,9 @@ mydev_callout(void *arg) } ``` -Any callout, taskqueue function, or kernel thread that might access VNET -state must establish the context. Missing this is the most common source -of VNET-related bugs. +任何可能访问 VNET 状态的 callout、taskqueue 函数或内核线程都必须建立上下文。遗漏这一点是 VNET 相关错误的最常见来源。 -### Pattern: VirtIO attach skeleton +### 模式:VirtIO 附加骨架 ```c static int @@ -2857,11 +2845,9 @@ fail: } ``` -The "negotiate, allocate, setup interrupts, start" rhythm is standard for -every VirtIO driver. Every VirtIO attach in `/usr/src/sys/dev/virtio/` is -a variation on this skeleton. +"协商、分配、设置中断、启动"的节奏是每个 VirtIO 驱动程序的标准。`/usr/src/sys/dev/virtio/` 中的每个 VirtIO 附加函数都是这个骨架的变体。 -### Pattern: Clean detach +### 模式:干净的分离 ```c static int @@ -2894,11 +2880,9 @@ mydev_detach(device_t dev) } ``` -Detach must be symmetric with attach: every resource attach allocated must -be released here, in reverse order. A clean detach is what makes the -driver safe for passthrough and for unload. +分离必须与附加对称:附加分配了每个资源都必须在此处按相反顺序释放。干净的分离使驱动程序对直通和卸载都是安全的。 -### Pattern: make_dev with sensible defaults +### 模式:使用合理默认值的 make_dev ```c sc->cdev = make_dev(&mydev_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "mydev%d", @@ -2908,68 +2892,63 @@ if (sc->cdev == NULL) sc->cdev->si_drv1 = sc; ``` -Use `0600` mode for nodes that should only be root-accessible, `0644` for -read-any / write-root, `0666` for rare read-and-write-any cases. The -`si_drv1` field is the conventional back-pointer from a `struct cdev` to -the driver's softc. +对于仅 root 可访问的节点使用 `0600` 模式,对于任何读取/root 写入使用 `0644`,对于罕见的任何读取和写入情况使用 `0666`。`si_drv1` 字段是从 `struct cdev` 到驱动程序 softc 的常规反向指针。 -## Appendix: Glossary +## 附录:词汇表 -A short glossary of the terms this chapter relies on. Refer back when a -term in a later section has slipped from memory. +本章所依赖术语的简短词汇表。当后续节次中的某个术语从记忆中消失时,可以回过来查阅。 -- **Bare metal**: A system running directly on physical hardware with no - hypervisor in between. -- **bhyve**: FreeBSD's native type-2 hypervisor. Runs as a user-space - program backed by the kernel's `vmm(4)` module. -- **Container**: In FreeBSD, a jail or a user-space framework built on top - of jails. -- **Credential (`struct ucred`)**: The per-process security context that - carries uid, gid, jail pointer, and privilege-related state. -- **devfs**: The special filesystem at `/dev` where devices are exposed. -- **devfs ruleset**: A named set of rules that controls which devfs nodes - are visible in a given devfs mount. -- **Emulated device**: A hypervisor-provided device that imitates a - real-hardware interface. -- **Guest**: The operating system running inside a virtual machine. -- **Host**: The physical machine (or container-enclosing system) that - hosts guests or jails. -- **Hypervisor**: Software that creates and manages virtual machines. -- **IOMMU**: A unit between a device and host memory that remaps DMA - addresses. Enables safe passthrough. -- **Jail**: FreeBSD's lightweight containerisation mechanism. -- **Paravirtual device**: A device with an interface designed to be easy - for a hypervisor to emulate and for a guest to drive. VirtIO is the - canonical example. -- **Passthrough**: Giving a guest direct access to a physical device. -- **Prison**: The kernel's internal name for a jail. `struct prison` is - the data structure. -- **rctl / racct**: The resource-control and resource-accounting - frameworks that enforce per-jail or per-process limits. +- **Bare metal**(裸金属):直接在物理硬件上运行的系统,之间没有 + 虚拟机监控程序。 +- **bhyve**:FreeBSD 的原生类型 2 虚拟机监控程序。作为用户空间 + 程序运行,由内核的 `vmm(4)` 模块支持。 +- **Container**(容器):在 FreeBSD 中,指 jail 或建立在 + jail 之上的用户空间框架。 +- **Credential(`struct ucred`)**:携带 uid、gid、jail 指针和 + 权限相关状态的每进程安全上下文。 +- **devfs**:位于 `/dev` 的特殊文件系统,设备在此暴露。 +- **devfs ruleset**(devfs 规则集):一组命名的规则,控制 + 在给定 devfs 挂载中哪些 devfs 节点可见。 +- **Emulated device**(模拟设备):由虚拟机监控程序提供的模拟 + 真实硬件接口的设备。 +- **Guest**(客户机):在虚拟机内部运行的操作系统。 +- **Host**(主机):承载客户机或 jail 的物理机器(或容器封闭系统)。 +- **Hypervisor**(虚拟机监控程序):创建和管理虚拟机的软件。 +- **IOMMU**:位于设备和主机内存之间重新映射 DMA + 地址的单元。实现安全直通。 +- **Jail**:FreeBSD 的轻量级容器化机制。 +- **Paravirtual device**(半虚拟化设备):接口设计为易于 + 虚拟机监控程序模拟和客户机驱动的设备。VirtIO 是 + 典型示例。 +- **Passthrough**(直通):让客户机直接访问物理设备。 +- **Prison**:内核中 jail 的内部名称。`struct prison` 是 + 数据结构。 +- **rctl / racct**:实施每个 jail 或每进程限制的 + 资源控制和资源核算框架。 - **Ruleset**: See *devfs ruleset*. -- **Transport (VirtIO)**: The bus-level mechanism that carries VirtIO - messages. Examples: PCI, MMIO. -- **Virtqueue**: The shared-ring data structure at the heart of VirtIO. -- **VirtIO**: The paravirtualisation standard used by most modern - hypervisors. +- **Transport(VirtIO,传输层)**:承载 VirtIO + 消息的总线级机制。示例:PCI、MMIO。 +- **Virtqueue**(虚拟队列):VirtIO 核心的共享环数据结构。 +- **VirtIO**:大多数现代虚拟机监控程序使用的 + 半虚拟化标准。 - **VM**: Virtual machine. -- **VNET**: FreeBSD's virtual network stack framework, providing per-jail - independent stacks. -- **vmm**: FreeBSD's kernel hypervisor core module, used by `bhyve(8)`. +- **VNET**:FreeBSD 的虚拟网络栈框架,提供每个 jail + 独立的网络栈。 +- **vmm**:FreeBSD 的内核虚拟机监控程序核心模块,由 `bhyve(8)` 使用。 -## Appendix: Observing VirtIO with DTrace +## 附录:使用 DTrace 观察 VirtIO -DTrace is one of FreeBSD's most capable diagnostic tools, and it is especially useful for understanding how a VirtIO driver behaves at runtime. This appendix collects several concrete DTrace recipes for VirtIO observability. None of them require modifying the driver; they work against the unmodified kernel because the `fbt` (function-boundary-tracing) provider instruments every kernel function. +DTrace 是 FreeBSD 最强大的诊断工具之一,它对于理解 VirtIO 驱动程序在运行时的行为特别有用。本附录收集了几个具体的 DTrace 配方用于 VirtIO 可观测性。它们都不需要修改驱动程序;它们针对未修改的内核工作,因为 `fbt`(函数边界跟踪)提供者插装了每个内核函数。 -### A First Probe: Counting virtqueue Enqueues +### 第一个探测:统计 virtqueue 入队次数 -The simplest useful probe counts how often `virtqueue_enqueue` is called per second. +最有用的最简单探测是统计每秒调用 `virtqueue_enqueue` 的次数。 ```sh sudo dtrace -n 'fbt::virtqueue_enqueue:entry /pid == 0/ { @[probefunc] = count(); } tick-1sec { printa(@); trunc(@); }' ``` -Running this on a busy VM shows numbers like: +在繁忙的 VM 上运行会显示如下数字: ```text virtqueue_enqueue 12340 @@ -2977,11 +2956,11 @@ virtqueue_enqueue 15220 virtqueue_enqueue 11890 ``` -Each number is enqueues per second across all virtqueues. A number in the thousands is normal for an active VM; a number in the millions suggests a pathological driver. The per-VM baseline depends on workload, but getting familiar with the baseline for your environment lets you spot anomalies later. +每个数字是所有虚拟队列每秒的入队次数。数千的数量级对于活跃 VM 是正常的;数百万的数量级表明驱动程序存在异常。每个 VM 的基线取决于工作负载,但熟悉您环境的基线可以让您以后发现异常。 -### Separating Queues by Virtqueue +### 按虚拟队列分离队列 -To see which virtqueue is being used, extend the probe to key on the virtqueue name. +要查看哪个虚拟队列正在被使用,扩展探测以虚拟队列名称为键。 ```sh sudo dtrace -n ' @@ -2998,7 +2977,7 @@ tick-1sec ' ``` -Output now looks like: +输出现在看起来像: ```text vtnet0-rx 482 @@ -3006,13 +2985,13 @@ vtnet0-tx 430 virtio_blk0 8220 ``` -This instantly reveals which device is doing work. A disk-heavy workload shows `virtio_blk0` dominating; a network-heavy workload shows `vtnet0-tx` and `vtnet0-rx`. This kind of first-level breakdown is usually enough to localise a performance problem. +这能立即揭示哪个设备正在进行工作。磁盘密集型工作负载显示 `virtio_blk0` 占主导;网络密集型工作负载显示 `vtnet0-tx` 和 `vtnet0-rx`。这种第一级分解通常足以定位性能问题。 -Note that the example dereferences an internal struct (`struct virtqueue`). The struct's layout is implementation-detail and can change between FreeBSD releases. Check `/usr/src/sys/dev/virtio/virtqueue.c` if the struct layout has changed and the probe fails. +注意示例解引用了内部结构体(`struct virtqueue`)。该结构体的布局是实现细节,可能在 FreeBSD 版本之间发生变化。如果结构体布局已更改且探测失败,请检查 `/usr/src/sys/dev/virtio/virtqueue.c`。 -### Measuring Time Spent in Enqueue +### 测量入队耗时 -Time-in-function is a standard DTrace recipe. +函数内耗时是一个标准的 DTrace 配方。 ```sh sudo dtrace -n ' @@ -3029,47 +3008,47 @@ fbt::virtqueue_enqueue:return ' ``` -The output is a histogram of how long each `virtqueue_enqueue` call took, in nanoseconds. For healthy VirtIO, most calls complete in the low microsecond range. A significant tail suggests lock contention (the function's mutex is held for too long), memory pressure, or expensive scatter-gather computation. +输出是每个 `virtqueue_enqueue` 调用所需时间的直方图,单位为纳秒。对于健康的 VirtIO,大多数调用在几微秒内完成。显著的尾部表明锁争用(该函数的互斥锁持有时间过长)、内存压力或昂贵的分散-聚集计算。 -### Watching for VM Exits +### 观察 VM 退出 -VM exits are the fundamental cost of virtualisation. DTrace's `vmm` probes (if available) let you count them. +VM 退出是虚拟化的基本成本。DTrace 的 `vmm` 探测(如果可用)让您对它们进行计数。 ```sh sudo dtrace -n 'fbt:vmm::*:entry { @[probefunc] = count(); } tick-1sec { printa(@); trunc(@); }' ``` -On a busy host, this shows dozens of `vmm` functions. The ones to watch are `vm_exit_*`, which handle different exit types (I/O, interrupt, hypercall). Seeing `vm_exit_inout` in the top results suggests the guest is doing a lot of I/O through emulated devices and would benefit from VirtIO. +在繁忙的主机上,这会显示数十个 `vmm` 函数。需要关注的是 `vm_exit_*`,它们处理不同的退出类型(I/O、中断、超级调用)。在顶部结果中看到 `vm_exit_inout` 表明客户机正在通过模拟设备进行大量 I/O,并将从 VirtIO 中受益。 -### Tracing a Specific Driver +### 追踪特定驱动程序 -To focus on a specific driver's functions, narrow the probe to its module name. +要关注特定驱动程序的函数,将探测范围缩小到其模块名称。 ```sh sudo dtrace -n 'fbt:virtio_blk::*:entry { @[probefunc] = count(); } tick-1sec { printa(@); trunc(@); }' ``` -This counts all `virtio_blk` function entries. On a quiescent VM, the output is empty; on an active VM, you see every function the driver calls, with counts. This is useful for getting a feel for a driver's internal structure. +这会统计所有 `virtio_blk` 函数入口。在静默的 VM 上,输出为空;在活跃的 VM 上,您会看到驱动程序调用的每个函数及其计数。这对于了解驱动程序内部结构很有用。 -### Tracing a Custom Driver +### 追踪自定义驱动程序 -For the `vtedu` driver from the case study, the same technique works as long as the module is loaded and named `virtio_edu`. +对于案例研究中的 `vtedu` 驱动程序,只要模块已加载且名称为 `virtio_edu`,同样的技术也适用。 ```sh sudo dtrace -n 'fbt:virtio_edu::*:entry { @[probefunc] = count(); } tick-1sec { printa(@); trunc(@); }' ``` -If no backend is attached, the counts will be zero. If a backend is attached and the driver is exercising the virtqueue, you see `vtedu_write`, `vtedu_submit_locked`, `vtedu_vq_intr`, and `vtedu_read` in the counts, in rough proportion to usage. +如果没有附加后端,计数将为零。如果附加了后端并且驱动程序正在操作虚拟队列,您会在计数中看到 `vtedu_write`、`vtedu_submit_locked`、`vtedu_vq_intr` 和 `vtedu_read`,大致与使用量成比例。 -### Observing the Guest-Host Boundary +### 观察客户机-主机边界 -A more ambitious use of DTrace is to correlate guest-side events with host-side events. This is possible when both sides are FreeBSD and DTrace is available on both. Run DTrace on the host to count `vmm` exits and on the guest to count driver calls; the numbers should correlate one-for-one on an unloaded system, diverging as the host batches exits or as posted interrupts kick in. +DTrace 的一个更雄心勃勃的用法是将客户机侧事件与主机侧事件关联起来。当双方都是 FreeBSD 且 DTrace 在双方都可用时,这是可能的。在主机上运行 DTrace 统计 `vmm` 退出,在客户机上统计驱动程序调用;在未加载的系统中,数字应该一一对应,当主机批量处理退出或发布中断启动时会出现差异。 -This is an advanced technique and mostly interesting for performance analysis. For day-to-day debugging, single-side DTrace is usually enough. +这是一种高级技术,主要用于性能分析。对于日常调试,单侧 DTrace 通常就足够了。 -### Saving and Reusing Probes +### 保存和重用探测脚本 -The `dtrace(1)` command-line form is fine for quick investigations. For repeated use, save probes to a file and invoke with `dtrace -s`. +`dtrace(1)` 命令行形式适合快速调查。对于重复使用,将探测保存到文件并使用 `dtrace -s` 调用。 ```sh % cat > virtio_probes.d <<'EOF' @@ -3091,25 +3070,25 @@ EOF % sudo dtrace -s virtio_probes.d ``` -A curated set of probes in `.d` files is a good investment for anyone who spends significant time debugging VirtIO. +对于花费大量时间调试 VirtIO 的人来说,将一组精选的探测保存在 `.d` 文件中是一项很好的投资。 -### When DTrace Cannot Help +### 当 DTrace 无法帮忙时 -DTrace can observe the kernel and, with `pid` provider, most user-space programs. It cannot directly observe guest kernels from the host, because the guest is a process whose internal structure `dtrace` does not know. You can trace the `bhyve(8)` process itself (as a user-space program) using the `pid` provider, which shows what `bhyve` is doing but not what its guest is doing. +DTrace 可以观察内核,并通过 `pid` 提供者观察大多数用户空间程序。它不能直接从主机观察客户机内核,因为客户机是一个其内部结构 `dtrace` 不知道的进程。您可以使用 `pid` 提供者跟踪 `bhyve(8)` 进程本身(作为用户空间程序),这显示了 `bhyve` 在做什么,但不能显示其客户机在做什么。 -For guest-side tracing, DTrace runs inside the guest. If the guest is FreeBSD 14.3, the full DTrace toolkit is available. If the guest is Linux, use `bpftrace` or `perf` instead; they are different tools with similar capabilities. +对于客户机侧跟踪,DTrace 在客户机内部运行。如果客户机是 FreeBSD 14.3,则完整的 DTrace 工具包可用。如果客户机是 Linux,请使用 `bpftrace` 或 `perf` 代替;它们是具有类似功能的不同工具。 -### A Closing Word +### 结语 -DTrace is one of FreeBSD's competitive advantages. Every driver author should be comfortable with it; the investment pays off repeatedly across years of debugging. This appendix gives you a starting point; the FreeBSD Handbook's DTrace chapter and the original *DTrace: Dynamic Tracing in Oracle Solaris* book (freely available online) are the next steps if you want to go deeper. +DTrace 是 FreeBSD 的竞争优势之一。每个驱动程序作者都应该熟悉它;这项投资在多年的调试中会反复回报。本附录为您提供了一个起点;FreeBSD 手册的 DTrace 章节和原版 *DTrace: Dynamic Tracing in Oracle Solaris* 书籍(可在线免费获取)是如果您想深入了解的下一步。 -## Appendix: A Complete bhyve Configuration Walkthrough +## 附录:完整的 bhyve 配置指南 -Readers who want to run the labs need a working `bhyve(8)` setup. This appendix walks through a complete configuration, from a bare FreeBSD 14.3 host to a guest with VirtIO devices, in enough detail for a beginner to reproduce it. If you have already built `bhyve` environments, skim this; the goal is to provide a reference for readers who have not. +想要运行实验的读者需要一个可工作的 `bhyve(8)` 设置。本附录从裸 FreeBSD 14.3 主机到带有 VirtIO 设备的客户机,逐步介绍完整的配置,详细到足以让初学者复现。如果你已经构建过 `bhyve` 环境,可以略读此处;目标是为尚未构建过的读者提供参考。 -### The Host Side +### 主机侧 -Start with a FreeBSD 14.3 host. Confirm the virtualisation extensions are enabled. +从一个 FreeBSD 14.3 主机开始。确认虚拟化扩展已启用。 ```sh % sysctl hw.vmm @@ -3120,19 +3099,19 @@ hw.vmm.topology.cpus: 0 ... ``` -If `hw.vmm` is absent entirely, the `vmm(4)` module is not loaded. Load it with `kldload vmm`. Add `vmm_load="YES"` to `/boot/loader.conf` to load it at every boot. +如果 `hw.vmm` 完全不存在,说明 `vmm(4)` 模块未加载。使用 `kldload vmm` 加载它。添加 `vmm_load="YES"` 到 `/boot/loader.conf` 以在每次启动时加载。 -If `vmm` is loaded but the VT-x/AMD-V features are absent, enable them in the host firmware. The setting is usually called "VT-x", "VMX", "AMD-V", or "SVM" in the BIOS/UEFI menu. After enabling, reboot. +如果 `vmm` 已加载但 VT-x/AMD-V 特性缺失,请在主机固件中启用它们。该设置在 BIOS/UEFI 菜单中通常称为"VT-x"、"VMX"、"AMD-V"或"SVM"。启用后,重新启动。 -### Install vm-bhyve +### 安装 vm-bhyve -`vm-bhyve` is a wrapper that makes `bhyve(8)` easier to use. Install it from ports or packages. +`vm-bhyve` 是一个使 `bhyve(8)` 更易于使用的包装器。从 ports 或软件包安装它。 ```sh % sudo pkg install vm-bhyve ``` -Create the VM directory. Using ZFS is convenient because it supports snapshotting. +创建 VM 目录。使用 ZFS 很方便,因为它支持快照。 ```sh % sudo zfs create -o mountpoint=/vm zroot/vm @@ -3151,70 +3130,70 @@ vm_enable="YES" vm_dir="zfs:zroot/vm" ``` -For UFS, use `vm_dir="/vm"` instead. Initialise the directory. +对于 UFS,改用 `vm_dir="/vm"`。初始化目录。 ```sh % sudo vm init % sudo cp /usr/local/share/examples/vm-bhyve/config_samples/default.conf /vm/.templates/ ``` -Edit `/vm/.templates/default.conf` if you want different defaults (memory size, CPU count). +如果您想要不同的默认值(内存大小、CPU 数量),请编辑 `/vm/.templates/default.conf`。 -### Create and Install a Guest +### 创建并安装客户机 -Download a FreeBSD 14.3 installation image. The file `FreeBSD-14.3-RELEASE-amd64-disc1.iso` is the standard installer; for faster setup, use `FreeBSD-14.3-RELEASE-amd64.qcow2` if you prefer a prebuilt image. +下载 FreeBSD 14.3 安装镜像。文件 `FreeBSD-14.3-RELEASE-amd64-disc1.iso` 是标准安装程序;为了更快设置,如果您更喜欢预构建镜像,请使用 `FreeBSD-14.3-RELEASE-amd64.qcow2`。 ```sh % sudo vm iso https://download.freebsd.org/releases/amd64/amd64/ISO-IMAGES/14.3/FreeBSD-14.3-RELEASE-amd64-disc1.iso ``` -Create the guest. +创建客户机。 ```sh % sudo vm create -t default -s 20G guest0 ``` -Start the installer. +启动安装程序。 ```sh % sudo vm install guest0 FreeBSD-14.3-RELEASE-amd64-disc1.iso ``` -Connect to the console. +连接到控制台。 ```sh % sudo vm console guest0 ``` -The FreeBSD installer runs; follow it through to completion. At the end, reboot the guest. +FreeBSD 安装程序运行;按照提示完成安装。最后,重新启动客户机。 -### Configure Networking +### 配置网络 -`vm-bhyve` supports two network styles: bridged and NAT. For simplicity, bridged is fine. +`vm-bhyve` 支持两种网络风格:桥接和 NAT。为简单起见,桥接就很好。 -Create a bridge. +创建桥接。 ```sh % sudo vm switch create public % sudo vm switch add public em0 ``` -Replace `em0` with your host's physical interface. Assign guests to the switch in their configuration. +将 `em0` 替换为您主机的物理接口。将客户机分配到其配置中的交换机。 ```sh % sudo vm configure guest0 ``` -In the editor that opens, ensure `network0_switch="public"` is set. +在打开的编辑器中,确保设置了 `network0_switch="public"`。 -### Start the Guest +### 启动客户机 ```sh % sudo vm start guest0 % sudo vm console guest0 ``` -Log in, run `pciconf -lvBb`, and confirm the VirtIO devices are present. +登录,运行 `pciconf -lvBb`,并确认 VirtIO 设备存在。 ```sh # pciconf -lvBb @@ -3228,80 +3207,80 @@ virtio_pci1@pci0:0:3:0: class=0x020000 rev=0x00 vendor=0x1af4 device=0x1041 ... ... ``` -### Troubleshooting the Host Side +### 主机侧故障排除 -If the guest does not start, run `vm start guest0` with the verbose flag (`vm -f start guest0` keeps it in the foreground), look at the error message, and consult the `bhyve(8)` manual. The most common issues are missing resources (disk image path wrong, switch not set up) and permissions (user not in the `vm` group, or directories not readable). +如果客户机无法启动,使用详细标志运行 `vm start guest0`(`vm -f start guest0` 使其保持在前台),查看错误信息,并查阅 `bhyve(8)` 手册。最常见的问题是资源缺失(磁盘镜像路径错误、交换机未设置)和权限问题(用户不在 `vm` 组中,或目录不可读)。 -If networking does not work inside the guest, check the bridge on the host (`ifconfig bridge0`), check the tap device (`ifconfig tapN`), and check that the VM's `network0` setting matches the switch name. `vm-bhyve` generates a tap device per VM and wires it into the specified switch. +如果客户机内部网络无法工作,请检查主机上的桥接(`ifconfig bridge0`),检查 tap 设备(`ifconfig tapN`),并检查 VM 的 `network0` 设置是否与交换机名称匹配。`vm-bhyve` 为每个 VM 生成一个 tap 设备并将其连接到指定的交换机。 -### Using This Setup for the Labs +### 使用此设置进行实验 -With a working host and guest, Lab 1 is essentially done (you have a VirtIO-using guest). Lab 2 and Lab 3 can be performed inside the guest. Lab 4 needs `if_epair` on the host; Lab 5 needs a spare PCI device and IOMMU-enabled firmware. Lab 6 (building vtedu) is done inside the guest. Lab 7 (measuring overhead) uses the guest as the test subject. +有了可工作的主机和客户机,实验 1 基本完成(您有了一个使用 VirtIO 的客户机)。实验 2 和实验 3 可以在客户机内部执行。实验 4 需要在主机上使用 `if_epair`;实验 5 需要备用 PCI 设备和启用 IOMMU 的固件。实验 6(构建 vtedu)在客户机内部完成。实验 7(测量开销)将客户机用作测试对象。 -In short: if your `vm-bhyve` setup is solid, the rest of the chapter's hands-on work is accessible. +简而言之:如果您的 `vm-bhyve` 设置可靠,本章剩余动手实验内容都是可操作的。 -## Appendix: VirtIO Feature Bits Reference +## 附录:VirtIO 特性位参考 -This appendix collects the VirtIO feature bits most likely to matter to a driver author, with a brief description of each. The authoritative source is the VirtIO specification; this is a digest for quick reference. +本附录汇集了最可能对驱动程序作者重要的 VirtIO 特性位,每个都有简短描述。权威来源是 VirtIO 规范;这是一个供快速参考的摘要。 -### Device-Independent Features +### 设备无关的特性 -These apply across all VirtIO device types. +这些适用于所有 VirtIO 设备类型。 -- `VIRTIO_F_NOTIFY_ON_EMPTY` (bit 24): The device should notify the driver when the virtqueue becomes empty, in addition to normal completion notifications. Useful for drivers that want to know when all outstanding requests have been processed. +- `VIRTIO_F_NOTIFY_ON_EMPTY`(第 24 位):除了正常的完成通知外,当虚拟队列变空时,设备应通知驱动程序。适用于想知道所有未完成请求何时已处理的驱动程序。 -- `VIRTIO_F_ANY_LAYOUT` (bit 27, deprecated in v1): Headers and data can be in any scatter-gather layout. Always negotiated in v1 drivers; not relevant for modern code. +- `VIRTIO_F_ANY_LAYOUT`(第 27 位,v1 中已弃用):头部和数据可以在任何分散-聚集布局中。在 v1 驱动程序中总是协商;与现代代码无关。 -- `VIRTIO_F_RING_INDIRECT_DESC` (bit 28): Indirect descriptors supported. An entry in the descriptor table can point to another table, allowing longer scatter-gather lists without expanding the main ring. Strongly recommended for drivers that handle large requests. +- `VIRTIO_F_RING_INDIRECT_DESC`(第 28 位):支持间接描述符。描述符表中的条目可以指向另一个表,允许更长的分散-聚集列表而无需扩展主环。强烈推荐用于处理大型请求的驱动程序。 -- `VIRTIO_F_RING_EVENT_IDX` (bit 29): Event-index interrupt suppression. Lets the driver tell the device "do not interrupt me before descriptor N is available", reducing interrupt rate. Strongly recommended for high-rate drivers. +- `VIRTIO_F_RING_EVENT_IDX`(第 29 位):事件索引中断抑制。让驱动程序告诉设备"在描述符 N 可用之前不要中断我",降低中断率。强烈推荐用于高频率驱动程序。 -- `VIRTIO_F_VERSION_1` (bit 32): Modern VirtIO (version 1.0 or later). Without this, the driver is in legacy mode, with different config-space layout and conventions. New drivers should require this. +- `VIRTIO_F_VERSION_1`(第 32 位):现代 VirtIO(1.0 或更高版本)。没有此位,驱动程序处于传统模式,具有不同的配置空间布局和约定。新驱动程序应要求此位。 -- `VIRTIO_F_ACCESS_PLATFORM` (bit 33): The device uses a platform-specific DMA address translation (for example, an IOMMU). Required for passthrough-capable deployments. +- `VIRTIO_F_ACCESS_PLATFORM`(第 33 位):设备使用特定平台的 DMA 地址转换(例如 IOMMU)。对于支持直通的部署是必需的。 -- `VIRTIO_F_RING_PACKED` (bit 34): Packed virtqueue layout. A newer, more cache-friendly layout than the classic split layout. Not supported by all backends; negotiate but do not require. +- `VIRTIO_F_RING_PACKED`(第 34 位):压缩虚拟队列布局。比经典拆分布局更新的、缓存更友好的布局。并非所有后端都支持;进行协商但不要求。 -- `VIRTIO_F_IN_ORDER` (bit 35): Descriptors are used in the same order they were made available. Allows optimisations in the driver (no need to track descriptor indexes); not supported by all backends. +- `VIRTIO_F_IN_ORDER`(第 35 位):描述符按可用顺序使用。允许驱动程序中的优化(无需跟踪描述符索引);并非所有后端都支持。 -### Block Device Features (`virtio_blk`) +### 块设备特性(`virtio_blk`) -- `VIRTIO_BLK_F_SIZE_MAX` (bit 1): The device has a maximum single-request size. -- `VIRTIO_BLK_F_SEG_MAX` (bit 2): The device has a maximum segment count per request. -- `VIRTIO_BLK_F_GEOMETRY` (bit 4): The device reports its cylinder/head/sector geometry. Mostly legacy. -- `VIRTIO_BLK_F_RO` (bit 5): The device is read-only. -- `VIRTIO_BLK_F_BLK_SIZE` (bit 6): The device reports its block size. -- `VIRTIO_BLK_F_FLUSH` (bit 9): The device supports flush (fsync) commands. -- `VIRTIO_BLK_F_TOPOLOGY` (bit 10): The device reports topology information (alignment, etc.). -- `VIRTIO_BLK_F_CONFIG_WCE` (bit 11): The driver can query and set the write-cache-enabled flag. -- `VIRTIO_BLK_F_DISCARD` (bit 13): The device supports discard (trim) commands. -- `VIRTIO_BLK_F_WRITE_ZEROES` (bit 14): The device supports write-zeroes commands. +- `VIRTIO_BLK_F_SIZE_MAX`(第 1 位):设备具有最大单次请求大小。 +- `VIRTIO_BLK_F_SEG_MAX`(第 2 位):设备具有每个请求的最大段数。 +- `VIRTIO_BLK_F_GEOMETRY`(第 4 位):设备报告其柱面/磁头/扇区几何结构。主要是遗留功能。 +- `VIRTIO_BLK_F_RO`(第 5 位):设备为只读。 +- `VIRTIO_BLK_F_BLK_SIZE`(第 6 位):设备报告其块大小。 +- `VIRTIO_BLK_F_FLUSH`(第 9 位):设备支持 flush(fsync)命令。 +- `VIRTIO_BLK_F_TOPOLOGY`(第 10 位):设备报告拓扑信息(对齐等)。 +- `VIRTIO_BLK_F_CONFIG_WCE`(第 11 位):驱动程序可以查询和设置写缓存启用标志。 +- `VIRTIO_BLK_F_DISCARD`(第 13 位):设备支持 discard(trim)命令。 +- `VIRTIO_BLK_F_WRITE_ZEROES`(第 14 位):设备支持写零命令。 -### Network Device Features (`virtio_net`) +### 网络设备特性(`virtio_net`) -- `VIRTIO_NET_F_CSUM` (bit 0): The device can offload checksum computation. -- `VIRTIO_NET_F_GUEST_CSUM` (bit 1): The driver can checksum-offload incoming packets. -- `VIRTIO_NET_F_MAC` (bit 5): The device provides a MAC address. +- `VIRTIO_NET_F_CSUM`(第 0 位):设备可以卸载校验和计算。 +- `VIRTIO_NET_F_GUEST_CSUM`(第 1 位):驱动程序可以对入站数据包进行校验和卸载。 +- `VIRTIO_NET_F_MAC`(第 5 位):设备提供 MAC 地址。 - `VIRTIO_NET_F_GSO` (bit 6): GSO (generic segmentation offload) supported. -- `VIRTIO_NET_F_GUEST_TSO4` (bit 7): Receive-side TSO over IPv4. -- `VIRTIO_NET_F_GUEST_TSO6` (bit 8): Receive-side TSO over IPv6. +- `VIRTIO_NET_F_GUEST_TSO4`(第 7 位):通过 IPv4 的接收端 TSO。 +- `VIRTIO_NET_F_GUEST_TSO6`(第 8 位):通过 IPv6 的接收端 TSO。 - `VIRTIO_NET_F_GUEST_ECN` (bit 9): ECN (explicit congestion notification) supported on receive. - `VIRTIO_NET_F_GUEST_UFO` (bit 10): Receive-side UFO (UDP fragmentation offload). -- `VIRTIO_NET_F_HOST_TSO4` (bit 11): Transmit-side TSO over IPv4. -- `VIRTIO_NET_F_HOST_TSO6` (bit 12): Transmit-side TSO over IPv6. +- `VIRTIO_NET_F_HOST_TSO4`(第 11 位):通过 IPv4 的发送端 TSO。 +- `VIRTIO_NET_F_HOST_TSO6`(第 12 位):通过 IPv6 的发送端 TSO。 - `VIRTIO_NET_F_HOST_ECN` (bit 13): ECN on transmit. - `VIRTIO_NET_F_HOST_UFO` (bit 14): Transmit-side UFO. - `VIRTIO_NET_F_MRG_RXBUF` (bit 15): Merged receive buffers. -- `VIRTIO_NET_F_STATUS` (bit 16): Configuration status is supported. +- `VIRTIO_NET_F_STATUS`(第 16 位):支持配置状态。 - `VIRTIO_NET_F_CTRL_VQ` (bit 17): Control virtqueue. - `VIRTIO_NET_F_CTRL_RX` (bit 18): Control channel for receive mode filtering. - `VIRTIO_NET_F_CTRL_VLAN` (bit 19): Control channel for VLAN filtering. - `VIRTIO_NET_F_MQ` (bit 22): Multiqueue support. - `VIRTIO_NET_F_CTRL_MAC_ADDR` (bit 23): Control channel for MAC-address setting. -### How to Read a Feature Word +### 如何读取特性字 -Features are a 64-bit word, with bits as described. To check whether a feature is negotiated: +特性是一个 64 位字,位如上所述。要检查特性是否已协商: ```c if ((sc->features & VIRTIO_F_RING_EVENT_IDX) != 0) { @@ -3309,17 +3288,17 @@ if ((sc->features & VIRTIO_F_RING_EVENT_IDX) != 0) { } ``` -To advertise a feature for negotiation, `|` it into the features mask before calling `virtio_negotiate_features`. The post-negotiation value of `sc->features` is the intersection of what the driver requested and what the backend offers. +要播发一个特性进行协商,在调用 `virtio_negotiate_features` 之前将其 `|` 到特性掩码中。`sc->features` 协商后的值是驱动程序请求和后端提供的交集。 -### Common Pitfalls +### 常见陷阱 -- Hard-coding feature requirements. A driver that requires `VIRTIO_NET_F_MRG_RXBUF` and falls over if it is absent will not work with simpler backends. Prefer to negotiate optimistically and adapt to what you get. -- Forgetting to check the post-negotiation features. A driver that behaves as if a feature is always present, without checking `sc->features`, will mis-program the device when the feature is absent. -- Ignoring version 1 requirements. Modern code should require `VIRTIO_F_VERSION_1`; legacy mode has too many quirks to be worth supporting in new drivers. +- 硬编码特性要求。要求 `VIRTIO_NET_F_MRG_RXBUF` 并且在缺少时崩溃的驱动程序将无法与更简单的后端一起工作。建议乐观地进行协商并适应获得的结果。 +- 忘记检查协商后的特性。在没有检查 `sc->features` 的情况下假设某个特性始终存在的驱动程序,在特性缺失时会错误地编程设备。 +- 忽略版本 1 要求。现代代码应要求 `VIRTIO_F_VERSION_1`;传统模式有太多古怪之处,不值得在新驱动程序中支持。 -### A Useful Habit +### 一个有用的习惯 -Log the negotiated feature word at attach time, with each interesting bit named. The `device_printf` below does this succinctly. +在附加时记录协商后的特性字,命名每个有趣的位。下面的 `device_printf` 简洁地做到了这一点。 ```c device_printf(dev, "features: ver1=%d evt_idx=%d indirect=%d mac=%d\n", @@ -3329,27 +3308,27 @@ device_printf(dev, "features: ver1=%d evt_idx=%d indirect=%d mac=%d\n", (sc->features & VIRTIO_NET_F_MAC) != 0); ``` -This single line in `dmesg` at attach time tells you, for any bug report, what feature set the driver is operating on. It is the VirtIO equivalent of logging a hardware revision; indispensable for support. +在附加时 `dmesg` 中的这一行告诉你,对于任何错误报告,驱动程序正在操作哪个特性集。这相当于记录硬件修订版的 VirtIO 方式;对于支持工作不可或缺。 -## Appendix: Further Reading +## 附录:延伸阅读 -For readers who want to go deeper, here is a short curated list. +对于想要深入了解的读者,这里是一个精选的简短列表。 -### FreeBSD source tree +### FreeBSD 源代码树 -- `/usr/src/sys/dev/virtio/random/virtio_random.c` - The smallest complete - VirtIO driver. Read first. -- `/usr/src/sys/dev/virtio/network/if_vtnet.c` - A larger VirtIO driver. -- `/usr/src/sys/dev/virtio/block/virtio_blk.c` - A request-response VirtIO - driver. -- `/usr/src/sys/dev/virtio/virtqueue.c` - The ring machinery. -- `/usr/src/sys/amd64/vmm/` - The bhyve kernel module. -- `/usr/src/usr.sbin/bhyve/` - The bhyve user-space emulator. -- `/usr/src/sys/kern/kern_jail.c` - Jail implementation. -- `/usr/src/sys/net/vnet.h`, `/usr/src/sys/net/vnet.c` - VNET framework. -- `/usr/src/sys/net/if_tuntap.c` - A VNET-aware cloning pseudo-driver. +- `/usr/src/sys/dev/virtio/random/virtio_random.c` - 最小的完整 + VirtIO 驱动程序。首先阅读。 +- `/usr/src/sys/dev/virtio/network/if_vtnet.c` - 一个较大的 VirtIO 驱动程序。 +- `/usr/src/sys/dev/virtio/block/virtio_blk.c` - 一个请求-响应类型的 VirtIO + 驱动程序。 +- `/usr/src/sys/dev/virtio/virtqueue.c` - 环机制。 +- `/usr/src/sys/amd64/vmm/` - bhyve 内核模块。 +- `/usr/src/usr.sbin/bhyve/` - bhyve 用户空间模拟器。 +- `/usr/src/sys/kern/kern_jail.c` - Jail 实现。 +- `/usr/src/sys/net/vnet.h`、`/usr/src/sys/net/vnet.c` - VNET 框架。 +- `/usr/src/sys/net/if_tuntap.c` - 一个 VNET 感知的克隆伪驱动程序。 -### Manual pages +### 手册页 - `virtio(4)`, `vtnet(4)`, `virtio_blk(4)` - `bhyve(8)`, `bhyvectl(8)`, `vmm(4)`, `vmm_dev(4)` @@ -3360,114 +3339,110 @@ For readers who want to go deeper, here is a short curated list. - `priv(9)`, `ucred(9)` - `if_epair(4)`, `vlan(4)`, `tun(4)`, `tap(4)` -### External standards +### 外部标准 -- The VirtIO 1.2 specification (OASIS) is the authoritative reference for - the protocol. Available from the OASIS VirtIO Technical Committee site. -- The PCI-SIG specifications for PCI Express, MSI-X, and ACS are relevant - for passthrough. +- VirtIO 1.2 规范(OASIS)是该协议的权威参考。 + 可从 OASIS VirtIO 技术委员会网站获取。 +- PCI-SIG 的 PCI Express、MSI-X 和 ACS 规范与 + 直通相关。 -### FreeBSD Handbook +### FreeBSD 手册 -- Chapter on jails, which complements this chapter with an administrative - perspective. -- Chapter on virtualisation, which covers `bhyve(8)` management in more - depth than this driver-focused chapter. +- 关于 jail 的章节,从管理角度补充本章内容。 +- 关于虚拟化的章节,比本章以驱动程序为重点的内容更深入地覆盖了 `bhyve(8)` 管理。 -These resources together form a reading programme that will carry a -motivated reader from this chapter's introduction to a practical fluency -in FreeBSD virtualisation and containerisation. You do not need to read -them all; pick the ones that fit your current project and build from -there. +这些资源共同构成了一个阅读计划,将把有动力的读者从本章的介绍带到 +FreeBSD 虚拟化和容器化的实际熟练程度。您不需要全部阅读; +选择适合您当前项目的内容,并在此基础上构建。 -## Appendix: Anti-Patterns in Virtualised Drivers +## 附录:虚拟化驱动程序中的反模式 -A good way to learn a craft is to study its common mistakes. This appendix collects the anti-patterns we have seen throughout the chapter, in a single place, with the fix for each. When reviewing a driver (your own or someone else's), scan for these patterns; each is a reliable sign of trouble. +学习一门手艺的好方法是研究其常见错误。本附录将我们在本章中看到的所有反模式收集在一个地方,并附有每个的修复方法。在审查驱动程序(自己的或他人的)时,扫描这些模式;每个都是问题的可靠迹象。 -### Busy-Waiting on a Status Register +### 在状态寄存器上忙等待 ```c -/* Anti-pattern */ +/* 反模式 */ while ((bus_read_4(sc->res, STATUS) & READY) == 0) ; ``` -Under virtualisation, each bus read is a VM exit. A tight loop consumes enormous CPU time and may never terminate if the guest is scheduled out. Use `DELAY(9)` inside the loop and a bounded iteration count, or use an interrupt-driven design that does not poll at all. +在虚拟化环境下,每次总线读取都是一次 VM 退出。紧密循环会消耗大量 CPU 时间,如果客户机被调度出去甚至可能永远不会终止。在循环中使用 `DELAY(9)` 和有界的迭代次数,或使用根本不轮询的中断驱动设计。 -### Caching Physical Addresses +### 缓存物理地址 ```c -/* Anti-pattern */ +/* 反模式 */ uint64_t phys_addr = vtophys(buffer); bus_write_8(sc->res, DMA_ADDR, phys_addr); /* ...later... */ bus_write_8(sc->res, DMA_ADDR, phys_addr); /* still valid? */ ``` -A physical address is a temporary view. Under memory compaction, live migration, or memory hotplug, the address may no longer refer to the same physical memory. Use `bus_dma(9)` and hold a DMA map; the map tracks the bus address correctly across kernel memory operations. +物理地址是临时视图。在内存压缩、实时迁移或内存热插拔下,该地址可能不再指向同一物理内存。使用 `bus_dma(9)` 并持有 DMA 映射;该映射在内核内存操作中正确跟踪总线地址。 -### Ignoring `si_drv1` +### 忽略 `si_drv1` ```c -/* Anti-pattern */ +/* 反模式 */ static int mydrv_read(struct cdev *dev, struct uio *uio, int flags) { struct mydrv_softc *sc = devclass_get_softc(mydrv_devclass, 0); - /* what if there are multiple units? */ + /* 如果有多个单元怎么办? */ } ``` -The `dev->si_drv1` slot is there to connect the cdev back to its softc. Setting it in attach and using it in read/write/ioctl is the idiomatic pattern. Using `devclass_get_softc` with a hardcoded unit number is a minefield as soon as more than one instance attaches. +`dev->si_drv1` 槽用于将 cdev 连接回其 softc。在附加中设置它并在 read/write/ioctl 中使用它是惯用模式。使用带有硬编码单元号的 `devclass_get_softc` 一旦有多个实例附加就成了雷区。 -### Assuming INTx +### 假设使用 INTx ```c -/* Anti-pattern */ +/* 反模式 */ sc->irq_rid = 0; sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid, RF_SHAREABLE | RF_ACTIVE); ``` -INTx is slower under virtualisation and does not scale to many-queue devices. Use `pci_alloc_msix` first, fall back to `pci_alloc_msi`, and only fall back to INTx for hardware that does not support message-signalled interrupts. +INTx 在虚拟化下速度较慢,并且不能扩展到多队列设备。首先使用 `pci_alloc_msix`,回退到 `pci_alloc_msi`,最后只对不支持消息信号中断的硬件回退到 INTx。 -### Hard-Coding Feature Bits +### 硬编码特性位 ```c -/* Anti-pattern */ +/* 反模式 */ if ((sc->features & VIRTIO_F_RING_INDIRECT_DESC) == 0) panic("device does not support indirect descriptors"); ``` -A driver that panics when a feature is missing is impossible to use with a backend that does not advertise the feature. Negotiate optimistically, check the post-negotiation result, and fall back gracefully to a less efficient path if the feature is missing. +在特性缺失时崩溃的驱动程序无法与不播发该特性的后端一起使用。乐观地进行协商,检查协商后的结果,并在特性缺失时优雅地回退到较低效率的路径。 -### Sleep-With-Spin-Lock Held +### 持有自旋锁时睡眠 ```c -/* Anti-pattern */ +/* 反模式 */ mtx_lock(&sc->lock); tsleep(sc, PWAIT, "wait", hz); mtx_unlock(&sc->lock); ``` -`tsleep` with an `mtx(9)` spin-lock held causes a panic on FreeBSD. Use `mtx_sleep` (which drops the mutex around the sleep) or use a blocking lock (`sx(9)`) when you need to sleep. +在持有 `mtx(9)` 自旋锁时调用 `tsleep` 会在 FreeBSD 上导致崩溃。使用 `mtx_sleep`(它在睡眠期间释放互斥锁)或在需要睡眠时使用阻塞锁(`sx(9)`)。 -### Returning ENOTTY for Unsupported Operations +### 对不支持的操作返回 ENOTTY ```c -/* Anti-pattern */ +/* 反模式 */ case MYDRV_PRIV_IOCTL: if (cred->cr_prison != &prison0) - return (ENOTTY); /* hide from jails */ + return (ENOTTY); /* 对 jail 隐藏 */ ... ``` -`ENOTTY` means "this ioctl does not exist". It hides the operation from jailed callers, but it also breaks tooling that introspects available ioctls. Prefer `EPERM` for "this ioctl exists but you cannot use it", leaving introspection correct. +`ENOTTY` 意味着"此 ioctl 不存在"。它会向被限制的调用者隐藏操作,但也会破坏内省可用 ioctl 的工具。对于"此 ioctl 存在但你不能使用它",建议使用 `EPERM`,保持内省的正确性。 -### Forgetting the Detach Path +### 忘记分离路径 ```c -/* Anti-pattern */ +/* 反模式 */ static int mydrv_detach(device_t dev) { @@ -3478,12 +3453,12 @@ mydrv_detach(device_t dev) } ``` -Missing callout drains, missing taskqueue drains, missing cdev destruction, missing mutex destruction, missing DMA map unload, missing interrupt teardown. Each becomes a leak or a crash at kldunload. The attach path is usually clean; the detach path is where bugs hide. +缺少 callout 排空、缺少 taskqueue 排空、缺少 cdev 销毁、缺少互斥锁销毁、缺少 DMA 映射卸载、缺少中断拆除。每个都在 kldunload 时成为泄漏或崩溃。附加路径通常是干净的;分离路径是错误隐藏的地方。 -### Assuming `device_printf` Works Without a Device +### 假设 `device_printf` 在没有设备时也能工作 ```c -/* Anti-pattern */ +/* 反模式 */ static int mydrv_modevent(module_t mod, int event, void *arg) { @@ -3491,40 +3466,40 @@ mydrv_modevent(module_t mod, int event, void *arg) } ``` -`device_printf` with a NULL `device_t` dereferences a null pointer. Inside module event handlers, before a device has been attached, use `printf` (with a "mydrv:" prefix to identify the source). `device_printf` is for per-device events after attach. +使用 NULL `device_t` 调用 `device_printf` 会解引用空指针。在模块事件处理程序内部,在设备还未附加之前,使用 `printf`(带有"mydrv:"前缀标识来源)。`device_printf` 用于附加后的每个设备事件。 -### Not Cleaning Up VNET State +### 未清理 VNET 状态 ```c -/* Anti-pattern */ +/* 反模式 */ static int mydrv_mod_event(module_t mod, int event, void *arg) { if (event == MOD_UNLOAD) - free(mydrv_state, M_DEVBUF); /* in which VNET? */ + free(mydrv_state, M_DEVBUF); /* 在哪个 VNET 中? */ } ``` -Per-VNET state is allocated in a specific VNET context. Freeing it without setting that context accesses the wrong VNET's data. Use `VNET_FOREACH` and `CURVNET_SET` to walk every VNET and clean up each one's state. +逐 VNET 状态在特定的 VNET 上下文中分配。在没有设置该上下文的情况下释放它会访问错误的 VNET 数据。使用 `VNET_FOREACH` 和 `CURVNET_SET` 遍历每个 VNET 并清理每个状态。 -### Using `getnanouptime` for Timing +### 使用 `getnanouptime` 进行计时 ```c -/* Anti-pattern */ +/* 反模式 */ struct timespec ts; getnanouptime(&ts); /* ...do work... */ struct timespec ts2; getnanouptime(&ts2); -/* difference is arbitrary inside a VM */ +/* VM 内部的差异是任意的 */ ``` -`getnanouptime` returns a low-resolution reading that the kernel caches. For precise short-duration timing, use `binuptime(9)` or `sbinuptime(9)`, which read the high-resolution time source. Under virtualisation, the precise readings are as correct as the time source allows; the cached readings have been stale for up to a tick. +`getnanouptime` 返回内核缓存的低分辨率读数。对于精确的短持续时间计时,使用 `binuptime(9)` 或 `sbinuptime(9)`,它们读取高分辨率时间源。在虚拟化下,精确读数在时间源允许的范围内是正确的;缓存的读数可能已经过时长达一个 tick。 -### Probing Hardware in the Probe Method +### 在探测方法中探测硬件 ```c -/* Anti-pattern */ +/* 反模式 */ static int mydrv_probe(device_t dev) { @@ -3533,133 +3508,133 @@ mydrv_probe(device_t dev) } ``` -The probe method should be purely identity-based: inspect the PNP information, return a priority, and do nothing that requires the hardware to be present and functional. Hardware interaction belongs in attach. Under virtualisation, a probe that pokes hardware before feature negotiation can mis-identify the device. +探测方法应纯粹基于身份:检查 PNP 信息,返回优先级,不做任何需要硬件存在和功能的事情。硬件交互属于附加函数。在虚拟化下,在特性协商前探测硬件的探测方法可能错误识别设备。 -### Storing Kernel Pointers Through `ioctl` +### 通过 `ioctl` 存储内核指针 ```c -/* Anti-pattern */ +/* 反模式 */ case MYDRV_GET_PTR: *(void **)data = sc->internal_state; return (0); ``` -Passing kernel pointers to user space is a security bug. Under virtualisation it can even leak hypervisor-relevant information. Always copy the data the caller asks for, never the pointer. +将内核指针传递给用户空间是一个安全错误。在虚拟化下它甚至可能泄漏与虚拟机监控程序相关的信息。始终复制调用者请求的数据,从不传递指针。 -### Summary +### 总结 -These anti-patterns cover most of the ways that FreeBSD drivers go wrong under virtualisation. They are not unique to VMs, but they are *amplified* under virtualisation: the same bug that corrupts memory once a day on bare metal might corrupt it hundreds of times per second under a VM whose timing is different. Fixing these patterns is not "fixing the VM case"; it is fixing the driver to meet the kernel's baseline expectations. +这些反模式涵盖了 FreeBSD 驱动程序在虚拟化下出错的大部分方式。它们并非 VM 独有,但在虚拟化下会被*放大*:在裸金属上每天只损坏一次内存的同一个错误,在时序不同的 VM 下可能每秒损坏数百次。修复这些模式不是"修复 VM 的情况";而是修复驱动程序以满足内核的基线期望。 -## Appendix: A Checklist for a Virtualisation-Ready Driver +## 附录:虚拟化就绪驱动程序检查清单 -A concrete checklist you can apply to your own driver before declaring it virtualisation-ready. Go through each item; any "no" answer is a task. +一个具体的检查清单,您可以在宣布驱动程序虚拟化就绪之前应用于自己的驱动程序。逐项检查;任何"否"的答案都是一个待办任务。 -### Device Binding and Probe +### 设备绑定与探测 -- Does the driver use `VIRTIO_SIMPLE_PNPINFO` or `VIRTIO_DRIVER_MODULE` rather than hand-rolling PNP entries? -- Does the probe method avoid hardware access and only use PNP identity? -- Does the attach method call `virtio_negotiate_features` and log the result? -- Does attach fail cleanly (releasing every resource it has allocated) if any step after virtqueue allocation fails? +- 驱动程序是否使用 `VIRTIO_SIMPLE_PNPINFO` 或 `VIRTIO_DRIVER_MODULE` 而不是手动编写 PNP 条目? +- 探测方法是否避免硬件访问而仅使用 PNP 标识? +- 附加方法是否调用 `virtio_negotiate_features` 并记录结果? +- 如果 virtqueue 分配后的任何步骤失败,附加是否干净地失败(释放其已分配的每个资源)? -### Resources +### 资源 -- Does the driver use `bus_alloc_resource_any` with a dynamic RID rather than hard-coding resource IDs? -- Does the driver use `pci_alloc_msix` (or `pci_alloc_msi`) in preference to INTx? -- Are all `bus_alloc_resource` calls matched by `bus_release_resource` in detach? +- 驱动程序是否使用带有动态 RID 的 `bus_alloc_resource_any` 而不是硬编码资源 ID? +- 驱动程序是否优先使用 `pci_alloc_msix`(或 `pci_alloc_msi`)而不是 INTx? +- 分离中的所有 `bus_alloc_resource` 调用是否都有对应的 `bus_release_resource`? ### DMA -- Does every address programmed into hardware come from `bus_dma_load` (or similar) rather than `vtophys`? -- Does the driver hold DMA tags and maps with appropriate lifetimes, not re-creating them per operation when avoidable? -- Does the driver handle `bus_dma_load_mbuf_sg` correctly for scatter-gather? -- Is the driver's `bus_dma_tag` created with the correct alignment, boundary, and maximum-segment constraints? +- 写入硬件的每个地址是否来自 `bus_dma_load`(或类似函数)而不是 `vtophys`? +- 驱动程序是否在适当的生命周期内持有 DMA 标签和映射,而不是在可避免的情况下每次操作都重新创建它们? +- 驱动程序是否正确处理用于分散-聚集的 `bus_dma_load_mbuf_sg`? +- 驱动程序的 `bus_dma_tag` 是否使用正确的对齐、边界和最大段约束创建? -### Interrupts +### 中断 -- Is the interrupt handler MP-safe (declared with `INTR_MPSAFE`)? -- Does the handler handle the "no work" case gracefully (in case of spurious wake-up)? -- Does the handler disable and re-enable virtqueue interrupts correctly, using the `virtqueue_disable_intr` / `virtqueue_enable_intr` pattern? -- Is the interrupt path free of blocking operations (no `malloc(M_WAITOK)`, no `mtx_sleep`)? +- 中断处理程序是否是 MP 安全的(使用 `INTR_MPSAFE` 声明)? +- 处理程序是否优雅地处理"无工作"情况(以防虚假唤醒)? +- 处理程序是否使用 `virtqueue_disable_intr` / `virtqueue_enable_intr` 模式正确地禁用和重新启用 virtqueue 中断? +- 中断路径是否没有阻塞操作(没有 `malloc(M_WAITOK)`,没有 `mtx_sleep`)? -### Character Device Interface +### 字符设备接口 -- Does attach set `cdev->si_drv1 = sc`? -- Does detach call `destroy_dev` before freeing the softc? -- Do read and write handle short I/O correctly (less than the full buffer size)? -- Does the driver check the result of `uiomove` for errors? -- Does ioctl use `priv_check` for operations that require elevated privilege? +- 附加是否设置了 `cdev->si_drv1 = sc`? +- 分离是否在释放 softc 之前调用 `destroy_dev`? +- 读取和写入是否正确处理了短 I/O(小于完整缓冲区大小)? +- 驱动程序是否检查 `uiomove` 的结果是否有错误? +- ioctl 是否对需要提升权限的操作使用 `priv_check`? -### Locking +### 锁定 -- Is every softc access covered by the softc's mutex? -- Is the detach path drain-then-free, not free-then-drain? -- Are sleeping waits done with `mtx_sleep` or `sx(9)` rather than `tsleep` with a mutex held? -- Is there a discernible ordering of acquisitions (to avoid deadlock)? +- 每个 softc 访问是否都被 softc 的互斥锁保护? +- 分离路径是否是先排空再释放,而不是先释放再排空? +- 等待睡眠是否使用 `mtx_sleep` 或 `sx(9)` 而不是在持有互斥锁时使用 `tsleep`? +- 是否有可辨识的获取顺序(以避免死锁)? -### Timing +### 时序 -- Does the driver use `DELAY(9)`, `pause(9)`, or `callout(9)` rather than busy loops? -- Does the driver avoid reading the TSC directly? -- Does every wait have a bounded timeout, with a sensible error on exceed? +- 驱动程序是否使用 `DELAY(9)`、`pause(9)` 或 `callout(9)` 而不是忙等待循环? +- 驱动程序是否避免直接读取 TSC? +- 每个等待是否有有界超时,并在超时时返回合理的错误? -### Privilege +### 权限 -- Does the driver call `priv_check` for all operations that should not be available to unprivileged users? -- Does the driver use the correct privilege (`PRIV_DRIVER`, `PRIV_IO`, not `PRIV_ROOT`)? -- Does the driver consider jailed callers, using `priv_check` which also calls `prison_priv_check`? +- 驱动程序是否对所有不应提供给非特权用户的操作调用 `priv_check`? +- 驱动程序是否使用了正确的权限(`PRIV_DRIVER`、`PRIV_IO`,而不是 `PRIV_ROOT`)? +- 驱动程序是否考虑了被限制的调用者,使用也会调用 `prison_priv_check` 的 `priv_check`? -### Detach and Unload +### 分离 and Unload -- Does detach drain all callouts (`callout_drain`)? -- Does detach drain all taskqueues (`taskqueue_drain_all`)? -- Does detach stop any kernel threads the driver has created (via condition variables or similar)? -- Does detach release every resource attach allocated? -- Can the module be unloaded at any time (no hangs on `kldunload`)? +- 分离是否排空了所有 callout(`callout_drain`)? +- 分离是否排空了所有 taskqueue(`taskqueue_drain_all`)? +- 分离是否停止了驱动程序创建的任何内核线程(通过条件变量或类似方式)? +- 分离是否释放了附加分配的每个资源? +- 模块是否可以随时卸载(`kldunload` 不会挂起)? -### VNET (if applicable) +### VNET(如适用) -- Does the driver register VNET sysinit/sysuninit for per-VNET state? -- Does the driver use `V_` prefix macros for per-VNET variables? -- Does the VNET move path allocate state on entry and free on exit? -- Does the driver use `CURVNET_SET` / `CURVNET_RESTORE` when accessing a VNET other than the current one? +- 驱动程序是否为逐 VNET 状态注册了 VNET sysinit/sysuninit? +- 驱动程序是否为逐 VNET 变量使用 `V_` 前缀宏? +- VNET 迁移路径是否在进入时分配状态并在退出时释放? +- 在访问当前 VNET 以外的 VNET 时,驱动程序是否使用 `CURVNET_SET` / `CURVNET_RESTORE`? -### Testing +### 测试 -- Does the driver have a `make test` target (even if it just builds and loads)? -- Has the driver been run through the attach-detach cycle at least 100 times? -- Has the driver been loaded under both VirtIO and passthrough (if applicable)? -- Has the driver been loaded inside at least one jail and one VNET jail? -- Has the driver been built on at least amd64; ideally also on arm64? +- 驱动程序是否有 `make test` 目标(即使它只是构建和加载)? +- 驱动程序是否已经通过附加-分离循环至少 100 次? +- 驱动程序是否在 VirtIO 和直通(如果适用)下都已加载? +- 驱动程序是否已在至少一个 jail 和一个 VNET jail 内加载? +- 驱动程序是否至少在 amd64 上构建过;理想情况下也在 arm64 上? -### Documentation +### 文档 -- Is there a README explaining what the driver does and how to build it? -- Is there a manual page describing the driver's user-visible interface? -- Is the PNP table complete enough that `kldxref` finds the driver for auto-loading? +- 是否有 README 解释驱动程序的作用以及如何构建它? +- 是否有描述驱动程序用户可见接口的手册页? +- PNP 表是否足够完整,使得 `kldxref` 能够找到驱动程序进行自动加载? -A driver that passes this checklist is well on its way to being virtualisation-ready. A driver that fails several items needs attention before it will behave well under the diverse environments of modern deployment. Run through the list for every driver you write; it is faster than debugging each issue individually when the driver hits a customer. +通过此检查清单的驱动程序已经在虚拟化就绪的道路上走得很好。在多个项目上失败的驱动程序在能够在现代部署的多样化环境中良好运行之前需要注意。为您编写的每个驱动程序检查清单;当驱动程序交付给客户时,这比逐个调试每个问题更快。 -## Appendix: Sketching a bhyve Backend for vtedu +## 附录:为 vtedu 草拟 bhyve 后端 -Challenge 5 asks the reader to write a `bhyve(8)` backend for the `vtedu` driver. This appendix sketches the architecture of such a backend at a level of detail useful for planning. It is not a complete implementation; writing one is the challenge. The goal here is to demystify the backend side of the VirtIO story so the challenge becomes tractable. +挑战 5 要求读者为 `vtedu` 驱动程序编写一个 `bhyve(8)` 后端。本附录在有助于规划的详细程度上勾勒了这样一个后端的架构。这不是一个完整的实现;编写一个是挑战本身。这里的目标是揭开 VirtIO 后端侧的神秘面纱,使挑战变得易于处理。 -### Where the Code Lives +### 代码位置 -The `bhyve(8)` user-space emulator lives under `/usr/src/usr.sbin/bhyve/`. Its source files are a mixture of CPU and chipset emulation, per-device emulators for different VirtIO types, and glue code that connects `bhyve(8)` to the `vmm(4)` kernel module. The relevant per-device files for VirtIO are: +`bhyve(8)` 用户空间模拟器位于 `/usr/src/usr.sbin/bhyve/` 下。其源文件混合了 CPU 和芯片组模拟、不同 VirtIO 类型的每个设备模拟器,以及将 `bhyve(8)` 连接到 `vmm(4)` 内核模块的胶水代码。VirtIO 相关的每个设备文件有: -- `/usr/src/usr.sbin/bhyve/pci_virtio_rnd.c`: virtio-rnd (random number generator). The simplest VirtIO backend. Read first. +- `/usr/src/usr.sbin/bhyve/pci_virtio_rnd.c`:virtio-rnd(随机数生成器)。最简单的 VirtIO 后端。首先阅读。 - `/usr/src/usr.sbin/bhyve/pci_virtio_block.c`: virtio-blk (block device). - `/usr/src/usr.sbin/bhyve/pci_virtio_net.c`: virtio-net (network). - `/usr/src/usr.sbin/bhyve/pci_virtio_9p.c`: virtio-9p (filesystem share). - `/usr/src/usr.sbin/bhyve/pci_virtio_console.c`: virtio-console (serial). -Each of these is a few hundred to a couple of thousand lines of code. They share a common backend framework in `/usr/src/usr.sbin/bhyve/virtio.h` and `/usr/src/usr.sbin/bhyve/virtio.c`. The `pci_virtio_*.c` files above are per-device consumers of that framework; each one registers a `struct virtio_consts`, a set of virtqueue callbacks, and the device-specific config-space layout. +每个都有几百到几千行代码。它们在 `/usr/src/usr.sbin/bhyve/virtio.h` 和 `/usr/src/usr.sbin/bhyve/virtio.c` 中共享一个公共后端框架。上述的 `pci_virtio_*.c` 文件是该框架的每个设备消费者;每个注册一个 `struct virtio_consts`、一组 virtqueue 回调和设备特定的配置空间布局。 -### The Framework Handles the Protocol +### 框架处理协议 -The good news for a backend author is that `bhyve(8)` already implements the VirtIO protocol. Feature negotiation, descriptor-ring management, notification delivery, interrupt injection, all of it lives in the `virtio.c` framework. A new backend implements only the device-specific behaviour: what happens when a buffer arrives on the virtqueue, what config-space fields the device exposes, and how device-level events are generated. +对于后端作者来说,好消息是 `bhyve(8)` 已经实现了 VirtIO 协议。特性协商、描述符环管理、通知传递、中断注入,所有这些都存在于 `virtio.c` 框架中。新的后端只实现设备特定行为:当缓冲区到达虚拟队列时会发生什么、设备暴露哪些配置空间字段、以及设备级事件如何生成。 -The framework-facing interface is a small set of callbacks, encapsulated in a `struct virtio_consts`. +框架面向的接口是一小组回调,封装在 `struct virtio_consts` 中。 ```c /* Sketch, not actual bhyve code. */ @@ -3676,11 +3651,11 @@ struct virtio_consts { }; ``` -A new backend fills in this struct and registers it with the framework. The framework calls into the backend when the guest-side driver does interesting things (resets the device, notifies the virtqueue, reads or writes config space). +新的后端填充此结构体并将其注册到框架。当客户机侧驱动程序执行有趣的操作(重置设备、通知虚拟队列、读取或写入配置空间)时,框架会调用后端。 -### Sketching the vtedu Backend +### 草拟 vtedu 后端 -For `vtedu`, the backend is simple. It has one virtqueue, no config-space fields beyond the generic ones, and one feature bit (`VTEDU_F_UPPERCASE`). Its state is: +对于 `vtedu`,后端很简单。它有一个虚拟队列,没有超出通用字段的配置空间字段,和一个特性位(`VTEDU_F_UPPERCASE`)。其状态如下: ```c struct pci_vtedu_softc { @@ -3691,7 +3666,7 @@ struct pci_vtedu_softc { }; ``` -The callbacks are small. +回调函数很小。 ```c static void @@ -3716,7 +3691,7 @@ pci_vtedu_apply_features(void *vsc, uint64_t features) } ``` -The interesting callback is `vc_qnotify`, called when the guest notifies the virtqueue. +有趣的回调是 `vc_qnotify`,当客户机通知虚拟队列时调用。 ```c static void @@ -3750,38 +3725,38 @@ pci_vtedu_qnotify(void *vsc, struct vqueue_info *vq) } ``` -That is the core of it. The `vq_has_descs`, `vq_getchain`, `vq_relchain`, and `vq_endchains` calls are framework helpers that unpack the virtqueue descriptors into `iovec` structures and repackage the results. +这就是核心。`vq_has_descs`、`vq_getchain`、`vq_relchain` 和 `vq_endchains` 调用是将虚拟队列描述符解包到 `iovec` 结构并重新打包结果的框架辅助函数。 -### Connecting to the Device Table +### 连接到设备表 -`bhyve(8)` maintains a table of device emulators; each backend registers itself at build time. The registration uses a `PCI_EMUL_TYPE(...)` macro (or similar) that adds the backend's vtable to a linker-set. Once registered, the `bhyve(8)` command line can reference the backend by name: +`bhyve(8)` 维护一个设备模拟器表;每个后端在构建时注册自己。注册使用 `PCI_EMUL_TYPE(...)` 宏(或类似)将后端的虚函数表添加到链接器集中。一旦注册,`bhyve(8)` 命令行可以按名称引用后端: ```sh bhyve ... -s 7,virtio-edu guest0 ``` -The `-s 7,virtio-edu` adds the `virtio-edu` device at PCI slot 7. When the guest boots, the FreeBSD kernel enumerates the PCI bus, finds the device with VirtIO vendor ID and the right device ID, and attaches `vtedu` to it. +`-s 7,virtio-edu` 在 PCI 插槽 7 上添加 `virtio-edu` 设备。当客户机启动时,FreeBSD 内核枚举 PCI 总线,找到具有 VirtIO 供应商 ID 和正确设备 ID 的设备,并将 `vtedu` 附加到它。 -### What the Backend Must Verify +### 后端必须验证的内容 -To make the backend correct, the author must verify: +要使后端正确,作者必须验证: -- The VirtIO device ID matches the driver's expectation (`VIRTIO_ID_EDU = 0xfff0`). -- The feature-negotiation response matches what the driver expects (advertise `VTEDU_F_UPPERCASE` and `VIRTIO_F_VERSION_1`). -- The virtqueue sizes are large enough for the driver's workload (256 is a reasonable default). -- The config-space size matches what the driver reads (zero for `vtedu`). +- VirtIO 设备 ID 与驱动程序的期望匹配(`VIRTIO_ID_EDU = 0xfff0`)。 +- 特性协商响应与驱动程序的期望匹配(播发 `VTEDU_F_UPPERCASE` 和 `VIRTIO_F_VERSION_1`)。 +- 虚拟队列的大小足够容纳驱动程序的工作负载(256 是合理的默认值)。 +- 配置空间大小与驱动程序的读取匹配(`vtedu` 为零)。 -### Testing the End-to-End Loop +### 测试 the End-to-End Loop -With both sides in place, the end-to-end test looks like this. +双方都就位后,端到端测试如下所示。 -On the host, after building the backend and installing the modified `bhyve(8)`: +在主机上,构建后端并安装修改后的 `bhyve(8)` 后: ```sh sudo bhyve ... -s 7,virtio-edu guest0 ``` -Inside the guest, after copying and building `vtedu.c`: +在客户机内部,复制并构建 `vtedu.c` 后: ```sh sudo kldload ./virtio_edu.ko @@ -3790,61 +3765,61 @@ echo "hello world" > /dev/vtedu0 cat /dev/vtedu0 ``` -The expected output of `cat` is `HELLO WORLD` (uppercased by the backend). +`cat` 的预期输出是 `HELLO WORLD`(由后端转换为大写)。 -If the output is `hello world` (not uppercased), the backend did not negotiate `VTEDU_F_UPPERCASE`. If the `echo` hangs, the virtqueue notification is not reaching the backend. If the `cat` hangs, the backend's interrupt injection is not reaching the guest. Each of these is a specific failure that the debugging techniques from the chapter can localise. +如果输出是 `hello world`(未大写),则后端未协商 `VTEDU_F_UPPERCASE`。如果 `echo` 挂起,则虚拟队列通知未到达后端。如果 `cat` 挂起,则后端的注入中断未到达客户机。这些每个都是本章调试技术可以定位的特定故障。 -### Why This Exercise Is Worth the Effort +### 为什么这个练习值得投入 -Writing a backend and a driver teaches both sides of the VirtIO story. The driver side is what most authors eventually write, but the backend side tells you *why* the VirtIO protocol is shaped the way it is. Feature bits make sense when you have to decide which to advertise. Virtqueue descriptors make sense when you have to unpack them. Interrupt delivery makes sense when you have to inject one. +编写后端和驱动程序教会了 VirtIO 故事的两个方面。驱动程序侧是大多数作者最终会编写的,但后端侧告诉您*为什么* VirtIO 协议被塑造成这样。当您必须决定播发哪些特性位时,特性位就变得有意义了。当您必须解包它们时,虚拟队列描述符就变得有意义了。当您必须注入一个中断时,中断投递就变得有意义了。 -Completing Challenge 5 promotes you from "VirtIO user" to "VirtIO author", which is a different level of understanding. If the challenge feels large, tackle it in stages: first get the device to appear in the guest (verify with `pciconf -lv`), then get feature negotiation to work, then handle a single virtqueue message, then polish the full pipeline. Each stage is a separate commit and a separate satisfying milestone. +完成挑战 5 将您从"VirtIO 用户"提升为"VirtIO 作者",这是不同层次的理解。如果挑战感觉很大,请分阶段处理:首先让设备出现在客户机中(使用 `pciconf -lv` 验证),然后使特性协商工作,然后处理单个虚拟队列消息,最后完善整个流水线。每个阶段都是一个独立的提交和一个独立的令人满意的里程碑。 -This is the end of the chapter's technical material. The remaining prose ties together what you have learned and points forward to Chapter 31. +这是本章技术内容的结束。剩下的文字将您所学的内容联系起来,并指向第 31 章。 -## Appendix: Running the Chapter's Techniques in CI +## 附录:在 CI 中运行本章的技术 -Continuous integration is now a standard part of most driver projects. This short appendix describes how the chapter's techniques fit into a CI pipeline. The goal is to show that virtualisation and containerisation are not just runtime concerns; they are also practical tools for keeping a driver honest across changes. +持续集成现在是大多数驱动程序项目的标准部分。这个简短的附录描述了本章的技术如何融入 CI 流水线。目标是展示虚拟化和容器化不仅仅是运行时关注点;它们也是确保驱动程序在变更中保持可靠性的实用工具。 -### Why CI Benefits from Virtualisation +### 为什么 CI 受益于虚拟化 -A CI system is, among other things, a place where you need reproducible test environments. Running tests on bare metal is possible but fragile: the test machine accumulates state, different machines have different hardware, and failures are hard to separate from hardware quirks. Running tests inside a VM removes most of these problems. The VM is a clean slate at the start of each run, its "hardware" is uniform across test runs, and its failures are the driver's failures, not the host's. +CI 系统是一个需要可重现测试环境的地方。在裸金属上运行测试是可能的但很脆弱:测试机器会累积状态,不同的机器有不同的硬件,故障很难与硬件问题分开。在 VM 内部运行测试消除了大多数这些问题。VM 在每次运行开始时是一个干净的状态,其"硬件"在测试运行间是一致的,其故障是驱动程序的故障,而不是主机的故障。 -For FreeBSD driver CI, the standard approach is to run a FreeBSD guest under `bhyve(8)` (if the CI host is FreeBSD) or under KVM/QEMU (if the CI host is Linux). The guest boots a FreeBSD image, loads the driver, runs the test harness, and exits. The whole cycle takes under a minute for a small driver, which means hundreds of tests per day against every commit. +对于 FreeBSD 驱动程序 CI,标准方法是在 `bhyve(8)`(如果 CI 主机是 FreeBSD)或 KVM/QEMU(如果 CI 主机是 Linux)下运行 FreeBSD 客户机。客户机启动 FreeBSD 镜像,加载驱动程序,运行测试框架,然后退出。对于小型驱动程序,整个周期需要不到一分钟,这意味着每天对每个提交进行数百次测试。 -### A Minimal CI Flow for a VirtIO Driver +### VirtIO 驱动程序的最小 CI 流程 -A reasonable flow for a VirtIO driver's CI is: +VirtIO 驱动程序的 CI 的合理流程是: -1. Check out the driver source. -2. Build the driver against the target FreeBSD kernel (often using a cross-compile on the CI host). -3. Start a FreeBSD VM with appropriate VirtIO devices. -4. Copy the built module into the VM. -5. SSH into the VM and load the module. -6. Run the test harness. -7. Capture the output. -8. Shut down the VM. -9. Report pass/fail. +1. 检出驱动程序源代码。 +2. 针对目标 FreeBSD 内核构建驱动程序(通常在 CI 主机上使用交叉编译)。 +3. 启动具有适当 VirtIO 设备的 FreeBSD VM。 +4. 将构建好的模块复制到 VM 中。 +5. 通过 SSH 进入 VM 并加载模块。 +6. 运行测试框架。 +7. 捕获输出。 +8. 关闭 VM。 +9. 报告通过/失败。 -Steps 1 and 2 are unchanged from a non-VM workflow. Steps 3 through 9 are what virtualisation adds. +步骤 1 和 2 与非 VM 工作流程相同。步骤 3 到 9 是虚拟化新增的内容。 -### Practical Tools +### 实用工具 -For step 3, `vm-bhyve` is convenient on FreeBSD hosts. For Linux CI hosts, `virt-install` from libvirt is a standard tool. Both produce a running VM in a few seconds with a pre-built image. +对于步骤 3,`vm-bhyve` 在 FreeBSD 主机上很方便。对于 Linux CI 主机,libvirt 的 `virt-install` 是标准工具。两者都使用预构建镜像在几秒内生成一个运行中的 VM。 -For step 4, a shared volume or a small SSH copy is usual. `virtfs` (9P) or `virtiofs` pass host directories into the guest; `scp` over a tap interface works as well. +对于步骤 4,通常使用共享卷或小型 SSH 复制。`virtfs`(9P)或 `virtiofs` 将主机目录传递给客户机;通过 tap 接口的 `scp` 也可以工作。 -For step 5, pre-installed SSH keys and a static IP address (or a DHCP reservation) make the connection painless. +对于步骤 5,预安装的 SSH 密钥和静态 IP 地址(或 DHCP 保留)使连接变得轻松。 -For steps 6 and 7, the test harness is whatever the driver author writes: a shell script, a C program, a Python harness. Whatever it is, it runs inside the VM. +对于步骤 6 和 7,测试框架是驱动程序作者编写的任何内容:shell 脚本、C 程序、Python 框架。无论是什么,它都在 VM 内部运行。 -For step 8, `vm stop guest0 --force` (or equivalent) shuts the VM down rapidly. The image is discarded; the next run starts fresh. +对于步骤 8,`vm stop guest0 --force`(或等效命令)快速关闭 VM。镜像被丢弃;下次运行从头开始。 -For step 9, the exit code of the test harness determines pass/fail. CI systems expect zero for success and nonzero for failure; be consistent. +对于步骤 9,测试框架的退出代码决定通过/失败。CI 系统期望零表示成功,非零表示失败;请保持一致。 -### A Minimal Test Harness +### 最小测试框架 -A simple pass/fail harness for a VirtIO driver might look like this. +一个 VirtIO 驱动程序的简单通过/失败测试框架可能如下所示。 ```sh #!/bin/sh @@ -3882,34 +3857,34 @@ echo "PASS" exit 0 ``` -Short, readable, and reports a clear result. CI scales with tests like this: add one per feature, run them all on every commit. +简短、可读性强,并报告清晰的结果。CI 通过这样的测试进行扩展:每个特性添加一个测试,每次提交运行所有测试。 -### Scaling to Multiple Configurations +### 扩展到多种配置 -A CI pipeline can run the same driver under multiple configurations by spinning up multiple VMs. Useful axes include: +CI 流水线可以通过启动多个 VM 在多种配置下运行相同的驱动程序。有用的维度包括: -- Kernel version (FreeBSD 14.3, 14.2, 13.5, -CURRENT). -- Architecture (amd64, arm64 with an arm64 guest). -- VirtIO feature set (force-disable certain features on the backend to exercise fallback paths). -- Hypervisor (bhyve, QEMU/KVM, VMware) where support varies. +- 内核版本(FreeBSD 14.3、14.2、13.5、-CURRENT)。 +- 架构(amd64、带 arm64 客户机的 arm64)。 +- VirtIO 特性集(在后端强制禁用某些特性以练习回退路径)。 +- 虚拟机监控程序(bhyve、QEMU/KVM、VMware),支持情况各不相同。 -Each configuration is an independent job that the CI system parallelises. The aggregate of "driver passes on every configuration" is a strong signal that the driver is robust. +每个配置都是一个独立的任务,由 CI 系统并行处理。"驱动程序在每个配置上都通过"的汇总结果是一个强有力的信号,表明驱动程序是稳健的。 -### A Note on Hardware-in-the-Loop CI +### 关于硬件在环 CI 的说明 -For drivers that talk to real hardware, CI needs a bare-metal or passthrough setup. This is more expensive and less common, but some projects maintain a small fleet of test machines for this purpose. The techniques from the chapter apply: a hardware test rig uses `ppt(4)` passthrough to give a guest access to a specific device, and the CI system drives the guest the same way it would drive a pure-VirtIO guest. +对于与真实硬件通信的驱动程序,CI 需要裸金属或直通设置。这更昂贵且不太常见,但一些项目为此目的维护了一小批测试机器。本章的技术适用:硬件测试平台使用 `ppt(4)` 直通让客户机访问特定设备,CI 系统以驱动纯 VirtIO 客户机的相同方式驱动客户机。 -Hardware CI is slower to set up and more expensive to run. For most projects, pure-VirtIO CI is enough for the bulk of tests, with a small suite of hardware tests run at a slower cadence. +硬件 CI 设置较慢且运行成本更高。对于大多数项目,纯 VirtIO CI 足以满足大部分测试,只有一小套硬件测试以较慢的频率运行。 -### The Payoff +### 回报 -CI that exercises a driver under realistic conditions catches regressions quickly, while the fix is still fresh in the author's mind. A regression caught at commit-time takes minutes to fix; a regression caught weeks later during a release candidate takes hours. Virtualisation makes the former affordable, and that is one of the strongest arguments for taking the techniques in this chapter seriously. +在现实条件下运行驱动程序的 CI 能快速捕获回归问题,此时修复方法在作者脑海中仍然新鲜。在提交时捕获的回归只需几分钟修复;在数周后的候选发布期间捕获的回归需要数小时。虚拟化使前者变得可行,这是认真对待本章技术的最有力论据之一。 -## Appendix: Commands Cheat Sheet +## 附录:命令速查表 -A compact list of the commands a driver author uses most often when working with virtualisation and containerisation on FreeBSD. Keep this page open while working through the labs. +驱动程序作者在 FreeBSD 上进行虚拟化和容器化工作时最常用命令的紧凑列表。在做实验时保持此页打开。 -### Host-Side Virtualisation +### 主机侧虚拟化 ```sh # Check hypervisor extensions @@ -3933,7 +3908,7 @@ bhyvectl --vm=guest0 --destroy bhyvectl --vm=guest0 --suspend=normal ``` -### Guest-Side Inspection +### 客户机侧检查 ```sh # Is this a guest? @@ -3950,7 +3925,7 @@ sysctl dev.virtio_pci sysctl dev.virtqueue ``` -### PCI Passthrough +### PCI 直通 ```sh # Mark a device as passthrough-capable (in /boot/loader.conf) @@ -3962,7 +3937,7 @@ dmesg | grep -i dmar # Intel dmesg | grep -i amdvi # AMD ``` -### Jails +### 监狱 ```sh # Create and manage jails @@ -3991,7 +3966,7 @@ jail -c name=vnet-test vnet vnet.interface=epair0b path=/jails/vnet-test persist ifconfig -j vnet-test epair0b ``` -### Resource Limits +### 资源限制 ```sh # rctl @@ -4001,7 +3976,7 @@ rctl -h jail:test rctl -l jail:test ``` -### Observability +### 可观测性 ```sh # Interrupt rate @@ -4018,7 +3993,7 @@ ktrace -i -p $(pgrep bhyve) kdump -p $(pgrep bhyve) ``` -### Module Lifecycle +### 模块生命周期 ```sh # Build, load, test, unload @@ -4029,6 +4004,6 @@ kldstat -v | grep mydriver sudo kldunload mydriver ``` -These are the day-to-day commands. A quick-reference card like this, pinned to a wall or kept in a terminal tab, saves hours over the course of a project. +这些是日常命令。像这样的快速参考卡,钉在墙上或保持在终端标签页中,可以在一个项目过程中节省数小时。 -With that, the chapter is complete. +至此,本章完成。 diff --git a/translations/zh_CN/chapters/part7/chapter-31.md b/translations/zh_CN/chapters/part7/chapter-31.md index e1210ec..49bd3ae 100644 --- a/translations/zh_CN/chapters/part7/chapter-31.md +++ b/translations/zh_CN/chapters/part7/chapter-31.md @@ -141,7 +141,7 @@ language: "zh-CN" 这种特权正是拥有内核的全部意义。没有它,内核将无法强制执行使多用户系统成为可能的边界。有了它,内核承担着没有任何用户空间程序承担的责任:每一行内核代码都以整个系统的权限运行,每一行内核代码中的漏洞,原则上都可以被提升为整个系统的权限。 -A driver is part of the kernel. Once loaded, a driver's code runs with the same privilege as the rest of the kernel. There is no finer-grained boundary inside the kernel that says "this code is only a driver, so it cannot touch the scheduler." A pointer dereference in your driver, if it lands on the wrong address, can corrupt any data structure the kernel uses. A buffer overflow in your driver, if it is large enough, can overwrite any function pointer the kernel uses. An uninitialised value in your driver, if it flows into the right place, can leak a neighbour's secrets. The kernel trusts the driver completely, because it has no mechanism to distrust it. +驱动程序是内核的一部分。一旦加载,驱动程序的代码以与内核其余部分相同的特权运行。内核内部没有更细粒度的边界会说"这段代码只是驱动程序,所以它不能触及调度器"。你的驱动程序中的指针解引用,如果落在错误的地址上,可能损坏内核使用的任何数据结构。你的驱动程序中的缓冲区溢出,如果足够大,可能覆盖内核使用的任何函数指针。你的驱动程序中未初始化的值,如果流入正确的位置,可能泄露邻居的秘密。内核完全信任驱动程序,因为它没有不信任它的机制。 这种不对称性是首先要内化的东西。用户空间程序在内核之下运行,内核可以对它们强制执行规则。驱动程序在内核内部运行,除了驱动程序作者自己之外,没有人对它们强制执行规则。 @@ -155,7 +155,7 @@ A driver is part of the kernel. Once loaded, a driver's code runs with the same 这不是假设性的扩展。这是内核漏洞被转化为利用的标准方式。内核的数据结构在内存中彼此相邻。能够在内核某处写入单个字节的攻击者通常可以——通过足够的巧妙手段——将该字节引导到重要的结构中。在正确的数据结构中几个字节错位就变成了一个可工作的利用。在正确的位置几个字节可以造成"我的编辑器崩溃了"和"攻击者现在拥有这台机器"之间的区别。 -This is why the mental framing of security must shift when you move from user-space to the kernel. You are not asking "what is the worst that can happen if this code goes wrong?" You are asking "what is the worst thing that someone could do to the system if they could steer this code to go wrong in exactly the way they wanted?" Those are different questions, and the second one is always the right one to ask inside the kernel. +这就是为什么从用户空间转向内核时,安全的心智框架必须改变。你不是在问"如果这段代码出了问题,最坏的情况是什么"。你是在问"如果有人能够引导这段代码精确地按照他们想要的方式出错,他们对系统能做的最坏的事情是什么"。这些是不同的问题,第二个问题在内核内部永远是正确的问题。 ### 风险清单 @@ -249,25 +249,25 @@ C 中的缓冲区是具有特定大小的内存区域。在驱动程序中,缓 所有缓冲区共有的一件事是大小。写入超过缓冲区末尾,或在其开头之前读取,或使用不适合的值进行索引,就是缓冲区溢出(或下溢)。溢出本身是机制;溢出写入的内容和写入的位置决定了严重程度。 -A stack overflow in a driver is the most dangerous kind, because the stack holds return addresses, saved registers, and local variables for the whole call chain. A write past the end of a stack buffer can reach into the caller's return address, and from there into arbitrary code execution. A heap overflow is less directly exploitable, but heap buffers are often adjacent to other kernel data structures, and a heap overflow that lands on the right structure is a clear path to compromise. A static-buffer overflow is the least common but can still lead to compromise if the static buffer is next to other writeable module data. +驱动程序中的栈溢出是最危险的类型,因为栈保存着整个调用链的返回地址、保存的寄存器和局部变量。写入超过栈缓冲区末尾可能触及调用者的返回地址,从那里可以实现任意代码执行。堆溢出的直接可利用性较低,但堆缓冲区通常与其他内核数据结构相邻,落在正确结构上的堆溢出是通向入侵的明确路径。静态缓冲区溢出最不常见,但如果静态缓冲区旁边是其他可写模块数据,仍然可能导致入侵。 -The vocabulary of "stack" and "heap" overflow should feel familiar from user-space work. The mechanism is the same. The consequences are worse, because the kernel's code and data share an address space with everything else it does. +"栈"和"堆"溢出的词汇应该让你感到熟悉,因为这在用户空间工作中也是如此。机制是相同的。后果更严重,因为内核的代码和数据与它所做的一切共享一个地址空间。 ### 内核代码中溢出是如何发生的 溢出不是因为作者写入了他们不打算写入的内存。它们发生是因为作者写入了他们确实打算写入的内存,但长度或偏移量是错误的。最常见的错误形式是: -**Trusting a length from user space.** The driver's `ioctl` argument contains a length field, and the driver uses that length to decide how much to `copyin` or how large a buffer to allocate. If the length is not bounded, the user can pick a length that makes the copy misbehave. +**信任来自用户空间的长度。** 驱动程序的 `ioctl` 参数包含一个长度字段,驱动程序使用该长度来决定 `copyin` 多少数据或分配多大的缓冲区。如果长度没有边界,用户可以选择一个使复制行为异常的长度。 -**Off-by-one in a loop.** A loop that iterates over an array uses `<=` where `<` was intended, or `<` where `<=` was intended. The extra iteration touches memory just past the end of the array. +**循环中的差一错误。** 遍历数组的循环在应该使用 `<` 的地方使用了 `<=`,或者在应该使用 `<=` 的地方使用了 `<`。额外的迭代触及了数组末尾之外的内存。 -**Incorrect buffer size in a call.** A call to `copyin`, `strlcpy`, `snprintf`, or similar takes a size argument. The author passes `sizeof(buf)` for a pointer-typed buf, which yields the pointer's size (four or eight bytes) rather than the buffer's size. The call writes far too many bytes. +**调用中缓冲区大小不正确。** 对 `copyin`、`strlcpy`、`snprintf` 或类似函数的调用接受一个大小参数。作者为指针类型的 buf 传递 `sizeof(buf)`,这产生的是指针的大小(四或八字节)而不是缓冲区的大小。该调用写入了过多的字节。 -**Arithmetic overflow in a length calculation.** The author multiplies or adds lengths to compute a buffer size, and the multiplication overflows a 32-bit integer. The resulting "size" is small, the allocation succeeds, and the subsequent copy writes far more than was allocated. +**长度计算中的算术溢出。** 作者将长度相乘或相加以计算缓冲区大小,而乘法溢出了 32 位整数。结果的"大小"很小,分配成功,随后的复制写入了远超已分配量的数据。 -**Truncating a string without terminating it.** The author uses `strncpy` or similar, but `strncpy` does not guarantee a null terminator; a later string operation reads past the end of the buffer. +**截断字符串但未终止。** 作者使用 `strncpy` 或类似函数,但 `strncpy` 不保证空终止符;后续的字符串操作会读取超过缓冲区末尾的内容。 -**Skipping a length check because the code "obviously" cannot reach a bad state.** The author convinces themselves that a given path cannot produce a length greater than some bound, so no check is needed. The path can produce such a length, because the author missed a case. +**因为代码"显然"不可能达到错误状态而跳过长度检查。** 作者说服自己给定路径不能产生超过某个界限的长度,因此不需要检查。该路径确实可以产生这样的长度,因为作者遗漏了一种情况。 每一种都是有对策的漏洞类别。本节的其余部分将逐步介绍这些对策。 @@ -275,7 +275,7 @@ The vocabulary of "stack" and "heap" overflow should feel familiar from user-spa 最简单和最有效的对策是限制每个长度。在使用来自不可信来源的长度之前,将其与已知最大值进行比较。在分配大小来自不可信来源的缓冲区之前,将大小与已知最大值进行比较。在复制到缓冲区之前,确认复制大小合适。 -Concretely, if your `ioctl` handler takes a structure with a `u_int32_t len` field, add a check like this at the very top of the handler: +具体来说,如果你的 `ioctl` 处理程序接受一个包含 `u_int32_t len` 字段的结构,在处理程序的最顶部添加一个这样的检查: ```c #define SECDEV_MAX_LEN 4096 @@ -306,15 +306,15 @@ secdev_ioctl_set_name(struct secdev_softc *sc, struct secdev_ioctl_args *args) 函数的第一行就是边界。无论调用者传递什么,`args->len` 现在最多是 `SECDEV_MAX_LEN`。分配是有界的,复制是有界的,空终止在缓冲区内。这种模式是安全驱动程序代码的主力。 -What should the bound be? It depends on the semantics of the argument. A name of a device might reasonably be bounded to a few hundred bytes. A configuration blob might be bounded to a few kilobytes. A firmware blob might be bounded to a few megabytes. Pick a number that is generous enough to accommodate legitimate use and small enough that its consequences, if reached, are bearable. If the bound is too small, users will complain about legitimate failures; if it is too large, an attacker can use the bound itself as an amplifier for denial of service. A generous bound is almost always the right choice. +边界应该是什么?这取决于参数的语义。设备名称可以合理地限制在几百字节。配置块可以限制在几千字节。固件块可以限制在几兆字节。选择一个足够宽松以容纳合法使用且足够小以至于达到该上限时后果可承受的数字。如果边界太小,用户会抱怨合法操作失败;如果太大,攻击者可以将边界本身用作拒绝服务的放大器。一个宽松的边界几乎总是正确的选择。 -Some drivers derive the bound from the structure of the hardware. A driver for a fixed-size register bank might bound reads and writes to the bank's size. A driver for a ring with 256 entries might bound the index to 255. Bounds derived from hardware structure are particularly robust, because they correspond to a physical constraint rather than an arbitrary choice. +有些驱动程序从硬件结构中推导边界。固定大小寄存器组的驱动程序可能将读写限制在寄存器组的大小。具有 256 个条目的环形缓冲区的驱动程序可能将索引限制为 255。从硬件结构推导出的边界特别稳健,因为它们对应于物理约束而非任意选择。 ### `sizeof(buf)` 陷阱 C 代码中最常见的缓冲区大小漏洞之一是 `sizeof(buf)` 和 `sizeof(*buf)` 之间的混淆,或者 `sizeof(buf)` 和 `buf` 指向的内存长度之间的混淆。当缓冲区传递给函数时,这个陷阱最常出现。 -Consider this unsafe function: +考虑这个不安全的函数: ```c static void @@ -324,9 +324,9 @@ bad_copy(char *dst, const char *src) } ``` -Here, `dst` is a `char *`, so `sizeof(dst)` is the size of a pointer: 4 on 32-bit systems, 8 on 64-bit systems. The call to `strlcpy` tells it that the destination is 8 bytes long, regardless of how big the real buffer is. On a 64-bit system, the function writes up to 8 bytes and terminates, and the caller's 4096-byte buffer now contains a short string, which is probably not what anyone wanted. On any system, if the caller's buffer was less than 8 bytes, the call overflows it. +这里,`dst` 是一个 `char *`,所以 `sizeof(dst)` 是指针的大小:在 32 位系统上是 4,在 64 位系统上是 8。对 `strlcpy` 的调用告诉它目标只有 8 字节长,无论实际缓冲区有多大。在 64 位系统上,该函数最多写入 8 字节然后终止,调用者的 4096 字节缓冲区现在包含一个短字符串,这可能不是任何人想要的。在任何系统上,如果调用者的缓冲区小于 8 字节,调用就会溢出它。 -The fix is to pass the buffer size explicitly: +修复方法是显式传递缓冲区大小: ```c static void @@ -336,7 +336,7 @@ good_copy(char *dst, size_t dstlen, const char *src) } ``` -The callers then use `sizeof(their_buf)` at the call site, where `their_buf` is known to be the array: +然后调用者在调用点使用 `sizeof(their_buf)`,其中 `their_buf` 已知是数组: ```c char name[64]; @@ -347,21 +347,21 @@ good_copy(name, sizeof(name), user_input); ### 有界字符串函数 -C's traditional string functions, `strcpy`, `strcat`, `sprintf`, were designed in an era when nobody took buffer overflows seriously. They do not take a size argument; they write until they see a null terminator. In kernel code, they are trouble, because the null terminator can be far away or absent entirely. +C 语言的传统字符串函数 `strcpy`、`strcat`、`sprintf` 设计于没有人认真对待缓冲区溢出的时代。它们不接受大小参数;它们写入直到看到空终止符。在内核代码中,它们是麻烦,因为空终止符可能很远或者完全不存在。 -FreeBSD provides bounded alternatives: +FreeBSD 提供了有界的替代方案: -- `strlcpy(dst, src, dstsize)`: copy at most `dstsize - 1` bytes plus a null terminator. Returns the length of the source string. Safe to use when you know `dstsize` correctly. -- `strlcat(dst, src, dstsize)`: append `src` to `dst`, ensuring the result is at most `dstsize - 1` bytes plus a null terminator. Like `strlcpy`, this is safe when `dstsize` is correct. -- `snprintf(dst, dstsize, fmt, ...)`: format into `dst`, writing at most `dstsize` bytes including the terminator. Returns the number of bytes that would have been written, which may be larger than `dstsize`. Check the return value if you need to know about truncation. +- `strlcpy(dst, src, dstsize)`:最多复制 `dstsize - 1` 字节加一个空终止符。返回源字符串的长度。当你正确知道 `dstsize` 时使用是安全的。 +- `strlcat(dst, src, dstsize)`:将 `src` 追加到 `dst`,确保结果最多是 `dstsize - 1` 字节加一个空终止符。与 `strlcpy` 一样,当 `dstsize` 正确时这是安全的。 +- `snprintf(dst, dstsize, fmt, ...)`:格式化到 `dst` 中,最多写入 `dstsize` 字节(包括终止符)。返回本应写入的字节数,可能大于 `dstsize`。如果你需要知道是否发生了截断,检查返回值。 -`strncpy` and `strncat` also exist, but they have surprising semantics. `strncpy` pads with nulls if the source is shorter than the destination size, and, more dangerously, it does not null-terminate if the source is longer. `strncat` is confusing in a different way. Prefer `strlcpy` and `strlcat` in new code. +`strncpy` 和 `strncat` 也存在,但它们有令人惊讶的语义。`strncpy` 在源字符串短于目标大小时用空字节填充,更危险的是,当源字符串更长时不添加空终止符。`strncat` 以另一种方式令人困惑。在新代码中优先使用 `strlcpy` 和 `strlcat`。 -For longer formatted output, the `sbuf(9)` API is safer still. It manages an auto-growing buffer with a clean interface for appending strings, printing formatted output, and bounding the final size. It is overkill for small fixed-size copies but excellent for anything that builds up a longer message. Section 8 returns to `sbuf` in the context of logging. +对于更长的格式化输出,`sbuf(9)` API 更安全。它管理一个自动增长的缓冲区,具有用于追加字符串、打印格式化输出和限制最终大小的简洁接口。对于小的固定大小复制来说是大材小用,但对于构建较长消息的任何内容来说非常出色。第8节在日志记录的上下文中将再次讨论 `sbuf`。 ### 算术与溢出 -A subtler class of buffer bug comes from arithmetic on sizes. The classic example is: +一类更微妙的缓冲区错误来自大小算术。经典的例子是: ```c uint32_t total = count * elem_size; /* may overflow */ @@ -369,9 +369,9 @@ buf = malloc(total, M_SECDEV, M_WAITOK); copyin(user_buf, buf, total); ``` -If `count * elem_size` overflows a 32-bit `uint32_t`, `total` wraps around to a small number. The `malloc` succeeds with that small number. The `copyin` is asked for the same small number of bytes, which makes the allocation-and-copy pair itself safe. But a later piece of the driver may treat `count * elem_size` as if it produced the full amount, and write past the end of the buffer. +如果 `count * elem_size` 溢出 32 位的 `uint32_t`,`total` 回绕到一个小的数字。`malloc` 以该小数字成功。`copyin` 被要求复制同样小数量的字节,这使得分配加复制对本身是安全的。但驱动程序后面的部分可能将 `count * elem_size` 视为产生了完整数量,从而写入超过缓冲区末尾。 -The fix is to check for overflow explicitly: +修复方法是显式检查溢出: ```c #include @@ -383,21 +383,21 @@ if (count > SIZE_MAX / elem_size) size_t total = count * elem_size; ``` -The division is exact (no rounding) for integer types, and the test `count > SIZE_MAX / elem_size` is equivalent to "would the multiplication overflow `size_t`?" This pattern is well worth memorising. It is one of those idioms that appears unnecessary in the common case and essential in the exceptional case. +对于整数类型,除法是精确的(没有舍入),测试 `count > SIZE_MAX / elem_size` 等价于"乘法会溢出 `size_t` 吗?"。这个模式非常值得记住。它是那种在常见情况下看似不必要但在异常情况下至关重要的惯用法之一。 -On modern compilers, FreeBSD also has `__builtin_mul_overflow` and its siblings, which perform the arithmetic and report overflow in a single operation. They are a little more convenient when you have them, but the explicit division check works everywhere. +在现代编译器上,FreeBSD 还有 `__builtin_mul_overflow` 及其兄弟函数,它们在单个操作中执行算术并报告溢出。当你有这些函数时它们更方便一些,但显式的除法检查在任何地方都有效。 ### 整数类型很重要 -Closely related is the choice of integer types for lengths and offsets. If a length is stored as `int`, it can be negative, and a negative value sneaking into a call that expects an unsigned length can cause spectacular misbehaviour. If a length is stored as `short`, it can only represent values up to 32767, and a caller passing a value near that limit can cause truncation. +与此密切相关的是长度和偏移量的整数类型选择。如果长度存储为 `int`,它可以是负数,而一个潜入期望无符号长度的调用的负值可能导致灾难性的异常行为。如果长度存储为 `short`,它只能表示到 32767 的值,接近该限制的调用者可能导致截断。 -The safe types for lengths in FreeBSD are `size_t` (unsigned, at least 32 bits, often 64 on 64-bit platforms) and `ssize_t` (signed `size_t`, usually for return values that may be negative to indicate error). Use them consistently. When you take a length as input, convert it to `size_t` at the earliest opportunity. When you store a length, store it as `size_t`. When you pass a length to a FreeBSD primitive, pass a `size_t`. +FreeBSD 中安全的长度类型是 `size_t`(无符号,至少 32 位,在 64 位平台上通常是 64 位)和 `ssize_t`(有符号的 `size_t`,通常用于可能为负以指示错误的返回值)。一致地使用它们。当你接受长度作为输入时,尽早将其转换为 `size_t`。当你存储长度时,存储为 `size_t`。当你向 FreeBSD 原语传递长度时,传递 `size_t`。 -If the length comes from user space and the user-facing structure uses a `uint32_t`, the conversion on a 64-bit kernel is safe (no truncation), and you should still validate the value before using it. If the user-facing structure uses `int64_t` and the kernel needs a `size_t`, check for negatives and for overflow before the conversion. +如果长度来自用户空间且面向用户的结构使用 `uint32_t`,在 64 位内核上的转换是安全的(没有截断),但你仍然应该在使用前验证该值。如果面向用户的结构使用 `int64_t` 而内核需要 `size_t`,在转换前检查负数和溢出。 ### 栈缓冲区廉价但有限 -A stack buffer is a local array: +栈缓冲区是局部数组: ```c static int @@ -415,15 +415,15 @@ secdev_read_name(struct secdev_softc *sc, struct uio *uio) } ``` -Stack buffers are allocated automatically, freed automatically when the function returns, and are essentially free to use. They are ideal for small, short-lived data that does not need to outlive the function call. +栈缓冲区自动分配,在函数返回时自动释放,使用基本上是免费的。它们非常适合不需要超出函数调用生命周期的短生命周期小数据。 -The limit on stack buffers is the size of the kernel stack itself. FreeBSD's kernel stack is small, typically 16 KiB or 32 KiB depending on the architecture, and that stack must accommodate the whole call chain, including nested calls into the VFS, the scheduler, interrupt handlers, and so on. A driver function that declares a 4 KiB local buffer is already using a quarter of the stack. A driver function that declares a 32 KiB local buffer has almost certainly blown the stack, and the kernel will panic or corrupt memory when it happens. +栈缓冲区的限制是内核栈本身的大小。FreeBSD 的内核栈很小,通常为 16 KiB 或 32 KiB,具体取决于架构,而且该栈必须容纳整个调用链,包括对 VFS、调度器、中断处理程序等的嵌套调用。声明 4 KiB 局部缓冲区的驱动程序函数已经使用了栈的四分之一。声明 32 KiB 局部缓冲区的驱动程序函数几乎肯定会炸毁栈,内核会在那时崩溃或损坏内存。 -A safe rule of thumb: keep local buffers under 512 bytes, and preferably under 256 bytes. For anything larger, allocate on the heap. The compiler will not warn you when you declare a stack buffer that is too large; it is the author's responsibility to keep stack usage bounded. +一个安全的经验法则:保持局部缓冲区在 512 字节以下,最好在 256 字节以下。对于更大的需求,在堆上分配。编译器在你声明过大的栈缓冲区时不会警告你;保持栈使用有界是作者的责任。 ### 堆缓冲区及其生命周期 -A heap buffer is allocated dynamically: +堆缓冲区是动态分配的: ```c char *buf; @@ -433,20 +433,20 @@ buf = malloc(size, M_SECDEV, M_WAITOK | M_ZERO); free(buf, M_SECDEV); ``` -Heap buffers can be arbitrarily large (up to the available memory), can outlive the function that allocates them, and give the author explicit control over when they are freed. They come at the cost of requiring deliberate attention: every allocation must be paired with a free, every free must happen after the last use, and every free must happen only once. +堆缓冲区可以任意大(最大到可用内存),可以比分配它们的函数活得更久,并给作者对何时释放它们的显式控制。它们的代价是需要刻意的关注:每次分配必须与一次释放配对,每次释放必须在最后一次使用之后,每次释放只能发生一次。 -The rules for heap buffers are: +堆缓冲区的规则是: -1. Always check the allocation if you used `M_NOWAIT`. With `M_WAITOK`, the allocation cannot fail; with `M_NOWAIT`, it can return `NULL` and your code must handle that. -2. Pair every `malloc` with exactly one `free`. Not zero, not two. -3. After calling `free`, do not access the buffer. If the pointer may be reused, set it to `NULL` immediately after the free, so that accidental use triggers a null-pointer panic rather than a subtle corruption. -4. If the buffer held sensitive data, zero it with `explicit_bzero` or use `zfree` before freeing. +1. 如果你使用了 `M_NOWAIT`,始终检查分配结果。使用 `M_WAITOK` 时,分配不会失败;使用 `M_NOWAIT` 时,它可能返回 `NULL`,你的代码必须处理这种情况。 +2. 将每次 `malloc` 与恰好一次 `free` 配对。不是零次,也不是两次。 +3. 调用 `free` 之后,不要访问缓冲区。如果指针可能被重用,在释放后立即将其设置为 `NULL`,这样意外使用会触发空指针崩溃而不是微妙的损坏。 +4. 如果缓冲区保存了敏感数据,在释放前用 `explicit_bzero` 清零或使用 `zfree`。 -Section 4 covers these rules in more depth, including the FreeBSD-specific flags on `malloc(9)`. +第4节更深入地涵盖这些规则,包括 `malloc(9)` 上 FreeBSD 特定的标志。 ### 完整示例:安全和不安全的复制例程 -To make the patterns concrete, here is an unsafe copy routine that you might find in a first-draft driver, followed by a safe rewrite. Read the unsafe version carefully and see if you can spot all the bugs before looking at the commentary. +为了使模式具体化,这里有一个你可能在一个初稿驱动程序中发现的不安全复制例程,后面跟着一个安全的重写。仔细阅读不安全版本,在查看注释之前看看你是否能发现所有错误。 ```c /* UNSAFE: do not use */ @@ -462,17 +462,17 @@ secdev_bad_copy(struct secdev_softc *sc, struct secdev_ioctl_args *args) } ``` -There are at least four bugs in those four lines. +这四行代码中至少有四个错误。 -First, `copyin`'s return value is ignored. If the user supplied a bad pointer, `copyin` returns `EFAULT`, but the function continues as if the copy succeeded. The subsequent operations on `buf` operate on whatever garbage the stack happened to hold. +第一,`copyin` 的返回值被忽略了。如果用户提供了一个错误的指针,`copyin` 返回 `EFAULT`,但函数继续执行,好像复制成功了一样。对 `buf` 的后续操作操作的是栈上碰巧保存的任何垃圾数据。 -Second, `args->len` is not bounded. If the user supplies a `len` of 1000, `copyin` writes 1000 bytes into a 256-byte stack buffer. The stack is corrupted. The driver has just become a vehicle for privilege escalation. +第二,`args->len` 没有边界。如果用户提供 `len` 为 1000,`copyin` 向 256 字节的栈缓冲区写入 1000 字节。栈被损坏。驱动程序刚刚成为权限提升的载体。 -Third, `buf[args->len] = '\0'` writes past the end of the buffer even in the non-malicious case. If `args->len == sizeof(buf)`, the assignment is to `buf[256]`, which is one past the end of the 256-byte array. +第三,即使在非恶意情况下,`buf[args->len] = '\0'` 也会写入超过缓冲区末尾。如果 `args->len == sizeof(buf)`,赋值目标是 `buf[256]`,这是超出 256 字节数组末尾一个位置的地方。 -Fourth, the function returns 0 regardless of whether anything went wrong. A caller receives a success code and has no way to know that the driver silently dropped their input. +第四,无论是否出了问题,函数都返回 0。调用者收到一个成功代码,没有办法知道驱动程序默默丢弃了他们的输入。 -Here is a safe rewrite: +这里是一个安全的重写: ```c /* SAFE */ @@ -499,13 +499,13 @@ secdev_copy_name(struct secdev_softc *sc, struct secdev_ioctl_args *args) } ``` -The bound is now `args->len >= sizeof(buf)`, which ensures that the terminator at `buf[args->len]` fits. The `copyin` return value is checked and propagated. The write to `sc->sc_name` happens under the mutex that protects it, ensuring that another thread reading the field at the same time sees a consistent value. The function returns the error code the caller needs to understand what happened. +现在的边界是 `args->len >= sizeof(buf)`,这确保了 `buf[args->len]` 处的终止符能够放下。检查了 `copyin` 的返回值并向上传播。对 `sc->sc_name` 的写入在保护它的互斥锁下进行,确保同时读取该字段的其他线程看到一致的值。函数返回调用者需要的错误代码以理解发生了什么。 -The unsafe version is eight lines; the safe version is thirteen. The five extra lines are the difference between a working driver and a security incident. +不安全版本是八行;安全版本是十三行。多出的五行就是一个能工作的驱动程序和一个安全事故之间的区别。 ### 第二个完整示例:描述符长度 -Here is a different class of bug that shows up in drivers for devices that present descriptor-like data (USB, virtio, PCIe configuration): +这里有一个不同类型的错误,出现在处理描述符类数据的设备驱动程序中(USB、virtio、PCIe 配置): ```c /* UNSAFE */ @@ -520,9 +520,9 @@ parse_descriptor(struct secdev_softc *sc, const uint8_t *buf, size_t buflen) } ``` -The length is taken from the first byte of the buffer, which is a value the device (or an attacker impersonating it) can set arbitrarily. If `buf[0]` is 200, the `memcpy` copies 200 bytes, regardless of whether `buf` actually contains 200 bytes of valid data or whether `sc->sc_descriptor` is that large. If `buflen` is less than `buf[0] + 1`, the `memcpy` reads past the end of the caller's buffer. If `sizeof(sc->sc_descriptor)` is less than `buf[0]`, the `memcpy` writes past the end of the destination. +长度取自缓冲区的第一个字节,这是设备(或冒充它的攻击者)可以任意设置的值。如果 `buf[0]` 是 200,`memcpy` 复制 200 字节,无论 `buf` 是否实际包含 200 字节的有效数据,或 `sc->sc_descriptor` 是否有那么大。如果 `buflen` 小于 `buf[0] + 1`,`memcpy` 会读取超过调用者缓冲区末尾的内容。如果 `sizeof(sc->sc_descriptor)` 小于 `buf[0]`,`memcpy` 会写入超过目标末尾的内容。 -The safe version validates both sides of the copy: +安全版本验证复制的两端: ```c /* SAFE */ @@ -544,51 +544,51 @@ parse_descriptor(struct secdev_softc *sc, const uint8_t *buf, size_t buflen) } ``` -Three checks, each guarding a different invariant: the buffer has at least one byte, the stated length fits in the buffer, and the stated length fits in the destination. Each check protects against a different adversarial or accidental input. +三个检查,每个守护一个不同的不变量:缓冲区至少有一个字节,声明的长度适合缓冲区,声明的长度适合目标。每个检查保护免受不同的对抗性或意外输入。 -A careful reader may notice that `len + 1 > buflen` can itself overflow if `len` is `SIZE_MAX`. For a `size_t` taken from a byte, `len` is at most 255, so the overflow cannot happen here; but if you write the same code for a 32-bit length field, the check should be rearranged to `len > buflen - 1` with an explicit `buflen >= 1` check. The habit of watching for arithmetic overflow is the same habit, applied at different scales. +细心的读者可能会注意到,如果 `len` 是 `SIZE_MAX`,`len + 1 > buflen` 本身可能溢出。对于从字节获取的 `size_t`,`len` 最多是 255,所以溢出不可能在这里发生;但如果你为 32 位长度字段编写相同的代码,应该将检查重新排列为 `len > buflen - 1` 并加上显式的 `buflen >= 1` 检查。关注算术溢出的习惯是相同的习惯,只是应用于不同的规模。 ### 缓冲区溢出作为一类漏洞 -Stepping back from the specific examples: buffer overflows are not a single bug. They are a family of bugs whose members share a structure: the code writes to or reads from a buffer with an incorrect size or offset. The concrete examples above show several members of the family, but the underlying pattern is the same: a length came from somewhere less trustworthy than the code believed it was, and the code was not prepared. +从具体例子退后一步:缓冲区溢出不是一个单一的漏洞。它们是一个共享结构的漏洞家族,其成员共享一个结构:代码以错误的大小或偏移量写入或读取缓冲区。上面的具体例子展示了家族中的几个成员,但底层模式是相同的:长度来自一个比代码认为的更不可信的地方,而代码没有做好准备。 -The countermeasures also share a structure. They all amount to: do not trust the length; check it against a known bound before you use it; keep the bound tight; propagate errors when the check fails; use bounded primitives (`strlcpy`, `snprintf`, `sbuf(9)`) when you have a choice; watch for arithmetic overflow in length calculations; and keep stack buffers small. That short list, consistently applied, eliminates most buffer overflow bugs before they are written. +对策也共享一个结构。它们都归结为:不要信任长度;在使用前将其与已知边界进行比较;保持边界紧凑;当检查失败时传播错误;当有选择时使用有界原语(`strlcpy`、`snprintf`、`sbuf(9)`);注意长度计算中的算术溢出;保持栈缓冲区小。这个简短的列表,如果一致应用,可以在大多数缓冲区溢出漏洞被写入之前消除它们。 ### 溢出之外的内存损坏 -Not every memory-corruption bug is a buffer overflow. Drivers can corrupt memory in several other ways, and a complete treatment of safety must mention them. +并非每个内存损坏漏洞都是缓冲区溢出。驱动程序可以以其他几种方式损坏内存,对安全性的完整讨论必须提及它们。 -**Use-after-free** is writing to, or reading from, a buffer after it has been freed. The allocator has almost certainly handed that memory to some other part of the kernel by now, so the write corrupts whatever that part of the kernel is doing. Section 4 covers use-after-free in depth. +**释放后使用** 是在缓冲区被释放后写入或读取它。分配器几乎肯定已经将该内存交给了内核的其他部分,因此写入会损坏该内核部分正在做的任何事情。第4节深入讨论释放后使用。 -**Double-free** is calling `free` twice on the same pointer. Depending on the allocator, this can corrupt the allocator's own data structures, leading to hard-to-diagnose panics minutes or hours later. Section 4 covers prevention. +**双重释放** 是对同一个指针调用两次 `free`。根据分配器的不同,这可能损坏分配器自身的数据结构,导致几分钟或几小时后难以诊断的崩溃。第4节讨论预防措施。 -**Out-of-bounds read** is the read-only cousin of buffer overflow. It does not corrupt memory directly, but it can leak information (see Section 7) and can cause the kernel to read from an unmapped page, which is a panic. It deserves the same countermeasures as overflow. +**越界读取** 是缓冲区溢出的只读表亲。它不直接损坏内存,但可能泄露信息(见第7节),并可能导致内核从未映射的页读取,这就是崩溃。它值得与溢出相同的对策。 -**Type confusion** is treating a block of memory as if it had a different type from what it actually has. For example, casting a pointer to the wrong structure type and accessing fields. In kernel C, type confusion is usually caught by the compiler, but it can still happen when a driver deals with void pointers or with structures shared across versions. +**类型混淆** 是将一块内存视为与其真实类型不同的类型。例如,将指针转换为错误的结构类型并访问字段。在内核 C 中,类型混淆通常被编译器捕获,但当驱动程序处理 void 指针或跨版本共享的结构时仍然可能发生。 -**Uninitialised memory use** is reading from a variable before assigning it a value. The value read is whatever happened to be in memory at that location, which may be previous callers' data. Section 7 covers this from the information-leak perspective. +**未初始化内存使用** 是在赋值之前从变量读取。读取的值是该位置内存中碰巧存在的任何内容,可能是前一个调用者的数据。第7节从信息泄露的角度讨论这一点。 -Each of these has its own countermeasures, but the single most effective tool across all of them is the set of kernel sanitizers FreeBSD provides: `INVARIANTS`, `WITNESS`, `KASAN`, `KMSAN`, and `KCOV`. Section 10 covers these tools in depth. The short version: build your driver against a kernel with `INVARIANTS` and `WITNESS` always. Build it against a `KASAN`-enabled kernel during development. Run your tests under the sanitized kernel. The sanitizers will find bugs you would otherwise not find until a customer did. +这些中的每一个都有自己的对策,但在所有这些中最有效的单一工具是 FreeBSD 提供的内核净化器集:`INVARIANTS`、`WITNESS`、`KASAN`、`KMSAN` 和 `KCOV`。第10节深入讨论这些工具。简要版本:始终在使用 `INVARIANTS` 和 `WITNESS` 的内核上构建你的驱动程序。在开发期间在启用 `KASAN` 的内核上构建它。在净化后的内核下运行你的测试。净化器会找到你否则只有在客户报告时才能找到的漏洞。 ### 编译器保护如何提供帮助,以及在哪里停止 -FreeBSD kernels are usually compiled with several exploit-mitigation features enabled in the compiler. Understanding what they do is part of understanding why certain defensive habits matter more than others. +FreeBSD 内核通常在编译时启用了几种利用缓解功能。理解它们的作用是理解为什么某些防御习惯比其他习惯更重要的一部分。 -**Stack-smashing protection (SSP)** inserts a canary value on the stack between local variables and the saved return address. When the function returns, the canary is checked against a reference value; if it has been modified (because a stack-buffer overflow clobbered it), the kernel panics. SSP does not prevent the overflow from happening, but it prevents many overflows from gaining control of execution. Without SSP, overwriting the return address would redirect execution to attacker-controlled code on return. With SSP, the overwrite is detected and the kernel stops. +**栈粉碎保护 (SSP)** 在栈上局部变量和保存的返回地址之间插入一个金丝雀值。当函数返回时,金丝雀与参考值进行检查;如果它被修改了(因为栈缓冲区溢出覆盖了它),内核崩溃。SSP 不阻止溢出的发生,但它阻止许多溢出获得执行控制权。没有 SSP,覆盖返回地址会在返回时将执行重定向到攻击者控制的代码。有了 SSP,覆盖被检测到,内核停止。 -SSP is heuristic. Not every function gets a canary: functions without stack-allocated buffers, for example, do not need protection. The compiler applies SSP to functions that look risky. A driver author should not assume SSP will catch any particular bug; SSP catches some stack overflows, not all, and catches them only at function return, not at the moment of the overflow. +SSP 是启发式的。并非每个函数都有金丝雀:例如,没有栈分配缓冲区的函数不需要保护。编译器基于看起来有风险的函数应用 SSP。驱动程序作者不应假设 SSP 会捕获任何特定的漏洞;SSP 捕获一些栈溢出,不是全部,而且只在函数返回时捕获它们,而不是在溢出发生的时刻。 -**kASLR** is orthogonal to SSP. It randomizes the base address of the kernel, loadable modules, and the stack. An attacker who wants to jump to a specific kernel function (say, to bypass a check) must first learn where that function is. kASLR makes this difficult. An information leak that exposes any kernel pointer can undo kASLR for the whole kernel: once you know one function's address, you know the offsets to all the others, and you can compute every other address. +**kASLR** 与 SSP 是正交的。它随机化内核的基地址、可加载模块和栈。想要跳转到特定内核函数的攻击者(例如,绕过检查)必须首先了解该函数在哪里。kASLR 使这变得困难。泄露任何内核指针的信息泄露可以撤销整个内核的 kASLR:一旦你知道一个函数的地址,你就知道所有其他函数的偏移量,你可以计算每个其他地址。 -**W^X enforcement** ensures that memory is either writable or executable, never both at once. Historically, attackers would overflow a buffer, write shellcode into the overflowed region, and jump to it. W^X breaks this by refusing to execute from writable memory. Modern attacks therefore use return-oriented programming (ROP), which chains together small snippets of existing code rather than introducing new code. ROP is still possible under W^X, but it is harder, and it is defeated by kASLR (ROP needs to know where the snippets are). +**W^X 强制执行** 确保内存要么可写要么可执行,不能同时兼具。历史上,攻击者会溢出缓冲区,将 shellcode 写入溢出区域,然后跳转到它。W^X 通过拒绝从可写内存执行来打破这一点。现代攻击因此使用面向返回的编程 (ROP),它将现有代码的小片段链接在一起而不是引入新代码。ROP 在 W^X 下仍然可能,但更难,而且它被 kASLR 击败(ROP 需要知道片段在哪里)。 -**Guard pages** surround kernel stacks with unmapped pages. A write past the end of the stack hits an unmapped page, causing a page fault that the kernel catches and turns into a panic. This prevents certain stack-smashing attacks from silently corrupting memory adjacent to the stack. The cost is one unusable page per kernel stack, which is cheap. +**保护页** 在内核栈周围包围未映射的页面。写入超过栈末尾会触及未映射的页面,导致内核捕获并转变为崩溃的页面错误。这防止某些栈粉碎攻击默默地损坏栈相邻的内存。代价是每个内核栈一个不可用的页面,这很便宜。 -**Shadow stacks and CFI (control-flow integrity)** are under discussion and partial deployment in modern kernels. They aim to prevent attackers from redirecting execution by verifying that every indirect jump lands at a legitimate target. They are not yet standard in FreeBSD, but the direction of the industry is clear: more compiler-enforced restrictions on what exploit writers can do. +**影子栈和 CFI(控制流完整性)** 在现代内核中正在讨论和部分部署中。它们旨在通过验证每个间接跳转落在合法目标处来防止攻击者重定向执行。它们尚未成为 FreeBSD 的标准,但行业的方向是明确的:对利用编写者能做的事情施加更多编译器强制执行的限制。 -The lesson for driver authors: these protections are real, and they raise the cost of exploitation. But they do not prevent bugs. A buffer overflow is still a bug, even if SSP catches it. An information leak is still a bug, even if kASLR makes it less useful. The compiler protections are a last line of defense; the first line is still your careful code. +对驱动程序作者的教训:这些保护是真实的,它们提高了利用的成本。但它们不阻止漏洞。缓冲区溢出仍然是漏洞,即使 SSP 捕获了它。信息泄露仍然是漏洞,即使 kASLR 使它不那么有用。编译器保护是最后一道防线;第一道防线仍然是你仔细的代码。 -When the first line fails, the protections buy time: time for the bug to be found and fixed before an attacker chains it into a complete exploit. An information leak that, combined with a buffer overflow, would have been trivially exploitable in 1995 now requires both bugs to exist in the same driver and several more mitigations to fall. The effect is that bug reports that once meant "this is a root exploit" now often mean "this is a pre-condition for a root exploit". That is progress. But it is progress bought by the compiler, not by the code. +当第一道防线失败时,保护争取了时间:在攻击者将漏洞链成完整利用之前找到并修复漏洞的时间。一个信息泄露,加上缓冲区溢出,在 1995 年会轻易可利用的漏洞现在需要两个漏洞存在于同一个驱动程序中,并且还需要更多缓解措施失败。效果是,曾经意味着"这是一个 root 利用"的错误报告现在通常意味着"这是 root 利用的前提条件"。这是进步。但这是编译器带来的进步,不是代码带来的。 ### 第2节总结 @@ -627,7 +627,7 @@ int copyout(const void *kaddr, void *udaddr, size_t len); 签名在 `/usr/src/sys/sys/systm.h` 中声明。像大多数内核原语一样,它们名称简短,只做一件事。然而,它们做的那一件事是必不可少的。如果驱动程序通过任何其他方式读取或写入用户内存,驱动程序几乎肯定是错误的。 -**Always check the return value.** This is the single most common source of copyin/copyout bugs: a driver calls `copyin` and proceeds as if it succeeded, when in fact it might have returned `EFAULT`. If the copy failed, the destination buffer contains whatever was there before (possibly uninitialised), and operating on it is a recipe for either a crash or an information disclosure. Every call to `copyin` or `copyout` must check the return value and either proceed with success or propagate the error: +**始终检查返回值。** 这是 `copyin/copyout` 漏洞最常见的来源:驱动程序调用 `copyin` 并假设它成功继续执行,而实际上它可能已经返回了 `EFAULT`。如果复制失败,目标缓冲区包含之前的任何内容(可能未初始化),对其操作会导致崩溃或信息泄露。每次调用 `copyin` 或 `copyout` 都必须检查返回值,要么在成功时继续,要么传播错误: ```c error = copyin(args->data, kbuf, args->len); @@ -639,11 +639,11 @@ if (error != 0) { 这种模式在 FreeBSD 内核中出现了数百次。学习它并在每个调用点使用它。 -**Never reuse a pointer after a failed copy.** If `copyin` returned `EFAULT`, the buffer may have been partially written. Do not try to "rescue" a partial result; do not assume that the first few bytes are valid. Discard the buffer, zero it if the remains may be sensitive, and return the error. +**复制失败后绝不重用指针。** 如果 `copyin` 返回了 `EFAULT`,缓冲区可能已被部分写入。不要试图"挽救"部分结果;不要假设前几个字节是有效的。丢弃缓冲区,如果残留可能敏感则清零,并返回错误。 -**Always validate lengths before calling.** We have seen this in Section 2, but it bears repeating here. The `len` you pass to `copyin` comes from somewhere; if it comes from the caller's structure, it must be bounded before the call. An unbounded `len` in a `copyin` is one of the most dangerous patterns in a driver. +**调用前始终验证长度。** 我们在第2节已经看到了这一点,但值得在这里重申。你传递给 `copyin` 的 `len` 来自某处;如果它来自调用者的结构,它必须在调用前被限制。`copyin` 中未限制的 `len` 是驱动程序中最危险的模式之一。 -**`copyin` and `copyout` can sleep.** These primitives may cause the calling thread to sleep while waiting for a user page to be resident. This means they cannot be called from contexts where sleeping is forbidden: interrupt handlers, spin-mutex critical sections, and the like. If you need to transfer data to or from user space from such a context, defer the work to a different context (typically a taskqueue or a regular process context) and have that context do the copy. +**`copyin` 和 `copyout` 可能睡眠。** 这些原语可能导致调用线程在等待用户页驻留时睡眠。这意味着它们不能从禁止睡眠的上下文调用:中断处理程序、自旋互斥锁临界区等。如果你需要从这样的上下文向用户空间传输数据或从用户空间获取数据,将工作推迟到不同的上下文(通常是 taskqueue 或常规进程上下文),让该上下文执行复制。 ### 用于字符串的 `copyinstr(9)` @@ -657,13 +657,13 @@ int copyinstr(const void *udaddr, void *kaddr, size_t len, size_t *lencopied); `copyinstr` 从 `udaddr` 复制字节到 `kaddr`,直到遇到空字节或复制了 `len` 字节,以先到者为准。如果 `lencopied` 不为 NULL,`*lencopied` 设置为复制的字节数(包括终止符,如果找到的话)。返回值成功时为0,出错时为 `EFAULT`,如果在 `len` 字节内未找到终止符则为 `ENAMETOOLONG`。 -The key safety rule is: **always pass a bounded `len`**. `copyinstr` without a bound (or with a huge bound) can cause large amounts of kernel memory to be written, and in older kernels could cause the kernel to scan huge amounts of user memory before giving up. In modern FreeBSD the scan itself is bounded by `len`, but you should still pass a tight bound appropriate to the string's expected size. A path name might reasonably be bounded to `MAXPATHLEN` (which is `PATH_MAX`, currently 1024 on FreeBSD). A device name might be bounded to 64. A command name might be bounded to 32. Pick a bound that fits the use and pass it. +关键的安全规则是:**始终传递有界的 `len`**。没有边界的 `copyinstr`(或使用巨大的边界)可能导致大量内核内存被写入,在较旧的内核中还可能导致内核在放弃前扫描大量用户内存。在现代 FreeBSD 中,扫描本身受 `len` 限制,但你仍应传递适合字符串预期大小的紧凑边界。路径名称可以合理地限制为 `MAXPATHLEN`(即 `PATH_MAX`,在 FreeBSD 上当前为 1024)。设备名称可以限制为 64。命令名称可以限制为 32。选择适合用途的边界并传递它。 -A second safety rule is: **always check the return value**, and treat `ENAMETOOLONG` as a distinct condition from `EFAULT`. The former means the user tried to pass a longer string than you were willing to accept, which is plausibly a legitimate mistake. The latter means the user's pointer was invalid, which may or may not be a legitimate mistake. Your driver may want to return a different error to user space depending on which condition occurred. +第二条安全规则是:**始终检查返回值**,并将 `ENAMETOOLONG` 视为与 `EFAULT` 不同的条件。前者意味着用户试图传递比你愿意接受的更长的字符串,这可能是合法的错误。后者意味着用户的指针无效,这可能是也可能不是合法的错误。你的驱动程序可能希望根据发生的是哪种条件向用户空间返回不同的错误。 -A third safety rule is: **check the copied length if you care**. The `lencopied` parameter tells you how many bytes were actually written, including the terminator. If your code depends on knowing the exact length, check it. If your buffer is exactly `len` bytes long and `copyinstr` returned 0, the terminator is at `kbuf[lencopied - 1]`, and the string is `lencopied - 1` bytes long. +第三条安全规则是:**如果你关心,检查复制的长度**。`lencopied` 参数告诉你实际写入了多少字节,包括终止符。如果你的代码依赖于知道确切长度,检查它。如果你的缓冲区恰好是 `len` 字节长且 `copyinstr` 返回了 0,终止符在 `kbuf[lencopied - 1]`,字符串长度为 `lencopied - 1` 字节。 -A safe use of `copyinstr`: +`copyinstr` 的安全使用: ```c static int @@ -692,21 +692,21 @@ secdev_ioctl_set_name(struct secdev_softc *sc, } ``` -The function takes a fixed-size stack buffer, calls `copyinstr` with a tight bound, handles the two error cases distinctly, asserts the invariants that `copyinstr` promises (`namelen > 0`, terminator at `name[namelen - 1]`), and copies into the softc under the lock. This is the canonical pattern. +该函数接受一个固定大小的栈缓冲区,以紧凑边界调用 `copyinstr`,区分处理两种错误情况,断言 `copyinstr` 承诺的不变量(`namelen > 0`,`name[namelen - 1]` 处的终止符),并在锁下复制到 softc 中。这是经典模式。 ### 用于流的 `uiomove(9)` -`read` and `write` entry points do not use `copyin`/`copyout` directly; they use `uiomove(9)`, which is a wrapper that handles the iteration over a `struct uio` descriptor. A `uio` describes an I/O operation with potentially multiple buffers (scatter-gather) and tracks how much has been transferred so far. +`read` 和 `write` 入口点不直接使用 `copyin`/`copyout`;它们使用 `uiomove(9)`,它是一个处理对 `struct uio` 描述符迭代的封装。`uio` 描述一个可能具有多个缓冲区(分散-聚集)的 I/O 操作,并跟踪到目前为止已传输的数据量。 ```c int uiomove(void *cp, int n, struct uio *uio); ``` -`uiomove` copies up to `n` bytes between the kernel buffer `cp` and whatever is described by `uio`. If `uio->uio_rw == UIO_READ`, the copy is kernel-to-user; if `UIO_WRITE`, user-to-kernel. The function updates `uio->uio_offset`, `uio->uio_resid`, and `uio->uio_iov` to reflect the bytes transferred. +`uiomove` 在内核缓冲区 `cp` 和 `uio` 描述的任何内容之间最多复制 `n` 字节。如果 `uio->uio_rw == UIO_READ`,复制方向是内核到用户;如果是 `UIO_WRITE`,则是用户到内核。该函数更新 `uio->uio_offset`、`uio->uio_resid` 和 `uio->uio_iov` 以反映已传输的字节数。 -Like `copyin`, `uiomove` returns 0 on success and an error code on failure. Like `copyin`, it can sleep. Like `copyin`, the caller must check the return value. +与 `copyin` 一样,`uiomove` 成功时返回 0,失败时返回错误代码。与 `copyin` 一样,它可能睡眠。与 `copyin` 一样,调用者必须检查返回值。 -A typical `read` implementation: +典型的 `read` 实现: ```c static int @@ -732,13 +732,13 @@ secdev_read(struct cdev *dev, struct uio *uio, int flag) } ``` -This handles the case where the user reads past the end of the data (returning 0 to indicate EOF), bounds the copy to the size of the kernel buffer, and propagates any error from `uiomove`. It is a safe pattern for short, fixed data; longer data typically uses `sbuf(9)` internally and copies out with `sbuf_finish`/`sbuf_len`/`uiomove` at the end. +这处理了用户读取超过数据末尾的情况(返回 0 表示 EOF),将复制限制在内核缓冲区的大小内,并传播 `uiomove` 的任何错误。这是短固定数据的安全模式;较长的数据通常内部使用 `sbuf(9)`,最后通过 `sbuf_finish`/`sbuf_len`/`uiomove` 复制出去。 ### 验证每个结构的每个字段 当 `ioctl` 接受结构时,驱动程序必须在信任任何字段之前验证每个字段。一个常见的错误是只验证驱动程序立即使用的字段,而忽略稍后使用的字段。结构在 `ioctl` 调用期间存在,驱动程序最终可能使用它未检查的字段。 -Concretely, if your `ioctl` takes this structure: +具体来说,如果你的 `ioctl` 接受这个结构: ```c struct secdev_config { @@ -750,7 +750,7 @@ struct secdev_config { }; ``` -validate every field at the top of the handler: +在处理程序顶部验证每个字段: ```c static int @@ -776,18 +776,18 @@ secdev_ioctl_config(struct secdev_softc *sc, struct secdev_config *cfg) 四个不变量,每个都被检查和强制执行。驱动程序现在知道 `version`、`flags`、`len` 和 `name` 都在预期范围内。它可以在没有进一步验证的情况下使用它们。没有这些检查,函数中后面的每次使用都变成另一个潜在的漏洞来源。 -An important subtlety: when a structure includes reserved fields or padding, the driver must decide what to do when those fields are non-zero. The safe choice is usually to require them to be zero: +一个重要的微妙之处:当结构包含保留字段或填充时,驱动程序必须决定当这些字段非零时该怎么办。安全的选择通常是要求它们为零: ```c if (cfg->reserved1 != 0 || cfg->reserved2 != 0) return (EINVAL); ``` -This preserves the possibility of using those fields in a future version of the protocol without breaking compatibility: if every current caller passes zero, any future non-zero value is necessarily from a caller that knows about the new version. Without the check, the driver cannot later distinguish old callers (who happened to leave garbage in the reserved fields) from new callers (who are using the field for a new purpose). +这保留了在协议的未来版本中使用这些字段的可能性而不破坏兼容性:如果每个当前调用者都传递零,任何未来的非零值必然来自了解新版本的调用者。没有这个检查,驱动程序以后无法区分旧调用者(碰巧在保留字段中留下垃圾)和新调用者(正在为新的目的使用该字段)。 ### 验证分多部分传入的结构 -Some `ioctl`s take a structure that contains a pointer to another block of data. The outer structure is copied in first; the pointer inside it then needs to be followed with a second `copyin`. Every field of both structures must be validated. +有些 `ioctl` 接受一个包含指向另一个数据块的指针的结构。外部结构首先被复制进来;然后需要通过第二次 `copyin` 来跟踪其中的指针。两个结构的每个字段都必须被验证。 ```c struct secdev_ioctl_args { @@ -827,39 +827,39 @@ secdev_ioctl_something(struct secdev_softc *sc, } ``` -The `uintptr_t` cast is worth commenting on. The user pointer arrives as a `uint64_t` in the structure, to avoid portability issues between 32-bit and 64-bit userlands. The cast to `uintptr_t` and then to `const void *` converts the integer representation back into a pointer. On a 64-bit kernel, this is a no-op; on a 32-bit kernel, the high bits of the `uint64_t` must be validated or dropped. FreeBSD runs on both, and 32-bit userland on a 64-bit kernel (via `COMPAT_FREEBSD32`) is a real case. Be explicit about the cast, and document the assumption. +`uintptr_t` 转换值得解释。用户指针在结构中作为 `uint64_t` 到达,以避免 32 位和 64 位用户态之间的可移植性问题。转换为 `uintptr_t` 然后转换为 `const void *` 将整数表示转换回指针。在 64 位内核上,这是一个空操作;在 32 位内核上,`uint64_t` 的高位必须被验证或丢弃。FreeBSD 在两者上运行,64 位内核上的 32 位用户态(通过 `COMPAT_FREEBSD32`)是一个真实的情况。显式处理转换,并记录假设。 ### "冻结"问题 -Some drivers have fields in user-space structures that are pointers, and the driver's convention is that the user-space memory stays valid until a particular operation completes. This pattern is common in drivers that do DMA directly from user memory. +有些驱动程序在用户空间结构中有指针字段,驱动程序的约定是用户空间内存在特定操作完成之前保持有效。这种模式在做直接从用户内存进行 DMA 的驱动程序中很常见。 -The pattern is tricky because the user can, in principle, change the memory between the driver's validation and the driver's use. Pointer-based DMA is also the wrong idea in modern drivers; safer alternatives include: +这种模式很棘手,因为用户原则上可以在驱动程序验证和驱动程序使用之间更改内存。基于指针的 DMA 在现代驱动程序中也是错误的做法;更安全的替代方案包括: -- `mmap`, in which the driver maps kernel memory into user space for direct access, with the kernel retaining ownership of the memory and its validity. -- A copy-through-kernel approach, in which the driver always copies in, validates, and operates on the kernel copy. -- The `busdma(9)` framework, which handles user-space buffers correctly when they need to be DMA'd to hardware. +- `mmap`,驱动程序将内核内存映射到用户空间以供直接访问,内核保留内存的所有权及其有效性。 +- 通过内核复制的方法,驱动程序始终复制进来、验证并操作内核副本。 +- `busdma(9)` 框架,当需要将用户空间缓冲区 DMA 到硬件时正确处理它们。 -If you find yourself writing code that keeps a user-space pointer around and uses it at a later moment, stop and think. It is almost always the wrong design. Section 5 returns to this issue as a TOCTOU problem. +如果你发现自己编写保持用户空间指针并在稍后使用它的代码,停下来想一想。这几乎总是错误的设计。第5节将此问题作为 TOCTOU 问题再次讨论。 ### 内核地址不会泄露到用户指针中 -A recurring class of bug is when a driver, trying to communicate a pointer to user space, copies out a kernel address. The user receives a pointer to kernel memory, which is a spectacular information leak (it reveals the kernel's layout, defeating KASLR) and, if the user can somehow convince the kernel to treat the copied pointer as a user pointer, can become an arbitrary kernel-memory access. +一类反复出现的漏洞是驱动程序试图向用户空间传递指针时,复制出了内核地址。用户收到一个指向内核内存的指针,这是一个严重的信息泄露(它暴露了内核的布局,使 KASLR 失效),如果用户能以某种方式说服内核将复制的指针视为用户指针,就可能变成任意的内核内存访问。 -The mistake is usually inadvertent. A common case is a structure that is shared between kernel and user space, and one of its fields is a pointer. If the driver fills in the field with a kernel pointer and then copies the structure to user space, the leak has happened. +这个错误通常是无意的。一种常见情况是一个在内核和用户空间之间共享的结构,其中一个字段是指针。如果驱动程序用内核指针填充该字段然后将结构复制到用户空间,泄露就发生了。 -The fix is structural: do not share structures between kernel and user that contain pointer fields intended to be used in either space. If a pointer field exists, make it `uint64_t` and treat it as an opaque integer. When the kernel fills in a user-visible pointer-like field, it must pick a value meaningful to user space, not reveal its own internal pointer. +修复是结构性的:不要在内核和用户之间共享包含打算在任一空间使用的指针字段的结构。如果存在指针字段,将其设为 `uint64_t` 并将其视为不透明整数。当内核填充用户可见的类似指针的字段时,它必须选择对用户空间有意义的值,而不是暴露自己的内部指针。 -A second class of leak is when a driver copies out a structure that contains uninitialised fields, and one of those fields happens to contain a kernel pointer (for example, because the allocator returned memory that was previously used for something that held a kernel pointer). Section 7 covers this in depth. +第二类泄露是当驱动程序复制出包含未初始化字段的结构,其中一个字段碰巧包含内核指针时(例如,因为分配器返回了之前用于保存内核指针的内存)。第7节深入讨论这一点。 ### `compat32` 和结构大小 -FreeBSD supports running 32-bit user-space programs on a 64-bit kernel through the `COMPAT_FREEBSD32` machinery. For a driver, this means that the structure the caller passes may be a 32-bit structure, with different layout and size from the 64-bit version. If the driver expects the 64-bit structure and the caller passed the 32-bit one, the fields the driver reads will be at the wrong offsets, and the driver will read garbage. +FreeBSD 通过 `COMPAT_FREEBSD32` 机制支持在 64 位内核上运行 32 位用户空间程序。对于驱动程序来说,这意味着调用者传递的结构可能是 32 位结构,与 64 位版本有不同的布局和大小。如果驱动程序期望 64 位结构而调用者传递了 32 位结构,驱动程序读取的字段将在错误的偏移量处,驱动程序将读取垃圾。 -Handling this is outside the scope of a typical driver; the framework helps by offering `ioctl32` entry points and automatic translation for many common cases. If your driver is used from 32-bit user-space and uses custom structures, consult the `freebsd32(9)` manual page and the `sys/compat/freebsd32` subsystem for guidance. Be aware of the issue, and test your driver from a 32-bit userland in the lab environment. +处理这超出了典型驱动程序的范围;框架通过为许多常见情况提供 `ioctl32` 入口点和自动转换来帮助。如果你的驱动程序从 32 位用户空间使用并使用自定义结构,请查阅 `freebsd32(9)` 手册页和 `sys/compat/freebsd32` 子系统以获取指导。了解这个问题,并在实验室环境中从 32 位用户态测试你的驱动程序。 ### 更大的示例:完整的 `ioctl` 处理程序 -Combining the patterns in this section, here is what a complete, safe `ioctl` handler looks like for a hypothetical operation: +结合本节的模式,这里是一个完整的、安全的 `ioctl` 处理程序对于假设操作的样子: ```c static int @@ -919,32 +919,32 @@ secdev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, } ``` -Each numbered step is a distinct concern. Each step handles errors locally and propagates them. The allocation is bounded by the validated length; the copy is bounded by the same length; the permission check is explicit; the cleanup is symmetric with the allocation; the final return code communicates success or the specific failure. This is what a safe ioctl handler looks like. It is not short, but every line is there for a reason. +每个编号的步骤是一个不同的关注点。每个步骤在本地处理错误并传播它们。分配受已验证长度的限制;复制受相同长度的限制;权限检查是显式的;清理与分配对称;最终返回代码传达成功或特定的失败。这就是一个安全的 ioctl 处理程序的样子。它不短,但每一行都有其存在的理由。 ### 用户输入处理中的常见错误 -A short checklist of the patterns to watch for, as a reference you can return to while reviewing your own code: +一个简短的模式检查清单,作为你在审查自己代码时可以返回的参考: -- `copyin` with a length from the user, without a prior bound check. -- `copyinstr` without an explicit bound. -- Return value of `copyin`, `copyout`, or `copyinstr` ignored. -- Structure fields used before they are validated. -- Pointer field cast from `uint64_t` to `void *` without thinking about 32-bit-userland compatibility. -- String field assumed null-terminated without a `memchr` check. -- Length used in arithmetic before being bounded. -- User-space pointer kept around and used later (TOCTOU territory). -- Kernel data structure (with pointer fields) directly copied out. -- Uninitialised fields copied out to user space. +- `copyin` 使用来自用户的长度,没有事先的边界检查。 +- `copyinstr` 没有显式边界。 +- `copyin`、`copyout` 或 `copyinstr` 的返回值被忽略。 +- 结构字段在验证之前就被使用。 +- 指针字段从 `uint64_t` 转换为 `void *` 而没有考虑 32 位用户态兼容性。 +- 字符串字段被假定为空终止而没有 `memchr` 检查。 +- 长度在有界之前被用于算术。 +- 用户空间指针被保持并在稍后使用(TOCTOU 领域)。 +- 内核数据结构(带指针字段)被直接复制出去。 +- 未初始化的字段被复制到用户空间。 -If a code review turns up any of these, pause the review, fix the pattern, and then continue. +如果代码审查发现其中任何一个,暂停审查,修复模式,然后继续。 ### 详细演示:从零开始设计安全的 Ioctl -The accumulated techniques of this section can feel like a long checklist. To show how they come together in practice, let us design a single ioctl carefully, from the user-space interface down to the kernel implementation. +本节积累的技术可能感觉像一份长长的检查清单。为了展示它们在实践中如何组合,让我们仔细地从头设计一个 ioctl,从用户空间接口到内核实现。 -**The problem.** Our driver needs an ioctl that lets a user set a configuration parameter consisting of a name string (bounded length), a mode (enum), and an opaque data blob (variable length). It should also return the driver's interpretation of the configuration (for example, the canonicalized form of the name). +**问题。** 我们的驱动程序需要一个 ioctl,让用户设置一个配置参数,由名称字符串(有界长度)、模式(枚举)和不透明数据块(可变长度)组成。它还应返回驱动程序对配置的解释(例如,名称的规范化形式)。 -**Defining the interface.** The user-visible structure, defined in a header that will ship with the driver, looks like: +**定义接口。** 用户可见的结构定义在随驱动程序发布的头文件中,如下所示: ```c #define SECDEV_NAME_MAX 64 @@ -966,17 +966,17 @@ struct secdev_config { }; ``` -Notes on the design: +关于设计的说明: -The name is a fixed-size inline buffer, not a pointer. This is deliberate: it avoids a separate `copyin` for the name and makes the interface simpler. The trade-off is that the buffer is always copied even if the name is short, but for 64 bytes that is negligible. +名称是固定大小的内联缓冲区,不是指针。这是深思熟虑的:它避免了单独为名称进行 `copyin` 并使接口更简单。权衡是即使名称很短也总是复制整个缓冲区,但对于 64 字节来说可以忽略不计。 -The mode is `uint32_t` rather than `enum secdev_mode` directly, because struct members that cross the user/kernel boundary should have explicit widths. The kernel validates that the value is one of the known enum values. +模式是 `uint32_t` 而不是直接使用 `enum secdev_mode`,因为跨越用户/内核边界的结构成员应该有显式宽度。内核验证该值是已知枚举值之一。 -The blob uses a separate pointer (`sc_blob`) and a length (`sc_bloblen`). The user sets both, and the kernel uses a second `copyin` to pull the data. The length is bounded by `SECDEV_BLOB_MAX`, a value we (the driver authors) choose based on what the driver is actually going to do with the data. +数据块使用单独的指针(`sc_blob`)和长度(`sc_bloblen`)。用户设置两者,内核使用第二次 `copyin` 来拉取数据。长度受 `SECDEV_BLOB_MAX` 限制,这是我们(驱动程序作者)基于驱动程序实际要对数据做什么而选择的值。 -The canonical output is another fixed inline buffer. The user-space caller may or may not care about this output, but the kernel always fills it. +规范化输出是另一个固定的内联缓冲区。用户空间调用者可能关心也可能不关心这个输出,但内核总是填充它。 -**The kernel handler.** Let us walk through the implementation step by step. The ioctl framework will copy the structure into the kernel for us, so by the time our handler runs, `cfg` points to kernel memory. The `sc_blob` field, however, is still a user-space pointer that we must handle ourselves. +**内核处理程序。** 让我们逐步了解实现。ioctl 框架会为我们复制结构到内核,所以当我们的处理程序运行时,`cfg` 指向内核内存。然而,`sc_blob` 字段仍然是用户空间指针,我们必须自己处理。 ```c static int @@ -1057,31 +1057,31 @@ out: } ``` -Now review this against the patterns we have discussed. +现在对照我们讨论过的模式审查这段代码。 -Privilege check. `priv_check(PRIV_DRIVER)` is the first line of business. No unprivileged caller ever reaches the rest. +权限检查。`priv_check(PRIV_DRIVER)` 是第一件事。没有非特权调用者能到达其余部分。 -Jail check. `jailed()` before any host-affecting work. +Jail 检查。在做任何影响主机的工作之前检查 `jailed()`。 -Name validation. The name is read from the already-copied-in `cfg`, forced NUL-terminated (defensive, in case the user did not terminate it), and whitelisted through `secdev_is_valid_name` (which presumably refuses non-alphanumeric characters). +名称验证。名称从已经复制进来的 `cfg` 中读取,强制 NUL 终止(防御性的,以防用户没有终止它),并通过 `secdev_is_valid_name` 进行白名单检查(它大概拒绝非字母数字字符)。 -Mode validation. An explicit whitelist of known mode values. An unknown value returns `EINVAL` immediately. +模式验证。已知模式值的显式白名单。未知值立即返回 `EINVAL`。 -Length validation. The blob length is checked against a defined maximum before being used for allocation. Without this check, a user could request a multi-gigabyte allocation. +长度验证。数据块长度在用于分配之前对照定义的最大值进行检查。没有这个检查,用户可能请求多 GB 的分配。 -Allocation with `M_ZERO`. The blob buffer is zeroed so that even if `copyin` fails partway, the contents are deterministic. +使用 `M_ZERO` 分配。数据块缓冲区被清零,即使 `copyin` 中途失败,内容也是确定性的。 -Error path cleanup. The `out:` label frees `kblob` if we did not transfer ownership. The `kblob = NULL` after transfer prevents a double-free. Every path through the function reaches `out:` with `kblob` in a consistent state. +错误路径清理。`out:` 标签在我们未转移所有权时释放 `kblob`。转移后的 `kblob = NULL` 防止双重释放。通过函数的每条路径都以 `kblob` 处于一致状态到达 `out:`。 -Explicit zeroing before free. The old blob (if any) is zeroed before being replaced, on the assumption that it may have contained sensitive data. The new blob on error path is also zeroed for the same reason. +释放前显式清零。旧的数据块(如果有的话)在替换前被清零,假设它可能包含敏感数据。错误路径上的新数据块也因同样的原因被清零。 -Locking. The softc is updated under `sc_mtx`. The canonical form is computed under the lock so the name and canonical match. +加锁。softc 在 `sc_mtx` 下更新。规范化形式在锁下计算,以便名称和规范化匹配。 -Output zeroing. `cfg->sc_canonical` is zeroed before being filled, so padding and any fields the canonicalizer did not set are guaranteed zero. +输出清零。`cfg->sc_canonical` 在填充前被清零,因此填充和规范化器未设置的任何字段保证为零。 -This function has about forty lines of actual code and roughly a dozen security-relevant decisions. Each decision individually is small; the compound effect is a function that is defensible against nearly every pattern discussed in this chapter. This is what secure driver code looks like in practice: not flashy, not tricky, just careful. +这个函数有大约四十行实际代码和大约一打安全相关的决策。每个决策单独来看都很小;复合效果是一个能够防御本章讨论的几乎所有模式的函数。这就是安全的驱动程序代码在实践中的样子:不华丽,不取巧,只是仔细。 -The key insight is that the careful code is the easiest to review, the easiest to maintain, and the one that tends to keep working as the driver evolves. Clever tricks, by contrast, are where bugs hide. +关键的洞察是,仔细的代码是最容易审查的,最容易维护的,并且在驱动程序演进过程中倾向于持续工作的代码。相比之下,巧妙的技巧正是漏洞隐藏的地方。 ### 第3节总结 @@ -1112,27 +1112,27 @@ MALLOC_DECLARE(M_SECDEV); MALLOC_DEFINE(M_SECDEV, "secdev", "Secure example driver"); ``` -The first argument, `M_SECDEV`, is the identifier; the second, `"secdev"`, is the short name that appears in `vmstat -m`; the third is a longer description. Use a naming scheme that makes it easy to find the driver's allocations in system output, especially when you are diagnosing a leak. +第一个参数 `M_SECDEV` 是标识符;第二个 `"secdev"` 是出现在 `vmstat -m` 中的短名称;第三个是更长的描述。使用使命名方案易于在系统输出中找到驱动程序分配的方案,特别是在你诊断泄漏时。 `flags` 参数控制分配的行为。三个标志是必不可少的: -- `M_WAITOK`: the allocator may sleep to satisfy the allocation. The call cannot fail; it either returns a valid pointer or the kernel panics (which it does only under very unusual circumstances). -- `M_NOWAIT`: the allocator must not sleep. If memory is not immediately available, the call returns `NULL`. The caller must check and handle the `NULL` case. -- `M_ZERO`: the returned memory is zeroed before being returned. Use this whenever the caller will fill in some but not all of the memory, to avoid leaking garbage. +- `M_WAITOK`:分配器可能睡眠以满足分配。调用不会失败;它要么返回有效指针,要么内核崩溃(这仅在非常不寻常的情况下发生)。 +- `M_NOWAIT`:分配器不得睡眠。如果内存不是立即可用的,调用返回 `NULL`。调用者必须检查并处理 `NULL` 情况。 +- `M_ZERO`:返回的内存返回前被清零。当调用者将填充部分但不是全部内存时使用此标志,以避免泄露垃圾。 -There are others (`M_USE_RESERVE`, `M_NODUMP`, `M_NOWAIT`, `M_EXEC`), but these three are the ones a driver uses daily. +还有其他标志(`M_USE_RESERVE`、`M_NODUMP`、`M_NOWAIT`、`M_EXEC`),但这三个是驱动程序日常使用的。 ### 何时使用 `M_WAITOK`,何时使用 `M_NOWAIT` -The choice between `M_WAITOK` and `M_NOWAIT` is dictated by context, not preference. +在 `M_WAITOK` 和 `M_NOWAIT` 之间的选择由上下文决定,不是偏好。 -Use `M_WAITOK` when the driver is in a context that can sleep. This is the case in most driver entry points: `open`, `close`, `read`, `write`, `ioctl`, `attach`, `detach`. In these contexts, sleeping is allowed, and the allocator's ability to sleep until memory is available is a significant simplification. +当驱动程序处于可以睡眠的上下文时使用 `M_WAITOK`。在大多数驱动程序入口点中是这种情况:`open`、`close`、`read`、`write`、`ioctl`、`attach`、`detach`。在这些上下文中,睡眠是允许的,分配器能够睡眠直到内存可用是一个显著的简化。 -Use `M_NOWAIT` when the driver is in a context that cannot sleep. This is the case in interrupt handlers, inside spin-mutex critical sections, and inside certain callback paths that the kernel specifies as non-sleeping. In these contexts, `M_WAITOK` would trigger a `WITNESS` assertion and a panic. Even if `WITNESS` is not enabled, sleeping in a non-sleeping context can deadlock the system. +当驱动程序处于不能睡眠的上下文时使用 `M_NOWAIT`。在中断处理程序、自旋互斥锁临界区内以及内核指定为不可睡眠的某些回调路径中是这种情况。在这些上下文中,`M_WAITOK` 会触发 `WITNESS` 断言和崩溃。即使没有启用 `WITNESS`,在不可睡眠的上下文中睡眠也可能死锁系统。 -The rule of thumb: if you can use `M_WAITOK`, use it. It removes a whole class of error handling (the NULL check), and it makes the driver's behaviour more predictable under memory pressure. Only fall back to `M_NOWAIT` when the context forces it. +经验法则:如果你能使用 `M_WAITOK`,就使用它。它消除了一整类错误处理(NULL 检查),并使驱动程序在内存压力下的行为更可预测。只有当上下文强制时才回退到 `M_NOWAIT`。 -With `M_NOWAIT`, you must check the return value: +使用 `M_NOWAIT` 时,你必须检查返回值: ```c buf = malloc(size, M_SECDEV, M_NOWAIT); @@ -1140,13 +1140,13 @@ if (buf == NULL) return (ENOMEM); ``` -Failure to check is a null-pointer panic waiting to happen. The compiler will not warn you about it. +不检查返回值就是等待发生的空指针崩溃。编译器不会对此发出警告。 ### `M_ZERO` 是你的朋友 -One of the subtlest classes of driver bug is the one where the driver allocates memory, fills in some fields, and then uses or exposes the rest. The "rest" is whatever the allocator happened to return, which in FreeBSD is whatever the allocator's free list last had there. If that memory held another subsystem's data before being freed, a driver that fails to clear it may accidentally expose that data (an information leak) or may behave incorrectly because a field it did not set has a non-zero value. +最微妙的驱动程序漏洞类别之一是驱动程序分配内存、填充一些字段、然后使用或暴露其余部分的那些。"其余部分"是分配器碰巧返回的任何内容,在 FreeBSD 中是分配器空闲列表上次放在那里的任何内容。如果该内存在被释放前保存了另一个子系统的数据,未清零它的驱动程序可能意外暴露该数据(信息泄露),或者可能因为未设置的字段具有非零值而行为不正确。 -`M_ZERO` prevents both problems: +`M_ZERO` 防止这两个问题: ```c struct secdev_state *st; @@ -1154,15 +1154,15 @@ struct secdev_state *st; st = malloc(sizeof(*st), M_SECDEV, M_WAITOK | M_ZERO); ``` -After this call, every byte of `*st` is zero. The driver can then fill in specific fields and trust that everything else is either zero or set explicitly. This is so important for safety that many FreeBSD driver authors treat `M_ZERO` as the default, adding it unless there is a specific reason not to. +此调用之后,`*st` 的每个字节都是零。驱动程序然后可以填充特定字段并信任其他所有内容要么为零要么被显式设置。这对安全性如此重要,以至于许多 FreeBSD 驱动程序作者将 `M_ZERO` 视为默认选项,除非有特定原因否则都会添加它。 -The exception is large allocations where you are certain you will overwrite every byte before use (for example, a buffer that is immediately filled by `copyin`). In that case, `M_ZERO` is a small waste, and you can omit it. In all other cases, prefer `M_ZERO` and accept the small cost. +例外是你确定在使用前会覆盖每个字节的大型分配(例如,一个立即被 `copyin` 填充的缓冲区)。在这种情况下,`M_ZERO` 是小的浪费,你可以省略它。在所有其他情况下,优先使用 `M_ZERO` 并接受小的成本。 -A particularly important case: **any structure that will be copied to user space must either have been `M_ZERO`'d at allocation time or have had every byte explicitly set before the copy**. Otherwise the structure may include kernel data that was there before. Section 7 returns to this. +一个特别重要的情况:**任何将被复制到用户空间的结构必须在分配时被 `M_ZERO` 或在复制前显式设置了每个字节**。否则结构可能包含之前在那里的内核数据。第7节将回到这一点。 ### 用于高频分配的 `uma_zone` -For allocations that happen many times per second with a fixed size, FreeBSD offers the UMA zone allocator: +对于每秒发生多次固定大小分配的情况,FreeBSD 提供 UMA 区域分配器: ```c uma_zone_t uma_zcreate(const char *name, size_t size, ...); @@ -1170,17 +1170,17 @@ void *uma_zalloc(uma_zone_t zone, int flags); void uma_zfree(uma_zone_t zone, void *item); ``` -UMA zones are significantly faster than `malloc` for repeated small allocations, because they maintain per-CPU caches and avoid the global allocator lock for most operations. Drivers that handle network packets, I/O requests, or other high-frequency events typically use UMA zones instead of `malloc`. +UMA 区域对于重复的小分配明显比 `malloc` 更快,因为它们维护每 CPU 缓存并在大多数操作中避免全局分配器锁。处理网络数据包、I/O 请求或其他高频事件的驱动程序通常使用 UMA 区域而不是 `malloc`。 -The security properties of UMA zones are similar to those of `malloc`. You still pass `M_WAITOK` or `M_NOWAIT`. You still may pass `M_ZERO` (or you may use `uma_zcreate_arg`'s `uminit`/`ctor`/`dtor` arguments to manage initial state). You still must check NULL on `M_NOWAIT`. +UMA 区域的安全属性与 `malloc` 类似。你仍然传递 `M_WAITOK` 或 `M_NOWAIT`。你仍然可以传递 `M_ZERO`(或者你可以使用 `uma_zcreate_arg` 的 `uminit`/`ctor`/`dtor` 参数来管理初始状态)。你仍然必须在 `M_NOWAIT` 上检查 NULL。 -UMA has one additional security consideration worth knowing: **items returned to a zone are not zeroed by default**. An item freed with `uma_zfree` may retain its previous contents and be handed out to a subsequent `uma_zalloc` with that same content. If the item held sensitive data, the driver must zero it before freeing, or must pass `M_ZERO` on every allocation, or must use the `uminit` constructor machinery to zero on allocation. The safest default is to use `explicit_bzero` on the item before calling `uma_zfree`. +UMA 有一个值得了解的额外安全考虑:**返回到区域的对象默认不被清零**。用 `uma_zfree` 释放的对象可能保留其之前的内容,并在随后的 `uma_zalloc` 中以该内容被分配出去。如果对象保存了敏感数据,驱动程序必须在释放前清零,或者每次分配时传递 `M_ZERO`,或者使用 `uminit` 构造器机制在分配时清零。最安全的默认做法是在调用 `uma_zfree` 前对对象使用 `explicit_bzero`。 ### 释放后使用:它是什么以及为什么重要 -A use-after-free bug occurs when a driver frees a pointer and then uses it. The allocator has, by now, almost certainly handed that memory to some other part of the kernel. Writes to the freed pointer corrupt that other part of the kernel; reads from it return whatever is now stored there. +释放后使用漏洞发生在驱动程序释放指针然后使用它时。分配器到现在几乎肯定已经将该内存交给了内核的其他部分。对已释放指针的写入损坏了内核那个其他部分正在做的事情;从中读取返回的是现在存储在那里的任何内容。 -The classic pattern: +经典模式: ```c /* UNSAFE */ @@ -1195,80 +1195,80 @@ secdev_cleanup(struct secdev_softc *sc) } ``` -The fix has two parts. First, set the pointer to NULL immediately after freeing it, so that any subsequent use is a null-pointer dereference (an immediate, diagnosable crash) rather than a dangling-pointer access (silent corruption): +修复有两个部分。首先,释放后立即将指针设置为 NULL,这样任何后续使用都是空指针解引用(立即的、可诊断的崩溃)而不是悬空指针访问(静默损坏): ```c free(sc->sc_buf, M_SECDEV); sc->sc_buf = NULL; ``` -Second, audit the code paths that might still hold references to the freed memory. The NULL-assignment prevents crashes at `sc->sc_buf` accesses, but a local variable or a caller's parameter that still holds the old pointer is not protected. The discipline is to free memory only when you are sure no one else holds a pointer to it. Reference counts (`refcount(9)`) are the FreeBSD primitive for this. +其次,审计可能仍然持有对已释放内存引用的代码路径。NULL 赋值防止了 `sc->sc_buf` 访问处的崩溃,但仍然持有旧指针的局部变量或调用者的参数不受保护。纪律是只在确定没有其他人持有指向它的指针时才释放内存。引用计数(`refcount(9)`)是 FreeBSD 用于此目的的原语。 -A variant of the bug is the **use-after-detach** pattern, in which a driver frees its softc during `detach` but an interrupt handler or a callback still runs and accesses the freed softc. The fix is to drain all asynchronous activity before freeing in `detach`: cancel outstanding callouts with `callout_drain`, drain taskqueues with `taskqueue_drain`, teardown interrupt handlers with `bus_teardown_intr`, and so on. Once all async paths are quiesced, the free is safe. +该漏洞的一个变体是**释放后使用-detach**模式,其中驱动程序在 `detach` 期间释放其 softc 但中断处理程序或回调仍然运行并访问已释放的 softc。修复方法是在 `detach` 中释放之前排空所有异步活动:用 `callout_drain` 取消未完成的 callout,用 `taskqueue_drain` 排空 taskqueue,用 `bus_teardown_intr` 拆除中断处理程序等。一旦所有异步路径静止,释放就是安全的。 ### 双重释放:它是什么以及为什么重要 -A double-free occurs when a driver calls `free` twice on the same pointer. The first `free` hands the memory back to the allocator. The second `free` corrupts the allocator's internal bookkeeping, because it tries to insert the same memory into the free list twice. +双重释放在驱动程序对同一指针调用两次 `free` 时发生。第一次 `free` 将内存交还给分配器。第二次 `free` 损坏分配器的内部簿记,因为它试图将同一内存两次插入空闲列表。 -FreeBSD's allocator detects many double-frees and panics immediately (especially with `INVARIANTS` enabled). But some double-frees slip past the detection, and the consequences are subtle: a later allocation may return memory that is claimed to be available but is actually still in use somewhere. +FreeBSD 的分配器检测到许多双重释放并立即崩溃(特别是在启用 `INVARIANTS` 时)。但一些双重释放逃脱了检测,后果是微妙的:后续分配可能返回声称可用但实际上仍在某处使用的内存。 -The prevention is the same NULL-assignment pattern: +预防是相同的 NULL 赋值模式: ```c free(sc->sc_buf, M_SECDEV); sc->sc_buf = NULL; ``` -`free(NULL, ...)` is defined to be a no-op in FreeBSD (as in most allocators), so a second call with `sc->sc_buf == NULL` does nothing. The NULL-assignment turns double-free into a safe no-op. +`free(NULL, ...)` 在 FreeBSD 中被定义为空操作(与大多数分配器一样),所以当 `sc->sc_buf == NULL` 时的第二次调用什么也不做。NULL 赋值将双重释放变成了安全的空操作。 -A related pattern is the **error-path double-free**, in which a function's cleanup logic frees a pointer, and then an outer function also frees the same pointer. The defence is to decide, explicitly, which function owns each allocation, and to have ownership transferred at clear moments. "Who frees this?" is a question that should have a clear answer at every line of the code. +一个相关的模式是**错误路径双重释放**,即函数的清理逻辑释放了一个指针,然后外部函数也释放了同一个指针。防御是显式地决定哪个函数拥有每个分配,并在明确的时刻转移所有权。"谁释放这个?"这个问题的答案应该在代码的每一行都有明确的回答。 ### 内存泄漏是安全问题 -A memory leak is a piece of memory that is allocated and never freed. In a long-running driver, leaks accumulate. Eventually the kernel runs out of memory, either for the driver's subsystem or for the system as a whole, and bad things happen. +内存泄漏是分配了但从未释放的内存。在长期运行的驱动程序中,泄漏会累积。最终内核耗尽内存,要么是驱动程序子系统的内存,要么是整个系统的内存,然后糟糕的事情就会发生。 -Why is a leak a security problem? Two reasons. First, a leak is a denial-of-service vector: an attacker who can trigger an allocation without a corresponding free can exhaust memory. If the attacker is unprivileged but the driver's `ioctl` allocates memory on each call, the attacker can loop on `ioctl` until the kernel OOM-kills something important. Second, a leak often hides other bugs: the leak's accumulation pressure changes the behaviour of subsequent allocations (more frequent `M_NOWAIT` failures, more unpredictable page cache), which can make racy or allocation-dependent bugs surface in production. +为什么泄漏是安全问题?两个原因。第一,泄漏是拒绝服务向量:可以触发分配而不相应释放的攻击者可以耗尽内存。如果攻击者是非特权的但驱动程序的 `ioctl` 在每次调用时分配内存,攻击者可以循环调用 `ioctl` 直到内核 OOM-kill 重要进程。第二,泄漏经常隐藏其他漏洞:泄漏的累积压力改变了后续分配的行为(更频繁的 `M_NOWAIT` 失败,更不可预测的页缓存),这可以使竞态或依赖分配的漏洞在生产环境中浮出水面。 -The prevention is discipline in allocation ownership: for every `malloc`, there must be exactly one `free`, reachable on every code path. The FreeBSD `vmstat -m` tool makes leak tracking easier in practice: `vmstat -m | grep secdev` shows, per type, how many allocations are outstanding. A driver with a leak will show a steadily rising number under load; a driver without will show a stable number. +预防是分配所有权的纪律:对于每个 `malloc`,必须有恰好一个 `free`,在每条代码路径上可达。FreeBSD 的 `vmstat -m` 工具使实际中的泄漏跟踪更容易:`vmstat -m | grep secdev` 按类型显示有多少分配未完成。有泄漏的驱动程序在负载下会显示持续上升的数字;没有泄漏的会显示稳定的数字。 -For new drivers, it is worth stress-testing the driver in the lab for leaks: open and close the device a million times in a loop, run the full `ioctl` matrix repeatedly, watch `vmstat -m` for the driver's type, and look for growth. Any sustained growth is a leak. Leaks found in the lab are a thousand times cheaper to fix than leaks found in production. +对于新驱动程序,值得在实验室中对驱动程序进行压力测试以查找泄漏:在一百万次循环中打开和关闭设备,重复运行完整的 `ioctl` 矩阵,观察 `vmstat -m` 中驱动程序类型的增长。任何持续增长都是泄漏。在实验室中发现的泄漏比在生产环境中发现的泄漏修复成本低一千倍。 ### 用于敏感数据的 `explicit_bzero` 和 `zfree` -Some data should not be allowed to linger in memory after the driver is done with it. Cryptographic keys, user passwords, device secrets, anything whose exposure in a memory snapshot would be harmful, must be erased before the memory is freed. +有些数据不应该在驱动程序使用完毕后继续留在内存中。加密密钥、用户密码、设备秘密、任何在内存快照中暴露会有害的东西,都必须在内存释放前被擦除。 -The naive approach is to use `bzero` or `memset(buf, 0, len)` before the free. This works, but it has a subtle flaw: the optimiser may remove the `bzero` if it can prove that the memory is not read after. The optimiser's logic is correct as far as language semantics go, but it defeats the security intent. +天真的方法是使用 `bzero` 或 `memset(buf, 0, len)` 然后释放。这可行,但有一个微妙的缺陷:如果优化器能证明内存在之后没有被读取,它可能移除 `bzero`。优化器的逻辑就语言语义而言是正确的,但它违背了安全意图。 -The correct primitive is `explicit_bzero(9)`: +正确的原语是 `explicit_bzero(9)`: ```c void explicit_bzero(void *buf, size_t len); ``` -`explicit_bzero` is declared in `/usr/src/sys/sys/systm.h`. It performs the zeroing and is guaranteed by the compiler not to be optimised away, even if the memory is not read after. Use it for any buffer that holds sensitive data: +`explicit_bzero` 在 `/usr/src/sys/sys/systm.h` 中声明。它执行清零并由编译器保证不会被优化掉,即使内存之后没有被读取。将它用于保存敏感数据的任何缓冲区: ```c explicit_bzero(key_buf, sizeof(key_buf)); free(key_buf, M_SECDEV); ``` -FreeBSD also provides `zfree(9)`, which zeros the memory before freeing: +FreeBSD 还提供 `zfree(9)`,它在释放前清零内存: ```c void zfree(void *addr, struct malloc_type *type); ``` -`zfree` is convenient: it combines the zero and the free into one call. It first zeros the memory using `explicit_bzero`, then frees it. Use `zfree` when you are about to free a buffer that held sensitive data. Use `explicit_bzero` followed by `free` if you need to zero the buffer without freeing it, or if you are working with memory from a source other than `malloc`. +`zfree` 很方便:它将清零和释放合并到一个调用中。它首先使用 `explicit_bzero` 清零内存,然后释放它。当你即将释放保存了敏感数据的缓冲区时使用 `zfree`。如果你需要在不释放的情况下清零缓冲区,或者你正在使用来自 `malloc` 以外来源的内存时,使用 `explicit_bzero` 后跟 `free`。 -A common question: what is "sensitive data"? The conservative answer is that any data that came from user space should be treated as sensitive, because you cannot know what it represents to the user. A more pragmatic answer is that data that is obviously a secret (a key, a password hash, a nonce, authentication material) must be zeroed, and data that might reveal information about the user's activities (file contents, network payloads, command text) should be zeroed when the driver is finished with it. When in doubt, zero. The cost is small. +一个常见问题:什么是"敏感数据"?保守的答案是来自用户空间的任何数据都应被视为敏感的,因为你不知道它对用户代表什么。更务实的答案是,显然是秘密的数据(密钥、密码哈希、随机数、认证材料)必须被清零,可能泄露用户活动信息的数据(文件内容、网络载荷、命令文本)应该在驱动程序使用完毕后清零。有疑问时,清零。成本很小。 ### `malloc_type` 标签与可追溯性 -The `malloc_type` tag on every allocation serves several purposes. It makes allocations visible in `vmstat -m`. It helps with panic debugging, because the tag is recorded in the allocator's metadata. It helps the allocator's own accounting, and in some configurations it enables per-type memory limits. +每次分配上的 `malloc_type` 标签有几个用途。它使分配在 `vmstat -m` 中可见。它有助于崩溃调试,因为标签被记录在分配器的元数据中。它有助于分配器自身的记账,在某些配置中它启用按类型的内存限制。 -A driver that uses a single `malloc_type` for all its allocations is easier to audit than a driver that uses many. Create one tag per logical subsystem within the driver, not one per allocation site. For small drivers, a single tag is usually enough. +使用单一 `malloc_type` 的驱动程序比使用多个的更容易审计。为驱动程序内的每个逻辑子系统创建一个标签,而不是每个分配点一个。对于小型驱动程序,单个标签通常就够了。 -The declaration pattern: +声明模式: ```c /* At the top of the driver source file: */ @@ -1279,15 +1279,15 @@ MALLOC_DEFINE(M_SECDEV, "secdev", "Secure example driver"); buf = malloc(size, M_SECDEV, M_WAITOK | M_ZERO); ``` -The `MALLOC_DECLARE` declares the tag for external visibility; the `MALLOC_DEFINE` actually allocates it (and registers it with the accounting system). Both are needed. Do not put `MALLOC_DEFINE` in a header, because the kernel linker will complain about duplicate definitions if multiple object files include the header. +`MALLOC_DECLARE` 声明标签以供外部可见;`MALLOC_DEFINE` 实际分配它(并将其注册到记账系统)。两者都需要。不要将 `MALLOC_DEFINE` 放在头文件中,因为如果多个目标文件包含该头文件,内核链接器会抱怨重复定义。 ### Softc 的生命周期 -The softc is the driver's per-instance state. It is typically allocated during `attach` and freed during `detach`. The softc's lifetime is one of the most important things to get right in a driver. +softc 是驱动程序的每实例状态。它通常在 `attach` 期间分配并在 `detach` 期间释放。softc 的生命周期是驱动程序中最重要的正确事项之一。 -The allocation usually happens via `device_get_softc`, which returns a pointer to a structure whose size was declared at driver-registration time. This means the softc memory is owned by the bus, not by the driver; the driver does not call `malloc` for it, and the driver does not call `free`. The bus allocates the softc when the driver is bound to the device and frees it when the driver is detached. +分配通常通过 `device_get_softc` 进行,它返回一个指向在驱动程序注册时声明大小的结构的指针。这意味着 softc 内存由总线拥有,而不是驱动程序;驱动程序不为它调用 `malloc`,也不调用 `free`。总线将 softc 分配给驱动程序绑定到设备时,并在驱动程序分离时释放它。 -But the softc often contains pointers to other memory that the driver did allocate. Those pointers must be freed in `detach`, in the reverse order of their allocation. A typical pattern: +但 softc 通常包含指向驱动程序确实分配的其他内存的指针。这些指针必须在 `detach` 中以分配顺序的逆序释放。典型模式: ```c static int @@ -1321,13 +1321,13 @@ secdev_detach(device_t dev) } ``` -Each step handles a specific concern. The order matters: destroy the device node before freeing resources the device callbacks depend on; drain async activity before freeing data the async paths might touch; destroy synchronization primitives last. +每一步处理一个特定的关注点。顺序很重要:在释放设备回调依赖的资源之前销毁设备节点;在释放异步路径可能触及的数据之前排干异步活动;最后销毁同步原语。 -A slip in any of these orderings is a bug. The wrong order can produce use-after-free or double-free patterns. The lab later in the chapter walks through a detach function that has subtle ordering bugs and asks you to fix them. +这些排序中的任何错误都是漏洞。错误的顺序可能产生释放后使用或双重释放模式。本章后面的实验室会引导你通过一个有微妙排序错误的 detach 函数并要求你修复它们。 ### 完整的分配/释放模式 -Pulling the patterns together, here is a safe allocation and use sequence: +将模式整合在一起,这里是一个安全的分配和使用序列: ```c static int @@ -1369,17 +1369,17 @@ done: } ``` -The function has a single exit point via the `done` label. The `blob = NULL` after ownership transfer ensures that the cleanup at `done` sees the transfer and does not re-free. The `explicit_bzero` before every `free` zeroes the buffer in case it held sensitive data. The existing `sc->sc_blob`, if present, is zeroed and freed before being replaced, to avoid leaking the old blob's contents. +该函数通过 `done` 标签有单一出口点。所有权转移后的 `blob = NULL` 确保清理在 `done` 处看到转移并不重新释放。每次 `free` 前的 `explicit_bzero` 清零缓冲区以防它保存了敏感数据。现有的 `sc->sc_blob`(如果存在)在替换前被清零并释放,以避免泄漏旧数据块的内容。 -This pattern (single exit point, ownership transfer, explicit zeroing, checked allocation, checked copyin) appears in variations throughout the FreeBSD kernel. Learn it well. +这个模式(单一出口点、所有权转移、显式清零、检查分配、检查 copyin)在整个 FreeBSD 内核中以变体形式出现。好好学习它。 ### 深入了解 UMA 区域 -`malloc(9)` is a general-purpose allocator suited to varying sizes. For fixed-size objects that are allocated and freed frequently, the UMA zone allocator is often the better choice. UMA stands for Universal Memory Allocator, and it is declared in `/usr/src/sys/vm/uma.h`. +`malloc(9)` 是适合可变大小的通用分配器。对于频繁分配和释放的固定大小对象,UMA 区域分配器通常是更好的选择。UMA 代表通用内存分配器,在 `/usr/src/sys/vm/uma.h` 中声明。 -A UMA zone is created once, at module load, and holds a pool of objects of a fixed size. `uma_zalloc(9)` returns an object from the pool (allocating a fresh one if necessary). `uma_zfree(9)` returns an object to the pool (or frees it back to the kernel if the pool is full). Because allocations come from a pre-configured pool, they are faster than general `malloc` and have better cache locality. +UMA 区域在模块加载时创建一次,持有固定大小对象的池。`uma_zalloc(9)` 从池中返回一个对象(必要时分配新的)。`uma_zfree(9)` 将对象返回到池中(如果池满了则释放回内核)。因为分配来自预配置的池,它们比通用 `malloc` 更快,缓存局部性更好。 -Creating a zone: +创建区域: ```c static uma_zone_t secdev_packet_zone; @@ -1406,7 +1406,7 @@ secdev_modevent(module_t mod, int event, void *arg) } ``` -Using a zone: +使用区域: ```c struct secdev_packet *pkt; @@ -1416,32 +1416,32 @@ pkt = uma_zalloc(secdev_packet_zone, M_WAITOK | M_ZERO); uma_zfree(secdev_packet_zone, pkt); ``` -The security advantages of a UMA zone over `malloc`: +UMA 区域相对于 `malloc` 的安全优势: -A zone can have a constructor and destructor that initialize or finalize objects. This can guarantee that every object returned to the caller is in a known state. +区域可以有构造函数和析构函数来初始化或终结对象。这可以保证返回给调用者的每个对象都处于已知状态。 -A zone is named, so `vmstat -z` attributes allocations to it. This helps detect leaks and unusual memory patterns in specific subsystems. +区域是有名称的,所以 `vmstat -z` 将分配归属到它。这有助于检测特定子系统中的泄漏和异常内存模式。 -The pool of objects can be drained under memory pressure. A malloc allocation is held for its lifetime; a UMA zone object can be returned to the kernel when freed if the pool is above its high-water mark. +对象池可以在内存压力下被排干。`malloc` 分配在其生命周期内被持有;UMA 区域对象在释放时如果池超过其高水位标记就可以返回给内核。 -The security pitfalls: +安全陷阱: -An object returned to the zone is not automatically zeroed. If the zone holds objects that may contain sensitive data, either add a destructor that zeros, or zero explicitly before freeing: +返回到区域的对象不会自动清零。如果区域保存可能包含敏感数据的对象,要么添加清零的析构函数,要么在释放前显式清零: ```c explicit_bzero(pkt, sizeof(*pkt)); uma_zfree(secdev_packet_zone, pkt); ``` -Because UMA reuses objects quickly, an object you just freed may be handed to another caller almost immediately. If the other caller is a different thread in another subsystem, residual data could flow between them. The fix, again, is explicit zeroing. +因为 UMA 快速重用对象,你刚释放的对象可能几乎立即被交给另一个调用者。如果另一个调用者是另一个子系统中的不同线程,残留数据可能流经它们之间。修复方法同样是显式清零。 -A destructor function passed to `uma_zcreate` is called when an object is about to be freed back to the kernel (not when it returns to the pool). For zeroing on every free, use `M_ZERO` on `uma_zalloc` (which zeros on allocation, equivalent to `bzero` immediately after) or zero explicitly. +传递给 `uma_zcreate` 的析构函数在对象即将被释放回内核时被调用(不是当它返回到池时)。对于每次释放时的清零,在 `uma_zalloc` 上使用 `M_ZERO`(等同于分配后立即 `bzero`)或显式清零。 -UMA zones are not appropriate for every driver allocation. For one-off or irregular allocations, `malloc(9)` is simpler. For high-frequency fixed-size objects, UMA wins on performance and makes memory accounting easier. Choose based on access pattern. +UMA 区域不适合每个驱动程序分配。对于一次性或不规则分配,`malloc(9)` 更简单。对于高频固定大小对象,UMA 在性能上获胜并使内存记账更容易。基于访问模式选择。 ### 共享对象的引用计数 -When an object in your driver can be held by multiple contexts (a softc that is referenced by both a callout and user-space file descriptors, for example), reference counting is the canonical tool for lifetime management. The `refcount(9)` family in `/usr/src/sys/sys/refcount.h` provides simple atomic helpers: +当驱动程序中的对象可以被多个上下文持有(例如,同时被 callout 和用户空间文件描述符引用的 softc)时,引用计数是生命周期管理的标准工具。`/usr/src/sys/sys/refcount.h` 中的 `refcount(9)` 系列提供了简单的原子辅助函数: ```c refcount_init(&obj->refcnt, 1); /* initial reference */ @@ -1452,17 +1452,17 @@ if (refcount_release(&obj->refcnt)) { } ``` -The invariant is simple: each context that holds a pointer to the object also holds a reference. When it finishes, it releases. Whichever context is last to release is responsible for freeing. +不变量很简单:每个持有指向对象指针的上下文也持有一个引用。当它完成时,释放。最后释放的上下文负责释放对象。 -Used correctly, refcounts prevent the classic "who frees it" ambiguity. Used incorrectly (unbalanced acquires and releases), they produce leaks or use-after-frees. The discipline is: +正确使用时,引用计数防止了经典的"谁来释放"歧义。错误使用时(不平衡的获取和释放),它们会产生泄漏或释放后使用。纪律是: -Every path that obtains a pointer to the object acquires a reference. +每个获取指向对象指针的路径获取一个引用。 -Every path that releases the pointer calls `refcount_release` and checks the return value. +每个释放指针的路径调用 `refcount_release` 并检查返回值。 -A single "owning" reference is held by whoever created the object; the owner is the default releaser. +一个单一的"拥有"引用由创建对象的人持有;拥有者是默认的释放者。 -Even simple refcount usage catches a large class of lifetime bugs. For complex drivers with multiple concurrent contexts, refcounts are indispensable. +即使是简单的引用计数使用也能捕获一大类生命周期漏洞。对于具有多个并发上下文的复杂驱动程序,引用计数是不可或缺的。 ### 第4节总结 @@ -1480,19 +1480,19 @@ Even simple refcount usage catches a large class of lifetime bugs. For complex d FreeBSD 驱动程序在多线程环境中运行。有几件事可以同时发生: -Two different user processes can call `read(2)`, `write(2)`, or `ioctl(2)` on the same device file. If the driver has a single `softc`, both calls run against the same state. +两个不同的用户进程可以在同一设备文件上调用 `read(2)`、`write(2)` 或 `ioctl(2)`。如果驱动程序有单个 `softc`,两个调用都针对相同的状态运行。 -One thread can be running your ioctl handler while an interrupt handler for the same device fires on another CPU. +一个线程可能正在运行你的 ioctl 处理程序,而同一设备的中断处理程序在另一个 CPU 上触发。 -A user thread can be in the middle of your driver while a callout or taskqueue entry scheduled earlier also runs. +用户线程可能在你的驱动程序中间,而之前调度的 callout 或 taskqueue 条目也在运行。 -The device can be unplugged, causing `detach` to run while any of the above is still in progress. +设备可能被拔出,导致 `detach` 在上述任何操作仍在进行时运行。 在没有适当同步的情况下被多个上下文触及的任何共享数据都是潜在的竞态。当共享数据控制访问、验证输入、跟踪缓冲区大小或保存生命周期信息时,竞态就变成了安全问题。 ### TOCTOU 模式 -The simplest TOCTOU pattern in a driver looks like this: +驱动程序中最简单的 TOCTOU 模式看起来像这样: ```c if (sc->sc_initialized) { @@ -1500,9 +1500,9 @@ if (sc->sc_initialized) { } ``` -Read it carefully. Nothing about it is obviously wrong. The driver checks that the buffer is initialized, then uses it. But if another thread can set `sc->sc_initialized` to `false` and free `sc->sc_buffer` between the check and the use, the use touches freed memory. The attacker does not need to corrupt the flag or the pointer. They only need to arrange timing. +仔细阅读。它没有任何明显错误。驱动程序检查缓冲区是否已初始化,然后使用它。但如果另一个线程可以在检查和使用之间将 `sc->sc_initialized` 设为 `false` 并释放 `sc->sc_buffer`,使用操作就触及了已释放的内存。攻击者不需要损坏标志或指针。他们只需要安排时序。 -A more subtle TOCTOU happens with user memory: +更微妙的 TOCTOU 发生在用户内存上: ```c if (args->len > MAX_LEN) @@ -1510,13 +1510,13 @@ if (args->len > MAX_LEN) error = copyin(args->data, kbuf, args->len); ``` -Look at `args`. If it was already copied in, this is safe. But if `args` still points into user space, a second user thread can change `args->len` between the check and the `copyin`. The check validates the old length. The copy uses the new length. If the new length exceeds `MAX_LEN`, the `copyin` overruns `kbuf`. +看看 `args`。如果它已经被复制进来了,这是安全的。但如果 `args` 仍然指向用户空间,第二个用户线程可以在检查和 `copyin` 之间更改 `args->len`。检查验证的是旧长度。复制使用的是新长度。如果新长度超过 `MAX_LEN`,`copyin` 就会越过 `kbuf`。 -The fix is copy-then-check, which we already covered in Section 3. The reason this technique exists is precisely because TOCTOU on user memory is a real attack vector. Always copy user data into kernel space first, then validate, then use. +修复是先复制再检查,我们已经在第3节讨论过。这种技术存在的原因正是因为对用户内存的 TOCTOU 是一个真实的攻击向量。始终先将用户数据复制到内核空间,然后验证,然后使用。 ### 真实世界示例:带路径的 Ioctl -Imagine an ioctl that takes a path and does something with the file: +想象一个接受路径并对文件做某些操作的 ioctl: ```c /* UNSAFE */ @@ -1536,7 +1536,7 @@ secdev_open_path(struct secdev_softc *sc, struct secdev_path_arg *args) } ``` -This has two races. First, `args->path` is still in user space if `args` was not copied in; a user thread can change it between the `strnlen` check and `namei`. Second, even if `args` was copied, using `UIO_USERSPACE` tells the VFS layer to read the path from user space, at which point the process can modify it again before VFS reads it. The fix is to copy the path into kernel space with `copyinstr(9)`, validate it as a kernel string, then pass it to VFS with `UIO_SYSSPACE`. +这有两个竞态。第一,如果 `args` 没有被复制进来,`args->path` 仍然在用户空间;用户线程可以在 `strnlen` 检查和 `namei` 之间更改它。第二,即使 `args` 被复制了,使用 `UIO_USERSPACE` 告诉 VFS 层从用户空间读取路径,此时进程可以在 VFS 读取之前再次修改它。修复是使用 `copyinstr(9)` 将路径复制到内核空间,将其验证为内核字符串,然后用 `UIO_SYSSPACE` 传递给 VFS。 ```c /* SAFE */ @@ -1558,37 +1558,37 @@ secdev_open_path(struct secdev_softc *sc, struct secdev_path_arg *args) } ``` -The corrected version copies the path into the kernel exactly once, validates it (by virtue of `copyinstr` bounding the length and guaranteeing a NUL terminator), then hands a stable kernel string to the VFS layer. The user process can change `args->path` as often as it likes; we are no longer reading from there. +修正后的版本将路径仅一次复制到内核中,验证它(通过 `copyinstr` 限制长度并保证 NUL 终止符),然后将稳定的内核字符串交给 VFS 层。用户进程可以随意更改 `args->path`;我们不再从那里读取了。 ### 共享状态与加锁 -For races between concurrent in-kernel contexts, the tool is a lock. FreeBSD offers several. The most common in drivers are: +对于并发内核上下文之间的竞态,工具是锁。FreeBSD 提供了几种。驱动程序中最常见的是: -`mtx_t`, a mutex, created with `mtx_init(9)`. Mutexes are fast, short, and must not be held across sleeps. Use them to protect a small critical section. +`mtx_t`,互斥锁,用 `mtx_init(9)` 创建。互斥锁快速、简短,不得跨睡眠持有。用它们保护小的临界区。 -`sx_t`, a shared-exclusive lock, created with `sx_init(9)`. Shared-exclusive locks can be held across sleeps. Use them when the critical section includes something like `malloc(M_WAITOK)` or a VFS call. +`sx_t`,共享排他锁,用 `sx_init(9)` 创建。共享排他锁可以跨睡眠持有。当临界区包含像 `malloc(M_WAITOK)` 或 VFS 调用之类的东西时使用它们。 -`struct rwlock`, a read-write lock, for the read-mostly case. Multiple readers can hold the lock in shared mode; an exclusive writer excludes all readers. +`struct rwlock`,读写锁,用于读多的情况。多个读者可以以共享模式持有锁;排他写者排除所有读者。 -`struct mtx` paired with condition variables (`cv_init(9)`, `cv_wait(9)`, `cv_signal(9)`) for producer-consumer patterns. +`struct mtx` 配合条件变量(`cv_init(9)`、`cv_wait(9)`、`cv_signal(9)`)用于生产者-消费者模式。 -The rules for safe locking are simple and absolute: +安全加锁的规则简单而绝对: -Define exactly what data each lock protects. Write it in a comment next to the softc field. +精确定义每个锁保护什么数据。在 softc 字段旁边的注释中写下来。 -Acquire the lock before reading or writing the protected data. Release it afterwards. +在读取或写入受保护数据之前获取锁。之后释放它。 -Do not hold locks longer than necessary. Long critical sections hurt performance and increase deadlock risk. +不要持有锁超过必要的时间。长临界区损害性能并增加死锁风险。 -Acquire multiple locks in a consistent order across all code paths. Inconsistent ordering leads to deadlock. +在所有代码路径上以一致的顺序获取多个锁。不一致的顺序导致死锁。 -Do not sleep while holding a mutex. Convert to an sx lock or drop the mutex first. +持有互斥锁时不要睡眠。转换为 sx 锁或先释放互斥锁。 -Do not call into user space (`copyin`, `copyout`) while holding a mutex. Copy first, then lock. Release, then copy back. +持有互斥锁时不要调用用户空间(`copyin`、`copyout`)。先复制,然后加锁。释放,然后复制回去。 ### 深入了解:修复有竞态的驱动程序 -Consider the following minimal handler: +考虑以下最小处理程序: ```c /* UNSAFE: races on sc_open */ @@ -1613,7 +1613,7 @@ secdev_close(struct cdev *dev, int fflags, int devtype, struct thread *td) } ``` -The intent is that only one process can have the device open at a time. The bug is that `sc_open` is checked and set without a lock. Two concurrent `open(2)` calls can both read `sc_open == false`, both decide they are the first, and both set it to `true`. Both succeed. Now two processes share a device that was meant to be exclusive. This is a real-world bug class that has affected real drivers. Fix: +意图是同一时间只有一个进程能打开设备。漏洞是 `sc_open` 在没有锁的情况下被检查和设置。两个并发的 `open(2)` 调用都可以读到 `sc_open == false`,都认为自己是第一个,都将其设为 `true`。两个都成功了。现在两个进程共享了一个设计为独占的设备。这是一个影响过真实驱动程序的真实漏洞类别。修复: ```c /* SAFE */ @@ -1644,23 +1644,23 @@ secdev_close(struct cdev *dev, int fflags, int devtype, struct thread *td) } ``` -Now the read and the write happen inside a single critical section. Only one caller at a time can be inside that section, so the check-then-set sequence is atomic from the perspective of any other caller. +现在读取和写入发生在单个临界区内。同一时间只有一个调用者可以在该临界区内,所以检查-然后-设置序列从任何其他调用者的角度来看是原子的。 ### 分离时的生命周期竞态 -The hardest races in drivers are lifetime races around `detach`. The device goes away, but a user thread is still inside your ioctl handler, or an interrupt is in flight, or a callout is pending. If `detach` frees the softc while one of these references it, you have a use-after-free. +驱动程序中最难的竞态是 `detach` 周围的生命周期竞态。设备消失了,但用户线程仍在你的 ioctl 处理程序中,或者中断正在传输中,或者 callout 正在等待。如果 `detach` 在其中一个引用了 softc 时释放了它,你就会有释放后使用。 -FreeBSD gives you tools to handle this: +FreeBSD 为你提供了处理这个的工具: -`callout_drain(9)` waits for any scheduled callout to finish before returning. Call it in `detach` before freeing anything the callout touches. +`callout_drain(9)` 在返回之前等待任何已调度的 callout 完成。在 `detach` 中释放 callout 触及的任何东西之前调用它。 -`taskqueue_drain(9)` and `taskqueue_drain_all(9)` wait for pending tasks to complete. +`taskqueue_drain(9)` 和 `taskqueue_drain_all(9)` 等待待处理的任务完成。 -`destroy_dev(9)` marks a character device as gone and waits for all in-flight threads to leave the device's d_* methods before returning. After `destroy_dev`, no new threads can enter and no old threads remain. +`destroy_dev(9)` 将字符设备标记为已消失并等待所有正在传输中的线程在返回之前离开设备的 d_* 方法。在 `destroy_dev` 之后,没有新线程可以进入,也没有旧线程留下。 -`bus_teardown_intr(9)` removes an interrupt handler and waits for any in-flight instance of that handler to complete. +`bus_teardown_intr(9)` 移除中断处理程序并等待该处理程序的任何正在传输的实例完成。 -A correct `detach` function in a driver that has all of these resources looks roughly like: +具有所有这些资源的驱动程序中正确的 `detach` 函数大致如下: ```c static int @@ -1689,45 +1689,45 @@ secdev_detach(device_t dev) } ``` -The order matters. We first stop accepting new work, then drain all in-flight work, then free the resources that the in-flight work was using. If we freed resources first and drained second, a callout still running could touch freed memory. That is a classic detach-time use-after-free, and it is a security bug, not just a crash. +顺序很重要。我们首先停止接受新工作,然后排干所有正在传输的工作,然后释放正在传输的工作正在使用的资源。如果我们先释放资源再排干,仍在运行的 callout 可能触及已释放的内存。那是经典的分离时释放后使用,它是安全漏洞,不仅仅是崩溃。 ### 原子操作与无锁代码 -FreeBSD provides atomic operations (`atomic_add_int`, `atomic_cmpset_int`, and so on) in `/usr/src/sys/sys/atomic_common.h` and architecture-specific headers. Atomics are useful for counters, reference counts, and simple flags. They are not a substitute for locks when multiple related fields must change together. +FreeBSD 提供原子操作(`atomic_add_int`、`atomic_cmpset_int` 等),位于 `/usr/src/sys/sys/atomic_common.h` 和特定架构的头文件中。原子操作对计数器、引用计数和简单标志很有用。当多个相关字段必须一起更改时,它们不能替代锁。 -A common beginner mistake is to say "I will use an atomic to avoid a lock". Sometimes this is correct. Often it leads to a subtly broken data structure because the atomic operation only makes one field safe, while the code really needed two fields updated together. +初学者常见的错误是说"我将使用原子操作来避免锁"。有时这是正确的。经常这会导致微妙损坏的数据结构,因为原子操作只使一个字段安全,而代码实际需要两个字段一起更新。 -The safe rule is: if you can express the invariant with a single atomic read or write, an atomic may be appropriate. If the invariant spans multiple fields or a compound condition, use a lock. +安全的规则是:如果你能用单次原子读或写表达不变量,原子操作可能是合适的。如果不变量跨越多个字段或复合条件,使用锁。 ### 引用计数作为生命周期工具 -When an object can be referenced from multiple contexts, a refcount helps manage lifetime. `refcount_init`, `refcount_acquire`, and `refcount_release` (declared in `/usr/src/sys/sys/refcount.h`) give you a simple atomic refcount. The last release returns true, at which point the caller is responsible for freeing the object. +当对象可以被多个上下文引用时,引用计数有助于管理生命周期。`refcount_init`、`refcount_acquire` 和 `refcount_release`(在 `/usr/src/sys/sys/refcount.h` 中声明)为你提供简单的原子引用计数。最后一次释放返回 true,此时调用者负责释放对象。 -Refcounts solve the classic problem where context A and context B both hold a pointer to an object. Either can finish with it first. The one that finishes last frees it. Neither needs to know whether the other is done, because the refcount tracks that for them. +引用计数解决了上下文 A 和上下文 B 都持有指向对象的指针的经典问题。任何一个都可能先完成。最后完成的那个释放它。两者都不需要知道另一个是否完成,因为引用计数为它们跟踪。 -A driver that uses a refcount on its softc, or on per-open state, can release that state safely even under concurrent access. The cost is some care at every entry and exit point to balance acquires and releases. +在其 softc 或每次打开状态上使用引用计数的驱动程序可以安全地释放该状态,即使在并发访问下。代价是在每个入口和出口点需要一些注意来平衡获取和释放。 ### 排序与内存屏障 -Modern CPUs reorder memory accesses. A write in your code may become visible to other CPUs in a different order than it was issued. This is usually invisible because locks on FreeBSD include the necessary barriers. When writing lock-free code, you may need explicit barriers (`atomic_thread_fence_acq`, `atomic_thread_fence_rel`, and variants). For almost all driver code, using a lock removes the need to think about barriers. That is another reason to prefer locks over hand-rolled lock-free constructs when you are still learning. +现代 CPU 重排序内存访问。你代码中的写入可能以与发出时不同的顺序对其他 CPU 可见。这通常是不可见的,因为 FreeBSD 上的锁包含必要的屏障。在编写无锁代码时,你可能需要显式屏障(`atomic_thread_fence_acq`、`atomic_thread_fence_rel` 及其变体)。对于几乎所有驱动程序代码,使用锁消除了考虑屏障的需要。这是在你仍在学习时优先使用锁而不是手工制作的无锁构造的另一个原因。 ### 信号与睡眠安全 -If your driver sleeps waiting for an event, using `msleep(9)`, `cv_wait(9)`, or `sx_sleep(9)`, use the interruptible variant (`msleep(..., PCATCH)`) when the wait is initiated by user space. Otherwise a stuck device can hold a process in an uninterruptible state forever, and a sufficiently patient attacker can use that to exhaust process slots. The interruptible wait lets the process be signalled. +如果你的驱动程序睡眠等待事件,使用 `msleep(9)`、`cv_wait(9)` 或 `sx_sleep(9)`,当等待由用户空间发起时使用可中断变体(`msleep(..., PCATCH)`)。否则,卡住的设备可能将进程永远保持在中断不可及的状态,而足够耐心的攻击者可以利用它来耗尽进程槽位。可中断等待让进程可以被信号中断。 -Always check the return value of a sleep. If it returns a non-zero value, the sleep was interrupted (either by a signal or by another condition), and the driver should typically unwind and return to user space. Don't assume the condition is true just because the sleep returned. +始终检查睡眠的返回值。如果它返回非零值,睡眠被中断了(要么被信号要么被另一个条件),驱动程序通常应该展开并返回用户空间。不要仅仅因为睡眠返回了就假设条件为真。 ### 速率限制与资源耗尽 -A final race-related security concern is resource exhaustion. If an attacker can call your ioctl a million times per second, and each call allocates a kilobyte of kernel memory that is not freed until close, they can drive the system out of memory. This is a denial of service attack, and a careful driver defends against it. +最后一个与竞态相关的安全问题是资源耗尽。如果攻击者可以每秒调用你的 ioctl 一百万次,每次调用分配一千字节的内核内存直到关闭才释放,他们可以将系统驱动到内存耗尽。这是拒绝服务攻击,仔细的驱动程序应该防御它。 -The defenses are: cap per-open resource use, cap global resource use, rate-limit expensive operations. FreeBSD provides `eventratecheck(9)` and `ppsratecheck(9)` in `/usr/src/sys/sys/time.h` for rate limiting, and you can build your own counters where needed. The principle is that the cost to call your driver should not be wildly asymmetric: if a single call allocates megabytes of state, either the caller needs a privilege check or the driver needs a hard cap. +防御措施是:限制每次打开的资源使用、限制全局资源使用、对昂贵操作进行速率限制。FreeBSD 在 `/usr/src/sys/sys/time.h` 中提供 `eventratecheck(9)` 和 `ppsratecheck(9)` 用于速率限制,你可以在需要时构建自己的计数器。原则是调用你的驱动程序的成本不应严重不对称:如果单次调用分配了 MB 级别的状态,要么调用者需要权限检查,要么驱动程序需要硬性上限。 ### 基于时代的回收:无锁读取器惯用法 -For read-mostly data structures where readers must never block and writers are rare, FreeBSD provides an epoch-based reclamation framework in `/usr/src/sys/sys/epoch.h`. Readers enter an epoch, access the shared data without taking a lock, and exit the epoch. Writers update the data (usually by replacing a pointer) and then wait for all readers currently in an epoch to exit before freeing the old data. +对于读多写少、读者必须永远不阻塞、写者很少的数据结构,FreeBSD 在 `/usr/src/sys/sys/epoch.h` 中提供了基于时代的回收框架。读者进入一个时代,在不获取锁的情况下访问共享数据,然后退出时代。写者更新数据(通常通过替换指针),然后等待当前在时代中的所有读者退出后再释放旧数据。 -The idiom is useful for driver code that has frequent reads on a hot path and wants to avoid locking overhead there. For example, a network driver that looks up a rule from a routing-table-like structure on every packet may want readers to run lock-free. +这个惯用法对于在频繁路径上有大量读取并希望避免那里加锁开销的驱动程序代码很有用。例如,一个在每个数据包上从类似路由表的结构中查找规则的网络驱动程序可能希望读者无锁运行。 ```c epoch_enter(secdev_epoch); @@ -1737,7 +1737,7 @@ do_stuff(rule); epoch_exit(secdev_epoch); ``` -A writer replacing the rule set: +替换规则集的写者: ```c new_rules = build_new_rules(); @@ -1747,60 +1747,60 @@ epoch_wait(secdev_epoch); free(old_rules, M_SECDEV); ``` -`epoch_wait` blocks until all readers that entered before the store have exited. After it returns, no reader can still be using `old_rules`, so it is safe to free. +`epoch_wait` 阻塞直到所有在存储之前进入的读者都已退出。在它返回后,没有读者仍然在使用 `old_rules`,所以释放是安全的。 -The security considerations with epochs are subtle: +时代的安全考虑是微妙的: -A reader inside an epoch may hold a pointer to something that is about to be replaced. The reader must finish using the pointer before exiting the epoch; any use after the exit is a use-after-free. +时代内的读者可能持有指向即将被替换的东西的指针。读者必须在退出时代之前完成使用该指针;退出后的任何使用都是释放后使用。 -A reader inside an epoch cannot sleep. The epoch is an asymmetric lock: writers wait on readers, so a reader that sleeps can starve writers indefinitely. +时代内的读者不能睡眠。时代是一个不对称锁:写者等待读者,所以睡眠的读者可能无限期地饿死写者。 -The writer must ensure that the replacement operation is atomic from a reader's perspective. For a single pointer, an atomic store does the job. For more complex updates, two epochs or a read-copy-update sequence may be needed. +写者必须确保替换操作从读者的角度来看是原子的。对于单个指针,原子存储可以完成工作。对于更复杂的更新,可能需要两个时代或读-复制-更新序列。 -Used correctly, epochs give very high performance on read-heavy workloads. Used incorrectly (a reader that sleeps, or a writer that fails to wait), they produce races that are hard to reproduce and hard to diagnose. Beginners should prefer locks until the performance profile justifies the complexity of epoch-based code. +正确使用时,时代在读密集工作负载上提供非常高的性能。错误使用时(睡眠的读者,或未等待的写者),它们产生难以重现和难以诊断的竞态。初学者应该优先使用锁,直到性能分析证明基于时代的代码的复杂性是合理的。 ### 第5节总结 竞态和 TOCTOU 漏洞是基于时间的漏洞。它们发生在两个上下文在没有协调的情况下触及共享数据时,或者驱动程序在两个不同时间检查条件并对其采取行动时。防止它们的工具很简单:将用户数据复制到内核一次并从副本工作;在每次访问共享可变状态时使用锁;定义每个锁保护什么并在完整的检查-行动序列中持有它;在释放异步工作触及的结构之前排空异步工作;使用引用计数进行多上下文生命周期管理。 -None of this is new to concurrency programming. What is new is the mindset: a race in a driver is not merely a correctness problem. It is a security problem, because an attacker can often arrange the timing they need to exploit it. The next section steps back from timing and looks at a different kind of defense: privilege checks, credentials, and access control. +这些都不是并发编程的新内容。新的是思维方式:驱动程序中的竞态不仅仅是正确性问题。它是安全问题,因为攻击者通常可以安排他们利用竞态所需的时序。下一节从时序转向不同类型的防御:权限检查、凭据和访问控制。 ## 第6节:访问控制与权限强制执行 并非驱动程序暴露的每个操作都应该对每个用户可用。读取温度传感器对每个人都可能没问题。重新编程设备的固件应该需要权限。向存储控制器写入原始字节可能需要更多权限。本节是关于 FreeBSD 驱动程序如何使用内核的凭据和权限机制来决定调用者是否被允许执行其请求的操作。 -The tools are `struct ucred`, `priv_check(9)` and `priv_check_cred(9)`, jail-aware checks, securelevel checks, and the broader MAC and Capsicum frameworks. +工具是 `struct ucred`、`priv_check(9)` 和 `priv_check_cred(9)`、jail 感知检查、安全级别检查以及更广泛的 MAC 和 Capsicum 框架。 ### 调用者的凭据:struct ucred -Every thread running in the FreeBSD kernel carries a credential, a pointer to a `struct ucred`. The credential records who the thread is running as, which jail they are confined to, which groups they belong to, and other security attributes. From inside a driver, the credential is almost always reached via `td->td_ucred`, where `td` is the `struct thread *` passed to your entry point. +在 FreeBSD 内核中运行的每个线程都携带一个凭据,即指向 `struct ucred` 的指针。凭据记录线程以谁的身份运行、被限制在哪个 jail 中、属于哪些组以及其他安全属性。在驱动程序内部,凭据几乎总是通过 `td->td_ucred` 访问,其中 `td` 是传递给你的入口点的 `struct thread *`。 -The structure is declared in `/usr/src/sys/sys/ucred.h`. The fields most relevant to drivers are: +该结构在 `/usr/src/sys/sys/ucred.h` 中声明。与驱动程序最相关的字段是: -`cr_uid`, the effective user ID. Usually what you check to answer "is this root". +`cr_uid`,有效用户 ID。通常用于检查"这是否是 root"。 -`cr_ruid`, the real user ID. +`cr_ruid`,真实用户 ID。 -`cr_gid`, the effective group ID. +`cr_gid`,有效组 ID。 -`cr_prison`, a pointer to the jail the process is in. All processes have one. Unjailed processes belong to `prison0`. +`cr_prison`,指向进程所在 jail 的指针。所有进程都有一个。未被 jail 的进程属于 `prison0`。 -`cr_flags`, a small set of flags including `CRED_FLAG_CAPMODE`, which indicates capability mode (Capsicum). +`cr_flags`,一小部分标志,包括 `CRED_FLAG_CAPMODE`,表示能力模式(Capsicum)。 -Do not check `cr_uid == 0` as your privilege gate. That is a common mistake and it is almost always wrong. The correct gate is `priv_check(9)`, which handles jails, securelevel, and MAC policies correctly. Checking `cr_uid` manually bypasses all of that and gives root inside a jail the same power as root on the host, which is not what jails are for. +不要将 `cr_uid == 0` 作为你的权限门控。这是一个常见错误,几乎总是错的。正确的门控是 `priv_check(9)`,它正确处理 jail、安全级别和 MAC 策略。手动检查 `cr_uid` 绕过了所有这些,并给 jail 内的 root 与主机上 root 相同的权力,这不是 jail 的用途。 ### priv_check 和 priv_check_cred -The canonical primitive for "may the caller do this privileged thing" is `priv_check(9)`. Its prototype, from `/usr/src/sys/sys/priv.h`: +"调用者是否可以做这件特权事情"的标准原语是 `priv_check(9)`。它的原型,来自 `/usr/src/sys/sys/priv.h`: ```c int priv_check(struct thread *td, int priv); int priv_check_cred(struct ucred *cred, int priv); ``` -`priv_check` operates on the current thread. `priv_check_cred` operates on an arbitrary credential; you use it when the credential to check is not the running thread's, for example when validating an operation on behalf of a file that was opened earlier. +`priv_check` 操作当前线程。`priv_check_cred` 操作任意凭据;当要检查的凭据不是运行线程的凭据时使用它,例如当验证代表之前打开的文件的操作时。 -Both return 0 if the privilege is granted and an errno (typically `EPERM`) if not. The driver's pattern is almost always: +两者在权限被授予时返回 0,在未授予时返回一个 errno(通常是 `EPERM`)。驱动程序的模式几乎总是: ```c error = priv_check(td, PRIV_DRIVER); @@ -1808,25 +1808,25 @@ if (error != 0) return (error); ``` -The `priv` argument selects one of several dozen named privileges. The full list lives in `/usr/src/sys/sys/priv.h` and covers areas like filesystem, networking, virtualization, and drivers. For most device drivers, the relevant names are: +`priv` 参数选择几十个命名权限之一。完整列表在 `/usr/src/sys/sys/priv.h` 中,涵盖文件系统、网络、虚拟化和驱动程序等领域。对于大多数设备驱动程序,相关的名称是: -`PRIV_DRIVER`, the generic driver privilege. Grants access to operations restricted to administrators. +`PRIV_DRIVER`,通用驱动程序权限。授予对限制为管理员的操作的访问。 -`PRIV_IO`, raw I/O to hardware. More restrictive than `PRIV_DRIVER`, appropriate for operations that bypass the driver's usual abstractions and talk directly to hardware. +`PRIV_IO`,对硬件的原始 I/O。比 `PRIV_DRIVER` 更严格,适合绕过驱动程序通常抽象并直接与硬件通信的操作。 -`PRIV_KLD_LOAD`, used by the module loader. You will not typically use this from a driver. +`PRIV_KLD_LOAD`,由模块加载器使用。你通常不会从驱动程序中使用它。 -`PRIV_NET_*`, used by network-related operations. +`PRIV_NET_*`,由网络相关操作使用。 -Several dozen more. Read the list in `priv.h` and pick the most specific match for the operation being gated. `PRIV_DRIVER` is a reasonable default when nothing more specific fits. +还有几十个。阅读 `priv.h` 中的列表并为被门控的操作选择最具体的匹配。当没有更具体的匹配时,`PRIV_DRIVER` 是合理的默认选择。 -A real-world example from the kernel: in `/usr/src/sys/dev/mmc/mmcsd.c`, the driver checks `priv_check(td, PRIV_DRIVER)` before allowing certain ioctls that would let a user reprogram the storage controller. In `/usr/src/sys/dev/syscons/syscons.c`, the console driver checks `priv_check(td, PRIV_IO)` before allowing operations that manipulate the hardware directly, since those bypass the normal tty abstraction. +内核中的一个真实例子:在 `/usr/src/sys/dev/mmc/mmcsd.c` 中,驱动程序在允许某些可能让用户重新编程存储控制器的 ioctl 之前检查 `priv_check(td, PRIV_DRIVER)`。在 `/usr/src/sys/dev/syscons/syscons.c` 中,控制台驱动程序在允许直接操作硬件的操作之前检查 `priv_check(td, PRIV_IO)`,因为那些操作绕过了正常的 tty 抽象。 ### Jail 感知 -FreeBSD jails (jail(8) and jail(9)) partition the system into compartments. Processes inside a jail share the host's kernel but have a restricted view of the system: their own hostname, their own network visibility, their own filesystem root, and reduced privileges. Inside a jail, `priv_check` refuses many privileges that would otherwise be granted to root. This is one of the main reasons to use `priv_check` instead of checking `cr_uid == 0`. +FreeBSD jail(jail(8) 和 jail(9))将系统划分为隔离区。jail 内的进程共享主机的内核,但拥有受限的系统视图:自己的主机名、自己的网络可见性、自己的文件系统根目录,以及减少的权限。在 jail 内,`priv_check` 拒绝许多否则会授予 root 的权限。这是使用 `priv_check` 而不是检查 `cr_uid == 0` 的主要原因之一。 -Some operations, however, make no sense inside a jail at all. Reprogramming device firmware, for example, is a host operation. A jailed root user should never be able to do it. For these, add an explicit jail check: +然而,有些操作在 jail 内根本没意义。例如,重新编程设备固件是主机操作。被 jail 的 root 用户永远不应该能够做这件事。对于这些,添加显式的 jail 检查: ```c if (jailed(td->td_ucred)) @@ -1836,24 +1836,24 @@ if (error != 0) return (error); ``` -The `jailed()` macro, defined in `/usr/src/sys/sys/jail.h`, returns true if the credential's prison is anything other than `prison0`. For operations that should never be performed from within a jail, check this first. +`jailed()` 宏定义在 `/usr/src/sys/sys/jail.h` 中,当凭据的 prison 是 `prison0` 以外的任何东西时返回 true。对于永远不应从 jail 内执行的操作,首先检查这个。 -For operations that should be allowed inside a jail but with restrictions, use the jail's own fields. `cred->cr_prison->pr_flags` carries per-jail flags; the jail framework also has helpers for checking whether certain capabilities are allowed in the jail. In most driver work you will not go beyond the simple `jailed()` check. +对于应该被允许在 jail 内但有限制的操作,使用 jail 自身的字段。`cred->cr_prison->pr_flags` 携带每 jail 标志;jail 框架还有用于检查 jail 中是否允许某些能力的辅助函数。在大多数驱动程序工作中,你不会超出简单的 `jailed()` 检查。 ### 安全级别 -FreeBSD supports a systemwide setting called securelevel. At securelevel 0, the system behaves normally. At higher securelevels, certain operations are restricted even for root: raw disk writes may be disabled, the system time cannot be set backwards, kernel modules cannot be unloaded, and so on. The rationale is that on a well-secured server, raising the securelevel at boot means an attacker who later gains root cannot disable logging, install a rootkit module, or rewrite core system files. +FreeBSD 支持一个名为安全级别的系统级设置。在安全级别 0,系统正常运行。在更高的安全级别,某些操作即使对 root 也被限制:原始磁盘写入可能被禁用,系统时间不能向后设置,内核模块不能卸载等等。理由是,在一个安全性良好的服务器上,在引导时提高安全级别意味着后来获得 root 权限的攻击者无法禁用日志、安装 rootkit 模块或重写核心系统文件。 -For drivers, the relevant helpers are declared in `/usr/src/sys/sys/priv.h`: +对于驱动程序,相关的辅助函数在 `/usr/src/sys/sys/priv.h` 中声明: ```c int securelevel_gt(struct ucred *cr, int level); int securelevel_ge(struct ucred *cr, int level); ``` -Their return values are counterintuitive and worth studying carefully. They return 0 when the securelevel is **not** above or at the threshold (that is, the operation is allowed), and `EPERM` when the securelevel **is** above or at the threshold (the operation should be denied). In other words, the return value is ready to be used directly as an error code. +它们的返回值是反直觉的,值得仔细研究。当安全级别**未**超过或达到阈值时(即操作被允许),它们返回 0;当安全级别**已**超过或达到阈值时(操作应被拒绝),返回 `EPERM`。换句话说,返回值可以直接用作错误代码。 -The usage pattern for a driver that should refuse to modify hardware at securelevel 1 or higher is: +对于应在安全级别 1 或更高时拒绝修改硬件的驱动程序,使用模式是: ```c error = securelevel_gt(td->td_ucred, 0); @@ -1861,13 +1861,13 @@ if (error != 0) return (error); ``` -Read carefully: this says "return an error if the securelevel is greater than 0". When securelevel is 0 (normal), `securelevel_gt(cred, 0)` returns 0 and the check passes. When securelevel is 1 or higher, it returns `EPERM` and the operation is refused. +仔细阅读:这说的是"如果安全级别大于 0 则返回错误"。当安全级别为 0(正常)时,`securelevel_gt(cred, 0)` 返回 0,检查通过。当安全级别为 1 或更高时,它返回 `EPERM`,操作被拒绝。 -Most drivers do not need securelevel checks. They make sense for operations that are potentially system-destabilizing: reprogramming firmware, writing to raw disk sectors, lowering the system clock, and so on. +大多数驱动程序不需要安全级别检查。它们适用于可能破坏系统稳定性的操作:重新编程固件、写入原始磁盘扇区、降低系统时钟等。 ### 分层检查 -A driver that wants to be defense-in-depth can layer these checks: +想要纵深防御的驱动程序可以分层这些检查: ```c static int @@ -1894,21 +1894,21 @@ secdev_reset_hardware(struct secdev_softc *sc, struct thread *td) } ``` -Each check answers a different question. `jailed()` asks whether we are in the right security domain. `securelevel_gt` asks whether the system administrator has told the kernel to refuse this kind of operation. `priv_check` asks whether this particular thread has the appropriate privilege. +每个检查回答不同的问题。`jailed()` 询问我们是否在正确的安全域中。`securelevel_gt` 询问系统管理员是否告诉内核拒绝此类操作。`priv_check` 询问这个特定线程是否有适当的权限。 -In many drivers, only the `priv_check` is strictly necessary, because it handles jails and securelevel through the MAC framework and the privilege definitions themselves. The explicit `jailed()` and `securelevel_gt` calls are appropriate for operations with known host-wide consequences. When in doubt, start with `priv_check(td, PRIV_DRIVER)` and add more layers only when you can explain what each additional check buys. +在许多驱动程序中,只有 `priv_check` 是严格必需的,因为它通过 MAC 框架和权限定义本身处理 jail 和安全级别。显式的 `jailed()` 和 `securelevel_gt` 调用适合具有已知主机范围后果的操作。有疑问时,从 `priv_check(td, PRIV_DRIVER)` 开始,只有当你能解释每个额外检查带来什么好处时才添加更多层。 ### Open、Ioctl 和其他路径上的凭据 -When designing privilege checks, think about where in the driver's lifecycle they live. There are two main places: +在设计权限检查时,考虑它们在驱动程序生命周期中的位置。有两个主要位置: -At open time. If only privileged users should be able to open the device, check privileges in `d_open`. This is simplest and gives per-open enforcement: once a user has opened the device, they are free to do what that device allows. This is the model used, for example, by `/dev/mem`, which is openable only with appropriate privilege. +在打开时。如果只有特权用户应该能够打开设备,在 `d_open` 中检查权限。这最简单并提供每次打开的强制执行:一旦用户打开了设备,他们就可以自由地做该设备允许的任何事情。这是 `/dev/mem` 使用的模型,只有具有适当权限的用户才能打开它。 -At operation time. If the device supports multiple operations with different privilege requirements, check each operation independently. A storage controller might allow reading device status to any user, reading SMART data to the owner of the device file, and triggering firmware update only to users with `PRIV_DRIVER`. Each operation has its own gate. +在操作时。如果设备支持具有不同权限要求的多个操作,独立检查每个操作。存储控制器可能允许任何用户读取设备状态,允许设备文件所有者读取 SMART 数据,只允许具有 `PRIV_DRIVER` 的用户触发固件更新。每个操作有自己的门控。 -A driver can combine both: a privilege check on open to keep unprivileged users out entirely, and additional checks on specific ioctls for operations that need more. +驱动程序可以结合两者:打开时进行权限检查以完全阻止非特权用户,以及对需要更多权限的特定 ioctl 进行额外检查。 -An open-time check is easy to implement: +打开时检查很容易实现: ```c static int @@ -1925,13 +1925,13 @@ secdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td) } ``` -An ioctl-time check follows the same pattern; the `struct thread *td` argument is available in every entry point. +ioctl 时检查遵循相同的模式;`struct thread *td` 参数在每个入口点都可用。 ### 设备文件权限 -Independent of in-driver privilege checks, FreeBSD also applies the usual UNIX permission model to device files themselves. When your driver calls `make_dev_s` or `make_dev_credf` to create a device node, you choose an owner, group, and mode. Those apply at the filesystem level: a user who fails the permission check on the device node never reaches your `d_open`. +独立于驱动程序内部权限检查,FreeBSD 还对设备文件本身应用通常的 UNIX 权限模型。当你的驱动程序调用 `make_dev_s` 或 `make_dev_credf` 创建设备节点时,你选择所有者、组和模式。这些在文件系统级别应用:未通过设备节点权限检查的用户永远不会到达你的 `d_open`。 -The `make_dev_args` structure, declared in `/usr/src/sys/sys/conf.h`, includes `mda_uid`, `mda_gid`, and `mda_mode` fields. The pattern is: +`make_dev_args` 结构在 `/usr/src/sys/sys/conf.h` 中声明,包含 `mda_uid`、`mda_gid` 和 `mda_mode` 字段。模式是: ```c struct make_dev_args args; @@ -1945,66 +1945,66 @@ args.mda_si_drv1 = sc; error = make_dev_s(&args, &sc->sc_cdev, "secdev"); ``` -`UID_ROOT` and `GID_OPERATOR` are conventional symbolic names. The mode `0640` means owner can read and write, group can read, others have no access. Choose these thoughtfully. A device that could expose sensitive data or cause hardware damage should not be world-readable or world-writable. +`UID_ROOT` 和 `GID_OPERATOR` 是传统的符号名称。模式 `0640` 意味着所有者可读写,组可读,其他人无访问权限。谨慎选择这些。可能暴露敏感数据或造成硬件损坏的设备不应该是全局可读或全局可写的。 -The usual pattern for a privileged device is mode `0600` (root-only) or `0660` (root and a specific group, often `operator` or `wheel`). Mode `0640` is common for devices readable by a trusted group for monitoring purposes. Modes like `0666` (world-writable) are almost never appropriate, even for simple pseudo-devices, unless the device really does nothing that should be restricted. +特权设备的常见模式是 `0600`(仅 root)或 `0660`(root 和特定组,通常是 `operator` 或 `wheel`)。模式 `0640` 对于受信任组出于监控目的可读的设备很常见。像 `0666`(全局可写)的模式几乎永远不合适,即使是简单的伪设备,除非该设备确实没有需要限制的功能。 ### Devfs 规则 -Even if your driver creates the device node with a conservative mode, the system administrator can change that through devfs rules. A devfs rule can relax or restrict permissions based on device name, jail, and other criteria. Your driver should not assume the mode it set at creation is the mode the device will have at runtime; it should continue to apply its in-kernel checks regardless. The filesystem mode and the in-kernel `priv_check` defend different attackers; keep both. +即使你的驱动程序以保守模式创建设备节点,系统管理员也可以通过 devfs 规则更改它。devfs 规则可以基于设备名称、jail 和其他标准放宽或限制权限。你的驱动程序不应假设创建时设置的模式就是运行时的模式;它应该继续应用其内核内检查。文件系统模式和内核内 `priv_check` 防御不同的攻击者;保持两者。 ### MAC 框架 -The FreeBSD Mandatory Access Control framework, declared in `/usr/src/sys/security/mac/`, lets policy modules hook into the kernel and make access decisions based on richer labels than UNIX permissions. A MAC policy can, for example, restrict which users can access which devices even if UNIX permissions allow it, or log every use of a sensitive operation. +FreeBSD 强制访问控制框架在 `/usr/src/sys/security/mac/` 中声明,它让策略模块挂钩到内核中并基于比 UNIX 权限更丰富的标签做出访问决策。MAC 策略可以,例如,限制哪些用户可以访问哪些设备即使 UNIX 权限允许,或记录每次敏感操作的使用。 -For driver authors, the point is this: `priv_check` already consults the MAC framework. When you use `priv_check`, you are opting into whatever MAC policies the administrator has configured. If you bypass `priv_check` and roll your own privilege check using `cr_uid`, you bypass MAC as well. That is one more reason to always use `priv_check`. +对于驱动程序作者,要点是:`priv_check` 已经咨询了 MAC 框架。当你使用 `priv_check` 时,你选择加入了管理员配置的任何 MAC 策略。如果你绕过 `priv_check` 并使用 `cr_uid` 自行检查权限,你也绕过了 MAC。这是始终使用 `priv_check` 的又一个原因。 -Writing your own MAC policy module is beyond the scope of this chapter; the MAC framework is a substantial subject and has its own documentation. The key takeaway is simply that MAC exists, `priv_check` honors it, and you should not fight it. +编写你自己的 MAC 策略模块超出了本章的范围;MAC 框架是一个相当大的主题,有自己的文档。关键的结论只是 MAC 存在,`priv_check` 遵守它,你不应该与之对抗。 -**A brief note on MAC policies shipped with FreeBSD.** The base system includes several MAC policies as loadable modules: `mac_bsdextended(4)` for file-system rule lists, `mac_portacl(4)` for network-port access control, `mac_biba(4)` for Biba integrity policy, `mac_mls(4)` for Multi-Level Security labels, and `mac_partition(4)` for partitioning processes into isolated groups. None of these need to be understood in detail by a driver author; the key point is that your driver, by using `priv_check`, gets their policy decisions for free. An administrator who enables `mac_bsdextended` gets additional filesystem-level restrictions; your driver does not need to know. +**关于 FreeBSD 附带的 MAC 策略的简要说明。** 基本系统包括几个 MAC 策略作为可加载模块:用于文件系统规则列表的 `mac_bsdextended(4)`,用于网络端口访问控制的 `mac_portacl(4)`,用于 Biba 完整性策略的 `mac_biba(4)`,用于多级安全标签的 `mac_mls(4)`,以及用于将进程分区为隔离组的 `mac_partition(4)`。驱动程序作者不需要详细了解这些;关键是你使用的驱动程序通过 `priv_check` 免费获得它们的策略决策。启用 `mac_bsdextended` 的管理员获得额外的文件系统级限制;你的驱动程序不需要知道。 -**MAC and the device node.** When you create a device with `make_dev_s`, the MAC framework may assign a label to the device node. Policies consult that label when access is attempted. A driver does not interact with labels directly; the framework handles it. But understanding that a label exists explains why, on a MAC-enabled system, access to your device may be refused even when UNIX permissions allow it. That is not a bug; it is MAC doing its job. +**MAC 与设备节点。** 当你用 `make_dev_s` 创建设备时,MAC 框架可能为设备节点分配一个标签。当尝试访问时,策略咨询该标签。驱动程序不直接与标签交互;框架处理它。但理解标签存在解释了为什么在启用 MAC 的系统上,即使 UNIX 权限允许,对你的设备的访问也可能被拒绝。那不是漏洞;那是 MAC 在做它的工作。 ### Capsicum 与能力模式 -Capsicum, declared in `/usr/src/sys/sys/capsicum.h`, is a capability system bolted onto FreeBSD. A process in capability mode has lost access to most global namespaces (no new file opens, no network with side effects, no arbitrary ioctl, and so on). It can only operate on file descriptors it already holds, and those file descriptors may themselves have limited rights (read only, write only, certain ioctls only, and so on). +Capsicum 在 `/usr/src/sys/sys/capsicum.h` 中声明,是一个附加到 FreeBSD 上的能力系统。处于能力模式的进程已经失去了对大多数全局命名空间的访问(没有新文件打开,没有带副作用的网络,没有任意 ioctl 等等)。它只能操作它已经持有的文件描述符,而这些文件描述符本身可能具有有限的权利(只读、只写、仅某些 ioctl 等等)。 -Capsicum was introduced to FreeBSD through the work of Robert Watson and collaborators. It sits alongside the traditional UNIX permission model and adds a second, more granular layer. Where UNIX permissions ask "can this user access this resource by name", Capsicum asks "does this process have a capability for this specific object". The two layers work together: the user must have UNIX permission to open the file in the first place, but once the file descriptor exists, Capsicum can further restrict what the holder of the descriptor can do with it. +Capsicum 通过 Robert Watson 及其合作者的工作引入到 FreeBSD。它与传统的 UNIX 权限模型并排,添加了第二个更细粒度的层。UNIX 权限问的是"这个用户能否按名称访问这个资源",Capsicum 问的是"这个进程是否拥有这个特定对象的能力"。两层协同工作:用户首先必须有 UNIX 权限才能打开文件,但一旦文件描述符存在,Capsicum 可以进一步限制描述符持有者可以用它做什么。 -For a driver, the main Capsicum concern is: some of your ioctls may be inappropriate for a process in capability mode. The helper `IN_CAPABILITY_MODE(td)`, defined in `capsicum.h`, tells you whether the calling thread is in capability mode. A driver can check it and refuse operations that are unsafe: +对于驱动程序,主要的 Capsicum 关注点是:你的一些 ioctl 可能不适合处于能力模式的进程。辅助函数 `IN_CAPABILITY_MODE(td)` 定义在 `capsicum.h` 中,告诉你调用线程是否处于能力模式。驱动程序可以检查它并拒绝不安全的操作: ```c if (IN_CAPABILITY_MODE(td)) return (ECAPMODE); ``` -This is appropriate for operations with global side effects that a capability-mode process should not have access to. Examples might be an ioctl that reconfigures the global driver state, an ioctl that affects other processes or other file descriptors, or an ioctl that performs an operation that requires querying the global filesystem namespace. If your driver's ioctl needs to touch something that is not already named by the file descriptor it was called on, a capability-mode check is appropriate. +这适合具有全局副作用的、能力模式进程不应访问的操作。例如可能重新配置全局驱动程序状态的 ioctl、影响其他进程或其他文件描述符的 ioctl,或执行需要查询全局文件系统命名空间的操作的 ioctl。如果你的驱动程序的 ioctl 需要触及不是已经由调用它的文件描述符命名的东西,能力模式检查是合适的。 -For most driver operations, however, the Capsicum story is simpler: the process that holds the file descriptor was granted the rights it needed when the descriptor was given to it. The driver does not need to re-check those rights; the file-descriptor layer already did. Just make sure your driver supports the normal cap-rights flow (it almost certainly does by default) and consider which individual ioctls should be marked with `CAP_IOCTL_*` rights at the VFS layer. +然而,对于大多数驱动程序操作,Capsicum 的故事更简单:持有文件描述符的进程在描述符被交给它时就被授予了它需要的权利。驱动程序不需要重新检查这些权利;文件描述符层已经做了。只需确保你的驱动程序支持正常的 cap-rights 流程(它几乎肯定默认就支持)并考虑哪些单独的 ioctl 应该在 VFS 层用 `CAP_IOCTL_*` 权限标记。 -**Cap rights at ioctl granularity.** FreeBSD allows a file descriptor to be restricted to a specific subset of ioctls via `cap_ioctls_limit(2)`. For example, a process can hold a file descriptor that allows `FIOASYNC` and `FIONBIO` but no other ioctls. The restriction is enforced by the VFS layer, not by your driver, but the set of ioctls you expose is what defines what can be selected for restriction. A driver that implements only meaningful, well-documented ioctls makes it easier for consumers to apply sensible cap-ioctl restrictions. +**ioctl 粒度上的能力权限。** FreeBSD 允许通过 `cap_ioctls_limit(2)` 将文件描述符限制为特定子集的 ioctl。例如,一个进程可以持有一个允许 `FIOASYNC` 和 `FIONBIO` 但不允许其他 ioctl 的文件描述符。该限制由 VFS 层强制执行,而不是你的驱动程序,但你暴露的 ioctl 集合定义了哪些可以被选择进行限制。只实现有意义的、文档齐全的 ioctl 的驱动程序使使用者更容易应用合理的能力-ioctl 限制。 -**Examining Capsicum usage in the tree.** For real-world examples of Capsicum-aware code, look at `/usr/src/sys/net/if_tuntap.c` alongside the core capability files under `/usr/src/sys/kern/sys_capability.c`. Most individual drivers rely on the VFS layer to enforce `caprights`, and only add an explicit `IN_CAPABILITY_MODE(td)` check on the handful of operations with global side effects. The pattern is consistent: preserve the normal behavior, add an `IN_CAPABILITY_MODE` check where operations would be unsafe, and document which ioctls are sandbox-safe. +**检查树中的 Capsicum 使用情况。** 有关 Capsicum 感知代码的真实世界示例,请查看 `/usr/src/sys/net/if_tuntap.c` 以及 `/usr/src/sys/kern/sys_capability.c` 下的核心能力文件。大多数单个驱动程序依赖 VFS 层来强制执行 `caprights`,只在少数具有全局副作用的操作上添加显式的 `IN_CAPABILITY_MODE(td)` 检查。模式是一致的:保留正常行为,在操作不安全的添加 `IN_CAPABILITY_MODE` 检查,并记录哪些 ioctl 是沙箱安全的。 ### 带安全标志的 Sysctl -Many drivers expose tunables and statistics through sysctls. A sysctl that exposes sensitive information, or that can be set to change driver behaviour, should use appropriate flags. From `/usr/src/sys/sys/sysctl.h`: +许多驱动程序通过 sysctl 暴露可调参数和统计信息。暴露敏感信息或可以设置来改变驱动程序行为的 sysctl 应该使用适当的标志。来自 `/usr/src/sys/sys/sysctl.h`: -`CTLFLAG_SECURE` (value `0x08000000`) asks the sysctl framework to consult `priv_check(PRIV_SYSCTL_SECURE)` before allowing the operation. It is useful for sysctls that should not be changed at elevated securelevel. +`CTLFLAG_SECURE` (值为 `0x08000000`) 让 sysctl 框架在允许操作前咨询 `priv_check(PRIV_SYSCTL_SECURE)`。这对于不应在升高的安全级别下更改的 sysctl 很有用。 -`CTLFLAG_PRISON` allows the sysctl to be visible and writable from inside a jail (rarely wanted for drivers). +`CTLFLAG_PRISON` 允许 sysctl 在 jail 内部可见和可写(驱动程序很少需要)。 -`CTLFLAG_CAPRD` and `CTLFLAG_CAPWR` allow the sysctl to be read or written from capability mode. By default, sysctls are inaccessible in capability mode. +`CTLFLAG_CAPRD` 和 `CTLFLAG_CAPWR` 允许 sysctl 从能力模式读取或写入。默认情况下,sysctl 在能力模式下是不可访问的。 -`CTLFLAG_TUN` makes the sysctl settable as a loader tunable (from `/boot/loader.conf`). +`CTLFLAG_TUN` 使 sysctl 可作为加载器可调参数设置(从 `/boot/loader.conf`)。 -`CTLFLAG_RD` vs `CTLFLAG_RW` determines read-only vs read-write access; prefer `CTLFLAG_RD` for anything that exposes state, and be deliberate about what you make writable. +`CTLFLAG_RD` 与 `CTLFLAG_RW` 决定只读与读写访问;对于任何暴露状态的 sysctl 优先使用 `CTLFLAG_RD`,并审慎决定哪些是可写的。 -A sysctl that exposes a driver-internal buffer for debugging should typically be `CTLFLAG_RD | CTLFLAG_SECURE` at minimum, and possibly not exist at all in production builds. +暴露驱动程序内部缓冲区用于调试的 sysctl 通常至少应为 `CTLFLAG_RD | CTLFLAG_SECURE`,可能根本不应存在于生产构建中。 ### 完整的权限门控 Ioctl -Putting the pieces together, here is what a privilege-gated ioctl looks like, end to end: +将各部分组合在一起,这里是一个端到端的权限门控 ioctl 的样子: ```c static int @@ -2044,15 +2044,15 @@ secdev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, } ``` -Different commands get different gates. The status command is unprivileged, since it just reads state. The reset command is the danger case, and it goes through the full layered check. +不同的命令有不同的门控。状态命令是非特权的,因为它只是读取状态。重置命令是危险情况,它经过完整的分层检查。 ### 第6节总结 FreeBSD 驱动程序中的访问控制是几个层之间的协作。设备节点上的文件系统权限决定谁可以打开它。`priv_check(9)` 函数族决定线程是否可以执行给定的特权操作。Jail 检查决定操作在调用者的安全域中是否有意义。安全级别检查决定系统管理员是否完全允许此类操作。MAC 框架让策略模块在上面添加自己的意见。Capsicum 权限限制受能力限制的进程可以做什么。 -The correct use of these tools comes down to a short list of rules: check the caller's credentials at the right points, prefer `priv_check` over ad-hoc UID checks, add `jailed()` and `securelevel_gt` when the operation has host-wide consequences, pick the most specific `PRIV_*` constant that fits the operation, and set conservative device-file modes in `make_dev_s`. +正确使用这些工具归结为一个简短的规则列表:在正确的点检查调用者的凭据,优先使用 `priv_check` 而不是临时的 UID 检查,当操作具有主机范围的后果时添加 `jailed()` 和 `securelevel_gt`,选择适合操作的最具体的 `PRIV_*` 常量,并在 `make_dev_s` 中设置保守的设备文件模式。 -The next section looks at a different kind of leak: not a privilege escape, but an information escape. Even operations that are properly gated can inadvertently reveal kernel memory contents if they are not written carefully. +下一节看不同类型的泄露:不是权限逃逸,而是信息逃逸。即使正确门控的操作也可能在不小心编写的情况下无意中揭示内核内存内容。 ## 第7节:防止信息泄露 @@ -2062,21 +2062,21 @@ The next section looks at a different kind of leak: not a privilege escape, but ### 信息泄露是如何发生的 -There are three main ways a driver leaks information: +驱动程序以三种主要方式泄露信息: -**Uninitialized structure fields copied to user space.** A structure has N defined fields plus padding and alignment slots. The code fills in the N fields and calls `copyout`. The padding goes along for the ride, carrying whatever uninitialized stack memory happened to be there. +**未初始化的结构字段被复制到用户空间。** 一个结构有 N 个定义的字段加上填充和对齐槽。代码填充了 N 个字段并调用 `copyout`。填充顺带被传递出去,携带了碰巧在那里的任何未初始化栈内存。 -**Partially initialized buffers.** The driver allocates a buffer, fills in some of it, and copies the whole buffer to user space. The uninitialized tail carries heap contents. +**部分初始化的缓冲区。** 驱动程序分配一个缓冲区,填充其中一部分,然后将整个缓冲区复制到用户空间。未初始化的尾部携带堆内容。 -**Oversized replies.** The driver is asked for `N` bytes, but returns a buffer of size `M > N`. The extra `M - N` bytes contain whatever was in the tail of the source buffer. +**过大的回复。** 驱动程序被请求 `N` 字节,但返回大小为 `M > N` 的缓冲区。额外的 `M - N` 字节包含源缓冲区尾部中的任何内容。 -**Reading beyond a NUL.** For string data, the driver copies a buffer up to its allocated size instead of up to the NUL terminator. The bytes after the NUL can carry any data that happened to be in that buffer earlier. +**读取超过 NUL。** 对于字符串数据,驱动程序复制到其分配大小而不是到 NUL 终止符。NUL 之后的字节可能携带该缓冲区中早期存在的任何数据。 -Each of these is easy to create by accident and easy to prevent once you know the pattern. +这些中的每一个都很容易意外创建,一旦你知道模式也很容易预防。 ### 填充问题 -Consider this structure: +考虑这个结构: ```c struct secdev_info { @@ -2087,9 +2087,9 @@ struct secdev_info { }; ``` -On a 64-bit system, the compiler inserts padding to align `flags` to 8 bytes. Between `version` (4 bytes) and `flags` (8 bytes), there are 4 bytes of padding. After `id` (2 bytes) and before `name` (1-byte alignment), there are 6 more bytes of padding at the end if the structure is sized up to a multiple of 8. +在 64 位系统上,编译器插入填充以将 `flags` 对齐到 8 字节。在 `version`(4 字节)和 `flags`(8 字节)之间,有 4 字节的填充。在 `id`(2 字节)和 `name`(1 字节对齐)之后,如果结构大小上调到 8 的倍数,还有 6 字节的填充。 -If your code does: +如果你的代码这样做: ```c struct secdev_info info; @@ -2102,9 +2102,9 @@ strncpy(info.name, "secdev0", sizeof(info.name)); error = copyout(&info, args->buf, sizeof(info)); ``` -then the padding bytes, which you never set, go out to user space. They contain whatever stack memory happened to be at those positions when the function was entered. That is an information leak. +那么你从未设置的填充字节就会传到用户空间。它们包含函数进入时那些位置碰巧保存的任何栈内存。这就是信息泄露。 -The fix is universal and cheap: zero the structure first. +修复是通用的且便宜的:先将结构清零。 ```c struct secdev_info info; @@ -2118,9 +2118,9 @@ strncpy(info.name, "secdev0", sizeof(info.name)); error = copyout(&info, args->buf, sizeof(info)); ``` -Now the padding is zero, as is any field you forgot to set. The cost is one call to `bzero`; the benefit is that your driver cannot leak kernel memory through this structure, no matter what fields are added later. Always zero structures before copyout. +现在填充是零,你忘记设置的任何字段也是零。代价是一次 `bzero` 调用;好处是你的驱动程序不能通过这个结构泄露内核内存,无论以后添加或删除什么字段。总是在 copyout 之前清零结构。 -An equivalent pattern using designated initializers works when you are declaring and initializing in one step: +使用指定初始化器的等效模式适用于你在一步中声明和初始化的情况: ```c struct secdev_info info = { 0 }; /* or { } in some standards */ @@ -2128,21 +2128,21 @@ info.version = 1; /* ... */ ``` -The `= { 0 }` zeros all bytes including padding. Combine this with setting the specific fields afterwards, and you have a clean pattern. +`= { 0 }` 清零所有字节包括填充。将此与之后设置特定字段结合,你就有一个干净的模式。 ### 堆分配情况 -When you allocate a buffer with `malloc(9)` and fill it before returning to user space, you have the same issue. Always use `M_ZERO` to zero-initialize, or explicitly zero the buffer before writing to it: +当你用 `malloc(9)` 分配缓冲区并在返回用户空间之前填充它时,你有同样的问题。始终使用 `M_ZERO` 进行零初始化,或者在写入前显式清零缓冲区: ```c buf = malloc(size, M_SECDEV, M_WAITOK | M_ZERO); ``` -Even if you intend to fill every byte, using `M_ZERO` is cheap insurance: if a bug causes a partial fill, the unfilled bytes are zero rather than stale heap contents. +即使你打算填充每个字节,使用 `M_ZERO` 也是便宜的保险:如果漏洞导致部分填充,未填充的字节是零而不是陈旧的堆内容。 ### 过大回复 -A subtle form of leak happens when the driver returns more data than the user asked for. Imagine an ioctl that returns a list of items: +一种微妙的泄露形式发生在驱动程序返回的数据比用户请求的多时。想象一个返回项目列表的 ioctl: ```c /* User asks for up to user_len bytes of list data. */ @@ -2152,20 +2152,20 @@ if (user_len > sc->sc_list_bytes) error = copyout(sc->sc_list, args->buf, sc->sc_list_bytes); /* BUG: wrong length */ ``` -The driver copies `sc_list_bytes` bytes regardless of what the user asked for. If `sc_list_bytes > user_len`, the driver writes past `args->buf`, which is a different bug (buffer overflow in user space). If the driver is writing to a local buffer first and then copying out, a similar error would write past the local buffer. +驱动程序复制 `sc_list_bytes` 字节,不管用户请求什么。如果 `sc_list_bytes > user_len`,驱动程序写入超过 `args->buf`,这是一个不同的漏洞(用户空间中的缓冲区溢出)。如果驱动程序先写入本地缓冲区然后复制出去,类似的错误会写入超过本地缓冲区。 -The correct pattern is to clamp the length and use the clamped length for the copy: +正确的模式是限制长度并使用限制后的长度进行复制: ```c size_t to_copy = MIN(user_len, sc->sc_list_bytes); error = copyout(sc->sc_list, args->buf, to_copy); ``` -Information leaks through oversized replies are common when driver code evolves: the original author wrote a paired check-and-copy; a later change altered one side but not the other. Every copyout should use the already-validated kernel-side length, and that length should be bounded by the user's buffer size. +通过过大回复的信息泄露在驱动程序代码演进时很常见:原始作者编写了配对的检查和复制;后来的更改修改了一侧而没有修改另一侧。每次 copyout 应使用已验证的内核侧长度,该长度应由用户缓冲区大小限制。 ### 字符串与 NUL 终止符 -Strings are a particularly rich source of information leaks because they have two different natural lengths: the length of the string (up to the NUL) and the size of the buffer it lives in. Suppose: +字符串是信息泄露的一个特别丰富的来源,因为它们有两种不同的自然长度:字符串的长度(到 NUL 为止)和它所在缓冲区的大小。假设: ```c char name[32]; @@ -2177,9 +2177,9 @@ strncpy(name, "xdev", sizeof(name)); /* copies 5 bytes, NUL-padded */ copyout(name, args->buf, sizeof(name)); /* copies all 32 bytes */ ``` -The second `strncpy` overwrites the first five bytes with "xdev\0" and then pads the rest of the buffer with NULs. That happens to be safe because `strncpy` pads with NULs when the source is shorter than the destination. But if the buffer came from `malloc(9)` without `M_ZERO`, or from a stack buffer that was written to by earlier code, bytes after the NUL may contain stale data. Copying the full buffer then leaks it. +第二个 `strncpy` 用 "xdev\0" 覆盖前五个字节,然后用 NUL 填充缓冲区的其余部分。这碰巧是安全的,因为当源短于目标时 `strncpy` 用 NUL 填充。但如果缓冲区来自没有 `M_ZERO` 的 `malloc(9)`,或来自被早期代码写入的栈缓冲区,NUL 之后的字节可能包含陈旧数据。复制整个缓冲区就会泄露它。 -The safe pattern is to copy only up to the NUL, or to zero the buffer before writing: +安全模式是只复制到 NUL,或在写入前清零缓冲区: ```c bzero(name, sizeof(name)); @@ -2187,21 +2187,21 @@ snprintf(name, sizeof(name), "%s", "secdev0"); copyout(name, args->buf, strlen(name) + 1); ``` -`snprintf` guarantees NUL termination. Zeroing first ensures the bytes after the NUL are zero. The `+ 1` in the copy length includes the NUL itself. +`snprintf` 保证 NUL 终止。先清零确保 NUL 之后的字节是零。复制长度中的 `+ 1` 包括 NUL 本身。 -Alternatively, copy only the string and let user space deal with its own padding: +或者,只复制字符串,让用户空间处理自己的填充: ```c copyout(name, args->buf, strlen(name) + 1); ``` -The cleanest pattern is to zero first and copy exactly the valid length. +最干净的模式是先清零然后精确复制有效长度。 ### 敏感数据:释放前显式清零 -When a driver allocates memory to hold sensitive data (cryptographic keys, user credentials, proprietary secrets), the memory should be zeroed explicitly before being freed. Otherwise the freed memory returns to the kernel allocator's free pool with the data still visible, and subsequent allocations from that pool may expose it. +当驱动程序分配内存来保存敏感数据(加密密钥、用户凭据、专有秘密)时,内存应在释放前显式清零。否则释放的内存带着数据仍然可见返回到内核分配器的空闲池,后续从该池的分配可能暴露它。 -FreeBSD provides `explicit_bzero(9)`, declared in `/usr/src/sys/sys/systm.h`, which zeroes memory in a way that the compiler cannot optimize away: +FreeBSD 提供 `explicit_bzero(9)`,在 `/usr/src/sys/sys/systm.h` 中声明,以编译器无法优化的方式清零内存: ```c explicit_bzero(sc->sc_secret, sc->sc_secret_len); @@ -2209,113 +2209,113 @@ free(sc->sc_secret, M_SECDEV); sc->sc_secret = NULL; ``` -Ordinary `bzero` can be eliminated by the compiler if the data is not read after being zeroed, which is exactly the situation before a free. `explicit_bzero` is guaranteed to perform the zeroing. Use it whenever sensitive data is about to be freed or go out of scope. +普通的 `bzero` 在数据清零后不被读取时可能被编译器消除,这恰好是释放前的情况。`explicit_bzero` 保证执行清零。每当敏感数据即将被释放或超出作用域时使用它。 -There is also `zfree(9)`, declared in `/usr/src/sys/sys/malloc.h`, which zeroes and frees in one call: +还有 `zfree(9)`,在 `/usr/src/sys/sys/malloc.h` 中声明,它在一个调用中清零并释放: ```c zfree(sc->sc_secret, M_SECDEV); sc->sc_secret = NULL; ``` -`zfree` knows the allocation size from the allocator metadata and zeroes that many bytes before freeing. This is usually the cleanest pattern for cryptographic material. +`zfree` 从分配器元数据知道分配大小并在释放前清零那么多字节。这通常是加密材料最干净的模式。 -For UMA zones, the equivalent is that the zone itself can be asked to zero on free, or you can `explicit_bzero` the object before calling `uma_zfree`. For stack buffers with sensitive content, `explicit_bzero` at the end of the function is the right tool. +对于 UMA 区域,等效做法是要求区域本身在释放时清零,或者你可以在调用 `uma_zfree` 前对对象使用 `explicit_bzero`。对于有敏感内容的栈缓冲区,函数末尾的 `explicit_bzero` 是正确的工具。 ### 永远不要泄露内核指针 -One specific form of information leak is returning a kernel pointer to user space. The kernel address of a softc, or of an internal buffer, is useful information to an attacker trying to exploit another bug. `printf("%p")` in log messages can also leak addresses. The general rule: do not put kernel addresses in user-visible output. +信息泄露的一种具体形式是将内核指针返回到用户空间。softc 或内部缓冲区的内核地址对试图利用另一个漏洞的攻击者来说是有用的信息。日志消息中的 `printf("%p")` 也可能泄露地址。一般规则:不要将内核地址放入用户可见的输出中。 -For sysctls and ioctls, the simplest rule is that no field in a user-facing structure should be a raw kernel pointer. If the driver wants to expose an identifier for a kernel object, use a small integer ID (an index into a table, for example), not the address of the object. Convert from one to the other inside the driver, never expose the raw pointer. +对于 sysctl 和 ioctl,最简单的规则是面向用户结构中不应有任何字段是原始内核指针。如果驱动程序想要暴露内核对象的标识符,使用小的整数 ID(例如到表中的索引),而不是对象的地址。在驱动程序内部从一种转换为另一种,永远不暴露原始指针。 -FreeBSD's `printf(9)` supports the `%p` format, which does print a pointer, but log messages in production drivers should avoid `%p` for anything where the pointer could aid exploitation. For debugging, `%p` is fine during development; before shipping the driver, audit `printf` and `log` calls to ensure no `%p` remains in paths accessible from user space. +FreeBSD 的 `printf(9)` 支持 `%p` 格式,它确实打印指针,但生产驱动程序中的日志消息应避免对指针可能有助于利用的任何东西使用 `%p`。对于调试,在开发期间 `%p` 没问题;在发布驱动程序之前,审计 `printf` 和 `log` 调用以确保从用户空间可达的路径中没有 `%p` 残留。 ### Sysctl 输出 -Sysctls that expose structures have the same rules as ioctls. Zero the structure before filling it, clamp the output length to the caller's buffer, and avoid pointer leaks. The `sysctl_handle_opaque` helper is often used for raw structures; make sure the structure is fully initialized before the handle returns. +暴露结构的 sysctl 有与 ioctl 相同的规则。在填充前清零结构,将输出长度限制在调用者缓冲区大小内,避免指针泄露。`sysctl_handle_opaque` 辅助函数通常用于原始结构;确保结构在句柄返回前完全初始化。 -A safer pattern is to expose each field as its own sysctl, using `sysctl_handle_int`, `sysctl_handle_string`, and so on. This avoids the padding problem entirely because each value is copied out as a primitive. It is also more ergonomic for users: `sysctl secdev.stats.packets` is more useful than an opaque blob they have to decode. +更安全的模式是将每个字段作为自己的 sysctl 暴露,使用 `sysctl_handle_int`、`sysctl_handle_string` 等。这完全避免了填充问题,因为每个值作为原语被复制出去。这对用户也更友好:`sysctl secdev.stats.packets` 比不透明的他们需要解码的块更有用。 ### copyout 错误 -`copyout` can fail. If the user buffer becomes unmapped between the validation and the copy, `copyout` returns `EFAULT`. Your driver must handle this cleanly: typically, return the error to the user, and make sure any partial success is rolled back. +`copyout` 可能失败。如果用户缓冲区在验证和复制之间变得未映射,`copyout` 返回 `EFAULT`。你的驱动程序必须干净地处理它:通常,将错误返回给用户,并确保任何部分成功被回滚。 -A sequence like "allocate state, fill output buffer, copyout, commit state" is safer than "commit state, copyout". If the copyout fails in the second pattern, the state is committed but the user never learned what happened. If it fails in the first pattern, nothing was committed, and the user gets a clean error. +像"分配状态、填充输出缓冲区、copyout、提交状态"这样的序列比"提交状态、copyout"更安全。如果 copyout 在第二种模式中失败,状态已提交但用户永远不知道发生了什么。如果它在第一种模式中失败,没有东西被提交,用户得到一个干净的错误。 ### 故意披露 -Some sysctls and ioctls are explicitly designed to reveal information that would otherwise be private. These need an especially careful threat model. Ask: who is allowed to call this? What do they learn? Could a less-trusted attacker who obtains that information use it for something worse? A dmesg-style sysctl that exposes recent kernel messages is fine, but only because it has been scoped and filtered; exposing raw kernel log buffers without scoping is very different. +有些 sysctl 和 ioctl 是显式设计来揭示否则为私有的信息的。这些需要特别仔细的威胁模型。问:谁被允许调用这个?他们会了解到什么?获得该信息的较低信任攻击者能否用它做更坏的事情?暴露最近内核消息的 dmesg 风格 sysctl 是可以的,但仅仅因为它已经被限定和过滤;在没有限定的情况下暴露原始内核日志缓冲区是非常不同的。 -When in doubt, a sysctl that reveals sensitive data should be gated with `CTLFLAG_SECURE`, restricted to privileged users, and exposed only through paths that users must explicitly opt into. Default to less disclosure rather than more. +有疑问时,揭示敏感数据的 sysctl 应该用 `CTLFLAG_SECURE` 门控,限制为特权用户,并仅通过用户必须明确选择加入的路径暴露。默认选择更少的披露而不是更多。 ### 内核指针哈希 -Sometimes a driver legitimately needs to expose something that identifies a kernel object, for debugging or for correlating events. The raw pointer address is the wrong answer for the reasons discussed. A better answer is a hashed or masked representation that identifies the object without revealing its address. +有时驱动程序确实需要暴露标识内核对象的东西,用于调试或关联事件。原始指针地址由于讨论过的原因不是正确答案。更好的答案是使用散列或掩码表示来标识对象而不暴露其地址。 -FreeBSD provides `%p` in `printf(9)`, which prints a pointer. It also provides a related mechanism where pointers can be "obfuscated" in user-visible output using a per-boot secret, so that two pointers in the same output are consistently distinguishable but their absolute values are not leaked. The support for this varies across subsystems; when designing your own output, consider whether a dense integer ID (an index into a table) is sufficient. Often it is. +FreeBSD 在 `printf(9)` 中提供 `%p`,它打印指针。它还提供了一种相关机制,其中指针可以在用户可见输出中使用每次引导的秘密进行"混淆",以便同一输出中的两个指针始终可区分但不泄露其绝对值。这方面的支持因子系统而异;在设计自己的输出时,考虑密集整数 ID(到表中的索引)是否足够。通常它就够了。 -For logs, `%p` is fine during development when logs are private. Before shipping, replace any `%p` in paths reachable from user space with either a debug-only guard (so the format is present only in debug builds) or with a non-pointer identifier. +对于日志,当日志是私有的时,在开发期间 `%p` 没问题。发布前,将用户空间可达路径中的任何 `%p` 替换为仅调试的保护(使格式仅存在于调试构建中)或非指针标识符。 ### 第7节总结 -Information leaks are the quieter cousin of buffer overflows: they do not crash, they do not corrupt, they merely send data to user space that should have stayed in the kernel. The tools to prevent them are simple and cheap. Zero structures before filling them. Use `M_ZERO` on heap allocations that will be copied to user space. Clamp copy lengths to the smaller of the caller's buffer and the kernel's source buffer. Use `explicit_bzero` or `zfree` for sensitive data before freeing. Keep kernel pointers out of user-visible output. Bound strings to their actual length, not their buffer size. +信息泄露是缓冲区溢出的更安静的表亲:它们不崩溃,不损坏,它们只是将本应留在内核中的数据发送到用户空间。防止它们的工具简单且便宜。在填充前清零结构。在将被复制到用户空间的堆分配上使用 `M_ZERO`。将复制长度限制在调用者缓冲区和内核源缓冲区中较小的一个。在释放前对敏感数据使用 `explicit_bzero` 或 `zfree`。将内核指针排除在用户可见输出之外。将字符串限制到其实际长度,而不是其缓冲区大小。 -A driver that applies these habits consistently will not leak information through its interfaces. The next section moves to the debugging and diagnostics side: how to log without leaking, how to debug without leaving production-hostile code behind, and how to keep the operator informed without handing an attacker a map. +一致应用这些习惯的驱动程序不会通过其接口泄露信息。下一节转向调试和诊断方面:如何在不泄露的情况下记录日志,如何在不留下对生产环境有害的代码的情况下调试,以及如何在不给攻击者地图的情况下通知运维人员。 ## 第8节:安全的日志记录与调试 每个驱动程序都会记录日志。`printf(9)` 和 `log(9)` 是驱动程序作者首先使用的工具之一,这是有充分理由的:一个放置得当的日志消息将神秘的失败转化为可读的叙述。但日志不是免费的。它们消耗磁盘空间,可能被淹没,并且可能泄露敏感数据。安全意识的驱动程序将日志记录视为一等设计关注,而不是调试的事后想法。 -This section is about writing log messages that help operators without hurting security. +本节是关于编写帮助运维人员而不损害安全的日志消息。 ### 日志记录原语 -FreeBSD drivers have two main ways to emit messages. +FreeBSD 驱动程序有两种主要的消息发送方式。 -`printf(9)`, the same name as the C library function but with kernel-specific semantics, writes to the kernel message buffer and, if the console is active, to the console. It is unconditional: every `printf` call results in a message. +`printf(9)`,与 C 库函数同名但具有内核特定语义,写入内核消息缓冲区,如果控制台活动的话还写入控制台。它是无条件的:每次 `printf` 调用都产生一条消息。 -`log(9)`, declared in `/usr/src/sys/sys/syslog.h`, writes to the kernel log ring with a syslog-compatible priority. Messages go to the in-kernel log buffer (readable by `dmesg(8)`) and, via `syslogd(8)`, to the configured log destinations. The priority is the familiar syslog scale: `LOG_EMERG`, `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`, `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`. +`log(9)`,在 `/usr/src/sys/sys/syslog.h` 中声明,以 syslog 兼容的优先级写入内核日志环。消息发送到内核内日志缓冲区(可通过 `dmesg(8)` 读取),并通过 `syslogd(8)` 发送到配置的日志目标。优先级是熟悉的 syslog 刻度:`LOG_EMERG`、`LOG_ALERT`、`LOG_CRIT`、`LOG_ERR`、`LOG_WARNING`、`LOG_NOTICE`、`LOG_INFO`、`LOG_DEBUG`。 -Use `log(9)` when you want the message to be filtered or routed by syslog. Use `printf(9)` when you want unconditional emission, typically for very important events or for output that should always appear on the console. +当你希望消息被 syslog 过滤或路由时使用 `log(9)`。当你希望无条件发送时使用 `printf(9)`,通常用于非常重要的事件或应该始终出现在控制台上的输出。 -`device_printf(9)` is a small wrapper over `printf` that prefixes the message with the device name (`secdev0: ...`). Prefer it inside driver code so messages are easy to attribute. +`device_printf(9)` 是 `printf` 的小型封装,在消息前加上设备名称(`secdev0: ...`)。在驱动程序代码中优先使用它,这样消息容易归属。 ### 该记录什么和不该记录什么 -A security-aware driver logs: +安全意识的驱动程序记录: -**State transitions that matter.** Attach, detach, reset, firmware update, link up, link down. These let an operator correlate driver behaviour with system events. +**重要的状态转换。** 附着、分离、重置、固件更新、链路启动、链路断开。这些让运维人员可以将驱动程序行为与系统事件关联。 -**Errors from the hardware or from user requests.** A bad ioctl argument, a DMA error, a timeout, a CRC mismatch. These let the operator diagnose problems. +**来自硬件或用户请求的错误。** 错误的 ioctl 参数、DMA 错误、超时、CRC 不匹配。这些让运维人员诊断问题。 -**Rate-limited summaries of anomalous events.** If a malformed ioctl is received a million times per second, log the first, summarize the rest. +**异常事件的速率限制摘要。** 如果每秒收到一百万个格式错误的 ioctl,记录第一个,总结其余的。 -A security-aware driver does not log: +安全意识的驱动程序不记录: -**User data.** The contents of buffers the user passed in. You never know what is in them. +**用户数据。** 用户传入的缓冲区内容。你永远不知道里面是什么。 -**Cryptographic material.** Keys, IVs, plaintext, ciphertext. Ever. +**加密材料。** 密钥、IV、明文、密文。永远不。 -**Sensitive hardware state.** On a security device, some register contents are themselves secrets. +**敏感硬件状态。** 在安全设备上,某些寄存器内容本身就是秘密。 -**Kernel addresses.** `%p` is fine in early development; it has no place in production logs. +**内核地址。** `%p` 在早期开发中没问题;它不属于生产日志。 -**Details of authentication failures.** A log message that says "user jane failed check X because register was 0x5d" tells an attacker what check to defeat. A log that says "authentication failed" tells the operator there was a failure without tutoring the attacker. +**认证失败的详细信息。** 一条说"用户 jane 因为寄存器为 0x5d 而未通过检查 X"的日志消息告诉攻击者要击败什么检查。一条说"认证失败"的日志告诉运维人员有失败发生而不会指导攻击者。 -Think about who reads the logs. On a multi-tenant server, other users may have log-reading privileges. On a shipped appliance, the log may be exported for remote support. Treat log messages as information that could end up on any surface the system touches. +想想谁阅读日志。在多租户服务器上,其他用户可能有日志阅读权限。在出厂设备上,日志可能被导出用于远程支持。将日志消息视为可能最终出现在系统接触的任何表面上的信息。 ### 速率限制 -A noisy driver is a security problem. If an attacker can trigger a log message, they can trigger a million of them. Log flooding consumes disk space, slows the system, and buries legitimate messages. FreeBSD provides `eventratecheck(9)` and `ppsratecheck(9)` in `/usr/src/sys/sys/time.h`: +嘈杂的驱动程序是安全问题。如果攻击者能触发一条日志消息,他们就能触发一百万条。日志泛洪消耗磁盘空间,减慢系统速度,淹没合法消息。FreeBSD 在 `/usr/src/sys/sys/time.h` 中提供 `eventratecheck(9)` 和 `ppsratecheck(9)`: ```c int eventratecheck(struct timeval *lasttime, int *cur_pps, int max_pps); int ppsratecheck(struct timeval *lasttime, int *cur_pps, int max_pps); ``` -Both return 1 if the event is allowed through and 0 if it has been rate-limited. `lasttime` and `cur_pps` are per-call state you keep in your softc. `max_pps` is the limit in events per second. +两者在事件被允许通过时返回 1,被速率限制时返回 0。`lasttime` 和 `cur_pps` 是你保存在 softc 中的每次调用状态。`max_pps` 是每秒事件数的限制。 -Pattern: +模式: ```c static struct timeval secdev_last_log; @@ -2327,35 +2327,35 @@ if (ppsratecheck(&secdev_last_log, &secdev_cur_pps, 5)) { } ``` -Now, no matter how many malformed ioctls the attacker sends, the driver emits at most 5 log messages per second. That is enough for the operator to notice something is happening without drowning the system. +现在,无论攻击者发送多少格式错误的 ioctl,驱动程序最多每秒发出 5 条日志消息。这足够让运维人员注意到正在发生的事情,而不会淹没系统。 -Per-event rate limiting (one `lasttime`/`cur_pps` pair per event type) is better than a single global limit, because it prevents a flood of one event type from masking other events. +每个事件的速率限制(每个事件类型一对 `lasttime`/`cur_pps`)比单一的全局限制更好,因为它防止一种事件类型的泛洪掩盖其他事件。 ### 实践中的日志级别 -A good rule of thumb is this: +一个好的经验法则是: -`LOG_ERR` for unexpected driver failures that require operator attention. "DMA mapping failed", "device returned CRC error", "firmware update aborted". +`LOG_ERR` 用于需要运维人员注意的意外驱动程序失败。"DMA 映射失败"、"设备返回 CRC 错误"、"固件更新中止"。 -`LOG_WARNING` for unusual but not necessarily critical situations. "Received oversized buffer, truncating", "falling back to polled mode". +`LOG_WARNING` 用于异常但不一定关键的情况。"收到超大缓冲区,正在截断"、"回退到轮询模式"。 -`LOG_NOTICE` for events that are normal but worth recording. "Firmware version 2.1 loaded", "device attached". +`LOG_NOTICE` 用于正常但值得记录的事件。"固件版本 2.1 已加载"、"设备已附着"。 -`LOG_INFO` for high-volume status information that operators may filter. +`LOG_INFO` 用于运维人员可能过滤的高频状态信息。 -`LOG_DEBUG` for debugging output. A production driver usually does not emit `LOG_DEBUG` unless the operator has enabled debug logging via a sysctl. +`LOG_DEBUG` 用于调试输出。生产驱动程序通常不发出 `LOG_DEBUG`,除非运维人员通过 sysctl 启用了调试日志。 -`LOG_EMERG` and `LOG_ALERT` are reserved for system-threatening conditions and are not typically emitted by device drivers. +`LOG_EMERG` 和 `LOG_ALERT` 保留给威胁系统的条件,设备驱动程序通常不发出。 -Choosing the right level matters because operators configure syslog to filter by level. A driver that logs every received packet at `LOG_ERR` makes the logs useless. +选择正确的级别很重要,因为运维人员配置 syslog 按级别过滤。一个在 `LOG_ERR` 级别记录每个收到的数据包的驱动程序会使日志变得无用。 ### 调试日志与生产环境 -During development, you will want verbose logging: every state transition, every entry and exit, every buffer allocation. That is fine. The question is how to turn it off in production without losing the ability to re-enable it when there is a bug to diagnose. +在开发过程中,你会想要详细日志:每个状态转换、每次进入和退出、每次缓冲区分配。那没问题。问题是如何在生产环境中关闭它而不失去在需要诊断错误时重新启用的能力。 -Two patterns are common: +两种常见的模式: -**A sysctl-controlled debug level.** The driver reads a sysctl at the top of each log-worthy event and emits or suppresses the message based on the level. This allows runtime control without recompiling. +**sysctl 控制的调试级别。** 驱动程序在每个值得记录的事件的顶部读取 sysctl,并根据级别发出或抑制消息。这允许运行时控制而无需重新编译。 ```c static int secdev_debug = 0; @@ -2368,64 +2368,64 @@ SYSCTL_INT(_hw_secdev, OID_AUTO, debug, CTLFLAG_RW, } while (0) ``` -**Compile-time control.** A driver can use `#ifdef SECDEV_DEBUG` to include or exclude debug blocks. This is faster (no runtime check) but requires a rebuild to change. Often the two are combined: `#ifdef SECDEV_DEBUG` wraps the infrastructure, and the sysctl controls verbosity within that. +**编译时控制。** 驱动程序可以使用 `#ifdef SECDEV_DEBUG` 来包含或排除调试块。这更快(没有运行时检查)但需要重新编译才能更改。通常两者结合:`#ifdef SECDEV_DEBUG` 包装基础设施,sysctl 在其中控制详细程度。 -Either way, avoid `printf` calls in hot paths that are not guarded by some kind of conditional. An uncommented `printf` in an interrupt handler or a per-packet path is a performance disaster waiting to be enabled. +无论哪种方式,避免在没有某种条件保护的频繁路径中使用 `printf` 调用。中断处理程序或每数据包路径中未注释的 `printf` 是等待被启用的性能灾难。 ### 不留痕迹 -Before committing driver changes, grep the driver for: +在提交驱动程序更改之前,grep 驱动程序中的: -Raw `printf` calls without `device_printf` prefixes. These make log attribution harder. +没有 `device_printf` 前缀的原始 `printf` 调用。这些使日志归属更难。 -`%p` format specifiers. If they appear in paths reachable from user space, replace with less sensitive formats (a sequence number, a hash, nothing). +`%p` 格式说明符。如果它们出现在可从用户空间到达的路径中,替换为不太敏感的格式(序列号、哈希、什么都不输出)。 -`LOG_ERR` on user-triggerable events without rate limiting. Attackers can weaponize these. +没有速率限制的用户可触发的 `LOG_ERR` 事件。攻击者可以将这些武器化。 -`TODO`, `XXX`, `FIXME`, `HACK` near security-related code. Leaving these for reviewers is fine; shipping them is not. +安全相关代码附近的 `TODO`、`XXX`、`FIXME`、`HACK`。留给审查者是可以的;发布它们则不行。 -Test-only fprintf-equivalents that were supposed to be removed. +本应被移除的测试用 fprintf 等价物。 ### dmesg 与内核消息缓冲区 -The kernel message buffer is a fixed-size ring buffer shared by every driver and the kernel itself. On a busy system, old messages scroll out as new ones arrive. A driver that floods the buffer pushes out useful messages from other drivers. +内核消息缓冲区是每个驱动程序和内核本身共享的固定大小环形缓冲区。在繁忙的系统上,旧消息随着新消息的到来而滚出。泛洪缓冲区的驱动程序会推出来自其他驱动程序的有用消息。 -`dmesg(8)` shows the current contents of the buffer. Operators rely on it. Being a good citizen in the buffer means: log important things, do not log in hot paths, rate-limit everything triggerable by users, and do not flood. +`dmesg(8)` 显示缓冲区的当前内容。运维人员依赖它。在缓冲区中做个好公民意味着:记录重要的事情,不在频繁路径中记录,对用户可触发的所有内容进行速率限制,不要泛洪。 -The buffer size is tunable (`kern.msgbufsize` sysctl), but you cannot count on a particular size. Write as if every message is valuable and must compete with others for space. +缓冲区大小是可调的(`kern.msgbufsize` sysctl),但你不能指望特定的大小。把每条消息当作有价值的、必须与其他消息竞争空间的东西来写。 ### KTR 与追踪 -For detailed tracing without the cost of `printf`, FreeBSD provides KTR (Kernel Tracing), declared in `/usr/src/sys/sys/ktr.h`. KTR macros, when enabled, record events in a compact in-kernel ring that is separate from the message buffer. A kernel compiled with `options KTR` can be queried with `sysctl debug.ktr.buf` and with `ktrdump(8)`. +对于不需要 `printf` 代价的详细追踪,FreeBSD 提供 KTR(内核追踪),在 `/usr/src/sys/sys/ktr.h` 中声明。KTR 宏在启用时将事件记录在与消息缓冲区分离的紧凑内核内环中。使用 `options KTR` 编译的内核可以通过 `sysctl debug.ktr.buf` 和 `ktrdump(8)` 查询。 -KTR events are best for per-operation tracing where a `printf` would be too heavy. They are almost free at runtime when disabled. For a security-sensitive driver, KTR gives you a way to leave tracing infrastructure in the code without paying for it in production. +KTR 事件最适合每次操作的追踪,在这种场景下 `printf` 会太重。禁用时它们在运行时几乎免费。对于安全敏感的驱动程序,KTR 给你一种在代码中保留追踪基础设施而不在生产环境中付出代价的方式。 -Other tracing frameworks (dtrace(1) via SDT probes) are worth learning for deep inspection. They are out of scope for this chapter, but know that they exist. +其他追踪框架(通过 SDT 探针的 dtrace(1))值得学习用于深度检查。它们超出了本章的范围,但知道它们存在。 ### 记录特权操作 -A specific case worth calling out: when your driver successfully performs a privileged operation, log it. This creates an audit trail. If a firmware update happens, log who triggered it. If a hardware reset is issued, log it. If a device is reconfigured, log the change. +一个值得强调的具体情况:当你的驱动程序成功执行了特权操作时,记录它。这创建了审计追踪。如果发生了固件更新,记录谁触发了它。如果发出了硬件重置,记录它。如果设备被重新配置,记录更改。 ```c log(LOG_NOTICE, "secdev: firmware update initiated by uid %u (euid %u)\n", td->td_ucred->cr_ruid, td->td_ucred->cr_uid); ``` -The operator can later see who did what. If there is ever a security incident, this log is the first evidence. Make it accurate and make it hard to forge. +运维人员以后可以看到谁做了什么。如果曾经发生安全事故,这条日志就是第一份证据。让它准确且难以伪造。 -Do not over-log legitimate privileged use; a firmware update triggered by `freebsd-update` once a month is one message, not a thousand. But the single message should carry enough detail to reconstruct what happened: who, when, what, with what arguments. +不要过度记录合法的特权使用;由 `freebsd-update` 每月触发一次的固件更新是一条消息,而不是一千条。但那条单一消息应该携带足够的细节来重建发生了什么:谁、何时、什么、带什么参数。 ### audit(4) 框架 -For deeper audit trails than `log(9)` provides, FreeBSD includes an audit subsystem (`audit(4)`) based on the BSM (Basic Security Module) audit format originally from Solaris. When enabled via `auditd(8)`, the kernel emits structured audit records for many security-relevant events: logins, privilege changes, file access, and, increasingly, driver-specific events when drivers instrument themselves. +对于比 `log(9)` 提供的更深层审计追踪,FreeBSD 包含一个基于最初来自 Solaris 的 BSM(基本安全模块)审计格式的审计子系统(`audit(4)`)。通过 `auditd(8)` 启用时,内核为许多安全相关事件发出结构化审计记录:登录、权限更改、文件访问,以及越来越多的驱动程序特定事件(当驱动程序自行接入时)。 -A driver that handles highly sensitive operations can emit custom audit records using `AUDIT_KERNEL_*` macros declared in `/usr/src/sys/security/audit/audit.h`. This is more involved than a `log(9)` call, but it produces records that fit into the operator's existing audit workflow, are structured (machine-readable), and can be forwarded to remote audit collectors for compliance. +处理高度敏感操作的驱动程序可以使用在 `/usr/src/sys/security/audit/audit.h` 中声明的 `AUDIT_KERNEL_*` 宏发出自定义审计记录。这比 `log(9)` 调用更复杂,但它产生适合运维人员现有审计工作流程的记录,是结构化的(机器可读),可以转发到远程审计收集器以满足合规要求。 -For most drivers, `log(9)` with `LOG_NOTICE` and a clear message is enough. For drivers that must meet specific compliance requirements (government, financial, medical), consider investing in audit integration. The infrastructure is already in the kernel; you just need to call into it. +对于大多数驱动程序,带有 `LOG_NOTICE` 和清晰消息的 `log(9)` 就够了。对于必须满足特定合规要求(政府、金融、医疗)的驱动程序,考虑投资审计集成。基础设施已经在内核中;你只需要调用它。 ### 在驱动程序中使用 dtrace -Alongside logging, `dtrace(1)` lets an operator observe driver behavior without recompiling. A driver that declares Statically Defined Trace (SDT) probes through `sys/sdt.h` exposes well-defined hook points that dtrace scripts can latch onto. +除了日志记录,`dtrace(1)` 让运维人员无需重新编译即可观察驱动程序行为。通过 `sys/sdt.h` 声明静态定义追踪 (SDT) 探针的驱动程序暴露了 dtrace 脚本可以挂钩的定义良好的钩子点。 ```c #include @@ -2442,15 +2442,15 @@ secdev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, } ``` -An operator can then write a dtrace script that fires on `secdev:::ioctl_called` and counts or logs each event. The advantage over `log(9)` is that dtrace probes have essentially no cost when disabled, and they let the operator decide what to observe rather than forcing the driver author to anticipate every useful question. +然后运维人员可以编写一个 dtrace 脚本,在 `secdev:::ioctl_called` 上触发并计数或记录每个事件。相对于 `log(9)` 的优势是 dtrace 探针在禁用时几乎没有开销,而且它们让运维人员决定观察什么,而不是强迫驱动程序作者预测每个有用的问题。 -For a security-focused driver, SDT probes on entry and exit of privileged operations let security monitoring tools observe usage patterns without the driver having to log every call. This is useful for anomaly detection: a sudden spike in ioctl calls from an unexpected UID, for example, can be flagged by a dtrace-based monitor. +对于安全聚焦的驱动程序,特权操作的入口和出口上的 SDT 探针让安全监控工具观察使用模式而无需驱动程序记录每次调用。这对于异常检测很有用:例如,来自意外 UID 的 ioctl 调用的突然激增可以被基于 dtrace 的监控器标记。 ### 第8节总结 -Logging is how a driver talks to its operator. Like any communication, it can be clear or confused, honest or misleading, helpful or harmful. A security-aware driver logs important events with appropriate levels, avoids logging sensitive data, rate-limits anything an attacker can trigger, and uses debug infrastructure that can be turned on and off without recompilation. It prefers `device_printf(9)` for attribution, uses `log(9)` with thoughtful priorities, and never leaves `%p` or unguarded `printf` statements in production paths. +日志记录是驱动程序与其运维人员对话的方式。像任何通信一样,它可以是清晰的或混乱的,诚实的或误导的,有帮助的或有害的。安全意识的驱动程序以适当的级别记录重要事件,避免记录敏感数据,对攻击者能触发的任何内容进行速率限制,并使用无需重新编译即可开关的调试基础设施。它优先使用 `device_printf(9)` 进行归属,使用 `log(9)` 配合深思熟虑的优先级,并且永远不在生产路径中留下 `%p` 或未保护的 `printf` 语句。 -The next section takes a broader view. Beyond specific techniques (bounds-checking, privilege checks, safe logging), there is a design-level question: what should a driver do by default when something goes wrong? What fail-safe behavior should it exhibit? That is the subject of secure defaults. +下一节采取更广泛的视角。在特定技术(边界检查、权限检查、安全日志记录)之外,还有一个设计层面的问题:当出现问题时驱动程序应该默认做什么?它应该表现出什么样的故障安全行为?这就是安全默认值的主题。 ## 第9节:安全默认值与故障安全设计 @@ -2460,7 +2460,7 @@ The next section takes a broader view. Beyond specific techniques (bounds-checki ### 故障时关闭 -The first and most important design decision is what happens when your code reaches a state it did not expect. Consider a switch statement: +第一个也是最重要的设计决策是当你的代码到达一个它没有预期的状态时会发生什么。考虑一个 switch 语句: ```c switch (op) { @@ -2472,9 +2472,9 @@ case OP_BAR: return (0); /* fall-through: everything else succeeds! */ ``` -This is a fail-open design. Any operation code that is not `OP_FOO` or `OP_BAR` succeeds silently, returning 0. That is almost never what you want. A new operation code added to the API but not handled in the driver becomes a silent no-op. An attacker who discovers this can use it to bypass checks. +这是一个故障时开放的设计。任何不是 `OP_FOO` 或 `OP_BAR` 的操作码都会静默成功,返回 0。这几乎永远不是你想要的。添加到 API 但未在驱动程序中处理的新操作码变成静默的空操作。发现这一点的攻击者可以用它来绕过检查。 -The fail-closed version: +故障时关闭的版本: ```c switch (op) { @@ -2487,9 +2487,9 @@ default: } ``` -Unknown operations explicitly return an error. If a new operation is added to the API, the compiler or the tests will tell you the moment you handle it and forget to update the switch, because the new case is needed to silence the `EINVAL`. +未知操作显式返回错误。如果向 API 添加了新操作,编译器或测试会在你处理了它但忘记更新 switch 的时候立即告诉你,因为需要新的 case 来消除 `EINVAL`。 -The same principle applies at every decision point. When a function checks a precondition: +同样的原则适用于每个决策点。当函数检查前置条件时: ```c /* Fail open: if the check is inconclusive, allow the operation. */ @@ -2503,11 +2503,11 @@ if (good_condition != true) return (0); ``` -The second form fails closed: if the precondition cannot be proven good, the operation is refused. This is safer when `good_condition` has any chance of being false due to an error in setup, a race, or a bug. +第二种形式故障时关闭:如果前置条件不能被证明为好,操作被拒绝。当 `good_condition` 因设置中的错误、竞态或漏洞而可能为 false 时,这更安全。 ### 白名单,不要黑名单 -Closely related: when deciding what is allowed, whitelist the known-good rather than blacklisting the known-bad. Blacklists are always incomplete, because you cannot enumerate every bad input. Whitelists are finite by construction. +密切相关:在决定什么被允许时,白名单已知的好的而不是黑名单已知的坏的。黑名单总是不完整的,因为你无法枚举每个坏输入。白名单按构造是有限的。 ```c /* Bad: blacklist */ @@ -2519,111 +2519,111 @@ if (!isalnum(c) && c != '-' && c != '_') return (EINVAL); ``` -The blacklist missed `\t`, `\x7f`, every high-bit character, and so on. The whitelist made the allowed set explicit and refused everything else. +黑名单遗漏了 `\t`、`\x7f`、每个高位字符等等。白名单使允许集显式并拒绝其他所有内容。 -This applies to input validation generally. A driver that accepts a set of configuration names should explicitly list them. A driver that accepts a set of operation codes should enumerate them. If a user sends something that is not on the list, refuse. +这普遍适用于输入验证。接受一组配置名称的驱动程序应该显式列出它们。接受一组操作码的驱动程序应该枚举它们。如果用户发送不在列表上的东西,拒绝。 ### 最小有用接口 -A driver exposes functionality to user space through device nodes, ioctls, sysctls, and sometimes network protocols. Every exposed entry is a potential attack surface. A secure driver exposes only what users actually need. +驱动程序通过设备节点、ioctl、sysctl 以及有时通过网络协议向用户空间暴露功能。每个暴露的入口点都是潜在的攻击面。安全的驱动程序只暴露用户实际需要的功能。 -Before shipping an ioctl, ask: does anyone actually use this? If a debugging ioctl was useful during development but has no production role, remove it or compile it out behind a debug flag. If a sysctl exposes internal state that only matters for engineering, hide it behind `CTLFLAG_SECURE` and consider removing it. +在发布 ioctl 之前,问:真的有人用这个吗?如果调试用的 ioctl 在开发期间很有用但在生产中没有作用,就删除它或在调试标志后编译掉它。如果 sysctl 暴露了仅对工程重要的内部状态,就将其隐藏在 `CTLFLAG_SECURE` 后面并考虑删除它。 -The cost of removing an interface now is small: a few lines of code. The cost later, when the interface has shipped and has users, is much larger. Smaller interfaces are easier to review, easier to test, and have fewer opportunities for bugs. +现在删除接口的成本很小:几行代码。等到接口已经发布并有用户之后的成本要大得多。较小的接口更容易审查,更容易测试,并且出现 bug 的机会更少。 ### 打开时的最低权限 -A device node can be created with restrictive or permissive modes. Start restrictive. A mode of `0600` or `0640` is almost always a better default than `0666`. If users complain that they cannot access the device, that is a conversation you want to have; you can always relax the mode, and the operator can use devfs rules to do so per-site. If users silently gain access they should not have, you will not have that conversation until something breaks. +设备节点可以用限制性或宽松的模式创建。从限制模式开始。`0600` 或 `0640` 的模式几乎总是比 `0666` 更好的默认值。如果用户抱怨无法访问设备,那是你想要进行的对话;你总是可以放宽模式,运维人员可以使用 devfs 规则在每个站点上进行放宽。如果用户在不应获得访问权限时悄悄获得了访问权限,你不会进行那个对话,直到有东西出问题。 -Similarly, a driver that supports jails should default to not being accessible in jails unless there is a specific reason. The reasoning is the same: it is easier to open up later than to retrofit a closed policy onto an open one. +同样,支持 jail 的驱动程序默认应不在 jail 中可访问,除非有特定原因。理由相同:以后开放比将封闭策略改造成开放策略更容易。 ### 保守的默认值 -Every configurable parameter has a default. Choose conservative ones. +每个可配置参数都有一个默认值。选择保守的值。 -A driver that has a configurable "allow user X to do Y" tunable should default to X = none. If an operator wants to grant access, they can change the tunable. If the default granted access, every deployment that missed the tunable would be open. +具有可配置的"允许用户 X 做 Y"可调参数的驱动程序应默认 X = none。如果运维人员想要授予访问权限,他们可以更改可调参数。如果默认值授予了访问权限,每个错过该可调参数的部署都将处于开放状态。 -A driver that has a timeout should default to a short timeout. If the operation usually finishes quickly, a short default is fine. If it sometimes takes longer, the operator can bump the timeout. A long default is a denial-of-service opportunity. +具有超时的驱动程序应默认使用短超时。如果操作通常很快完成,短默认值就可以了。如果有时需要更长的时间,运维人员可以增加超时。长默认值是拒绝服务的机会。 -A driver that has a buffer size limit should default to a small limit. Again, operators can raise it; attackers cannot. +具有缓冲区大小限制的驱动程序应默认使用小的限制。同样,运维人员可以调高它;攻击者不能。 ### 纵深防御 -No single security mechanism is perfect. A defense-in-depth driver assumes any one layer can fail and builds multiple layers. +没有单一安全机制是完美的。纵深防御的驱动程序假设任何一层都可能失效,并构建多层防御。 -Example: suppose a driver accepts an ioctl that requires privilege. The layers of defense are: +例如:假设驱动程序接受一个需要特权的 ioctl。防御的层级是: -The device node mode blocks unprivileged users from opening the device at all. +设备节点模式阻止非特权用户打开设备。 -A `priv_check` at open time blocks unprivileged users even if the mode is misconfigured. +打开时的 `priv_check` 即使在模式配置错误时也能阻止非特权用户。 -A `priv_check` on the specific ioctl catches the case where an unprivileged user somehow reached the ioctl handler. +特定 ioctl 上的 `priv_check` 捕获非特权用户以某种方式到达了 ioctl 处理程序的情况。 -A `jailed()` check on the ioctl blocks jailed users. +ioctl 上的 `jailed()` 检查阻止被 jail 的用户。 -Input validation on the ioctl arguments refuses malformed requests. +ioctl 参数的输入验证拒绝格式错误的请求。 -A rate-limit log records repeated malformed requests. +速率限制的日志记录重复的格式错误请求。 -If all five are present, a failure in any one is contained by the others. If only one is present and it fails, the driver is compromised. Defense in depth costs a little more code and a little more CPU; it buys real resilience. +如果全部五层都存在,任何一层的失败都被其他层控制住。如果只有一层存在而它失败了,驱动程序就被攻破。纵深防御需要多一些代码和一点 CPU;它换来的是真正的韧性。 ### 超时与看门狗 -A driver that waits on external events should have timeouts. Hardware can fail to respond. User space can stop reading. Networks can stall. Without a timeout, a waiting driver can hold resources forever, and an attacker who controls the external event can deny service by simply not responding. +等待外部事件的驱动程序应该有超时。硬件可能无法响应。用户空间可能停止读取。网络可能停滞。没有超时,等待的驱动程序可能永远持有资源,控制外部事件的攻击者可以通过简单的不响应来拒绝服务。 -`msleep(9)` accepts a timeout argument in ticks. Use it. A sleep with no timeout is rarely the right answer in driver code. +`msleep(9)` 接受以 ticks 为单位的超时参数。使用它。没有超时的睡眠在驱动程序代码中很少是正确的答案。 -For longer-lived operations, a watchdog timer can detect that an operation has stalled and take recovery action: abort, retry, or reset. The `callout(9)` framework is the usual mechanism. +对于更长时间的操作,看门狗定时器可以检测到操作已停滞并采取恢复措施:中止、重试或重置。`callout(9)` 框架是常用的机制。 ### 有界资源使用 -Every resource a driver can allocate on behalf of a caller should have a cap. Buffer sizes have maximum values. Per-open resource counts have maximum values. Global resource counts have maximum values. When a cap is hit, the driver returns an error, not an attempt at "best effort". +驱动程序代表调用者可以分配的每个资源都应该有一个上限。缓冲区大小有最大值。每次打开的资源计数有最大值。全局资源计数有最大值。当达到上限时,驱动程序返回错误,而不是尝试"尽力而为"。 -Without caps, a misbehaving or hostile process can exhaust resources. The exhaustion might be memory, file-descriptor-like state, interrupt-worthy events, or simply CPU time. Caps ensure that no single caller can dominate. +没有上限,行为不良或恶意的进程可以耗尽资源。耗尽的可能是内存、类似文件描述符的状态、中断相关的事件,或者仅仅是 CPU 时间。上限确保没有单个调用者可以独占。 -A reasonable default structure: +合理的默认结构: ```c -#define SECDEV_MAX_BUFLEN (1 << 20) /* per buffer */ -#define SECDEV_MAX_OPEN_BUFS 16 /* per open */ -#define SECDEV_MAX_GLOBAL 256 /* driver-wide */ +#define SECDEV_MAX_BUFLEN (1 << 20) /* 每缓冲区 */ +#define SECDEV_MAX_OPEN_BUFS 16 /* 每次打开 */ +#define SECDEV_MAX_GLOBAL 256 /* 驱动程序全局 */ ``` -Check each cap explicitly before allocating. Return `EINVAL`, `ENOMEM`, or `ENOBUFS` as appropriate when the cap is hit. +在分配之前显式检查每个上限。达到上限时,酌情返回 `EINVAL`、`ENOMEM` 或 `ENOBUFS`。 ### 安全的模块加载与卸载 -A driver that supports being unloaded must handle cleanup correctly. An unsafe unload is a security bug. If unload leaves a callback registered, or a mapping in place, or a DMA in flight, then re-loading the module (or unloading and resuming) can touch memory that is no longer owned by the driver. That is a use-after-free waiting to happen. +支持卸载的驱动程序必须正确处理清理。不安全的卸载是一个安全漏洞。如果卸载在回调仍注册、映射仍存在或 DMA 仍在进行时就完成了,那么重新加载模块(或卸载后恢复)可能会触及不再属于驱动程序的内存。那是一个等待发生的释放后使用。 -The rule: if any part of `detach` or `unload` fails, either propagate the error (and keep the driver loaded) or drive the cleanup to completion. Partial teardown is worse than no teardown. +规则:如果 `detach` 或 `unload` 的任何部分失败,要么传播错误(并保持驱动程序加载),要么将清理进行到底。部分拆卸比不拆卸更糟。 -A reasonable strategy: make the unload path paranoid. It checks every resource and tears down every one that was allocated, in reverse order of allocation. It uses the `callout_drain` and `taskqueue_drain` helpers to wait for async work. Only after every such resource is quiet does it free the softc. +一个合理的策略:使卸载路径偏执。它检查每个资源,并按照分配的逆序拆除每个已分配的资源。它使用 `callout_drain` 和 `taskqueue_drain` 辅助函数等待异步工作。只有在每个这样的资源都安静下来之后,才释放 softc。 -If any step fails, return `EBUSY` from `detach` and document that the driver cannot currently be unloaded. That is better than half-freeing and crashing later. +如果任何步骤失败,从 `detach` 返回 `EBUSY` 并记录驱动程序当前无法卸载。这比半释放然后稍后崩溃更好。 ### 安全的并发入口 -A driver's entry points (open, close, read, write, ioctl) can be called concurrently. The driver should be written as if every entry point could be called from any context at any time. Anything else is a race waiting to fire. +驱动程序的入口点(open、close、read、write、ioctl)可以被并发调用。驱动程序应该写得好像每个入口点都可能随时从任何上下文被调用。否则就是等待触发的竞态。 -The practical implication: every entry point that touches shared state acquires the softc lock first. Every operation that uses resources from the softc does so under the lock. If the operation has to sleep or do user-space work, the code drops the lock, does the work, and re-acquires carefully, checking that the state it had not changed under its feet. +实际含义:每个触及共享状态的入口点首先获取 softc 锁。每个使用 softc 资源的操作都在锁下进行。如果操作必须睡眠或执行用户空间工作,代码会释放锁,执行工作,然后小心地重新获取,检查状态没有在它脚下改变。 -Concurrency is not an afterthought. It is part of the interface. +并发不是事后考虑的事情。它是接口的一部分。 ### 错误路径就是正常路径 -A subtle aspect of secure design is that error paths get the same care as success paths. In a driver, error paths often free resources, release locks, and restore state. A bug on an error path is just as exploitable as a bug on a success path; often more so, because error paths are less tested. +安全设计的一个微妙方面是错误路径得到与成功路径相同的关注。在驱动程序中,错误路径通常释放资源、释放锁并恢复状态。错误路径上的 bug 与成功路径上的 bug 同样可利用;通常更容易被利用,因为错误路径测试更少。 -Write every error path as if it were the happy path for a user who is trying to find bugs. Every `goto cleanup` or `out:` label is a candidate for a double-free, a missed unlock, or a left-behind mapping. Walk each error path mentally and confirm that: +将每个错误路径写得像是试图寻找 bug 的用户的快乐路径。每个 `goto cleanup` 或 `out:` 标签都是双重释放、遗漏解锁或留下映射的候选者。在脑海中走过每个错误路径并确认: -Every resource allocated on the success path is freed on the error path. +成功路径上分配的每个资源都在错误路径上释放。 -No resource is freed twice. +没有资源被释放两次。 -Every lock held is released exactly once. +持有的每个锁恰好被释放一次。 -No error path leaves partially initialized state visible to other contexts. +没有错误路径将部分初始化的状态暴露给其他上下文。 -A systematic pattern helps. The "single cleanup path" idiom (one label, cleanup proceeds in reverse order of allocation) catches most such bugs by construction: +系统性的模式有帮助。"单一清理路径"惯用法(一个标签,清理按分配的逆序进行)从结构上捕获了大多数此类 bug: ```c static int @@ -2658,56 +2658,56 @@ done: } ``` -Each allocation is paired with a cleanup at `done`. The cleanup uses `NULL` checks so that resources freed earlier (or never allocated) do not cause double-frees. Ownership transfers set the pointer to `NULL`, which suppresses the cleanup. +每次分配都与 `done` 处的清理配对。清理使用 `NULL` 检查,以便较早释放(或从未分配)的资源不会导致双重释放。所有权转移将指针设置为 `NULL`,从而抑制清理。 -Consistent use of this pattern eliminates most cleanup-path bugs. The code is longer than an early-return style, but it is dramatically safer. +一致使用此模式消除了大多数清理路径的 bug。代码比早期返回风格更长,但明显更安全。 ### 也不要信任你自己 -A final aspect of fail-safe design is to assume that even your own code has bugs. Include `KASSERT(9)` checks for invariants. `KASSERT` does nothing when `INVARIANTS` is not configured (typical in release builds), but in developer kernels it checks every assertion and panics on failure. That turns a subtle corruption bug into a loud, debuggable panic. +故障安全设计的最后一个方面是假设即使是你自己的代码也有 bug。为不变量包含 `KASSERT(9)` 检查。当未配置 `INVARIANTS` 时(发布构建中的典型情况),`KASSERT` 什么也不做,但在开发者内核中,它检查每个断言并在失败时 panic。这将微妙的损坏 bug 变成了响亮的、可调试的 panic。 ```c KASSERT(sc != NULL, ("secdev: NULL softc")); KASSERT(len <= SECDEV_MAX_BUFLEN, ("secdev: len %zu too large", len)); ``` -Invariants documented as `KASSERT` help readers (future you, future colleagues) understand what the code expects. They also catch regressions that would otherwise silently corrupt state. +记录为 `KASSERT` 的不变量帮助读者(未来的你、未来的同事)理解代码的期望。它们还捕获否则会静默损坏状态的回归。 ### 优雅降级与完全拒绝 -A design choice that often arises in fail-safe work: when a non-critical part of an operation fails, should the driver continue with a degraded result, or should it refuse the operation entirely? +故障安全工作中经常出现的一个设计选择是:当操作的非关键部分失败时,驱动程序应该以降级结果继续,还是应该完全拒绝该操作? -There is no universal answer. Each case depends on what the caller is likely to do with partial success. A driver that returns a packet with some fields uninitialized (because a subsystem call failed) is inviting the caller to trust the zero bytes as meaningful. A driver that fails the whole operation is more disruptive but less surprising. +没有通用的答案。每种情况取决于调用者可能如何处理部分成功。返回包含某些未初始化字段的数据包的驱动程序(因为子系统调用失败)是在邀请调用者将零字节视为有意义的。使整个操作失败的驱动程序更具破坏性但更少意外。 -For security-relevant operations, prefer full refusal. A privilege check that fails should not result in "most of the operation ran, but we did not do the privileged step"; it should result in the whole thing refused. A partial success that depended on the skipped step is a bug waiting to be found. +对于安全相关的操作,优先完全拒绝。失败的权限检查不应导致"大部分操作已运行,但我们没有执行特权步骤";它应该导致整个操作被拒绝。依赖于被跳过步骤的部分成功是等待被发现的 bug。 -For non-security operations, graceful degradation is often the right call. If an optional statistics update fails, the main operation should still succeed. Document what the degradation looks like so callers can anticipate it. +对于非安全操作,优雅降级通常是正确的选择。如果可选的统计信息更新失败,主操作仍应成功。记录降级的样子,以便调用者可以预期它。 ### 案例研究:/dev/null 中真实世界的安全默认值 -The FreeBSD `null` driver, at `/usr/src/sys/dev/null/null.c`, is worth studying as an example of secure-by-default design. It is one of the simplest drivers in the tree, yet its construction embodies most of the principles in this chapter. +位于 `/usr/src/sys/dev/null/null.c` 的 FreeBSD `null` 驱动程序值得作为安全默认设计的示例来学习。它是树中最简单的驱动程序之一,然而其构造体现了本章中的大多数原则。 -It creates two device nodes, `/dev/null` and `/dev/zero`, both with world-accessible permissions (`0666`). This is intentional: they are meant to be used by every process, privileged or not, and neither can leak information or corrupt kernel state. The permission decision is deliberate and documented. +它创建了两个设备节点,`/dev/null` 和 `/dev/zero`,都具有世界可访问的权限(`0666`)。这是有意为之:它们旨在被每个进程使用,无论特权与否,两者都不能泄露信息或损坏内核状态。权限决定是审慎的并有文档记录。 -The read, write, and ioctl handlers are minimal. `null_read` returns 0 (end of file). `null_write` consumes input without touching kernel state. `zero_read` fills the user buffer with zeros using `uiomove_frombuf` against a static zero-filled buffer. +读、写和 ioctl 处理程序是最简的。`null_read` 返回 0(文件结束)。`null_write` 消耗输入而不触及内核状态。`zero_read` 使用 `uiomove_frombuf` 针对静态零填充缓冲区用零填充用户缓冲区。 -The ioctl handler returns `ENOIOCTL` for unknown commands, so the upper layers can translate to the proper error. A small set of specific `FIO*` commands for non-blocking and async behavior are handled, each doing only the minimal bookkeeping that makes sense for a null or zero stream. +ioctl 处理程序对未知命令返回 `ENOIOCTL`,以便上层可以转换为适当的错误。处理了一小组特定的 `FIO*` 命令用于非阻塞和异步行为,每个只做对 null 或 zero 流有意义的极简簿记。 -The driver has no locking because it has no mutable state worth protecting: the zero buffer is constant, and the read/write operations do not modify any shared data. The absence of locking is not carelessness; it is a consequence of the design minimizing what is shared in the first place. +驱动程序没有加锁,因为它没有值得保护的可变状态:零缓冲区是常量,读/写操作不修改任何共享数据。没有加锁不是粗心;它是从一开始就最小化共享内容的设计结果。 -The driver's `detach` is straightforward, destroying the device nodes. Because there is no async state, no callouts, no interrupts, no taskqueues, the cleanup is correspondingly simple. +驱动程序的 `detach` 很简单,销毁设备节点。因为没有异步状态、没有 callout、没有中断、没有 taskqueue,清理相应地简单。 -What makes this a good example of secure defaults is the discipline of not doing more than is needed. The driver does not speculatively add features, does not expose internal state, does not support ioctls that were not demanded by specific users. Its interface is minimal, which keeps its attack surface minimal. Its behaviour is predictable and has been exactly the same for decades. +这成为安全默认值的好示例的原因是不做超出需要的功能的纪律。驱动程序不投机地添加功能,不暴露内部状态,不支持未被特定用户要求的 ioctl。其接口是最小的,这使其攻击面最小化。其行为是可预测的,并且几十年来一直完全相同。 -Real drivers cannot always be this simple; most have state to manage, hardware to talk to, and operations to perform. But the design principle generalizes: the simpler the driver, the fewer the failure modes. When faced with a choice between adding functionality and leaving it out, the more secure choice is usually to leave it out. +真实的驱动程序不能总是这么简单;大多数有状态要管理,有硬件要通信,有操作要执行。但设计原则是通用的:驱动程序越简单,失败模式就越少。当面临添加功能还是保留原样的选择时,更安全的选择通常是保留原样。 ### 第9节总结 -Secure defaults come down to a disposition toward refusal. Default to `EINVAL` for unknown inputs. Default to restrictive modes on device nodes. Default to conservative limits on resources. Default to short timeouts. Default to strict privilege requirements. Whitelist, do not blacklist. Fail closed, not open. +安全默认值归结为一种倾向于拒绝的态度。对未知输入默认返回 `EINVAL`。对设备节点默认使用限制性模式。对资源默认使用保守限制。对超时默认使用短时间。对权限要求默认严格。白名单,不要黑名单。故障时关闭,不要开放。 -None of these are exotic. They are design habits that add up. A driver built on them is not merely a driver that can be made secure; it is a driver that is secure by default, and has to be actively broken before it becomes insecure. +这些都不是异国情调的。它们是积累起来的设计习惯。建立在它们之上的驱动程序不仅仅是一个可以被变得安全的驱动程序;它是一个默认安全的驱动程序,必须被主动破坏才会变得不安全。 -The next section brings the chapter to a close by looking at the other end of the development cycle: testing. How do you know your driver is as safe as you think it is? How do you hunt for the bugs that review missed? +下一节通过查看开发周期的另一端来结束本章:测试。你如何知道你的驱动程序像你认为的那样安全?你如何找到审查遗漏的漏洞? ## 第10节:测试与加固驱动程序 @@ -2715,7 +2715,7 @@ The next section brings the chapter to a close by looking at the other end of th ### 演示:使用 KASAN 发现漏洞 -Before the general guidance, consider a specific scenario. You have a driver that passes all your functional tests but that you suspect has a memory-safety bug. You build a kernel with `options KASAN`, boot it, load your driver, and run a stress test. The test crashes the kernel with output that looks something like: +在给出通用指导之前,考虑一个特定场景。你有一个通过所有功能测试但怀疑存在内存安全 bug 的驱动程序。你构建一个带有 `options KASAN` 的内核,启动它,加载你的驱动程序,并运行压力测试。测试使内核崩溃,输出看起来像这样的内容: ```text ================================================================== @@ -2742,35 +2742,35 @@ The buffer was freed by thread 100089: ================================================================== ``` -Read the output carefully. KASAN tells you the exact instruction that accessed freed memory (`secdev_callout_fn`), the exact allocation that was freed (in `secdev_attach`), and the exact free (in `secdev_detach`). Now the bug is obvious: the callout was scheduled at attach, but detach freed the buffer before draining the callout. When the callout fires after the free, it accesses the freed buffer. +仔细阅读输出。KASAN 告诉你访问已释放内存的确切指令(`secdev_callout_fn`)、被释放的确切分配(在 `secdev_attach` 中)以及确切的释放(在 `secdev_detach` 中)。现在 bug 很明显了:callout 在 attach 时被调度,但 detach 在排空 callout 之前释放了缓冲区。当 callout 在释放后触发时,它访问了已释放的缓冲区。 -The fix: add `callout_drain` to detach before the `free`. KASAN helped you find, in thirty seconds, a bug that might have taken hours or weeks to find by inspection, and that might never have been found in production until a customer reported a random crash. +修复方法:在 `free` 之前向 detach 添加 `callout_drain`。KASAN 帮助你在三十秒内找到了一个可能需要数小时或数周通过审查才能发现、并且可能直到客户报告随机崩溃才会在生产中被发现的 bug。 -KASAN is not free. The runtime overhead is substantial, both in CPU (perhaps 2 to 3 times slower) and in memory (each byte of allocated memory has an accompanying shadow byte). You would not run production with it. But for developer testing, and especially for driver authors, it is one of the most effective tools available. +KASAN 不是免费的。运行时开销很大,无论是在 CPU(可能慢 2 到 3 倍)还是在内存方面(每个已分配内存字节都有一个附带的影子字节)。你不会在生产中使用它。但对于开发者测试,特别是对于驱动程序作者,它是最有效的可用工具之一。 -KMSAN works analogously for uninitialized memory reads, and KCOV powers coverage-guided fuzzing. Together they address the main classes of memory-safety bugs: use-after-free (KASAN), uninitialized memory (KMSAN), and bugs not reached by your tests (KCOV plus a fuzzer). +KMSAN 类似地适用于未初始化内存读取,KCOV 为覆盖引导的模糊测试提供支持。它们共同解决了内存安全 bug 的主要类别:释放后使用(KASAN)、未初始化内存(KMSAN)以及你的测试未触及的 bug(KCOV 加模糊测试器)。 ### 使用内核净化器构建 -A stock FreeBSD kernel is optimized for production. A development kernel for driver testing should be optimized for finding bugs. The options you add to the kernel config file turn on extra checking. +标准的 FreeBSD 内核为生产环境优化。用于驱动程序测试的开发内核应该为发现 bug 而优化。你添加到内核配置文件中的选项启用额外的检查。 -**`options INVARIANTS`** enables `KASSERT(9)`. Every assertion is checked at runtime. A failed assertion panics the kernel with a stack trace pointing to the assertion. This catches invariant violations that would otherwise corrupt data silently. +**`options INVARIANTS`** 启用 `KASSERT(9)`。每个断言在运行时被检查。断言失败会使内核 panic,并带有指向该断言的栈跟踪。这捕获了否则会静默损坏数据的不变量违反。 -**`options INVARIANT_SUPPORT`** is implied by `INVARIANTS` but is sometimes needed as a separate option for modules built against an `INVARIANTS` kernel. +**`options INVARIANT_SUPPORT`** 由 `INVARIANTS` 隐含,但有时需要作为针对 `INVARIANTS` 内核构建的模块的单独选项。 -**`options WITNESS`** turns on the WITNESS lock-order checker. Every lock acquisition is recorded, and the kernel panics if a cycle is detected (A held, then B acquired; later, B held, then A acquired). This catches deadlock bugs before they deadlock. +**`options WITNESS`** 开启 WITNESS 锁顺序检查器。每次锁获取被记录,如果检测到循环则内核 panic(先持有 A,然后获取 B;稍后,持有 B,然后获取 A)。这会在死锁发生之前捕获死锁 bug。 -**`options WITNESS_SKIPSPIN`** disables WITNESS for spin mutexes, which can reduce overhead at the cost of missing some checks. +**`options WITNESS_SKIPSPIN`** 禁用在自旋互斥锁上的 WITNESS,这可以减少开销,代价是丢失一些检查。 -**`options DIAGNOSTIC`** enables additional runtime checks in various subsystems. It is looser than `INVARIANTS` and catches some additional cases. +**`options DIAGNOSTIC`** 在各个子系统中启用额外的运行时检查。它比 `INVARIANTS` 宽松,并捕获一些额外的情况。 -**`options KASAN`** enables the Kernel Address Sanitizer, which detects use-after-free, out-of-bounds access, and some uninitialized memory uses. It requires compiler support and a substantial memory overhead but is excellent for finding memory-safety bugs. +**`options KASAN`** 启用内核地址净化器,检测释放后使用、越界访问和一些未初始化内存使用。它需要编译器支持和大量的内存开销,但对于发现内存安全 bug 非常出色。 -**`options KMSAN`** enables the Kernel Memory Sanitizer, which detects uses of uninitialized memory. This directly catches the information-leak bugs described in Section 7. +**`options KMSAN`** 启用内核内存净化器,检测未初始化内存的使用。这直接捕获第 7 节中描述的信息泄露 bug。 -**`options KCOV`** enables kernel coverage tracking, which is what makes coverage-guided fuzzing work. +**`options KCOV`** 启用内核覆盖跟踪,这使得覆盖引导的模糊测试成为可能。 -A driver-development kernel might add: +一个驱动程序开发内核可能会添加: ```text options INVARIANTS @@ -2779,163 +2779,163 @@ options WITNESS options DIAGNOSTIC ``` -and, for deeper memory-safety testing, `KASAN` or `KMSAN` on supported architectures. Build that kernel, boot it, and run your driver against it. Many bugs surface immediately. +并且,对于更深度的内存安全测试,在支持的架构上添加 `KASAN` 或 `KMSAN`。构建那个内核,启动它,并针对它运行你的驱动程序。许多 bug 会立即浮出水面。 -Production builds do not typically include these options (they slow the kernel significantly). Use them as a development safety net. +生产构建通常不包括这些选项(它们会显著降低内核速度)。将它们用作开发安全网。 ### 压力测试 -A driver that passes functional tests can still fail under stress. Stress testing exercises the driver's concurrency, its allocation patterns, and its error paths at volumes that amplify race conditions. +通过功能测试的驱动程序在压力下仍可能失败。压力测试以放大竞态条件的量级来锻炼驱动程序的并发性、分配模式和错误路径。 -A simple stress harness for a character device might: +一个简单的字符设备压力测试框架可能: -Open the device from N processes concurrently. +从 N 个进程并发打开设备。 -Each process issues M ioctls with valid and invalid arguments in a random order. +每个进程以随机顺序发出 M 个有效和无效参数的 ioctl。 -A separate process periodically detaches and re-attaches the device (or kldunload/kldload). +一个单独的进程周期性地分离和重新附着设备(或 kldunload/kldload)。 -This quickly exposes races between user-space operations and detach, which are among the hardest race categories to catch by inspection. +这迅速暴露了用户空间操作与 detach 之间的竞态,这是最难通过审查捕获的竞态类别之一。 -FreeBSD's `stress2` test framework at `https://github.com/pho/stress2` has a long history of finding kernel bugs. It includes scenarios for VFS, networking, and various subsystems. A driver author can learn a lot by reading those scenarios and adapting them to the driver's interface. +位于 `https://github.com/pho/stress2` 的 FreeBSD `stress2` 测试框架在发现内核 bug 方面有着悠久的历史。它包括用于 VFS、网络和各种子系统的场景。驱动程序作者可以通过阅读这些场景并将其适应于驱动程序的接口来学到很多。 ### 模糊测试 -Fuzzing is the technique of generating large numbers of random or semi-random inputs and observing whether the program crashes, asserts, or misbehaves. Modern fuzzers are coverage-guided: they watch which code paths are exercised and evolve inputs that explore new paths. This is far more effective than purely random input. +模糊测试是生成大量随机或半随机输入并观察程序是否崩溃、断言或行为异常的技术。现代模糊测试器是覆盖引导的:它们观察哪些代码路径被执行,并演化出探索新路径的输入。这比纯随机输入有效得多。 -For driver testing, the key fuzzer is **syzkaller**, an external project that understands syscall semantics and produces structured inputs. Syzkaller is not part of the FreeBSD base system; it is an external tool that runs on top of a FreeBSD kernel built with `KCOV` coverage instrumentation. Syzkaller has found many bugs in the FreeBSD kernel over the years, and a driver that wants to be exercised thoroughly benefits from being described in a syzkaller syscall description (`.txt` file under syzkaller's `sys/freebsd/`). +对于驱动程序测试,关键的模糊测试器是 **syzkaller**,一个理解系统调用语义并产生结构化输入的外部项目。Syzkaller 不是 FreeBSD 基本系统的一部分;它是一个运行在带有 `KCOV` 覆盖工具的 FreeBSD 内核之上的外部工具。多年来,Syzkaller 在 FreeBSD 内核中发现了许多 bug,想要被彻底测试的驱动程序受益于在 syzkaller 系统调用描述(syzkaller 的 `sys/freebsd/` 下的 `.txt` 文件)中被描述。 -If your driver exposes a substantial ioctl or sysctl interface, consider writing a syzkaller description for it. The format is straightforward, and the investment pays off the first time syzkaller finds a bug no human reviewer would have spotted. +如果你的驱动程序暴露了重要的 ioctl 或 sysctl 接口,考虑为其编写 syzkaller 描述。格式很直接,当 syzkaller 第一次发现人类审查者不会发现的 bug 时,投资就得到了回报。 -Simpler fuzzing approaches also work. A shell script that issues random ioctls with random arguments and watches `dmesg` for panics is better than no fuzzing at all. The goal is to generate inputs your design did not anticipate. +更简单的模糊测试方法也有效。一个发出随机 ioctl 和随机参数并观察 `dmesg` 中 panic 的 shell 脚本总比没有模糊测试好。目标是生成你的设计未预料到的输入。 ### ASLR、PIE 和栈保护 -Modern FreeBSD kernels use several exploit-mitigation techniques. Understanding them is part of understanding why the bugs we have discussed matter. +现代 FreeBSD 内核使用几种利用缓解技术。理解它们是我们讨论的 bug 为何重要的部分原因。 -**kASLR**, kernel Address Space Layout Randomization, places the kernel's code, data, and stacks at randomized addresses at boot. An attacker who wants to jump to kernel code, or to overwrite a specific function pointer, does not know where that code or pointer is. kASLR is foundational for making many memory-safety bugs unexploitable in practice. +**kASLR**,内核地址空间布局随机化,将内核的代码、数据和栈在启动时放置在随机地址。想要跳转到内核代码或覆盖特定函数指针的攻击者不知道该代码或指针在哪里。kASLR 是使许多内存安全 bug 在实践中不可利用的基础。 -Information leaks (Section 7) are particularly dangerous because they can defeat kASLR. A single leaked kernel pointer gives the attacker the base address and unlocks everything else. +信息泄露(第 7 节)特别危险,因为它们可以击败 kASLR。单个泄露的内核指针就给了攻击者基地址并解锁了其他一切。 -**SSP**, the Stack-Smashing Protector, places a canary value on the stack between local variables and the return address. When a function returns, the canary is checked; if it has been overwritten (because a buffer overflow clobbered it on the way to the return address), the kernel panics. SSP does not prevent overflows but it prevents many of them from gaining control of execution. +**SSP**,栈粉碎保护器,在栈上的局部变量和返回地址之间放置一个金丝雀值。当函数返回时检查金丝雀;如果它已被覆盖(因为缓冲区溢出在通往返回地址的路上破坏了它),内核 panic。SSP 不能防止溢出,但能阻止许多溢出获得执行控制权。 -Not every function is protected. The compiler applies SSP based on heuristics: functions with local buffers, functions that take addresses of locals, and so on. Understanding this means understanding why certain buffer-overflow patterns are more exploitable than others. +并非每个函数都被保护。编译器基于启发式规则应用 SSP:有局部缓冲区的函数、获取局部变量地址的函数等等。理解这一点意味着理解为什么某些缓冲区溢出模式比其他模式更容易被利用。 -**PIE**, Position-Independent Executables, allows the kernel (and modules) to be relocated to random addresses. Combined with kASLR, this is what makes the randomization effective. +**PIE**,位置无关可执行文件,允许内核(和模块)被重定位到随机地址。与 kASLR 结合,这就是随机化有效的原因。 -**Stack guards and guard pages** surround kernel stacks with unmapped pages. An attempt to write past the stack hits an unmapped page and panics rather than silently corrupting adjacent memory. +**栈防护与防护页** 用未映射的页面包围内核栈。试图写入超过栈末尾会触及未映射的页面并 panic,而不是静默损坏相邻内存。 -**W^X**, write-xor-execute, keeps kernel memory either writable or executable, never both. This prevents many classic exploits that relied on writing shellcode into memory and then jumping to it. +**W^X**,写异或执行,使内核内存要么可写要么可执行,不能同时兼具。这防止了许多依赖于将 shellcode 写入内存然后跳转到它的经典利用。 -A driver author does not implement any of these; they are kernel-wide protections. But a driver's bugs can undermine them. An information leak defeats kASLR. A buffer overflow that reliably hits a function pointer or vtable defeats SSP. A use-after-free that races a fresh allocation gives an attacker controlled memory at a kernel address. +驱动程序作者不实现这些中的任何一个;它们是内核范围的保护。但驱动程序的 bug 可以破坏它们。信息泄露击败了 kASLR。可靠地命中函数指针或 vtable 的缓冲区溢出击败了 SSP。与新鲜分配竞态的释放后使用在某个内核地址给了攻击者受控的内存。 -In short: the point of careful driver code is not just to avoid crashes. It is to keep the kernel's defenses intact. When your driver leaks a pointer, you did not merely expose information; you downgraded the entire system's exploit-mitigation posture. +简而言之:仔细的驱动程序代码的意义不仅仅是避免崩溃。它是保持内核的防御完好无损。当你的驱动程序泄露指针时,你不仅仅暴露了信息;你降低了整个系统的利用缓解态势。 ### 审查你的差异 -Every time you modify the driver, read the diff carefully. Look for: +每次修改驱动程序时,仔细阅读差异。寻找: -New `copyin` or `copyout` calls: are the lengths clamped? Are the buffers zeroed first? +新的 `copyin` 或 `copyout` 调用:长度是否被限制?缓冲区是否先被清零? -New privilege-sensitive operations: do they have `priv_check` or equivalent? +新的特权敏感操作:它们有 `priv_check` 或等价物吗? -New locking: is the lock order consistent with other code? +新的加锁:锁顺序与其它代码一致吗? -New allocations: are they paired with frees on every path, including error paths? +新的分配:它们在每条路径(包括错误路径)上都与释放配对吗? -New log messages: are they rate-limited? Do they leak sensitive data? +新的日志消息:它们被速率限制了吗?它们泄露敏感数据吗? -New user-visible fields in structures: are they initialized? Is the structure zeroed before the copyout? +结构中新的用户可见字段:它们被初始化了吗?结构在 copyout 前被清零了吗? -A diff-review habit catches many regressions. If your project uses code review (it should), make these questions part of the checklist. +审查差异的习惯能捕获许多回归。如果你的项目使用代码审查(它应该如此),让这些问题成为检查清单的一部分。 ### 静态分析 -FreeBSD kernel code can be analyzed by several static-analysis tools, including `cppcheck`, `clang-analyzer` (scan-build), and, increasingly, Coverity and GitHub CodeQL-style tools. These tools often report warnings that a human reviewer would miss: a conditional that can never be true, a pointer used after a path where it was freed, a missing null check. +FreeBSD 内核代码可以通过几种静态分析工具分析,包括 `cppcheck`、`clang-analyzer`(scan-build),以及越来越多的 Coverity 和 GitHub CodeQL 风格的工具。这些工具通常报告人类审查者会遗漏的警告:永远不可能为真的条件、在指针被释放的路径之后使用指针、缺少空检查。 -Treat static-analysis warnings seriously. Most are false positives; some are real bugs. Silencing a warning should be a decision, not a reflex. When the tool is wrong, add a comment explaining why. When the tool is right, fix the code. +认真对待静态分析警告。大多数是误报;有些是真正的 bug。静默警告应该是一个决定,而不是一种反射。当工具错了时,添加注释解释原因。当工具对了时,修复代码。 -`syntax check` with `bmake` on the kernel source tree is a fast first pass. Running `clang --analyze` or `scan-build` against your driver is a deeper pass. Neither replaces review or testing, but both catch bugs at low cost. +在内核源代码树上使用 `bmake` 进行 `syntax check` 是一个快速的初步检查。对你的驱动程序运行 `clang --analyze` 或 `scan-build` 是更深度的检查。两者都不能替代审查或测试,但都能以低成本捕获 bug。 ### 代码审查 -No tool replaces another pair of eyes. Review is especially important for security-relevant code. When proposing a change to a security-sensitive path, find someone else to look at it. Describe what the change is, what invariants it preserves, and what you checked. Be grateful when they find a problem you missed. +没有工具能替代另一双眼睛。审查对于安全相关代码尤其重要。当提议对安全敏感路径进行更改时,找其他人看看。描述更改是什么、它保留了哪些不变量以及你检查了什么。当他们发现你遗漏的问题时,心存感激。 -For open-source projects, the FreeBSD review system (`reviews.freebsd.org`) provides a convenient way to get external review. Use it. The community has a long tradition of thoughtful, security-aware review, and reviewers often catch things you would not. +对于开源项目,FreeBSD 审查系统(`reviews.freebsd.org`)提供了一种获得外部审查的便捷方式。使用它。社区有着深思熟虑、安全意识审查的悠久传统,审查者经常捕获你不会注意到的东西。 ### 修改后的测试 -When a bug is found and fixed, add a test that would have caught it. This matters because: +当发现并修复了一个 bug 时,添加一个本可以捕获它的测试。这很重要,因为: -The same bug class often recurs in other places. A test that catches the specific instance may catch future similar bugs. +相同的 bug 类别经常在其他地方重现。捕获特定实例的测试可能捕获未来类似的 bug。 -Without a test, you have no way to know that the fix worked. +没有测试,你就无法知道修复是否有效。 -Without a test, a future refactoring may re-introduce the bug. +没有测试,未来的重构可能会重新引入该 bug。 -Tests can be unit tests (in user space, exercising individual functions), integration tests (loading the driver in a VM and exercising it), or fuzz cases (inputs that used to crash and should not now). All have their place. +测试可以是单元测试(在用户空间,练习单个函数)、集成测试(在 VM 中加载驱动程序并练习它)或模糊测试用例(以前会导致崩溃而现在不应该的输入)。它们各有各的位置。 ### 持续集成 -Automated testing on every change catches regressions early. A CI setup that builds the driver against a development kernel with `INVARIANTS`, `WITNESS`, and possibly `KASAN` runs the stress harness, and checks the result, is the backbone of a driver that stays safe. +每次更改后的自动测试能及早捕获回归。一个 CI 设置,用带有 `INVARIANTS`、`WITNESS` 和可能的 `KASAN` 的开发内核构建驱动程序,运行压力测试框架,并检查结果,是保持驱动程序安全的主干。 -For a driver in the FreeBSD tree, this is already provided by the project's CI. For out-of-tree drivers, setting up CI takes some effort but pays back quickly. +对于 FreeBSD 树中的驱动程序,这已经由项目的 CI 提供了。对于树外的驱动程序,设置 CI 需要一些努力但很快就能得到回报。 ### 严肃对待漏洞报告 -When someone reports a crash or a suspected vulnerability in your driver, treat it as real until you have evidence otherwise. Even a "harmless" bug may be exploitable in ways the reporter did not see. "I can crash the kernel with this ioctl" is not a minor issue; it is at minimum a denial-of-service bug, and very often a memory-safety bug that could become arbitrary code execution. +当有人报告你的驱动程序崩溃或疑似漏洞时,将其视为真实情况,直到你找到相反的证据。即使是"无害"的 bug 也可能以报告者未发现的方式被利用。"我可以用这个 ioctl 使内核崩溃"不是一个小问题;它至少是一个拒绝服务 bug,而且通常是一个可能变成任意代码执行的内存安全 bug。 -The FreeBSD security team (`secteam@freebsd.org`) is the right audience for vulnerability reports in the base system. For out-of-tree drivers, have a similar channel. Respond quickly, fix carefully, and credit the reporter when appropriate. +FreeBSD 安全团队(`secteam@freebsd.org`)是基本系统中漏洞报告的正确接收者。对于树外驱动程序,设置类似的渠道。快速响应,仔细修复,并在适当时感谢报告者。 ### 随时间推移进行加固 -A driver's security posture is not static. New classes of bugs emerge. New mitigations become available. New attack techniques make old bugs more exploitable. Budget time every release cycle to: +驱动程序的安全态势不是静态的。新类别的 bug 会出现。新的缓解措施变得可用。新的攻击技术使旧 bug 更容易被利用。每个发布周期都要预算时间来: -Re-read the security-relevant paths of the driver. +重新阅读驱动程序中与安全相关的路径。 -Check for newly discovered compiler warnings or static-analysis findings. +检查新发现的编译器警告或静态分析发现。 -Try the latest tools (KASAN, KMSAN, syzkaller) against the driver. +尝试最新的工具(KASAN、KMSAN、syzkaller)针对驱动程序。 -Update the privilege model if FreeBSD has added new `PRIV_*` codes or more specific checks. +如果 FreeBSD 添加了新的 `PRIV_*` 代码或更具体的检查,更新权限模型。 -Remove interfaces that no user actually needs. +删除没有用户实际需要的接口。 -The discipline of regular re-examination is what distinguishes a driver that is secure on the day it ships from one that stays secure through its lifetime. +定期重新检查的纪律是区分发布当天安全的驱动程序和在其整个生命周期中保持安全的驱动程序的因素。 ### 事后处理:当漏洞变成 CVE 时该做什么 -A realistic chapter on security must cover the possibility that, despite all the precautions, a bug in your driver gets reported externally as a vulnerability. The pathway is typically: +一个关于安全的现实章节必须涵盖这样一种可能性:尽管采取了所有预防措施,你的驱动程序中的 bug 仍被外部报告为漏洞。路径通常是: -A researcher or user discovers unexpected behavior in your driver. +研究人员或用户在你的驱动程序中发现了意外行为。 -They investigate and determine that the behavior is a security bug: information leak, privilege escalation, crash-on-untrusted-input, or similar. +他们进行调查并确定该行为是一个安全 bug:信息泄露、权限提升、对不可信输入的崩溃,或类似情况。 -They report the bug, ideally via a responsible-disclosure channel (for FreeBSD base-system drivers, this is the `secteam@freebsd.org` address). +他们报告该 bug,理想情况下通过负责的披露渠道(对于 FreeBSD 基本系统驱动程序,这是 `secteam@freebsd.org` 地址)。 -You receive the report. +你收到报告。 -The first response matters. Even if the bug turns out to be less serious than it looks, treat the reporter as a collaborator, not an adversary. Acknowledge receipt promptly. Ask clarifying questions if needed. Do not dismiss without investigation. Do not attempt to gag the reporter. Most vulnerability researchers want the bug fixed; if you cooperate, you get a fix faster and usually get public credit that reflects well on the project. +第一反应很重要。即使 bug 最终看起来不那么严重,也要将报告者视为合作者,而不是对手。及时确认收到。如果需要,提出澄清性问题。未经调查不要驳回。不要试图让报告者保持沉默。大多数漏洞研究人员希望 bug 被修复;如果你合作,你会更快地得到修复,并且通常会得到对项目有益的公开认可。 -Triage the report technically. Can you reproduce the bug? Is it a crash, an information leak, a privilege escalation, or something else? What is the attacker model: who has to have access, and what do they gain? Is it exploitable in combination with other known bugs? +对报告进行技术分类。你能复现这个 bug 吗?是崩溃、信息泄露、权限提升还是其他什么?攻击者模型是什么:谁必须拥有访问权限,他们能得到什么?它是否与其他已知 bug 结合可利用? -If confirmed, coordinate a fix. Keep in mind that for FreeBSD base-system drivers, the fix must flow through the project's normal review process and, where appropriate, through the security advisory process. For out-of-tree drivers, you have more flexibility but still should write the fix carefully and test it thoroughly. +如果确认,协调修复。记住,对于 FreeBSD 基本系统驱动程序,修复必须通过项目正常的审查流程,并在适当时通过安全公告流程。对于树外驱动程序,你有更多灵活性,但仍应仔细编写修复并彻底测试。 -Prepare the disclosure. Typical disclosure practice gives the project time to fix the bug before details become public. Industry norms are usually 90 days. Within that window, the advisory is prepared, a patched version is released, and public disclosure happens simultaneously with the release. Do not leak details early; do not delay past the agreed date. +准备披露。典型的披露实践给予项目时间在细节公开之前修复 bug。行业规范通常是 90 天。在这个窗口内,准备公告,发布修补版本,公开披露与发布同时进行。不要提前泄露细节;不要延迟超过约定的日期。 -Write the commit message carefully. Security fix commits should mention the vulnerability without giving attackers a roadmap. "Fix incorrect bounds check in secdev_write that could allow kernel memory disclosure" is better than either "tweak write" (too vague, reviewers miss it) or "Fix CVE-2026-12345, where an attacker can read arbitrary kernel memory by issuing a write of X bytes followed by a read, bypassing Y check" (too specific, attackers read your commit history before users can upgrade). +仔细编写提交消息。安全修复提交应提及漏洞而不给攻击者提供路线图。"修复 secdev_write 中可能允许内核内存泄露的错误边界检查"既好于"调整 write"(太模糊,审查者错过),也好于"修复 CVE-2026-12345,攻击者可以通过先写入 X 字节然后读取来绕过 Y 检查读取任意内核内存"(太具体,攻击者在用户可以升级之前阅读你的提交历史)。 -After the release, if details become public, be prepared to answer questions. Users want to know: am I vulnerable, how do I upgrade, and how can I tell if I was attacked? Have clear, calm answers ready. +发布之后,如果细节公开,准备回答问题。用户想知道:我是否易受攻击,如何升级,以及如何判断我是否被攻击了?准备好清晰、冷静的答案。 -Post-mortem the bug. Not to blame, but to learn. Why did the bug exist? Was there a pattern the review missed? Could a tool have caught it? Should the team's process change? Write the conclusions down; apply them in future work. +对 bug 进行事后分析。不是为了指责,而是为了学习。为什么这个 bug 存在?审查遗漏了哪种模式?工具本可以捕获它吗?团队的流程应该改变吗?写下结论;在未来的工作中应用它们。 -Security is a continuing practice, and post-incident learning is one of its most important parts. A project that fixes the bug and moves on has learned nothing; a project that reflects on why the bug occurred makes the next bug less likely. +安全是一个持续的实践,事后学习是其最重要的部分之一。修复了 bug 然后继续前进的项目什么也没学到;反思 bug 为何发生的项目使下一个 bug 更不可能发生。 ### 第10节总结 -Testing and hardening are how a careful design becomes a secure one. Build your development kernel with `INVARIANTS`, `WITNESS`, and, where possible, `KASAN` or `KMSAN`. Stress-test under concurrent load. Fuzz with syzkaller or, at minimum, with a random-input harness. Use static analysis. Review diffs. Respond seriously to bug reports. Re-test after every fix. Harden over time. +测试和加固是精心设计变成安全设计的方式。用 `INVARIANTS`、`WITNESS` 以及可能的情况下用 `KASAN` 或 `KMSAN` 构建你的开发内核。在并发负载下进行压力测试。用 syzkaller 或至少在随机输入框架下进行模糊测试。使用静态分析。审查差异。认真对待 bug 报告。每次修复后重新测试。随时间推移进行加固。 -A driver does not become secure by accident. It becomes secure because the author assumed bugs existed, looked for them with every tool available, and fixed them one at a time. +驱动程序不是偶然变安全的。它之所以安全,是因为作者假设有 bug 存在,用每个可用的工具寻找它们,并逐一修复。 ## 动手实验 @@ -2943,7 +2943,7 @@ A driver does not become secure by accident. It becomes secure because the autho 这些实验设计为在 FreeBSD 14.3 虚拟机或测试主机上运行,内核崩溃是可以接受的。不要在运行重要服务的机器上运行它们;不安全驱动程序中的错误可能导致内核崩溃。 -If you are running these labs inside a VM, make sure the VM is configured to write crash dumps to a location you can recover after reboot. Enable `dumpon(8)` and set `/etc/fstab` appropriately so that core dumps land in `/var/crash` after a panic. See `/usr/src/sbin/savecore/savecore.8` for details. This infrastructure is how you will diagnose any panics the labs provoke. +如果你在虚拟机内运行这些实验,确保虚拟机配置为将崩溃转储写入重启后可以恢复的位置。启用 `dumpon(8)` 并适当设置 `/etc/fstab`,以便核心转储在 panic 后落入 `/var/crash`。详细信息请参阅 `/usr/src/sbin/savecore/savecore.8`。这个基础设施是你诊断实验引发的任何 panic 的方式。 这些实验的配套文件位于 `examples/part-07/ch31-security/` 下。每个实验都有自己的子文件夹,包含 `secdev.c` 源文件、`Makefile`、描述实验的 `README.md`,以及适当情况下包含小型用户空间测试程序的 `test/` 子文件夹。 @@ -2959,52 +2959,52 @@ If you are running these labs inside a VM, make sure the VM is configured to wri **步骤。** -1. Copy `examples/part-07/ch31-security/lab01-unsafe/` to a working directory on your FreeBSD test machine. You can either clone the book's companion repository or copy the files manually if you extracted them locally. +1. 将 `examples/part-07/ch31-security/lab01-unsafe/` 复制到 FreeBSD 测试机器上的工作目录。你可以克隆书籍的配套仓库,或者如果本地提取了文件则手动复制。 -2. Read `secdev.c` carefully. Note what it does: it provides a `/dev/secdev` character device with `read`, `write`, and `ioctl` operations. `read` returns the contents of an internal buffer. `write` copies user data into the buffer. An ioctl (`SECDEV_GET_INFO`) returns a structure describing the device. +2. 仔细阅读 `secdev.c`。注意它的功能:它提供一个带有 `read`、`write` 和 `ioctl` 操作的 `/dev/secdev` 字符设备。`read` 返回内部缓冲区的内容。`write` 将用户数据复制到缓冲区中。ioctl(`SECDEV_GET_INFO`)返回描述设备的结构。 -3. Read `Makefile`. It should be a standard FreeBSD kernel module makefile using `bsd.kmod.mk`. +3. 阅读 `Makefile`。它应该是一个使用 `bsd.kmod.mk` 的标准 FreeBSD 内核模块 makefile。 -4. Build the module with `make`. Address any build errors by consulting earlier chapters on module-building. A successful build produces `secdev.ko`. +4. 用 `make` 构建模块。通过查阅前面关于模块构建的章节来解决任何构建错误。成功的构建会产生 `secdev.ko`。 -5. Load the module with `kldload ./secdev.ko`. Verify with: +5. 用 `kldload ./secdev.ko` 加载模块。验证: ``` kldstat | grep secdev ls -l /dev/secdev ``` - You should see the module listed and the device node present with whatever permissions the unsafe driver created. + 你应该看到模块被列出,设备节点存在,具有不安全驱动程序创建的任何权限。 -6. Exercise the device as a normal functional test: +6. 作为正常功能测试练习设备: ``` echo "hello" > /dev/secdev cat /dev/secdev ``` - You should see `hello` printed back. If you do not, check `dmesg` for error messages. + 你应该看到 `hello` 被打印回来。如果没有,检查 `dmesg` 的错误消息。 -7. Now, review the code with the security mindset from this chapter. For each of the following categories, find at least one issue in the unsafe code: - - Buffer overflow opportunity. - - Information leak opportunity. - - Missing privilege check. - - Unchecked user input. - Write down each finding in your lab logbook, including the line number and the specific concern. +7. 现在,用本章的安全思维方式审查代码。针对以下每个类别,在不安全代码中找到至少一个问题: + - 缓冲区溢出机会。 + - 信息泄露机会。 + - 缺少权限检查。 + - 未检查的用户输入。 + 在你的实验日志中写下每个发现,包括行号和具体关注点。 -8. Unload the module with `kldunload secdev` when you are done. Verify with `kldstat` that it is gone. +8. 完成后用 `kldunload secdev` 卸载模块。用 `kldstat` 验证它已消失。 **观察。** -The unsafe `secdev` has several issues by design. In `secdev_write`, the code calls `uiomove(sc->sc_buf, uio->uio_resid, uio)`, which copies `uio_resid` bytes regardless of `sizeof(sc->sc_buf)`. A write of 8192 bytes to a 4096-byte buffer overflows the internal buffer. Depending on what lies next to `sc_buf` in memory, this may or may not crash immediately, but it always corrupts adjacent kernel memory. +不安全的 `secdev` 故意有多个问题。在 `secdev_write` 中,代码调用 `uiomove(sc->sc_buf, uio->uio_resid, uio)`,它复制 `uio_resid` 字节而不考虑 `sizeof(sc->sc_buf)`。向 4096 字节缓冲区写入 8192 字节会使内部缓冲区溢出。根据内存中 `sc_buf` 旁边是什么,这可能不会立即崩溃,但它总是会损坏相邻的内核内存。 -`SECDEV_GET_INFO` returns a `struct secdev_info` that is filled in field-by-field without being zeroed first. Any padding bytes between fields carry stack contents to user space. The structure likely has padding around the `uint64_t` members for alignment. +`SECDEV_GET_INFO` 返回一个 `struct secdev_info`,它逐字段填充而没有先清零。字段之间的任何填充字节都将栈内容传送到用户空间。该结构可能为了对齐而在 `uint64_t` 成员周围有填充。 -The device is created with `args.mda_mode = 0666` (or equivalent), allowing any user on the system to read and write. A user with no special privilege can corrupt the kernel buffer or leak information through the ioctl. +设备以 `args.mda_mode = 0666`(或等效)创建,允许系统上的任何用户读写。没有特殊特权的用户可以损坏内核缓冲区或通过 ioctl 泄露信息。 -The ioctl handler does not check `priv_check` or similar. Any user who can open the device can issue any ioctl. +ioctl 处理程序不检查 `priv_check` 或类似机制。任何可以打开设备的用户都可以发出任何 ioctl。 -`secdev_read` copies `sc->sc_buflen` bytes regardless of the caller's buffer size, potentially reading beyond valid data if `sc_buflen` was ever larger than the currently valid content. +`secdev_read` 复制 `sc->sc_buflen` 字节而不考虑调用者的缓冲区大小,如果 `sc_buflen` 曾经大于当前有效内容,可能会读取超出有效数据的范围。 **额外探索。** -As a non-root user, try the operations that should be privileged and confirm that they succeed when they should not. Write a short C program that issues `SECDEV_GET_INFO` and prints the returned structure as a hex dump. Look for non-zero bytes in fields that were not explicitly set; those are leaked kernel data. +作为非 root 用户,尝试那些应该是特权的操作,并确认它们在不该成功时成功了。编写一个简短的 C 程序,发出 `SECDEV_GET_INFO` 并将返回的结构打印为十六进制转储。查找未显式设置的字段中的非零字节;那些就是泄露的内核数据。 **总结。** @@ -3016,30 +3016,30 @@ As a non-root user, try the operations that should be privileged and confirm tha **步骤。** -1. Start from `lab02-bounds/secdev.c`. This is `lab01`'s code plus some `TODO` comments marking where you will add checks. +1. 从 `lab02-bounds/secdev.c` 开始。这是 `lab01` 的代码加上一些标记你将添加检查位置的 `TODO` 注释。 -2. In `secdev_write`, calculate how much data can safely be written to the internal buffer. Remember that `uiomove` writes at most the length you pass. Clamp `uio->uio_resid` to the remaining space before calling `uiomove`. +2. 在 `secdev_write` 中,计算可以安全写入内部缓冲区的数据量。记住 `uiomove` 最多写入你传入的长度。在调用 `uiomove` 之前,将 `uio->uio_resid` 钳制到剩余空间。 -3. In `secdev_read`, make sure you only copy out as much data as is actually valid in the buffer, not its full allocated size. +3. 在 `secdev_read` 中,确保你只复制出缓冲区中实际有效的数据量,而不是其完整的分配大小。 -4. Rebuild and re-test. With the fixes in place, a write of 10KB to a 4KB buffer should simply fill the buffer, not overflow it. +4. 重新构建并重新测试。有了修复,向 4KB 缓冲区写入 10KB 应该只是填满缓冲区,而不是溢出它。 -5. Stress-test the fixed driver: +5. 对修复后的驱动程序进行压力测试: ``` dd if=/dev/zero of=/dev/secdev bs=8192 count=100 dd if=/dev/secdev of=/dev/null bs=8192 count=100 ``` - Neither command should crash the kernel or produce warnings in `dmesg`. If they do, your bounds check is incomplete. + 这两个命令都不应使内核崩溃或在 `dmesg` 中产生警告。如果出现这种情况,你的边界检查不完整。 -6. Compare your fix with `lab02-fixed/secdev.c`. If your fix is different but correct, that is fine; multiple solutions can be valid. If yours is incorrect, study the reference fix and understand where you went wrong. +6. 将你的修复与 `lab02-fixed/secdev.c` 进行比较。如果你的修复不同但正确,那也没问题;多种解决方案都可以是有效的。如果你的是错误的,研究参考修复并理解你哪里出错了。 -**Building confidence.** +**建立信心。** -Write a small C program that issues writes of various sizes (0 bytes, 1 byte, buffer size, buffer size + 1, much larger than buffer size) and verifies that each returns the expected number of bytes written or a sensible error. This kind of boundary testing is what real driver tests look like. +编写一个简短的 C 程序,发出各种大小的写入(0 字节、1 字节、缓冲区大小、缓冲区大小 + 1、远大于缓冲区大小),并验证每个返回预期的写入字节数或合理的错误。这种边界测试就是真实驱动程序测试的样子。 **总结。** -Bounds checking is the simplest security fix and it catches a large fraction of real-world driver bugs. Internalize the pattern: every `uiomove`, `copyin`, `copyout`, and memcpy bounds the length against both source and destination sizes. The compiler cannot catch this for you; it is entirely the author's responsibility. +边界检查是最简单的安全修复,它捕获了很大一部分真实世界驱动程序 bug。内化这个模式:每个 `uiomove`、`copyin`、`copyout` 和 memcpy 都对照源和目标大小限制长度。编译器不能为你捕获这个;这完全是作者的责任。 ### 实验3:copyout 前清零 @@ -3047,9 +3047,9 @@ Bounds checking is the simplest security fix and it catches a large fraction of **步骤。** -1. Start from `lab03-info-leak/secdev.c`. This contains the ioctl as in the original unsafe code. +1. 从 `lab03-info-leak/secdev.c` 开始。这包含了原始不安全代码中的 ioctl。 -2. Observe the structure definition. Note the padding between fields: +2. 观察结构定义。注意字段之间的填充: ```c struct secdev_info { uint32_t version; @@ -3060,21 +3060,21 @@ Bounds checking is the simplest security fix and it catches a large fraction of char name[32]; }; ``` - Check the size with `pahole` or a small C program that prints `sizeof(struct secdev_info)`. + 用 `pahole` 或打印 `sizeof(struct secdev_info)` 的简短 C 程序检查大小。 -3. Before fixing, build and load the broken version. Run the test program provided in `lab03-info-leak/test/leak_check.c`. It issues the ioctl repeatedly and dumps the returned structure as a hex dump. Look at the padding bytes. You should see non-zero values that differ between runs; those are leaked kernel stack bytes. +3. 在修复之前,构建并加载有问题的版本。运行 `lab03-info-leak/test/leak_check.c` 中提供的测试程序。它重复发出 ioctl 并将返回的结构转储为十六进制转储。查看填充字节。你应该看到每次运行不同的非零值;那些是泄露的内核栈字节。 -4. In `secdev_ioctl`, before filling in the `struct secdev_info`, zero the structure with `bzero` (or use `= { 0 }` initialization). +4. 在 `secdev_ioctl` 中,在填充 `struct secdev_info` 之前,用 `bzero` 清零结构(或使用 `= { 0 }` 初始化)。 -5. Also fix the name field: use `snprintf` instead of `strncpy` to guarantee a NUL terminator, and copy only up to the NUL rather than the full buffer size. +5. 同时修复 name 字段:使用 `snprintf` 而不是 `strncpy` 以保证 NUL 终止符,并且只复制到 NUL 而不是整个缓冲区大小。 -6. Rebuild and re-test with the same `leak_check` program. The padding bytes should now be zero on every run. The visible behavior from user space is unchanged; the internal change is that padding bytes no longer carry stack contents. +6. 重新构建并用相同的 `leak_check` 程序重新测试。填充字节现在在每次运行时应该为零。用户空间可见的行为不变;内部变化是填充字节不再携带栈内容。 -7. Compare with `lab03-fixed/secdev.c`. +7. 与 `lab03-fixed/secdev.c` 进行比较。 -**A deeper exploration.** +**更深入的探索。** -If you have `KMSAN` built into your kernel, load the broken version of the driver and run `leak_check`. KMSAN should report an uninitialized read when the structure is copied out. This demonstrates why KMSAN is valuable: it catches information leaks that are invisible without it. +如果你的内核中构建了 `KMSAN`,加载有问题的驱动程序版本并运行 `leak_check`。KMSAN 应该在结构被复制出去时报告未初始化的读取。这说明了 KMSAN 为何有价值:它捕获了没有它就会不可见的信息泄露。 **总结。** @@ -3086,59 +3086,59 @@ If you have `KMSAN` built into your kernel, load the broken version of the drive **步骤。** -1. Start from `lab04-privilege/secdev.c`. +1. 从 `lab04-privilege/secdev.c` 开始。 -2. Modify the device-node creation code in `secdev_modevent` (or `secdev_attach`, depending on structure) to use a restrictive mode (`0600`) and the root user and group: +2. 修改 `secdev_modevent`(或 `secdev_attach`,取决于结构)中的设备节点创建代码,使用限制性模式(`0600`)和 root 用户及组: ```c args.mda_uid = UID_ROOT; args.mda_gid = GID_WHEEL; args.mda_mode = 0600; ``` -3. In `secdev_open`, add a `priv_check(td, PRIV_DRIVER)` call at the top: +3. 在 `secdev_open` 中,在顶部添加一个 `priv_check(td, PRIV_DRIVER)` 调用: ```c error = priv_check(td, PRIV_DRIVER); if (error != 0) return (error); ``` - Return the error if the check fails. + 如果检查失败则返回错误。 -4. Rebuild and reload the module. +4. 重新构建并重新加载模块。 -5. Test from a non-root shell: +5. 从非 root shell 测试: ``` % cat /dev/secdev cat: /dev/secdev: Permission denied ``` - Open should fail with `EPERM` (reported as "Permission denied"). The filesystem mode blocks access before `d_open` is even reached. + 打开应该以 `EPERM` 失败(报告为"Permission denied")。文件系统模式在到达 `d_open` 之前就阻止了访问。 -6. Temporarily change the device-node mode (as root) with `chmod 0666 /dev/secdev`. Try again as non-root. This time the filesystem allows the open, but `priv_check` in `d_open` refuses: +6. 临时用 `chmod 0666 /dev/secdev` 更改设备节点模式(以 root 身份)。以非 root 身份再次尝试。这次文件系统允许打开,但 `d_open` 中的 `priv_check` 拒绝: ``` % cat /dev/secdev cat: /dev/secdev: Operation not permitted ``` - This demonstrates the in-kernel layer of the defense. + 这展示了内核内防御层。 -7. Reset the permissions with `chmod 0600 /dev/secdev` or reload the module to restore the default. +7. 用 `chmod 0600 /dev/secdev` 重置权限,或重新加载模块以恢复默认值。 -8. As root, the device should continue to work normally. Verify: +8. 以 root 身份,设备应继续正常工作。验证: ``` # echo "hello" > /dev/secdev # cat /dev/secdev hello ``` -9. Compare with `lab04-fixed/secdev.c`. +9. 与 `lab04-fixed/secdev.c` 进行比较。 -**Digging deeper.** +**更深入的探索。** -Try creating a jailed environment and running a shell as root inside the jail: +尝试创建一个 jail 环境并在 jail 内以 root 身份运行 shell: ```console # jail -c path=/ name=testjail persist # jexec testjail sh # cat /dev/secdev ``` -Depending on whether your driver has added a `jailed()` check, the behavior differs. If the driver does not check `jailed`, jailed-root can still access the device. Add `if (jailed(td->td_ucred)) return (EPERM);` at the top of `secdev_open` and verify that the jailed access is now refused. +根据你的驱动程序是否添加了 `jailed()` 检查,行为会有所不同。如果驱动程序不检查 `jailed`,jail 内的 root 仍然可以访问设备。在 `secdev_open` 顶部添加 `if (jailed(td->td_ucred)) return (EPERM);`,并验证 jail 内的访问现在被拒绝。 **总结。** @@ -3150,15 +3150,15 @@ Depending on whether your driver has added a `jailed()` check, the behavior diff **步骤。** -1. Start from `lab05-ratelimit/secdev.c`. +1. 从 `lab05-ratelimit/secdev.c` 开始。 -2. Add a static `struct timeval` and a static `int` to hold rate-limit state. These are global per-driver, not per-softc, unless you specifically want per-device limits: +2. 添加一个静态的 `struct timeval` 和一个静态的 `int` 来保存速率限制状态。这些是每个驱动器的全局变量,不是每个 softc 的,除非你特别想要每设备限制: ```c static struct timeval secdev_log_last; static int secdev_log_pps; ``` -3. In `secdev_ioctl`, in the `default` branch (the case that handles unknown ioctls), use `ppsratecheck` to decide whether to log: +3. 在 `secdev_ioctl` 的 `default` 分支(处理未知 ioctl 的情况)中,使用 `ppsratecheck` 来决定是否记录: ```c default: if (ppsratecheck(&secdev_log_last, &secdev_log_pps, 5)) { @@ -3168,11 +3168,11 @@ Depending on whether your driver has added a `jailed()` check, the behavior diff } return (ENOTTY); ``` - The third argument, `5`, is the maximum messages per second. + 第三个参数 `5` 是每秒最大消息数。 -4. Rebuild and reload. +4. 重新构建并重新加载。 -5. Write a tiny test program that issues a million bad ioctls in a tight loop: +5. 编写一个微小测试程序,在紧凑循环中发出百万次错误 ioctl: ```c #include #include @@ -3184,15 +3184,15 @@ Depending on whether your driver has added a `jailed()` check, the behavior diff } ``` -6. While it runs (as root), monitor `dmesg -f`. You should see messages arriving, but at no more than about 5 per second. Without rate limiting, you would have a million messages. +6. 在它运行时(以 root 身份),监控 `dmesg -f`。你应该看到消息到达,但不超过每秒约 5 条。没有速率限制,你将有一百万条消息。 -7. Count the messages with something like `dmesg | grep "unknown ioctl" | wc -l`. Compare to one million (the number of attempts). +7. 用类似 `dmesg | grep "unknown ioctl" | wc -l` 的命令计数消息。与一百万(尝试次数)进行比较。 -8. Compare with `lab05-fixed/secdev.c`. +8. 与 `lab05-fixed/secdev.c` 进行比较。 -**Variations to try.** +**可尝试的变体。** -Replace `ppsratecheck` with `eventratecheck` and note the difference (event-based vs per-second). Experiment with different maximum rates. Add a suppressed-count summary that emits periodically ("suppressed N messages in last M seconds") for operator visibility. +将 `ppsratecheck` 替换为 `eventratecheck` 并注意区别(基于事件 vs 每秒)。尝试不同的最大速率。添加一个定期发出的抑制计数摘要("最近 M 秒内抑制了 N 条消息")以提高运维人员可见性。 **总结。** @@ -3204,39 +3204,39 @@ Replace `ppsratecheck` with `eventratecheck` and note the difference (event-base **步骤。** -1. Start from `lab06-detach/secdev.c`. This version introduces a small callout that periodically updates an internal counter, and an ioctl that sleeps briefly to simulate long-running work. +1. 从 `lab06-detach/secdev.c` 开始。这个版本引入了一个定期更新内部计数器的小型 callout,以及一个短暂睡眠以模拟长时间运行的 ioctl。 -2. Review the current `detach` function. Note what it frees and in what order. The starter file intentionally has a flawed detach that frees the softc without draining. +2. 审查当前的 `detach` 函数。注意它释放了什么以及以什么顺序。起始文件故意有一个有缺陷的 detach,它在没有排干的情况下释放了 softc。 -3. Test the flawed version first (build with `INVARIANTS` and `WITNESS` in the kernel): - - Start a test program that holds `/dev/secdev` open and issues the slow ioctl in a loop. - - While it runs, issue `kldunload secdev`. - - Observe the result. You may see a kernel panic, a stuck kldunload, or, if you are lucky, nothing visible (the race may not fire on every run). `WITNESS` may complain about lock state. - - Rebuild and try again until you see the problem. Concurrent races can be flaky. +3. 首先测试有缺陷的版本(在内核中构建 `INVARIANTS` 和 `WITNESS`): + - 启动一个保持 `/dev/secdev` 打开并在循环中发出慢速 ioctl 的测试程序。 + - 在它运行时,发出 `kldunload secdev`。 + - 观察结果。你可能会看到内核 panic、卡住的 kldunload,或者如果幸运的话,什么也看不到(竞态可能不是每次运行都触发)。`WITNESS` 可能会抱怨锁状态。 + - 重新构建并再次尝试直到你看到问题。并发竞态可能不稳定。 -4. Now fix the detach: - - Use `destroy_dev` on the cdev before any other cleanup, so that no new user-space thread can enter the driver, and any in-flight thread finishes before `destroy_dev` returns. - - Add a `callout_drain` call before freeing the softc. This ensures that any in-flight callout has finished. - - If the driver uses a taskqueue, add `taskqueue_drain_all`. - - Only after all draining, free resources. +4. 现在修复 detach: + - 在任何其他清理之前,在 cdev 上使用 `destroy_dev`,这样没有新的用户空间线程可以进入驱动程序,任何正在进行中的线程在 `destroy_dev` 返回之前完成。 + - 在释放 softc 之前添加 `callout_drain` 调用。这确保任何正在进行的 callout 已经完成。 + - 如果驱动程序使用了 taskqueue,添加 `taskqueue_drain_all`。 + - 只有在所有排干之后,才释放资源。 -5. Rebuild and re-test the same race: - - The user program continues running uninterrupted during `kldunload`. - - After `kldunload`, the user program's next ioctl receives an error (typically `ENXIO`) because the cdev was destroyed. - - The kernel remains stable. No panic, no WITNESS complaint. +5. 重新构建并重新测试相同的竞态: + - 在 `kldunload` 期间用户程序继续不间断地运行。 + - `kldunload` 之后,用户程序的下一个 ioctl 收到错误(通常是 `ENXIO`),因为 cdev 已被销毁。 + - 内核保持稳定。没有 panic,没有 WITNESS 投诉。 -6. Compare with `lab06-fixed/secdev.c`. Confirm that the fixed version handles in-flight activity safely. +6. 与 `lab06-fixed/secdev.c` 进行比较。确认修复版本安全地处理正在进行的活动。 -**Understanding what happened.** +**理解发生了什么。** -The flawed version races because: -- `destroy_dev` is called, or is not called early enough. In-flight d_* calls continue. -- The callout is scheduled in the future and has not fired yet. -- The softc is freed while something still references it. -- The freed softc is reused by the allocator for some other purpose. -- The callout fires, touches what it thinks is its softc, and corrupts whatever memory is now there. +有缺陷的版本发生竞态是因为: +- `destroy_dev` 被调用,或者没有尽早被调用。正在进行的 d_* 调用继续。 +- callout 被调度在未来且尚未触发。 +- softc 在有东西仍在引用它时被释放。 +- 已释放的 softc 被分配器重用于其他目的。 +- callout 触发,触及它认为是其 softc 的东西,并损坏现在在那里的任何内存。 -The fix sequences the cleanup: stop accepting new entries first (`destroy_dev`), stop in-flight entries by waiting for them to leave (part of `destroy_dev`'s contract), stop scheduled work (`callout_drain`), and only then free state. Each step closes a door; nothing beyond a closed door can reach the memory being freed. +修复方法对清理进行排序:首先停止接受新条目(`destroy_dev`),通过等待它们离开来停止正在进行的条目(`destroy_dev` 约定的一部分),停止计划的工作(`callout_drain`),然后才释放状态。每一步关闭一扇门;没有东西能穿过已关闭的门到达正在释放的内存。 **总结。** @@ -3248,42 +3248,42 @@ The fix sequences the cleanup: stop accepting new entries first (`destroy_dev`), **步骤。** -1. Start from `lab07-secure/secdev.c`. This is a skeleton with `TODO` markers in many places. +1. 从 `lab07-secure/secdev.c` 开始。这是一个在许多地方有 `TODO` 标记的骨架。 -2. Fill in each `TODO`, applying the lessons from Labs 1 to 6 plus any additional defenses you think appropriate. Suggested additions: - - A `MALLOC_DEFINE` for the driver's memory. - - A softc mutex protecting all shared fields. - - `priv_check(td, PRIV_DRIVER)` in `d_open` and in each privileged ioctl. - - `jailed()` checks for operations that should not be available to jailed users. - - `securelevel_gt` for operations that should be refused at elevated securelevel. - - `bzero` on every structure before filling it for `copyout`. - - `M_ZERO` on every allocation that will be copied to user space. - - `explicit_bzero` on sensitive buffers before `free`. - - Rate-limited `device_printf` on every log message triggerable from user space. - - `destroy_dev`, `callout_drain`, and other drains in `detach` before any free. - - A sysctl-controlled `secdev_debug` flag that gates verbose logging. - - Input validation that whitelists allowed operation codes. - - Bounded copies in both directions. - - `KASSERT` statements documenting internal invariants. +2. 填充每个 `TODO`,应用实验 1 到 6 的经验教训以及你认为合适的任何额外防御。建议添加: + - 驱动程序内存的 `MALLOC_DEFINE`。 + - 保护所有共享字段的 softc 互斥锁。 + - `d_open` 中以及每个特权 ioctl 中的 `priv_check(td, PRIV_DRIVER)`。 + - 对不应供 jailed 用户使用的操作进行 `jailed()` 检查。 + - 对应在升高安全级别时拒绝的操作进行 `securelevel_gt` 检查。 + - 在填充每个结构用于 `copyout` 之前使用 `bzero`。 + - 每个将被复制到用户空间的分配使用 `M_ZERO`。 + - 在 `free` 之前对敏感缓冲区使用 `explicit_bzero`。 + - 每个可从用户空间触发的日志消息上使用速率限制的 `device_printf`。 + - 在任何释放之前,在 `detach` 中使用 `destroy_dev`、`callout_drain` 和其他排干操作。 + - 一个 sysctl 控制的 `secdev_debug` 标志,用于门控详细日志记录。 + - 白名单允许操作码的输入验证。 + - 两个方向的有界复制。 + - 记录内部不变量的 `KASSERT` 语句。 -3. Rebuild and load the module. +3. 重新构建并加载模块。 -4. Run a comprehensive functional test to confirm everything still works: - - As root, open the device, read, write, ioctl. - - As non-root, confirm `/dev/secdev` is inaccessible. - - Inside a jail, confirm sensitive operations are refused. +4. 运行全面功能测试以确认一切仍然有效: + - 以 root 身份,打开设备,读取,写入,ioctl。 + - 以非 root 身份,确认 `/dev/secdev` 不可访问。 + - 在 jail 内部,确认敏感操作被拒绝。 -5. Run a security stress test: - - Boundary cases (0-byte reads, exactly buffer-size writes, one-byte-over writes). - - Malformed ioctls. - - Concurrent open/read/write/close from multiple processes. - - `kldunload` during active use. +5. 运行安全压力测试: + - 边界情况(0 字节读取、恰好缓冲区大小的写入、超出一字节的写入)。 + - 格式错误的 ioctl。 + - 多个进程并发 open/read/write/close。 + - 活跃使用期间的 `kldunload`。 -6. Compare your work with `lab07-fixed/secdev.c`. Note differences. Where your version is more defensive, ask whether the extra defense is worth the complexity. Where the reference is more defensive, ask whether you missed a defense. +6. 将你的工作与 `lab07-fixed/secdev.c` 进行比较。注意差异。如果你的版本更防御性,询问额外的防御是否值得复杂性。如果参考版本更防御性,询问你是否遗漏了某种防御。 -**A self-review.** +**自我审查。** -Once your lab 7 driver builds and passes tests, put on the reviewer hat. Go through the Security Checklist section of this chapter and confirm each item. Any items you cannot confirm are gaps in your driver. Fix them now, while the code is fresh; later, finding and fixing such gaps is slower and more error-prone. +一旦你的实验 7 驱动程序构建并通过测试,戴上审查者的帽子。浏览本章的安全检查清单部分并确认每个项目。任何你无法确认的项目都是驱动程序中的缺口。现在修复它们,趁代码还在新鲜状态;以后找到并修复这样的缺口会更慢、更容易出错。 **总结。** @@ -3297,273 +3297,273 @@ Once your lab 7 driver builds and passes tests, put on the reviewer hat. Go thro ### 挑战1:添加多步骤 ioctl -Design and implement an ioctl that performs a multi-step operation on `secdev`: first, the user uploads a blob; second, the user requests processing; third, the user downloads the result. Each step is a separate ioctl call. +设计并实现一个在 `secdev` 上执行多步骤操作的 ioctl:首先,用户上传一个数据块;其次,用户请求处理;第三,用户下载结果。每个步骤是一个独立的 ioctl 调用。 -The challenge is to manage per-open state correctly: the blob uploaded in step 1 must be associated with the calling file descriptor, not globally. Two concurrent users must not see each other's blobs. State must be cleaned up when the file descriptor is closed, even if the user never reached step 3. +挑战在于正确管理每次打开的状态:步骤 1 中上传的数据块必须与调用文件描述符关联,而不是全局的。两个并发用户不能看到彼此的数据块。当文件描述符关闭时,即使从未到达步骤 3,状态也必须被清理。 -Security considerations: bound the blob size, validate each step of the state machine (cannot request processing without a blob; cannot download without completing processing), make sure partial state on error paths is cleaned up, and make sure a user-visible identifier (if you expose one) is not a kernel pointer. +安全考虑:限制数据块大小,验证状态机的每个步骤(没有数据块就不能请求处理;没有完成处理就不能下载),确保错误路径上的部分状态被清理,并确保用户可见的标识符(如果你暴露了一个)不是内核指针。 ### 挑战2:编写 syzkaller 描述 -Write a syzkaller syscall description for `secdev`'s ioctl interface. The format is documented in the syzkaller repository. Install syzkaller and feed it your driver; run it for at least an hour (ideally longer) and see what it finds. +为 `secdev` 的 ioctl 接口编写一个 syzkaller 系统调用描述。格式在 syzkaller 仓库中有文档记录。安装 syzkaller 并将其输入你的驱动程序;运行至少一小时(理想情况下更长时间),看看它能找到什么。 -If it finds bugs, fix them. Write a note about what each bug was and how the fix works. If it does not find bugs in several hours, consider whether your syzkaller description really exercises the driver. Often a description that does not find bugs is not exploring the interface thoroughly. +如果它发现了 bug,修复它们。写下每个 bug 是什么以及修复是如何工作的。如果它几小时内没有发现 bug,考虑你的 syzkaller 描述是否真的在练习驱动程序。通常没有发现 bug 的描述并没有彻底探索接口。 ### 挑战3:在自己的代码中检测双重释放 -Intentionally introduce a double-free bug into a copy of your secure `secdev`. Build the module against a kernel with `INVARIANTS` and `WITNESS`. Load and exercise the module in a way that triggers the double-free. Observe what happens. +故意在你的安全 `secdev` 副本中引入一个双重释放 bug。针对带有 `INVARIANTS` 和 `WITNESS` 的内核构建模块。以触发双重释放的方式加载并练习该模块。观察发生了什么。 -Now rebuild the kernel with `KASAN`. Load and exercise the same broken module. Observe the difference in how the bug is detected. +现在用 `KASAN` 重新构建内核。加载并练习相同的有问题模块。观察在如何检测 bug 方面的差异。 -Write down what each sanitizer caught and how readable the output was. This exercise builds intuition for which sanitizer to reach for first in which situation. +写下每个净化器捕获了什么以及输出的可读性。这个练习建立了关于在哪种情况下首先使用哪个净化器的直觉。 ### 挑战4:对现有驱动程序进行威胁建模 -Pick a driver in the FreeBSD tree that you have not previously examined (something small, ideally under 2000 lines). Read it carefully. Write a threat model: who are the callers, what privileges do they need, what could go wrong, what mitigations are in place, what could be added? +在 FreeBSD 树中选择一个你以前没有检查过的驱动程序(小型的,理想情况下少于 2000 行)。仔细阅读它。编写一个威胁模型:调用者是谁,他们需要什么权限,可能出什么问题,有哪些缓解措施,可以添加什么? -The goal is not to find specific bugs. It is to practice the security mindset on real code. A good threat model is a few pages of prose that would let another engineer review the same driver efficiently. +目标不是找到特定的 bug。它是在真实代码上练习安全思维方式。一个好的威胁模型是几页文字,能让另一位工程师高效地审查同一个驱动程序。 ### 挑战5:比较 `/dev/null` 和 `/dev/mem` -Open `/usr/src/sys/dev/null/null.c` and `/usr/src/sys/dev/mem/memdev.c` (or the per-architecture equivalents). Read both. +打开 `/usr/src/sys/dev/null/null.c` 和 `/usr/src/sys/dev/mem/memdev.c`(或每个架构的等价物)。阅读两者。 -Write a short essay (a page or two) on the security differences. `/dev/null` is one of the simplest drivers in FreeBSD; what does it do, and why is it safe? `/dev/mem` is one of the most dangerous; what does it do, and how does FreeBSD keep it safe? What can you learn about the shape of secure driver code from the contrast? +就安全差异写一篇短文(一两页)。`/dev/null` 是 FreeBSD 中最简单的驱动程序之一;它做什么,为什么安全?`/dev/mem` 是最危险的之一;它做什么,FreeBSD 如何保持其安全?从对比中你可以学到安全驱动程序代码的形状? ## 故障排除与常见错误 -A short catalogue of mistakes I have seen repeatedly in real driver code, with the symptom, the cause, and the fix. +一个我在真实驱动程序代码中反复看到的错误简短目录,包括症状、原因和修复方法。 ### "有时能工作,有时不能" -**Symptom.** A test passes most of the time but occasionally fails. Running under load amplifies the failure rate. +**症状。** 测试大部分时间通过但偶尔失败。在负载下运行会放大失败率。 -**Cause.** Almost always a race condition. Something is being read and written concurrently without a lock. +**原因。** 几乎总是竞态条件。某物被并发读写而没有锁。 -**Fix.** Identify the shared state. Add a lock. Acquire the lock for the whole check-and-act sequence. Do not trust `atomic_*` operations to solve a multi-field invariant problem. +**修复。** 识别共享状态。添加锁。为整个检查-行动序列获取锁。不要信任 `atomic_*` 操作来解决多字段不变量问题。 ### "驱动程序在卸载时崩溃" -**Symptom.** `kldunload` triggers a panic or a stuck kernel. +**症状。** `kldunload` 触发 panic 或卡住内核。 -**Cause.** A callout, taskqueue task, or kernel thread is still running when `detach` frees the structure it uses. Or an in-flight cdev operation is still in the driver's code when `destroy_dev` is skipped. +**原因。** 当 `detach` 释放 callout、taskqueue 任务或内核线程使用的结构时,它们仍在运行。或者当 `destroy_dev` 被跳过时,正在进行中的 cdev 操作仍在驱动程序的代码中。 -**Fix.** In `detach`, call `destroy_dev` before anything else. Then `callout_drain` every callout, `taskqueue_drain_all` every taskqueue, and wait for every kernel thread to exit. Only then free state. Structure the detach as a strict reverse of attach. +**修复。** 在 `detach` 中,在任何其他操作之前调用 `destroy_dev`。然后对每个 callout 使用 `callout_drain`,对每个 taskqueue 使用 `taskqueue_drain_all`,并等待每个内核线程退出。只有这样才释放状态。将 detach 构建为 attach 的严格逆操作。 ### "ioctl 以 root 身份可以工作,但以服务账户不行" -**Symptom.** User reports that root can use the device, but a non-root account cannot. +**症状。** 用户报告 root 可以使用设备,但非 root 账户不能。 -**Cause.** Device node permissions are too restrictive, or a `priv_check` call refuses the operation. +**原因。** 设备节点权限过于严格,或者 `priv_check` 调用拒绝了操作。 -**Fix.** If the operation truly should be privileged, this is working as intended; document it. If not, reconsider: was the privilege check added in error? Is the device-node mode too tight? The correct answer depends on the operation; most real answers are "yes, it should be privileged, update the docs". +**修复。** 如果操作确实应该是特权的,这就是按预期工作;记录它。如果不是,重新考虑:权限检查是否错误地添加了?设备节点模式是否过紧?正确答案取决于操作;大多数真实答案是"是的,它应该是特权的,更新文档"。 ### "dmesg 被淹没" -**Symptom.** `dmesg` shows thousands of identical messages from the driver. Legitimate messages are being pushed out. +**症状。** `dmesg` 显示来自驱动程序的数千条相同消息。合法消息被推出。 -**Cause.** A log statement in a path triggerable from user space, without rate limiting. +**原因。** 在可从用户空间触发的路径中的日志语句,没有速率限制。 -**Fix.** Wrap the log in `ppsratecheck` or `eventratecheck`. Limit to a few per second. If the message is about an error, include a count of suppressed messages when the rate returns to normal (the rate helpers support this). +**修复。** 将日志包裹在 `ppsratecheck` 或 `eventratecheck` 中。限制为每秒几条。如果消息是关于错误的,在速率恢复正常时包括抑制消息的计数(速率辅助函数支持此功能)。 ### "返回的结构中包含垃圾字节" -**Symptom.** A user-space tool reports seeing apparently random data in a field it did not expect to be set. +**症状。** 用户空间工具报告在它不期望设置的字段中看到明显随机的数据。 -**Cause.** The driver did not zero the structure before filling and copying out. The "random" data is actually stack or heap content from before. +**原因。** 驱动程序在填充和复制出去之前没有清零结构。"随机"数据实际上是之前的栈或堆内容。 -**Fix.** Add a `bzero` at the top of the function, or initialize the structure with `= { 0 }` at declaration. Never `copyout` an uninitialized structure. +**修复。** 在函数顶部添加 `bzero`,或在声明时用 `= { 0 }` 初始化结构。永远不要 `copyout` 未初始化的结构。 ### "内存泄漏但看不到在哪里" -**Symptom.** `vmstat -m` shows the driver's malloc type growing over time. Eventually the system runs out of memory. +**症状。** `vmstat -m` 显示驱动程序的 malloc 类型随时间增长。最终系统内存耗尽。 -**Cause.** An allocation path that does not pair with a free path, or an error path that returns without freeing. +**原因。** 一个没有与释放路径配对的分配路径,或者一个返回而未释放的错误路径。 -**Fix.** Use a named malloc type (`MALLOC_DEFINE`). Audit every allocation. Walk every error path. Consider the single-cleanup-label pattern. Build with `INVARIANTS` and watch for allocator warnings on unload. +**修复。** 使用命名的 malloc 类型(`MALLOC_DEFINE`)。审计每个分配。遍历每个错误路径。考虑单一清理标签模式。用 `INVARIANTS` 构建并注意卸载时的分配器警告。 ### "kldload 成功但设备没有出现在 /dev 中" -**Symptom.** `kldstat` shows the module loaded, but there is no `/dev/secdev` entry. +**症状。** `kldstat` 显示模块已加载,但没有 `/dev/secdev` 条目。 -**Cause.** Usually an error in the `attach` sequence before `make_dev_s` is called, or `make_dev_s` itself failed silently. +**原因。** 通常是在调用 `make_dev_s` 之前的 `attach` 序列中的错误,或者 `make_dev_s` 本身静默失败。 -**Fix.** Check the return value of `make_dev_s`. Add a `device_printf` reporting any error. Verify `attach` is being reached by adding a `device_printf` at the top. +**修复。** 检查 `make_dev_s` 的返回值。添加报告任何错误的 `device_printf`。通过在顶部添加 `device_printf` 验证 `attach` 是否被到达。 ### "简单的 C 测试通过,但循环执行的 shell 脚本失败" -**Symptom.** Single-shot testing works. Rapid repeated testing fails. +**症状。** 单次测试有效。快速重复测试失败。 -**Cause.** Likely a race between repeated operations, or a resource that is not being cleaned up between calls. Sometimes a TOCTOU bug that is timing-sensitive. +**原因。** 可能是重复操作之间的竞态,或者调用之间未清理的资源。有时是对时序敏感的 TOCTOU bug。 -**Fix.** Stress-test harder. Use `dtrace` or `ktrace` to see what is happening. Look for state that persists across calls and should not. +**修复。** 更努力地进行压力测试。使用 `dtrace` 或 `ktrace` 查看正在发生的事情。寻找跨调用持续存在且不应存在的状态。 ### "KASAN 报告释放后使用,但我的 malloc/free 是平衡的" -**Symptom.** `KASAN` reports access to freed memory, but visual inspection of the driver shows each allocation freed exactly once. +**症状。** `KASAN` 报告对已释放内存的访问,但对驱动程序的目视检查显示每个分配恰好被释放一次。 -**Cause.** A common subtle case: a callout or taskqueue task still holds a pointer to the freed object. The callout fires after free. +**原因。** 一种常见的微妙情况:callout 或 taskqueue 任务仍持有指向已释放对象的指针。callout 在释放后触发。 -**Fix.** Trace the callout lifecycle. Ensure `callout_drain` (or equivalent) runs before any free. A related case is an asynchronous completion callback; ensure the operation is either completed or cancelled before the owning structure is freed. +**修复。** 追踪 callout 生命周期。确保 `callout_drain`(或等效操作)在任何释放之前运行。一个相关的情况是异步完成回调;确保操作在拥有它的结构被释放之前要么完成要么被取消。 ### "WITNESS 抱怨锁顺序" -**Symptom.** `WITNESS` reports "lock order reversal" and identifies two locks that were acquired in inconsistent order. +**症状。** `WITNESS` 报告"锁顺序反转"并标识了两个按不一致顺序获取的锁。 -**Cause.** At one point the code acquired lock A then lock B; at another point it acquired lock B then lock A. This can deadlock. +**原因。** 在一个点代码获取了锁 A 然后锁 B;在另一个点它获取了锁 B 然后锁 A。这可能导致死锁。 -**Fix.** Decide on a canonical order for your locks. Document it. Acquire them in that order everywhere. If a code path legitimately needs the reverse order, use `mtx_trylock` with a backoff-and-retry pattern. +**修复。** 为你的锁决定一个规范顺序。记录它。在所有地方按该顺序获取它们。如果某个代码路径合法地需要相反的顺序,使用带有回退和重试模式的 `mtx_trylock`。 ### "vmstat -m 显示负数的空闲计数" -**Symptom.** `vmstat -m` lists the driver's malloc type with a negative number of allocations, or with an inuse count that increases over time without bound. +**症状。** `vmstat -m` 列出驱动程序的 malloc 类型时显示的分配数为负数,或者正在使用的计数无限制地随时间增长。 -**Cause.** A mismatched `malloc`/`free` type, or a leak where allocations happen without corresponding frees. +**原因。** `malloc`/`free` 类型不匹配,或者有分配而无对应释放的泄漏。 -**Fix.** A negative free count almost always means a `free` call passed the wrong type tag. Audit every `free(ptr, M_TYPE)` and confirm the type matches the `malloc`. A continuously rising inuse count is a leak; audit every path that allocates and confirm it has a matching free on every exit. +**修复。** 负数空闲计数几乎总是意味着 `free` 调用传递了错误的类型标签。审计每个 `free(ptr, M_TYPE)` 并确认类型与 `malloc` 匹配。持续增长的 inuse 计数是一个泄漏;审计每个分配的路径,并确认它在每个出口都有匹配的释放。 ### "驱动程序在 amd64 上工作但在 arm64 上崩溃" -**Symptom.** Functional testing on amd64 passes; the same driver panics on arm64. +**症状。** amd64 上的功能测试通过;相同的驱动程序在 arm64 上 panic。 -**Cause.** Often a mismatch in structure padding or alignment. arm64 has different padding rules from amd64 for some structures. An access that is aligned on amd64 may be misaligned on arm64 and panic. +**原因。** 通常是结构填充或对齐的不匹配。arm64 对于某些结构有与 amd64 不同的填充规则。在 amd64 上对齐的访问可能在 arm64 上未对齐并 panic。 -**Fix.** Use `__packed` carefully (it changes alignment), use `__aligned(N)` where alignment matters, and avoid assuming the size or layout of a structure matches between architectures. For fields crossing the user/kernel boundary, use explicit widths (`uint32_t` rather than `int`, `uint64_t` rather than `long`). +**修复。** 小心使用 `__packed`(它改变对齐),在对齐重要的地方使用 `__aligned(N)`,并避免假设结构的大小或布局在架构之间匹配。对于跨越用户/内核边界的字段,使用显式宽度(`uint32_t` 而不是 `int`,`uint64_t` 而不是 `long`)。 ### "驱动程序编译无错误但 dmesg 显示内核构建警告" -**Symptom.** The module builds, but loading it produces warnings about unresolved symbols or ABI mismatches. +**症状。** 模块构建成功,但加载时产生关于未解析符号或 ABI 不匹配的警告。 -**Cause.** The module was built against a different kernel than the one it is being loaded into. The kernel ABI is not guaranteed stable across versions, so a module built against 14.2 may not load cleanly on 14.3. +**原因。** 模块是针对与加载到的目标不同的内核构建的。内核 ABI 不保证跨版本稳定,所以针对 14.2 构建的模块可能无法在 14.3 上干净加载。 -**Fix.** Rebuild the module against the running kernel's source tree. `uname -r` shows the running kernel version; verify that `/usr/src` matches. If they do not, install the matching source (via `freebsd-update`, `svn`, or `git`, depending on your source distribution). +**修复。** 针对正在运行的内核源代码树重新构建模块。`uname -r` 显示正在运行的内核版本;验证 `/usr/src` 匹配。如果不匹配,安装匹配的源代码(通过 `freebsd-update`、`svn` 或 `git`,取决于你的源代码分发)。 ### "驱动程序间歇性地比预期慢" -**Symptom.** Benchmarks show occasional large latency spikes even under moderate load. +**症状。** 基准测试显示即使在中等负载下也会偶尔出现大的延迟峰值。 -**Cause.** Often a lock-contention issue: multiple threads queue on a single mutex. Sometimes an allocator stall: `malloc(M_WAITOK)` in a hot path waits for memory to become available. +**原因。** 通常是锁争用问题:多个线程排队等待单个互斥锁。有时是分配器停顿:热点路径中的 `malloc(M_WAITOK)` 等待内存可用。 -**Fix.** Use `dtrace` to profile lock contention (`lockstat` provider) and identify which lock is hot. Restructure to reduce the critical section, split the lock, or use a lock-free approach. For allocator stalls, preallocate or use a UMA zone with a high-water mark. +**修复。** 使用 `dtrace` 分析锁争用(`lockstat` 提供者)并识别哪个锁是热点。重构以减少临界区,拆分锁,或使用无锁方法。对于分配器停顿,预分配或使用带有高水位标记的 UMA 区域。 ## 驱动程序代码审查安全检查清单 -This section is a reference checklist you can keep next to your code as you review a driver, yours or someone else's. It is not exhaustive, but if every item on the list has been consciously considered, the driver is in much better shape than the average. +本节是一个参考检查清单,你可以放在代码旁边,在审查驱动程序(你自己的或别人的)时使用。它不是详尽的,但如果清单上的每个项目都被有意识地考虑过,驱动程序的状态会比平均水平好得多。 ### 结构检查 -The driver's module-load and module-unload paths are symmetric. Every resource allocated on load is freed on unload, and the order of freeing is the reverse of the order of allocation. +驱动程序的模块加载和模块卸载路径是对称的。加载时分配的每个资源在卸载时释放,释放顺序与分配顺序相反。 -The driver uses `make_dev_s` or `make_dev_credf` (not the legacy `make_dev` alone) so that errors during device-node creation are reported and handled. +驱动程序使用 `make_dev_s` 或 `make_dev_credf`(而不是单独的遗留 `make_dev`),以便设备节点创建期间的错误被报告和处理。 -The device node is created with conservative permissions. Mode `0600` or `0640` is the default; anything more permissive has an explicit reason recorded in comments or commit messages. +设备节点以保守权限创建。模式 `0600` 或 `0640` 是默认值;任何更宽松的权限都有明确的原因记录在注释或提交消息中。 -The driver declares a named `malloc_type` via `MALLOC_DECLARE` and `MALLOC_DEFINE`. All allocations use this type. +驱动程序通过 `MALLOC_DECLARE` 和 `MALLOC_DEFINE` 声明了一个命名的 `malloc_type`。所有分配都使用此类型。 -Every lock in the driver has a comment next to its declaration saying what it protects. The comment is accurate. +驱动程序中的每个锁在其声明旁边都有一条注释说明它保护什么。注释是准确的。 ### 输入与边界检查 -Every `copyin` call is paired with a size argument that cannot exceed the destination buffer size. +每个 `copyin` 调用都有一个不能超过目标缓冲区大小的大小参数。 -Every `copyout` call uses a length that is the minimum of the caller's buffer size and the kernel source's size. +每个 `copyout` 调用使用调用者缓冲区大小和内核源大小中较小的一个。 -`copyinstr` is used for strings that should be NUL-terminated. The return value (including `done`) is checked. +`copyinstr` 应用于应为 NUL 终止的字符串。检查返回值(包括 `done`)。 -Every ioctl argument structure is copied into kernel space before any of its fields are read. +每个 ioctl 参数结构在其任何字段被读取之前被复制到内核空间。 -`uiomove` calls pass a length that is clamped to the buffer being read from or written to, not `uio->uio_resid` alone. +`uiomove` 调用传递被钳制到正在读取或写入的缓冲区大小的长度,而不是单独使用 `uio->uio_resid`。 -Every user-provided length field is validated: non-zero when required, bounded below the appropriate maximum, checked against remaining buffer space. +每个用户提供的长度字段都被验证:在需要时非零,限制在适当的最大值以下,对照剩余缓冲区空间检查。 ### 内存管理 -Every `malloc` call checks the return value if `M_NOWAIT` is used. `M_WAITOK` without `M_NULLOK` is never null-checked uselessly; the code relies on the allocator's guarantee. +如果使用 `M_NOWAIT`,每个 `malloc` 调用都会检查返回值。不带 `M_NULLOK` 的 `M_WAITOK` 永远不会无用地进行空值检查;代码依赖分配器的保证。 -Every `malloc` is paired with exactly one `free` on every code path. Success paths and error paths are both audited. +每个 `malloc` 在每条代码路径上都与恰好一个 `free` 配对。成功路径和错误路径都被审计。 -Sensitive data (keys, passwords, credentials, proprietary secrets) is zeroed with `explicit_bzero` or `zfree` before the memory is released. +敏感数据(密钥、密码、凭据、专有秘密)在内存释放前用 `explicit_bzero` 或 `zfree` 清零。 -Structures that will be copied to user space are zeroed before being filled. +将被复制到用户空间的结构在填充之前被清零。 -Buffers allocated for user output use `M_ZERO` at allocation time to prevent stale-data leaks through the tail. +为用户输出分配的缓冲区在分配时使用 `M_ZERO` 以防止通过尾部泄露陈旧数据。 -After a pointer is freed, it is either set to NULL or the scope immediately ends. +指针被释放后,要么设置为 NULL,要么作用域立即结束。 ### 权限与访问控制 -Operations that require administrative privilege call `priv_check(td, PRIV_DRIVER)` or a more specific `PRIV_*` constant. +需要管理权限的操作调用 `priv_check(td, PRIV_DRIVER)` 或更具体的 `PRIV_*` 常量。 -Operations that should not be allowed inside a jail explicitly check `jailed(td->td_ucred)` and return `EPERM` if jailed. +不应在 jail 内允许的操作显式检查 `jailed(td->td_ucred)`,如果被 jailed 则返回 `EPERM`。 -Operations that depend on the system's securelevel call `securelevel_gt` or `securelevel_ge` and handle the return value correctly (note the inverted semantics: nonzero means refuse). +依赖于系统安全级别的操作调用 `securelevel_gt` 或 `securelevel_ge` 并正确处理返回值(注意反转的语义:非零意味着拒绝)。 -No operation uses `cr_uid == 0` as a privilege gate. `priv_check` is used instead. +没有操作使用 `cr_uid == 0` 作为权限门控。而是使用 `priv_check`。 -Sysctls that expose sensitive data use `CTLFLAG_SECURE` or restrict themselves to privileged users via permission checks. +暴露敏感数据的 sysctl 使用 `CTLFLAG_SECURE` 或通过权限检查限制自己仅供特权用户使用。 ### 并发 -Every field of the softc that is accessed by more than one context is protected by a lock. +softc 中被多个上下文访问的每个字段都由锁保护。 -The full check-and-act sequence (including lookups that decide whether an operation is legal) is held under the appropriate lock. +完整的检查-行动序列(包括决定操作是否合法的查找)在适当的锁下持有。 -No `copyin`, `copyout`, or `uiomove` call is made while holding a mutex. If user-space I/O is needed, the code drops the lock, does the I/O, and re-acquires, checking invariants. +持有互斥锁时不进行 `copyin`、`copyout` 或 `uiomove` 调用。如果需要用户空间 I/O,代码释放锁,执行 I/O,然后重新获取,检查不变量。 -`detach` calls `destroy_dev` (or equivalent) first, then drains callouts, taskqueues, and interrupts, then frees state. +`detach` 首先调用 `destroy_dev`(或等效操作),然后排干 callout、taskqueue 和中断,然后释放状态。 -Callouts, taskqueues, and kernel threads are tracked so that every one of them can be drained during unload. +Callout、taskqueue 和内核线程被跟踪,以便它们中的每一个都可以在卸载期间被排干。 ### 信息卫生 -No kernel pointer (`%p` or equivalent) is returned to user space through an ioctl, sysctl, or log message in a user-triggerable path. +没有内核指针(`%p` 或等效物)通过用户可触发的路径中的 ioctl、sysctl 或日志消息返回给用户空间。 -No user-triggerable log message is uncapped; `ppsratecheck` or similar wraps every such message. +没有用户可触发的日志消息是不设上限的;`ppsratecheck` 或类似的机制包裹每条这样的消息。 -Logs do not include user-supplied data that could contain control characters or sensitive information. +日志不包括可能包含控制字符或敏感信息的用户提供的数据。 -Debug logging is wrapped in a conditional (sysctl or compile-time) so that production builds do not emit it by default. +调试日志被包裹在条件(sysctl 或编译时)中,以便生产构建默认不发出它们。 ### 故障模式 -Every switch statement has a `default:` branch that returns a sensible error. +每个 switch 语句都有一个返回合理错误的 `default:` 分支。 -Every parser or validator whitelists what is allowed, rather than blacklisting what is not. +每个解析器或验证器白名单允许的内容,而不是黑名单不允许的内容。 -Every operation with resource use has a cap. The cap is documented. +每个有资源使用的操作都有一个上限。上限被记录。 -Every sleep has a finite timeout unless a genuine reason requires unbounded waiting (and even then, `PCATCH` is used to allow signals). +每次睡眠都有一个有限的超时,除非有真正的理由需要无限等待(即使如此,也使用 `PCATCH` 来允许信号)。 -Every error path frees the resources its success path would have kept. +每个错误路径都会释放其成功路径本会保留的资源。 -The driver's response to unexpected input is to refuse the operation, not to guess. +驱动程序对意外输入的响应是拒绝操作,而不是猜测。 ### 测试 -The driver has been loaded and tested against a kernel built with `INVARIANTS` and `WITNESS`. No assertions fire and no lock-order violations are reported. +驱动程序已加载并针对使用 `INVARIANTS` 和 `WITNESS` 构建的内核进行了测试。没有断言触发,没有锁顺序违规报告。 -The driver has been tested under concurrent load (multiple processes, multiple open file descriptors, interleaved operations). +驱动程序已在并发负载下测试(多进程、多打开文件描述符、交织操作)。 -The driver has been tested under detach-time concurrency (a user is inside the driver while unload is attempted). +驱动程序已在分离时并发下测试(在尝试卸载时用户位于驱动程序内部)。 -Some form of fuzzing (ideally syzkaller, at minimum a randomized shell test) has been run against the driver. +已对驱动程序运行了某种形式的模糊测试(理想情况下是 syzkaller,至少是随机化的 shell 测试)。 -The driver has been reviewed by someone other than its author. The review was specifically for security considerations, not only functionality. +驱动程序已由作者以外的人审查。审查专门针对安全考虑,而不仅仅是功能。 ### 演进 -The driver's security posture is re-examined at regular intervals. New compiler warnings and new sanitizer findings are triaged seriously. New FreeBSD privilege codes are considered. Unused interfaces are removed. +驱动程序的安全态势定期重新检查。新的编译器警告和新的净化器发现被认真分类。考虑新的 FreeBSD 权限代码。删除未使用的接口。 -Bug reports against the driver are treated as possibly exploitable until proven otherwise. +针对驱动程序的 bug 报告被视为可能可利用,直到证明并非如此。 -Commit history shows that security-relevant changes receive careful commit messages that explain what was wrong and what the fix does. +提交历史显示安全相关的更改有仔细的提交消息,解释了什么出错了以及修复做了什么。 ## 深入了解真实世界的漏洞模式 -The principles in this chapter are abstractions over real bugs that happened in real kernels. This section studies a few patterns that have appeared across the FreeBSD, Linux, and other open-source operating systems over the years. The goal is not to catalogue CVEs (there are whole databases for that) but to train pattern recognition. +本章的原则是对真实内核中发生的真实 bug 的抽象。本节研究了一些多年来出现在 FreeBSD、Linux 和其他开源操作系统中的模式。目标不是编录 CVE(有整个数据库做这个),而是训练模式识别。 ### 不完整的复制 -A classic pattern: a driver receives a variable-length user buffer. It copies a fixed header, extracts a length field from the header, then copies the variable portion according to that length. +一个经典模式:驱动程序接收一个可变长度的用户缓冲区。它复制一个固定头部,从头部提取长度字段,然后根据该长度复制可变部分。 ```c error = copyin(uaddr, &hdr, sizeof(hdr)); @@ -3576,13 +3576,13 @@ if (hdr.body_len > MAX_BODY) error = copyin(uaddr + sizeof(hdr), body, hdr.body_len); ``` -The bug is that the length check compares `body_len` against `MAX_BODY`, but `body` may be a fixed-size buffer sized differently. If `MAX_BODY` is defined carelessly, or if it was once the size of `body` but `body` has since shrunk, the copy overflows `body`. +bug 在于长度检查将 `body_len` 与 `MAX_BODY` 进行比较,但 `body` 可能是一个不同大小的固定大小缓冲区。如果 `MAX_BODY` 定义不小心,或者它曾经是 `body` 的大小但后来 `body` 缩小了,复制就会溢出 `body`。 -Every time you see a pattern of "validate header, then copy body based on header", check that the length bound actually matches the destination buffer size. Use `sizeof(body)` directly if you can, rather than a macro that might drift. +每当你看到"验证头部,然后根据头部复制主体"的模式时,检查长度边界是否实际匹配目标缓冲区大小。如果可能,直接使用 `sizeof(body)`,而不是可能漂移的宏。 ### 符号混淆 -A length is stored as `int` but should be non-negative. A caller passes `-1`. Your code: +长度存储为 `int` 但应为非负数。调用者传入 `-1`。你的代码: ```c if (len > MAX_LEN) @@ -3592,28 +3592,28 @@ buf = malloc(len, M_FOO, M_WAITOK); copyin(uaddr, buf, len); ``` -Does the first check pass? Yes, because `-1` is less than `MAX_LEN` when compared as a signed `int`. What happens in `malloc(len, ...)` with `len = -1`? On many platforms, `-1` silently becomes a very large positive `size_t`. The allocation fails (or worse, succeeds at a huge size), or `copyin` tries to copy a huge buffer. +第一次检查通过了吗?是的,因为 `-1` 作为有符号 `int` 比较时小于 `MAX_LEN`。当 `len = -1` 时在 `malloc(len, ...)` 中会发生什么?在许多平台上,`-1` 静默变成非常大的正数 `size_t`。分配失败(或者更糟,以巨大的大小成功),或者 `copyin` 尝试复制一个巨大的缓冲区。 -The fix is to use unsigned types for sizes (preferably `size_t`), or to check for negative values explicitly: +修复方法是对大小使用无符号类型(最好是 `size_t`),或显式检查负值: ```c if (len < 0 || len > MAX_LEN) return (EINVAL); ``` -Or, better, change the type so that negative values cannot exist: +或者,更好的是,改变类型使负值不可能存在: ```c -size_t len = arg->len; /* copied from user, already size_t */ +size_t len = arg->len; /* 从用户复制过来,已经是 size_t */ if (len > MAX_LEN) return (EINVAL); ``` -Sign confusion is one of the most common root causes of buffer overflows in kernel code. Use `size_t` for sizes. Use `ssize_t` only when negative values are meaningful. Never mix signed and unsigned in a size check. +符号混淆是内核代码中缓冲区溢出最常见的根本原因之一。对大小使用 `size_t`。只有在负值有意义时才使用 `ssize_t`。永远不要在大小检查中混合有符号和无符号。 ### 不完整的验证 -A driver accepts a complex structure with many fields. The validation function checks some fields but forgets others: +驱动程序接收一个具有许多字段的复杂结构。验证函数检查了一些字段但忘记了其他字段: ```c if (args->type > TYPE_MAX) @@ -3625,13 +3625,13 @@ if (args->count > COUNT_MAX) use(args->offset); /* attacker-controlled */ ``` -The bug is that `args->offset` is used as an index into an array without being bounds-checked. An attacker supplies a huge offset and reads or writes kernel memory. +bug 在于 `args->offset` 被用作数组索引而未进行边界检查。攻击者提供一个巨大的偏移量并读取或写入内核内存。 -The fix is to treat validation as a checklist. For every field in the input structure, ask: what values are legal? Enforce them all. A helper function `is_valid_arg` that centralizes the validation and is called early is better than scattered checks. +修复方法是将验证视为检查清单。对于输入结构中的每个字段,问:哪些值合法?强制执行所有合法值。一个集中验证并尽早调用的辅助函数 `is_valid_arg` 比分散的检查更好。 ### 错误路径上跳过的检查 -A driver carefully validates input on the success path, but the error path cleans up based on a field that was never validated: +驱动程序在成功路径上仔细验证输入,但错误路径基于从未验证的字段进行清理: ```c if (args->count > COUNT_MAX) @@ -3647,13 +3647,13 @@ if (error != 0) { } ``` -The error path uses `args->free_flag` and `args->ptr`, neither of which were validated. If the attacker arranges for `copyin` to fail (say, by unmapping the memory), the error path frees an attacker-controlled pointer, corrupting the kernel heap. +错误路径使用了 `args->free_flag` 和 `args->ptr`,两者都未被验证。如果攻击者安排 `copyin` 失败(例如,通过取消映射内存),错误路径会释放攻击者控制的指针,损坏内核堆。 -The lesson: validation must cover every field that any code path reads. It is tempting to think "the error path is unusual; it is fine". Attackers specifically aim for error paths because they are less tested. +教训:验证必须覆盖任何代码路径读取的每个字段。人们很容易认为"错误路径不常见;没问题"。攻击者专门针对错误路径,因为它们测试较少。 ### 双重查找 -A driver looks up an object in a table by name or ID, then performs an operation. Between the lookup and the operation, the object is removed by another thread. The operation then acts on freed memory. +驱动程序通过名称或 ID 在表中查找对象,然后执行操作。在查找和操作之间,该对象被另一个线程移除。然后操作作用于已释放的内存。 ```c obj = lookup(id); @@ -3662,27 +3662,27 @@ if (obj == NULL) do_operation(obj); /* obj may have been freed in between */ ``` -The fix is to take a reference on the object (using a refcount) inside the lookup, hold the reference across the operation, and release it at the end. The lookup function takes the lock, increments the refcount, and releases the lock. The operation then works with a refcount-held pointer that cannot be freed out from under it. The release decrements the refcount; when it drops to zero, the last holder frees the object. +修复方法是在查找内部获取对象上的引用(使用引用计数),在整个操作期间持有引用,并在结束时释放它。查找函数获取锁,增加引用计数,并释放锁。然后操作使用持有引用的指针,该指针不能从它下面被释放。释放递减引用计数;当它降到零时,最后一个持有者释放对象。 -Reference counts are the FreeBSD-canonical answer to the double-lookup problem. See `/usr/src/sys/sys/refcount.h`. +引用计数是 FreeBSD 规范的对双重查找问题的答案。参见 `/usr/src/sys/sys/refcount.h`。 ### 增长的缓冲区 -A buffer was once 256 bytes. A constant `BUF_SIZE = 256` was defined. The code checked `len <= BUF_SIZE` and copied `len` bytes into the buffer. Later, someone increased the buffer to 1024 bytes but forgot to update the constant. Or the constant was updated but an `sizeof(buf)` in one call was not, because it was not using the constant. +一个缓冲区曾经是 256 字节。定义了一个常量 `BUF_SIZE = 256`。代码检查 `len <= BUF_SIZE` 并将 `len` 字节复制到缓冲区中。后来,有人将缓冲区增加到 1024 字节但忘记更新常量。或者常量被更新了但一个调用中的 `sizeof(buf)` 没有被更新,因为它没有使用常量。 -This class of bug is prevented by always using `sizeof` on the destination buffer directly, rather than a constant that may drift: +这类 bug 可以通过始终直接对目标缓冲区使用 `sizeof` 来防止,而不是使用可能漂移的常量: ```c char buf[BUF_SIZE]; -if (len > sizeof(buf)) /* always matches the actual buf size */ +if (len > sizeof(buf)) /* 始终匹配实际的 buf 大小 */ return (EINVAL); ``` -Constants are useful when multiple places need the same bound. If you use a constant, keep the definition and the array adjacent in the source code, and consider adding a `_Static_assert(sizeof(buf) == BUF_SIZE, ...)` to catch drift. +当多个地方需要相同的边界时,常量是有用的。如果你使用常量,将定义和数组放在源代码中相邻的位置,并考虑添加 `_Static_assert(sizeof(buf) == BUF_SIZE, ...)` 以捕获漂移。 ### 结构中未检查的指针 -A driver receives a structure from user space that contains pointers. The driver uses the pointers directly: +驱动程序从用户空间接收一个包含指针的结构。驱动程序直接使用指针: ```c error = copyin(uaddr, &cmd, sizeof(cmd)); @@ -3690,13 +3690,13 @@ error = copyin(uaddr, &cmd, sizeof(cmd)); use(cmd.data_ptr); /* treating user pointer as kernel pointer */ ``` -This is a catastrophic bug: the pointer is a user-space address, but the code dereferences it as if it were kernel memory. On some architectures this may access whatever memory happens to be at that address in kernel space, which is usually garbage or invalid. On others, it faults. In some specific pathological cases, it accesses sensitive kernel data. +这是一个灾难性的 bug:该指针是用户空间地址,但代码将其解引用为内核内存。在某些架构上,这可能会访问内核空间中碰巧在该地址的任何内存,通常是垃圾或无效的。在其他架构上,它会引发故障。在某些特定的病理情况下,它会访问敏感的内核数据。 -The fix: never dereference a pointer obtained from user space. Pointers in user-supplied structures must be passed to `copyin` or `copyout`, which correctly translate user addresses. Never treat them as kernel addresses. +修复方法:永远不要解引用从用户空间获得的指针。用户提供结构中的指针必须传递给 `copyin` 或 `copyout`,它们正确翻译用户地址。永远不要将它们视为内核地址。 ### 被遗忘的 copyout -A driver reads a structure from user space, modifies it, but forgets to copy the modified version back: +驱动程序从用户空间读取一个结构,修改它,但忘记将修改后的版本复制回去: ```c error = copyin(uaddr, &cmd, sizeof(cmd)); @@ -3708,13 +3708,13 @@ cmd.status = STATUS_OK; return (0); ``` -This is a functional bug, not strictly a security bug, but its mirror image is: forgetting `copyin` and assuming a field was already set. "I set `cmd.status` in `copyin`, then I read it later" is wrong if the field was actually set by user space; the user's value is what the code reads. +这是一个功能 bug,不完全是安全 bug,但它的镜像问题是:忘记 `copyin` 并假设字段已被设置。"我在 `copyin` 中设置了 `cmd.status`,然后稍后读取它"是错误的,如果该字段实际上是由用户空间设置的;代码读取的是用户的值。 -Every structure that flows user-to-kernel and back needs a clear convention about when `copyin` and `copyout` happen, and what fields are authoritative in which direction. Document it and follow it. +每个从用户到内核再返回的结构都需要关于 `copyin` 和 `copyout` 何时发生、以及哪些字段在哪个方向是权威的明确约定。记录它并遵循它。 ### 意外的竞态 -A driver takes a lock, reads a field, releases the lock, and then uses the value: +驱动程序获取锁,读取字段,释放锁,然后使用该值: ```c mtx_lock(&sc->sc_mtx); @@ -3730,279 +3730,279 @@ if (val == sc->sc_val) { mtx_unlock(&sc->sc_mtx); ``` -The driver assumes `val` is still current because it re-checks. But "act on val" uses the stale copy, not the current field. If `sc_val` is a pointer, the act may operate on a freed object. If `sc_val` is an index, the act may use a stale index. +驱动程序假设 `val` 仍然是最新的,因为它重新检查。但"对 val 采取行动"使用的是过时的副本,而不是当前字段。如果 `sc_val` 是指针,操作可能作用于已释放的对象。如果 `sc_val` 是索引,操作可能使用过时的索引。 -The lesson: once you release a lock, any value you read under that lock is stale. If you need to re-act under the lock, re-read the state inside the re-acquisition. The `if (val == sc->sc_val)` check protects against changes; the act needs to use the current value, not the stored one. +教训:一旦释放锁,你在该锁下读取的任何值都是过时的。如果你需要在锁下重新操作,在重新获取锁时重新读取状态。`if (val == sc->sc_val)` 检查防止了更改;操作需要使用当前值,而不是存储的值。 ### 静默截断 -A driver receives a string of up to 256 bytes, stores it in a 128-byte buffer. The code uses `strncpy`: +驱动程序接收一个最长 256 字节的字符串,将其存储在 128 字节缓冲区中。代码使用 `strncpy`: ```c strncpy(sc->sc_name, user_name, sizeof(sc->sc_name)); ``` -`strncpy` stops at the destination size. But `strncpy` does not guarantee a NUL terminator if the source was longer. Later code does: +`strncpy` 在达到目标大小时停止。但如果源字符串更长,`strncpy` 不保证 NUL 终止符。后面的代码: ```c printf("name: %s\n", sc->sc_name); ``` -`printf("%s", ...)` reads until a NUL. If `sc_name` is not NUL-terminated, printf reads past the end of the array into adjacent memory, potentially leaking that memory in the log or crashing. +`printf("%s", ...)` 读取直到遇到 NUL。如果 `sc_name` 不是 NUL 终止的,printf 会读取数组末尾进入相邻内存,可能在日志中泄露该内存或崩溃。 -Safer options: `strlcpy` (guarantees NUL termination, truncates if needed), or `snprintf` (same guarantee with formatting). `strncpy` is a landmine; it is in the standard library only for historical reasons. +更安全的选择:`strlcpy`(保证 NUL 终止,必要时截断),或 `snprintf`(带有格式化的相同保证)。`strncpy` 是一个地雷;它仅出于历史原因存在于标准库中。 ### 过度记录的事件 -A driver logs every time an event fires. The event is user-triggerable. A user sends a million events in a loop. The kernel message buffer fills and overflows; legitimate messages are lost. The user has accomplished a denial-of-service on the logging subsystem itself. +驱动程序在每次事件触发时记录日志。该事件是用户可触发的。用户在循环中发送一百万次事件。内核消息缓冲区填满并溢出;合法消息丢失。用户已经对日志子系统本身完成了拒绝服务攻击。 -The fix, as discussed in Section 8, is rate limiting. Every user-triggerable log message should be wrapped in a rate-limit check. A suppressed-count summary ("[secdev] 1234 suppressed messages in last 5 seconds") can be emitted periodically to inform the operator of ongoing flooding. +修复方法,如第 8 节所讨论的,是速率限制。每个用户可触发的日志消息都应该包裹在速率限制检查中。可以定期发出抑制计数摘要("[secdev] 最近 5 秒内抑制了 1234 条消息")以通知运维人员正在发生的泛洪。 ### 隐形漏洞 -A driver works fine for years. Then a compiler update changes how it handles a specific idiom, or a kernel API changes semantics in a new FreeBSD release, and the driver's behaviour changes. A check that used to work silently stops working. Users do not notice until an exploit appears. +一个驱动程序正常工作多年。然后编译器更新改变了它处理特定惯用法的方式,或者内核 API 在 FreeBSD 新版本中改变了语义,驱动程序的行为发生了变化。曾经安静工作的检查停止了工作。用户直到利用出现时才注意到。 -Invisible bugs are the strongest argument for `KASSERT`, sanitizers, and tests. A `KASSERT(p != NULL)` at the top of every function documents what that function expects. An `INVARIANTS` kernel catches the moment an invariant breaks. A good test suite notices when behavior changes. +隐形 bug 是 `KASSERT`、净化器和测试的最有力论据。每个函数顶部的 `KASSERT(p != NULL)` 记录了该函数的期望。`INVARIANTS` 内核捕获不变量被破坏的时刻。一个好的测试套件注意到行为何时改变。 -The simpler the function and the clearer its contract, the fewer places invisible bugs can hide. This is one reason the FreeBSD kernel coding style described in `style(9)` values short functions with clear responsibilities: they are easier to reason about, which makes invisible bugs easier to avoid in the first place. +函数越简单,其契约越清晰,隐形 bug 可以隐藏的地方就越少。这是 `style(9)` 中描述的 FreeBSD 内核编码风格重视具有清晰职责的简短函数的原因之一:它们更容易推理,这使隐形 bug 从一开始就更容易避免。 ### 漏洞模式目录总结 -Each of the patterns above has been seen in real kernel code. Many have been CVEs. The defenses are: +上述每种模式都在真实内核代码中出现过。许多已成为 CVE。防御措施是: -- Use `size_t` for sizes; avoid sign confusion. -- Whitelist validation; do not forget fields. -- Treat error paths with the same rigor as success paths. -- Use refcounts to manage object lifetime under concurrency. -- Use `sizeof` directly on the buffer rather than a drift-prone constant. -- Never dereference user pointers. -- Keep the `copyin` / `copyout` story explicit per field. -- Remember that a value read under a lock is stale after the lock is released. -- Use `strlcpy` or `snprintf`, never `strncpy`. -- Rate-limit every user-triggerable log. -- Write invariants as `KASSERT` so regressions are caught. +- 对大小使用 `size_t`;避免符号混淆。 +- 白名单验证;不要忘记字段。 +- 以与成功路径相同的严谨对待错误路径。 +- 使用引用计数来管理并发下的对象生命周期。 +- 直接在缓冲区上使用 `sizeof`,而不是可能漂移的常量。 +- 永远不要解引用用户指针。 +- 保持每个字段的 `copyin`/`copyout` 过程明确。 +- 记住在锁下读取的值在锁释放后是过时的。 +- 使用 `strlcpy` 或 `snprintf`,永远不要用 `strncpy`。 +- 对每个用户可触发的日志进行速率限制。 +- 将不变量写为 `KASSERT`,以便捕获回归。 -Memorize these patterns. Apply them as a mental checklist on every function you write or review. +记住这些模式。将它们作为心理检查清单应用到你编写或审查的每个函数上。 ## 附录:本章使用的头文件和 API -A short reference to the FreeBSD headers referenced throughout this chapter, grouped by topic. Each header is in `/usr/src/sys/` followed by the path listed. +一个按主题分组的本章引用的 FreeBSD 头文件的简短参考。每个头文件在 `/usr/src/sys/` 后跟列出的路径。 ### 内存与复制操作 -- `sys/systm.h`: declarations for `copyin`, `copyout`, `copyinstr`, `bzero`, `explicit_bzero`, `printf`, `log`, and many kernel core primitives. -- `sys/malloc.h`: `malloc(9)`, `free(9)`, `zfree(9)`, `MALLOC_DECLARE`, `MALLOC_DEFINE`, M_* flags. -- `sys/uio.h`: `struct uio`, `uiomove(9)`, UIO_READ / UIO_WRITE constants. -- `vm/uma.h`: UMA zone allocator (`uma_zcreate`, `uma_zalloc`, `uma_zfree`, `uma_zdestroy`). -- `sys/refcount.h`: reference-count primitives (`refcount_init`, `refcount_acquire`, `refcount_release`). +- `sys/systm.h`: `copyin`、`copyout`、`copyinstr`、`bzero`、`explicit_bzero`、`printf`、`log` 和许多内核核心原语的声明。 +- `sys/malloc.h`: `malloc(9)`、`free(9)`、`zfree(9)`、`MALLOC_DECLARE`、`MALLOC_DEFINE`、M_* 标志。 +- `sys/uio.h`: `struct uio`、`uiomove(9)`、UIO_READ / UIO_WRITE 常量。 +- `vm/uma.h`: UMA 区域分配器(`uma_zcreate`、`uma_zalloc`、`uma_zfree`、`uma_zdestroy`)。 +- `sys/refcount.h`: 引用计数原语(`refcount_init`、`refcount_acquire`、`refcount_release`)。 ### 权限与访问控制 -- `sys/priv.h`: `priv_check(9)`, `priv_check_cred(9)`, `PRIV_*` constants, `securelevel_gt`, `securelevel_ge`. -- `sys/ucred.h`: `struct ucred` and its fields. -- `sys/jail.h`: `struct prison`, `jailed(9)` macro, prison-related helpers. -- `sys/capsicum.h`: Capsicum capabilities, `cap_rights_t`, `IN_CAPABILITY_MODE(td)`. -- `security/mac/mac_framework.h`: MAC framework hooks (mostly for policy writers, but reference). +- `sys/priv.h`: `priv_check(9)`、`priv_check_cred(9)`、`PRIV_*` 常量、`securelevel_gt`、`securelevel_ge`。 +- `sys/ucred.h`: `struct ucred` 及其字段。 +- `sys/jail.h`: `struct prison`、`jailed(9)` 宏、与监狱相关的辅助函数。 +- `sys/capsicum.h`: Capsicum 能力、`cap_rights_t`、`IN_CAPABILITY_MODE(td)`。 +- `security/mac/mac_framework.h`: MAC 框架钩子(主要供策略编写者使用,但作为参考)。 ### 加锁与并发 -- `sys/mutex.h`: `struct mtx`, `mtx_init`, `mtx_lock`, `mtx_unlock`, `mtx_destroy`. -- `sys/sx.h`: shared/exclusive locks. -- `sys/rwlock.h`: read/write locks. -- `sys/condvar.h`: condition variables (`cv_init`, `cv_wait`, `cv_signal`). -- `sys/lock.h`: common lock infrastructure. -- `sys/atomic_common.h`: atomic operations (and architecture-specific headers). +- `sys/mutex.h`: `struct mtx`、`mtx_init`、`mtx_lock`、`mtx_unlock`、`mtx_destroy`。 +- `sys/sx.h`: 共享/排他锁。 +- `sys/rwlock.h`: 读写锁。 +- `sys/condvar.h`: 条件变量(`cv_init`、`cv_wait`、`cv_signal`)。 +- `sys/lock.h`: 通用锁基础设施。 +- `sys/atomic_common.h`: 原子操作(以及架构特定的头文件)。 ### 设备文件与 Dev 基础设施 -- `sys/conf.h`: `struct cdev`, `struct cdevsw`, `struct make_dev_args`, `make_dev_s`, `make_dev_credf`, `destroy_dev`. -- `sys/module.h`: `DRIVER_MODULE`, `MODULE_VERSION`, kernel module declarations. -- `sys/kernel.h`: SYSINIT, SYSUNINIT, and related kernel hook macros. -- `sys/bus.h`: `device_t`, device methods, `bus_alloc_resource`, `bus_teardown_intr`. +- `sys/conf.h`: `struct cdev`、`struct cdevsw`、`struct make_dev_args`、`make_dev_s`、`make_dev_credf`、`destroy_dev`。 +- `sys/module.h`: `DRIVER_MODULE`、`MODULE_VERSION`、内核模块声明。 +- `sys/kernel.h`: SYSINIT、SYSUNINIT 及相关内核钩子宏。 +- `sys/bus.h`: `device_t`、设备方法、`bus_alloc_resource`、`bus_teardown_intr`。 ### 定时、速率限制、调用 -- `sys/time.h`: `eventratecheck(9)`, `ppsratecheck(9)`, `struct timeval`. -- `sys/callout.h`: `struct callout`, `callout_init_mtx`, `callout_reset`, `callout_drain`. -- `sys/taskqueue.h`: task queue primitives (`taskqueue_create`, `taskqueue_enqueue`, `taskqueue_drain`). +- `sys/time.h`: `eventratecheck(9)`、`ppsratecheck(9)`、`struct timeval`。 +- `sys/callout.h`: `struct callout`、`callout_init_mtx`、`callout_reset`、`callout_drain`。 +- `sys/taskqueue.h`: 任务队列原语(`taskqueue_create`、`taskqueue_enqueue`、`taskqueue_drain`)。 ### 日志与诊断 -- `sys/syslog.h`: `LOG_*` priority constants for `log(9)`. -- `sys/kassert.h`: `KASSERT`, `MPASS`, assertion macros. -- `sys/ktr.h`: KTR tracing macros. -- `sys/sdt.h`: Statically Defined Tracing probes for dtrace(1). +- `sys/syslog.h`: 用于 `log(9)` 的 `LOG_*` 优先级常量。 +- `sys/kassert.h`: `KASSERT`、`MPASS`、断言宏。 +- `sys/ktr.h`: KTR 跟踪宏。 +- `sys/sdt.h`: 用于 dtrace(1) 的静态定义跟踪探针。 ### Sysctl -- `sys/sysctl.h`: `SYSCTL_*` macros, `CTLFLAG_*` flags including `CTLFLAG_SECURE`, `CTLFLAG_PRISON`, `CTLFLAG_CAPRD`, `CTLFLAG_CAPWR`. +- `sys/sysctl.h`: `SYSCTL_*` 宏、`CTLFLAG_*` 标志,包括 `CTLFLAG_SECURE`、`CTLFLAG_PRISON`、`CTLFLAG_CAPRD`、`CTLFLAG_CAPWR`。 ### 网络(适用时) -- `sys/mbuf.h`: `struct mbuf`, mbuf allocation and manipulation. -- `net/if.h`: `struct ifnet`, network interface primitives. +- `sys/mbuf.h`: `struct mbuf`、mbuf 分配和操作。 +- `net/if.h`: `struct ifnet`、网络接口原语。 ### 时代与无锁 -- `sys/epoch.h`: epoch-based reclamation primitives (`epoch_enter`, `epoch_exit`, `epoch_wait`). -- `sys/atomic_common.h` and architecture-specific atomic headers: memory barriers, atomic reads and writes. +- `sys/epoch.h`: 基于时代的回收原语(`epoch_enter`、`epoch_exit`、`epoch_wait`)。 +- `sys/atomic_common.h` 和架构特定的原子头文件:内存屏障、原子读写。 ### 追踪与可观测性 -- `security/audit/audit.h`: kernel audit framework (when compiled in). -- `sys/sdt.h`: Statically Defined Tracing for dtrace integration. -- `sys/ktr.h`: KTR in-kernel tracing. +- `security/audit/audit.h`: 内核审计框架(编译时启用)。 +- `sys/sdt.h`: 用于 dtrace 集成的静态定义跟踪。 +- `sys/ktr.h`: KTR 内核内跟踪。 -This appendix is not exhaustive; the full set of headers a driver may need is far larger. It covers the ones referenced in this chapter. When writing your own driver, `grep` through `/usr/src/sys/sys/` for the primitive you need, and read the header to understand what is available. Many of these headers are well commented and repay careful reading. +本附录并不详尽;驱动程序可能需要的一整套头文件要大得多。它涵盖了本章中引用的头文件。在编写自己的驱动程序时,通过 `/usr/src/sys/sys/` 中 `grep` 你需要的原语,并阅读头文件以了解可用的内容。这些头文件中有许多注释良好,值得仔细阅读。 -Reading the headers is itself a security practice. Every primitive has a contract: what arguments it accepts, what constraints it imposes, what it guarantees on success, what it returns on failure. A driver that uses a primitive without reading its contract is relying on assumptions that may not hold. A driver that reads the contract, and holds itself to it, is a driver that benefits from the kernel's own discipline. +阅读头文件本身就是一种安全实践。每个原语都有一个契约:它接受什么参数,它施加什么约束,它在成功时保证什么,它在失败时返回什么。在不阅读契约的情况下使用原语的驱动程序正在依赖可能不成立的假设。阅读契约并遵守契约的驱动程序是受益于内核自身纪律的驱动程序。 -Many of the headers listed above are themselves worth studying as examples of good kernel design. `sys/refcount.h` is small, carefully commented, and demonstrates how a simple primitive is built from atomic operations. `sys/kassert.h` shows how conditional compilation is used to build a feature that costs nothing in production but catches bugs in developer kernels. `sys/priv.h` shows how a long list of named constants can be organized by subsystem and used as the grammar of a policy. When you run out of ideas for how to structure your own driver's internals, these headers are a good place to find inspiration. +上面列出的许多头文件本身也值得作为良好内核设计的例子来学习。`sys/refcount.h` 很小,注释仔细,并展示了如何从原子操作构建一个简单的原语。`sys/kassert.h` 展示了如何使用条件编译来构建一个在生产中零成本但在开发者内核中捕获 bug 的功能。`sys/priv.h` 展示了如何按子系统组织一长串命名常量并将其用作策略的语法。当你对如何构建自己的驱动程序内部结构失去想法时,这些头文件是寻找灵感的好地方。 ## 附录:延伸阅读 -A short list of resources that go deeper into FreeBSD security than this chapter can: +一个比本章更深入探讨 FreeBSD 安全的简短资源列表: -**FreeBSD Architecture Handbook**, in particular the chapters on the jail subsystem, Capsicum, and MAC framework. Available online at `https://docs.freebsd.org/en/books/arch-handbook/`. +**FreeBSD Architecture Handbook**,特别是关于 jail 子系统、Capsicum 和 MAC 框架的章节。可在 `https://docs.freebsd.org/en/books/arch-handbook/` 在线获取。 -**FreeBSD Handbook security chapter**, which is oriented toward administrators but includes useful context on how system-level features (jails, securelevel, MAC) interact. +**FreeBSD Handbook security chapter**,面向管理员,但包括关于系统级功能(jails、securelevel、MAC)如何交互的有用上下文。 -**Capsicum: Practical Capabilities for UNIX**, the original paper by Robert Watson, Jonathan Anderson, Ben Laurie, and Kris Kennaway. Explains the design rationale behind Capsicum, which helps when deciding how your driver should behave in capability mode. +**Capsicum: Practical Capabilities for UNIX**,Robert Watson、Jonathan Anderson、Ben Laurie 和 Kris Kennaway 的原始论文。解释了 Capsicum 背后的设计原理,有助于决定你的驱动程序在能力模式下应如何表现。 -**"The Design and Implementation of the FreeBSD Operating System"**, by Marshall Kirk McKusick, George V. Neville-Neil, and Robert N. M. Watson. The second edition covers FreeBSD 11; many security-relevant chapters remain applicable in later versions. +**"The Design and Implementation of the FreeBSD Operating System"**,作者 Marshall Kirk McKusick、George V. Neville-Neil 和 Robert N. M. Watson。第二版涵盖 FreeBSD 11;许多与安全相关的章节在后续版本中仍然适用。 -**style(9)**, the FreeBSD kernel coding style guide, available as a manual page: `man 9 style`. Readable kernel code is safer kernel code; the conventions in `style(9)` are part of how the tree stays reviewable at scale. +**style(9)**,FreeBSD 内核编码风格指南,可作为手册页获取:`man 9 style`。可读的内核代码是更安全的内核代码;`style(9)` 中的约定是树在规模上保持可审查性的一部分。 -**KASAN, KMSAN, and KCOV documentation** in `/usr/src/share/man/` and related sections. Reading these helps you configure and interpret sanitizer output. +**KASAN、KMSAN 和 KCOV 文档** 在 `/usr/src/share/man/` 和相关章节中。阅读这些内容有助于你配置和解释净化器输出。 -**syzkaller documentation**, at `https://github.com/google/syzkaller`. The `sys/freebsd/` directory contains syscall descriptions that illustrate how to describe your own driver's interface. +**syzkaller 文档**,位于 `https://github.com/google/syzkaller`。`sys/freebsd/` 目录包含系统调用描述,展示了如何描述你自己的驱动程序接口。 -**CVE databases** such as `https://nvd.nist.gov/vuln/search` or `https://cve.mitre.org/`. Searching for "FreeBSD" or specific driver names shows real bugs that have been found and fixed. Reading a few CVE reports per month teaches a great deal about what kinds of bugs occur in practice. +**CVE 数据库**,如 `https://nvd.nist.gov/vuln/search` 或 `https://cve.mitre.org/`。搜索"FreeBSD"或特定驱动程序名称会显示已发现和修复的真实 bug。每月阅读一些 CVE 报告能让你了解到实践中出现什么样的 bug。 -**FreeBSD security advisories**, at `https://www.freebsd.org/security/advisories/`. These are official reports on fixed vulnerabilities. Many are kernel-side and relevant to driver authors. +**FreeBSD 安全公告**,位于 `https://www.freebsd.org/security/advisories/`。这些是关于已修复漏洞的官方报告。许多是内核端的,与驱动程序作者相关。 -**The FreeBSD source tree itself** is the largest and most authoritative reference. Spend time reading drivers similar to yours. Look at how they validate input, check privilege, manage locking, and handle detach. Imitating the patterns you see in well-reviewed code is one of the fastest ways to learn. +**FreeBSD 源代码树本身** 是最大和最权威的参考。花时间阅读与你类似的驱动程序。看看它们如何验证输入、检查权限、管理加锁和处理 detach。模仿你在经过良好审查的代码中看到的模式是学习最快的方法之一。 -**Security mailing lists**, such as `freebsd-security@` and the broader `oss-security` list, carry daily traffic on kernel and driver issues across open-source projects. Subscribing passively and skimming a few posts a week builds awareness of threat trends without demanding much effort. +**安全邮件列表**,如 `freebsd-security@` 和更广泛的 `oss-security` 列表,每天都有关于开源项目中内核和驱动程序问题的信息。被动订阅并每周浏览几篇文章可以建立对威胁趋势的认识,而不需要太多精力。 -**Formal verification literature**, although specialist, has begun to touch kernel code. Projects like seL4 demonstrate what a fully verified microkernel looks like. FreeBSD is not that, but reading about formal verification shapes how you think about invariants and contracts in your own code. +**形式化验证文献**,虽然是专业领域,但已经开始触及内核代码。像 seL4 这样的项目展示了完全验证的微内核是什么样子。FreeBSD 不是那样,但阅读形式化验证会塑造你对自己代码中不变量和契约的思考方式。 -**Books on secure coding practices in C** such as `Secure Coding in C and C++` by Robert Seacord translate well to kernel work, since kernel C is a dialect of the same language and has the same pitfalls, plus more. Chapter-by-chapter, they provide the mental catalogue of bugs that this chapter could only sketch. +**关于 C 语言安全编码实践的书籍**,如 Robert Seacord 的 `Secure Coding in C and C++`,很好地适用于内核工作,因为内核 C 是同一种语言的方言,有相同的陷阱,甚至更多。逐章来看,它们提供了本章只能勾勒的 bug 的心理目录。 -**FreeBSD-specific books**, notably the McKusick, Neville-Neil, and Watson book mentioned above, but also older volumes that cover the evolution of specific subsystems. Reading about how jails evolved, how Capsicum was designed, or how MAC came to be helps you understand the rationale behind the primitives rather than just their mechanics. +**FreeBSD 特定书籍**,特别是上面提到的 McKusick、Neville-Neil 和 Watson 的书,但也有涵盖特定子系统演变的较旧卷。阅读关于 jails 如何演变、Capsicum 如何设计或 MAC 如何形成的,有助于你理解原语背后的原理而不仅仅是它们的机制。 -**Conference talks** from BSDCan, EuroBSDCon, and AsiaBSDCon often touch security topics. Video archives let you watch years of past talks at your own pace. Many talks are given by active FreeBSD developers and reflect current thinking. +**会议演讲**,来自 BSDCan、EuroBSDCon 和 AsiaBSDCon,经常涉及安全主题。视频档案让你可以按自己的节奏观看过去几年的演讲。许多演讲由活跃的 FreeBSD 开发者发表,反映了当前的思考。 -**Academic papers on operating system security** from venues such as USENIX Security, IEEE S&P, and CCS provide a longer-term view. Not every paper is relevant to drivers, but the ones that are deepen your understanding of threat models, attacker capabilities, and the theoretical basis for mitigations. +**操作系统安全领域的学术论文**,来自 USENIX Security、IEEE S&P 和 CCS 等会议,提供了更长远的视角。并非每篇论文都与驱动程序相关,但相关的那些加深了你对威胁模型、攻击者能力以及缓解措施理论基础的理解。 -**The CVE feed**, particularly when filtered for kernel issues, is a continuous drip of real-world examples. Reading a few each week builds intuition for what bugs look like in practice and which classes recur most often. +**CVE 推送**,特别是在过滤内核问题时,是持续不断的真实世界示例流。每周阅读几条有助于建立对实践中 bug 看起来是什么样以及哪些类别最常重复出现的直觉。 -**Your own code, six months later**. Rereading your earlier work with the benefit of distance is a valuable learning tool. The bugs you will notice are the bugs you have learned to see since you wrote it. Make a habit of this; schedule time for it. +**你自己的代码,六个月后**。以后退一步的视角重新阅读你早期的作品是一个宝贵的学习工具。你会注意到的 bug 是你自编写以来学会看到的 bug。养成习惯;为此安排时间。 -The resources above, even a small subset of them, will keep you growing for years. Security is a field of continuous learning. This chapter is one step in that learning; the next step is yours. +以上资源,即使只是其中一小部分,也将让你在多年内持续成长。安全是一个持续学习的领域。本章是那个学习中的一步;下一步是你的。 -Every security-minded driver author should have read at least a few of these. The field moves, and staying current is part of the craft. +每个有安全意识的驱动程序作者都应该至少阅读过其中的一些内容。这个领域在变化,保持最新状态是这门手艺的一部分。 ## 总结 设备驱动程序中的安全不是单一技术。它是一种工作方式。每一行代码都为内核的安全承担一点责任。本章涵盖了主要支柱: -**The kernel trusts every driver fully.** Once code runs in the kernel, there is no sandbox, no isolation, no second chance. The driver author's discipline is the system's last line of defense. +**内核完全信任每个驱动程序。** 一旦代码在内核中运行,就没有沙箱、没有隔离、没有第二次机会。驱动程序作者的纪律是系统的最后一道防线。 -**Buffer overflows and memory corruption** are the classical kernel vulnerability. They are prevented by bounding every copy, preferring bounded string functions, and treating pointer arithmetic with suspicion. +**缓冲区溢出和内存损坏** 是经典的内核漏洞。通过限制每次复制、优先使用有界字符串函数以及以怀疑态度对待指针算术来预防。 -**User input crosses a trust boundary.** Every byte from user space must be copied into the kernel with `copyin(9)`, `copyinstr(9)`, or `uiomove(9)` before it is used. Every byte going back must be copied out with `copyout(9)` or `uiomove(9)`. The user-space memory is not trustworthy; kernel memory is. Keep them cleanly separated. +**用户输入跨越信任边界。** 来自用户空间的每个字节必须在使用前通过 `copyin(9)`、`copyinstr(9)` 或 `uiomove(9)` 复制到内核中。每个返回的字节必须通过 `copyout(9)` 或 `uiomove(9)` 复制出去。用户空间内存不可信;内核内存可信。保持它们干净分离。 -**Memory allocation** must be checked, balanced, and accounted for. Always check `M_NOWAIT` returns. Use `M_ZERO` by default. Pair every `malloc` with exactly one `free`. Use a per-driver `malloc_type` for accountability. Use `explicit_bzero` or `zfree` for sensitive data. +**内存分配** 必须被检查、平衡和记账。始终检查 `M_NOWAIT` 返回值。默认使用 `M_ZERO`。将每个 `malloc` 与恰好一次 `free` 配对。使用每驱动程序 `malloc_type` 进行追溯。对敏感数据使用 `explicit_bzero` 或 `zfree`。 -**Races and TOCTOU bugs** are caused by inconsistent locking or by treating user-space data as stable. Fix them with locks around shared state and by copying user data before validating. +**竞态和 TOCTOU 漏洞** 由不一致的加锁或将用户空间数据视为稳定而引起。用共享状态周围的锁和在验证前复制用户数据来修复它们。 -**Privilege checks** use `priv_check(9)` as the canonical primitive. Layer with jail awareness and securelevel where appropriate. Set conservative device-node permissions. Let the MAC and Capsicum frameworks work alongside. +**权限检查** 使用 `priv_check(9)` 作为标准原语。在适当时叠加 jail 感知和安全级别。设置保守的设备节点权限。让 MAC 和 Capsicum 框架在旁边工作。 -**Information leaks** are prevented by zeroing structures before filling them, bounding copy lengths on both ends, and keeping kernel pointers out of user-visible output. +**信息泄露** 通过在填充前清零结构、限制两端的复制长度以及将内核指针排除在用户可见输出之外来预防。 -**Logging** is part of the driver's interface. Use it to help the operator without helping the attacker. Rate-limit anything triggerable from user space. Do not log sensitive data. +**日志记录** 是驱动程序接口的一部分。用它帮助运维人员而不帮助攻击者。对用户空间可触发的任何内容进行速率限制。不要记录敏感数据。 -**Secure defaults** mean failing closed, whitelisting rather than blacklisting, setting conservative default values, and treating error paths with the same care as success paths. +**安全默认值** 意味着故障时关闭、白名单而不是黑名单、设置保守的默认值、并以与成功路径相同的关注处理错误路径。 -**Testing and hardening** turn careful code into trustworthy code. Build with `INVARIANTS`, `WITNESS`, and the kernel sanitizers. Stress-test. Fuzz. Review. Re-test. +**测试和加固** 将仔细的代码变为可信赖的代码。使用 `INVARIANTS`、`WITNESS` 和内核净化器构建。压力测试。模糊测试。审查。重新测试。 这些都不是一次性的努力。驱动程序保持安全是因为其作者在代码的整个生命周期中,每次提交、每个版本都持续应用这些习惯。 -The discipline is not glamorous. It is boring work: zero the structure, check the length, acquire the lock, use `priv_check`. But this boring work is exactly what keeps systems secure. An exploited kernel is a catastrophic event for users. An exploited driver is a foothold into the kernel. The person at the keyboard of that driver, deciding whether to add the bounds check or to skip it, is making a security decision that may be invisible for years and then suddenly matter very much. +这种纪律并不光鲜。它是枯燥的工作:清零结构、检查长度、获取锁、使用 `priv_check`。但这种枯燥的工作正是保持系统安全的要素。被利用的内核对用户来说是灾难性事件。被利用的驱动程序是进入内核的立足点。在键盘前决定是添加边界检查还是跳过它的人,正在做一个可能多年不可见但突然变得非常重要的安全决策。 -Be the author who adds the bounds check. +做那个添加边界检查的作者。 ### 再一次反思:安全作为职业身份 -Something worth saying explicitly: the habits in this chapter are not merely techniques. They are what distinguishes a journeyman kernel author from an apprentice. Every mature kernel engineer carries this mental checklist not because they memorized it but because they have, over years, internalized a skepticism toward their own code. The skepticism is not anxiety. It is discipline. +值得明确说的是:本章中的习惯不仅仅是技术。它们是区分熟练内核作者和学徒的东西。每个成熟的内核工程师都带着这个心理检查清单,不是因为他们记住了它,而是因为多年来他们已经内化了对自己的代码的怀疑。这种怀疑不是焦虑。它是纪律。 -Write code, and then read it back as if a stranger had written it. Ask what happens if the caller is hostile. Ask what happens if the value is zero, or negative, or impossibly large. Ask what happens if the other thread arrives between these two statements. Ask what happens on the error path you did not plan to test. Write the check. Write the assertion. Move on. +编写代码,然后像陌生人写的那样回读它。问如果调用者是敌意的会发生什么。问如果值为零、或负数、或不可能大的时候会发生什么。问如果另一个线程到达这两条语句之间会发生什么。问你没有计划测试的错误路径上会发生什么。写检查。写断言。继续前进。 -This is what professional kernel engineers do. It is not glamorous, it is rarely applauded, and it is what keeps the operating system we all rely on from falling apart. The kernel is not magic; it is millions of lines of carefully checked code, written and rewritten by people who treat every line as a small responsibility. Joining that profession means joining that discipline. +这就是专业内核工程师所做的。它不光鲜,很少被喝彩,它正是保持我们都依赖的操作系统不崩溃的要素。内核不是魔法;它是数百万行经过仔细检查的代码,由将每一行视为小责任的人编写和重写。加入那个职业意味着加入那种纪律。 -You have now been given the tools. The rest is practice. +你现在已经被赋予了工具。剩下的就是练习。 ## 展望:设备树与嵌入式开发 -This chapter trained you to look at your driver from the outside, through the eyes of whoever might try to misuse it. The boundaries you learned to watch were invisible to the compiler but very real to the kernel: user space on one side, kernel memory on the other; one thread with privilege, another without; a length field the caller claimed, a length the driver had to verify. Chapter 31 was about *who is allowed to ask the driver to do something*, and *what the driver should check before it agrees*. +本章训练你从外部,通过可能试图误用它的人的眼睛来审视你的驱动程序。你学到要关注的边界对编译器来说是不可见的,但对内核来说是非常真实的:一边是用户空间,另一边是内核内存;一个线程有权限,另一个没有;调用者声称的长度字段,驱动程序必须验证的长度。第31章是关于*谁被允许要求驱动程序做某事*,以及*驱动程序在同意之前应该检查什么*。 -Chapter 32 shifts the perspective entirely. The question stops being *who wants this driver to run* and becomes *how does this driver find its hardware at all*. On the PC-like machines we have leaned on so far, that question had a comfortable answer. PCI devices announced themselves through standard configuration registers. ACPI-described peripherals appeared in a table the firmware handed to the kernel. The bus did the looking, the kernel probed each candidate, and your driver's `probe()` function only had to look at an identifier and say yes or no. Discovery was mostly someone else's problem. +第32章完全改变了视角。问题不再是*谁想让这个驱动程序运行*,而是*这个驱动程序如何找到它的硬件*。在我们一直依赖的 PC 类机器上,这个问题有一个舒适的答案。PCI 设备通过标准配置寄存器宣布自己。ACPI 描述的外围设备出现在固件交给内核的表中。总线做了查找工作,内核探测每个候选者,你的驱动程序的 `probe()` 函数只需查看一个标识符并说是或否。发现主要是别人的问题。 -On embedded platforms that assumption breaks. A small ARM board does not speak PCI, does not carry an ACPI BIOS, and does not hand the kernel a neat table of devices. The SoC has an I2C controller at a fixed physical address, three UARTs at three other fixed addresses, a GPIO bank at a fourth, a timer, a watchdog, a clock tree, and a dozen other peripherals soldered onto the board in a particular arrangement. Nothing in the silicon announces itself. If the kernel is going to attach drivers to these peripherals, something has to tell the kernel where they are, what they are, and how they relate. +在嵌入式平台上,这个假设不成立。小型 ARM 板不使用 PCI,不携带 ACPI BIOS,也不向内核交出一个整齐的设备表。SoC 在固定物理地址有一个 I2C 控制器,在另外三个固定地址有三个 UART,在第四个地址有一个 GPIO 银行,一个定时器、一个看门狗、一个时钟树,以及十几个以特定排列焊接到板上的其他外围设备。硅片中没有任何东西自我宣布。如果内核要将驱动程序附着到这些外围设备上,必须有东西告诉内核它们在哪里、它们是什么,以及它们如何关联。 -That something is the **Device Tree**, and Chapter 32 is where you learn to work with it. You will see how `.dts` source files describe the hardware, how the Device Tree Compiler (`dtc`) turns them into the `.dtb` blobs the bootloader hands to the kernel, and how FreeBSD's FDT support walks those blobs to decide which drivers to attach. You will meet the `ofw_bus` interfaces, the `simplebus` enumerator, and the Open Firmware helpers (`ofw_bus_search_compatible`, `ofw_bus_get_node`, the property-reading calls) that turn a Device Tree node into a working driver attachment. You will compile a small overlay, load it, and watch a pedagogical driver attach in `dmesg`. +那个东西就是**设备树**,第32章就是你学习使用它的地方。你将看到 `.dts` 源文件如何描述硬件,设备树编译器(`dtc`)如何将它们转化为引导加载程序交给内核的 `.dtb` 二进制块,以及 FreeBSD 的 FDT 支持如何遍历这些块来决定附着哪些驱动程序。你将遇到 `ofw_bus` 接口、`simplebus` 枚举器和 Open Firmware 辅助函数(`ofw_bus_search_compatible`、`ofw_bus_get_node`、属性读取调用),它们将设备树节点转化为可工作的驱动程序附着。你将编译一个小型覆盖层,加载它,并观察教学驱动程序在 `dmesg` 中附着。 -The security habits you have built in this chapter travel with you into that territory. A driver for an embedded board is still a driver: it still runs in kernel space, still copies data across user-space boundaries, still needs bounds checks, still takes locks, still cleans up in detach. An ARM board does not loosen any of those requirements. If anything, embedded systems raise the stakes, because the same board image may ship to thousands of devices in the field, each one harder to patch than a server in a data center. The disposition you have just learned, skeptical of inputs, careful with memory, conservative about privilege, is exactly the disposition an embedded driver author needs. +你在本章中建立的安全习惯将伴随你进入那个领域。嵌入式板的驱动程序仍然是驱动程序:它仍然在内核空间运行,仍然跨用户空间边界复制数据,仍然需要边界检查,仍然获取锁,仍然在 detach 中清理。ARM 板不会放宽这些要求中的任何一个。如果有的话,嵌入式系统提高了赌注,因为同一个板镜像可能发布到现场数千台设备,每台都比数据中心中的服务器更难打补丁。你刚刚学到的性格——怀疑输入、小心处理内存、对权限保守——正是嵌入式驱动程序作者需要的性格。 -What changes in Chapter 32 is the set of helpers you call to discover your hardware and the files you read to know where to point them. The probe-attach-detach shape stays. The softc stays. The lifecycle stays. A handful of new calls and a new way of thinking about hardware description are what you add. The chapter builds them up gently, from the shape of a `.dts` file to a working driver that blinks an LED on a real or emulated board. +第32章中改变的是你用来发现硬件的辅助函数集和你阅读以知道指向它们的文件。probe-attach-detach 形状保留。softc 保留。生命周期保留。少量新调用和一种思考硬件描述的新方式是你添加的东西。本章温和地构建它们,从 `.dts` 文件的形状到一个在真实或模拟板上闪烁 LED 的可工作驱动程序。 -See you there. +在那里见。 ## 关于习惯的最终说明 -This chapter has been longer than some. The length is deliberate. Security is not a topic that can be summarized into a single punchy rule; it is a way of thinking that requires examples, practice, and repetition. A reader who finishes this chapter once will have been exposed to the patterns. A reader who returns to this chapter when starting a new driver will find new meaning in passages that seemed merely informative on the first read. +本章比一些章节要长。长度是有意为之的。安全不是一个可以总结为一条有力规则的主题;它是一种需要示例、练习和重复的思维方式。一次读完本章的读者已经接触到了这些模式。在开始新驱动程序时回到本章的读者会在第一次阅读时看似只是信息性的段落中找到新的含义。 -Here are the most important habits, condensed into a single list for you to carry forward. They are the reflexes that matter most in daily driver work: +这里是最重要的习惯,浓缩成单一列表供你随身携带。它们是日常驱动程序工作中最重要的反射: -Every user-space value is hostile until copied in, bounded, and validated. +每个用户空间值都是敌对的,直到被复制进来、限制和验证。 -Every length has a maximum. The maximum is enforced before anything uses the length. +每个长度都有最大值。最大值在任何东西使用长度之前被执行。 -Every structure copied to user space is zeroed first. +每个复制到用户空间的结构首先被清零。 -Every allocation is paired with a free on every code path. +每个分配在每条代码路径上与一次释放配对。 -Every critical section is held across the full check-and-act sequence it protects. +每个临界区都持有在它保护的完整检查-行动序列上。 -Every privilege-sensitive operation checks `priv_check` before acting. +每个权限敏感操作在行动前检查 `priv_check`。 -Every detach path drains async work before freeing state. +每个 detach 路径在释放状态前排干异步工作。 -Every log message triggerable from user space is rate-limited. +每个可从用户空间触发的日志消息都被速率限制。 -Every unknown input returns an error, never a silent success. +每个未知输入返回错误,永远不静默成功。 -Every assumption worth making is worth writing as a `KASSERT`. +每个值得做的假设都值得写为 `KASSERT`。 -Nine lines. If these become automatic, you have the core of what this chapter teaches. +九行。如果这些变得自动,你就拥有了本章教授的核心。 -The craft grows from here. There are more patterns, more subtleties, more tools; you will encounter them as you read more FreeBSD source, as you review more code, as you write more drivers. What stays the same is the disposition: skeptical of hostile inputs, careful with memory, clear about lock boundaries, conservative about what to expose. That disposition is the one kernel engineers share across decades. You have it now. Use it well. +工艺从这里继续增长。还有更多的模式、更多的微妙之处、更多的工具;当你阅读更多 FreeBSD 源代码、审查更多代码、编写更多驱动程序时,你会遇到它们。保持不变的是那种性格:对敌对输入的怀疑、对内存的小心、对锁边界的清晰、对暴露什么的保守。那种性格是内核工程师跨越几十年共享的。你现在拥有了它。好好使用它。 ## 关于不断演变的威胁的说明 -One further thought before the closing words. The threats we defend against today are not the threats we will defend against in ten years. Attackers evolve. Mitigations evolve. New classes of bugs are discovered, old classes are retired. A driver that was state-of-the-art in its defenses in 2020 may need updating to be considered safe in 2030. +在结束语之前还有一个想法。我们今天防御的威胁不是我们十年后将防御的威胁。攻击者演进。缓解措施演进。新的漏洞类别被发现,旧的类别被淘汰。在 2020 年其防御方面是最先进的驱动程序可能需要更新才能在 2030 年被认为是安全的。 -This is not a reason for despair. It is a reason for continuous learning. Every year, a responsible driver author should read a few new security papers, try a few new sanitizers, and look at the recent CVEs affecting kernels similar to their own. Not to memorize specific vulnerabilities, but to keep a sense of where the bugs are being found today. +这不是绝望的理由。这是持续学习的理由。每年,负责任的驱动程序作者应该阅读几篇新的安全论文,尝试几个新的净化器,看看影响类似内核的最新 CVE。不是为了记住特定的漏洞,而是为了保持对今天漏洞在哪里被发现的感觉。 -The patterns this chapter teaches are stable. Buffer overflows have been bugs since before UNIX. Use-after-free has been a bug since C had malloc. Race conditions have been bugs since kernels had multiple threads. The specific incarnations change, but the underlying defenses endure. A driver written with the disposition this chapter encourages will be mostly right in any decade; when the details shift, the author who built the disposition will adapt faster than one who merely memorized a checklist. +本章教授的模式是稳定的。缓冲区溢出从 UNIX 之前就是漏洞了。释放后使用从 C 有 malloc 以来就是漏洞。竞态条件从内核有多个线程以来就是漏洞。具体的化身会变,但底层防御是持久的。以本章鼓励的性格编写的驱动程序在任何十年中都大体正确;当细节变化时,建立了那种性格的作者会比仅仅记住检查清单的人适应得更快。 ## 结语 -A driver is small. A driver's influence is large. The code you write runs in the most privileged part of the system, touches memory that every other process depends on, and is trusted with the secrets of users who will never see your name. That trust is not automatic; it is earned, one careful line at a time, by authors who assumed the attacker was watching and built accordingly. +驱动程序很小。驱动程序的影响力很大。你编写的代码运行在系统中特权最高的部分,触及每个其他进程依赖的内存,并被信任保护永远不会看到你名字的用户的秘密。那种信任不是自动的;它是赢得的,一次仔细的一行,由假设攻击者在观察并据此构建的作者赢得。 -The authors of FreeBSD have been writing that kind of code for decades. The FreeBSD kernel is not perfect; no kernel of its scale can be. But it has a culture of care, a set of primitives that reward diligence, and a community that treats security bugs as learning opportunities rather than embarrassments. When you write a FreeBSD driver, you are writing into that culture. Your code will be read by people who know the difference between a buffer overflow and a buffer that happens to be large enough; who know the difference between a privilege check that catches root-outside-jail and one that catches root-inside-jail; who know that a race condition is not a rare timing fluke but a vulnerability waiting for the right attacker. +FreeBSD 的作者们几十年来一直在编写那种代码。FreeBSD 内核不完美;没有它那样规模的内核可以完美。但它有一种关爱的文化、一组奖励勤奋的原语,以及一个将安全漏洞视为学习机会而不是尴尬的社区。当你编写 FreeBSD 驱动程序时,你是在那种文化中编写。你的代码将被知道缓冲区溢出和碰巧足够大的缓冲区之间区别的人阅读;知道捕获 jail 外 root 和捕获 jail 内 root 的权限检查之间区别的人;知道竞态条件不是罕见的时序偶然而是等待正确攻击者的漏洞的人阅读。 -Write for those readers. Write for the user whose laptop runs your code without knowing it is there. Write for the maintainer who will inherit your work in ten years. Write for the reviewer who will spot the defensive check you added and feel quietly glad that someone thought of it. +为那些读者编写。为在笔记本电脑上运行你的代码却不知道它在那里的用户编写。为十年后继承你工作的维护者编写。为会注意到你添加的防御性检查并暗自高兴有人想到了它的审查者编写。 -That is what chapter 31 has been about. That is what the rest of your career as a kernel author will be about. Thank you for taking the time to work through it carefully. The chapter ends here; the practice begins tomorrow. +这就是第31章一直在讲的。这就是你作为内核作者职业生涯的其余部分将一直讲的。感谢你花时间仔细阅读。本章在这里结束;实践从明天开始。 diff --git a/translations/zh_CN/chapters/part7/chapter-34.md b/translations/zh_CN/chapters/part7/chapter-34.md index 4be1529..fcc839c 100644 --- a/translations/zh_CN/chapters/part7/chapter-34.md +++ b/translations/zh_CN/chapters/part7/chapter-34.md @@ -13,326 +13,109 @@ estimatedReadTime: 135 language: "zh-CN" --- -# Advanced Debugging Techniques +# 高级调试技术 ## 引言 -In the previous chapter we learned how to measure what a driver does and how -fast it does it. We watched performance counters grow, we ran DTrace -aggregations to spot hot paths, and we used `pmcstat` to see which instructions -were actually consuming cycles. Measurement gave us a language for asking -whether the driver behaves the way we expect. +在前一章中,我们学习了如何测量驱动程序做了什么以及它的执行速度。我们观察性能计数器的增长,运行 DTrace 聚合来发现热点路径,并使用 `pmcstat` 查看哪些指令真正消耗了 CPU 周期。测量为我们提供了一种语言,用来询问驱动程序是否按照我们期望的方式运行。 -Debugging asks a different question. Instead of "how fast is this?" it asks -"why is this wrong?" A performance problem usually produces slow but running -code. A correctness problem can produce a crash, a deadlock, silent data -corruption, a driver that refuses to unload, a pointer that dereferences into -garbage, or a lock that is somehow held by nobody. These are the bugs that -make a seasoned kernel engineer take a slow breath and reach for better tools. +调试提出的是一个不同的问题。它问的不是"这有多快?"而是"为什么这是错的?"性能问题通常产生的是运行缓慢但仍在运行的代码。正确性问题则可能导致崩溃、死锁、静默数据损坏、驱动程序拒绝卸载、指针解引用到垃圾数据,或者一把不知为何无人持有的锁。这些正是让经验丰富的内核工程师深吸一口气,然后去寻找更好工具的那类 bug。 -FreeBSD gives us those tools. They range from very small and very fast -assertions that live inside the kernel and catch the bug the instant it -happens, to full post-mortem analysis of a crash dump on a machine that is no -longer running. There are lightweight tracing rings that cost almost nothing -at runtime, heavyweight tracers that can unwind the entire call graph, and -memory allocators that can be swapped in during development to turn subtle -use-after-free bugs into immediate, diagnosable crashes. A well-equipped -driver author learns to reach for the right tool for the right bug, rather -than staring at `printf` output hoping for enlightenment. +FreeBSD 为我们提供了这些工具。它们涵盖的范围从驻留在内核中、在 bug 发生瞬间就能捕获它的极小极快断言,到对已经不再运行的机器进行完整的崩溃转储事后分析。还有运行时几乎零开销的轻量级跟踪环形缓冲区、能展开整个调用图的重型跟踪器,以及在开发期间可以替换进来、将微妙的释放后使用(use-after-free)bug 转化为立即可诊断崩溃的内存分配器。一个装备齐全的驱动程序作者会学会为正确的 bug 选择正确的工具,而不是盯着 `printf` 输出期盼顿悟。 -The goal of this chapter is to teach you that toolkit. We will begin by -understanding when advanced debugging is the right response and when a simpler -approach will serve better. We will then work through the in-kernel assertion -macros, the panic path, and how to read and analyze a crash dump offline with -`kgdb`. We will build a debug-friendly kernel so those tools are actually -available when we need them, learn how to trace driver behavior with DTrace -and `ktrace`, and finally study how to hunt memory leaks and invalid accesses -with `memguard(9)`, `redzone`, and guard pages. We will close with the -discipline of debugging on production systems, where every action has -consequences, and with a short study of how to refactor a driver after a hard -failure so that it is more resilient to the next one. +本章的目标就是教你这套工具集。我们将首先理解何时应该使用高级调试、何时更简单的方法就足够了。然后我们将学习内核断言宏、panic 路径,以及如何使用 `kgdb` 离线读取和分析崩溃转储。我们将构建一个对调试友好的内核,使这些工具在需要时真正可用,学习如何使用 DTrace 和 `ktrace` 跟踪驱动程序行为,最后研究如何使用 `memguard(9)`、`redzone` 和保护页来追踪内存泄漏和无效访问。我们将以生产系统上的调试纪律作为结束——在那里每个操作都有后果,并简要研究如何在严重故障后重构驱动程序,使其对下一次故障更具韧性。 -Throughout the chapter we will use a small companion driver called `bugdemo`. -It is a pseudo-device with deliberate, controlled bugs that we can trigger -through simple `ioctl(2)` calls and then hunt with each of the techniques the -chapter teaches. Nothing we do touches real hardware, so the lab environment -stays safe even when we deliberately crash the kernel. +在本章中,我们将使用一个名为 `bugdemo` 的配套驱动程序。它是一个伪设备,包含蓄意的、可控的 bug,我们可以通过简单的 `ioctl(2)` 调用触发这些 bug,然后用本章教授的每种技术来追踪它们。我们所做的一切都不涉及真实硬件,因此即使我们故意让内核崩溃,实验环境也是安全的。 -By the end of the chapter you will be able to add defensive assertions to a -driver, build a debug kernel, capture a crash dump, open it in `kgdb`, trace -live behavior with DTrace and `ktrace`, trap memory misuse with `memguard(9)` -and friends, and apply all of this discipline safely on systems where other -people are relying on the machine. +到本章结束时,你将能够为驱动程序添加防御性断言、构建调试内核、捕获崩溃转储、在 `kgdb` 中打开它、使用 DTrace 和 `ktrace` 跟踪实时行为、使用 `memguard(9)` 及相关工具捕获内存误用,并安全地将所有这些规范应用在其他人依赖该机器运行的系统上。 ## 读者指南:如何使用本章 -This chapter sits in Part 7 of the book, alongside performance tuning, -asynchronous I/O, and other mastery topics. It assumes you have already -written at least a simple character device driver, understand the load and -unload lifecycle, and have worked with `sysctl`, `counter(9)`, and DTrace at -the level introduced in Chapter 33. If any of that feels uncertain, a quick -revisit of Chapters 8 through 14 and Chapter 33 will pay for itself several -times over in this chapter. +本章位于本书第七部分,与性能调优、异步 I/O 等其他精通主题并列。本章假设你已经编写过至少一个简单的字符设备驱动程序,理解加载和卸载的生命周期,并且已经使用过 `sysctl`、`counter(9)` 和 DTrace(在第 33 章中介绍的水平)。如果其中任何内容感觉不确定,快速回顾第 8 章到第 14 章以及第 33 章将在本章中为你带来数倍的回报。 ### 与第23章一起阅读本章 -This chapter deliberately picks up where Chapter 23 left off. Chapter -23, "Debugging and Tracing," introduced the fundamentals: how to think -about bugs, how to reach for `printf`, how to use `dmesg` and the -kernel log, how to read a simple panic, how to turn on DTrace probes, -and how to make a driver easier to observe from the start. It stays -close to the everyday debugging habits a new driver author needs. +本章特意从第 23 章结束的地方接续。第 23 章"调试与跟踪"介绍了基础知识:如何思考 bug、如何使用 `printf`、如何使用 `dmesg` 和内核日志、如何阅读简单的 panic、如何启用 DTrace 探针,以及如何从一开始就让驱动程序更容易观察。它紧密围绕新驱动程序作者所需的日常调试习惯。 -Chapter 23 also ends with an explicit hand-off. It flags that deep -`kgdb` scripting on top of a crash dump and the live-kernel -breakpoint workflows are reserved for a later, more advanced -chapter. That later chapter is this one. You are reading the second -half of a pair. If Chapter 23 is the first aid kit, Chapter 34 is -the full clinical toolbox. +第 23 章还以明确的交接作为结尾。它标明了对崩溃转储进行深度 `kgdb` 脚本编写和活内核断点工作流将留给后续更高级的章节。那后续的章节就是本章。你正在阅读的是一对章节的后半部分。如果第 23 章是急救箱,第 34 章就是完整的临床工具箱。 -In practice, this means two things. First, we will not re-explain the -fundamentals Chapter 23 already covered; we will assume you are -comfortable with `printf`, basic panic reading, and introductory -DTrace. If any of those feel shaky, reread the relevant section of -Chapter 23 first, because the advanced material builds directly on -those habits. Second, when a technique here has a simpler counterpart -in Chapter 23 (for example, a basic `bt` in `kgdb` is simpler than -walking `struct thread` fields), we will point to the Chapter 23 -version and then show why the advanced version earns its extra -complexity. +在实践中,这意味着两件事。首先,我们不会重新解释第 23 章已经涵盖的基础知识;我们假设你已经熟悉 `printf`、基本的 panic 阅读和入门级 DTrace。如果其中任何一个让你觉得不稳妥,请先重读第 23 章的相关章节,因为高级材料是直接建立在那些习惯之上的。其次,当这里的技术在第 23 章中有更简单的对应方法时(例如,`kgdb` 中基本的 `bt` 比遍历 `struct thread` 字段更简单),我们会指向第 23 章的版本,然后展示为什么高级版本值得其额外的复杂性。 -Think of the two chapters as a single arc. Chapter 23 teaches you -how to notice that something is wrong and take a first look. Chapter -34 teaches you how to reconstruct, in detail, what the kernel was -doing at the moment the bug occurred, even on a machine that is no -longer running. +将这两章视为一个完整的弧线。第 23 章教你如何注意到出了问题并进行初步查看。第 34 章教你如何详细重建 bug 发生时内核正在做什么,即使是在一台已经不再运行的机器上。 -The material is cumulative. Each section adds another layer onto the -`bugdemo` driver, so the labs read most naturally in order. You can skim -ahead for reference, but if this is your first encounter with kernel -debugging tools, walking through the labs in sequence will build the -mental model we want. +本章内容是累积的。每个部分都在 `bugdemo` 驱动程序上增加一层,因此实验最好按顺序阅读。你可以先浏览以供参考,但如果这是你第一次接触内核调试工具,按顺序完成实验将建立我们期望的思维模型。 -You do not need any special hardware. A modest FreeBSD 14.3 virtual machine -is enough for every lab in the chapter. For Lab 3 and Lab 4 you will want to -have configured a crash dump device, which the chapter walks through, and -for Lab 5 you will need DTrace available in your kernel. Both are standard -on an ordinary FreeBSD installation. +你不需要任何特殊硬件。一台适中的 FreeBSD 14.3 虚拟机就足以完成本章中的每个实验。对于实验 3 和实验 4,你需要配置崩溃转储设备(本章会逐步介绍),对于实验 5,你需要在内核中启用 DTrace。这两者在普通的 FreeBSD 安装中都是标准的。 -Some of the techniques in this chapter deliberately crash the kernel. This is -safe on a development machine and expected as part of the learning process. -It is not safe on a production machine where other people depend on -uninterrupted service. The final section of the chapter is dedicated to that -distinction, because the discipline of knowing when not to use a tool is as -important as knowing how to use it. +本章中的一些技术会故意使内核崩溃。这在开发机器上是安全的,也是学习过程的预期部分。但在其他人依赖不间断服务的生产机器上是不安全的。本章的最后一节专门讨论这个区别,因为知道何时不该使用工具的纪律与知道如何使用工具同样重要。 ## 如何从本章获得最大收益 -The chapter is organized around a pattern you will see repeated throughout. -First we explain what a technique is, then we explain why it exists and what -kind of bug it is meant to catch, then we ground it in real FreeBSD source -code so you can see where the idea lives in the kernel, and finally we apply -it to the `bugdemo` driver through a small lab. Reading and experimenting -together is the most effective approach. The labs are deliberately small -enough to run in a few minutes each. +本章围绕一个反复出现的模式组织。首先我们解释一种技术是什么,然后解释它为什么存在以及它要捕获什么类型的 bug,然后我们将其落实到真实的 FreeBSD 源代码中,让你看到这个想法在内核中的位置,最后我们通过一个小实验将其应用到 `bugdemo` 驱动程序上。阅读和实验相结合是最有效的方法。实验被特意设计得足够小,每个只需几分钟即可运行。 -A few habits will make the work smoother. Keep a terminal open to -`/usr/src/` so you can look at the real code whenever the chapter references -it. The book teaches through observation of real FreeBSD practice, not -through invented pseudo-code, and you will build stronger intuition by -confirming with your own eyes that `KASSERT` really is defined where the -chapter says it is, or that `memguard(9)` really has the API we describe. +一些习惯会让工作更顺畅。保持一个终端打开到 `/usr/src/`,这样每当本章引用真实代码时你就可以查看。本书通过观察真实的 FreeBSD 实践来教学,而不是通过编造的伪代码,通过亲眼确认 `KASSERT` 确实定义在本章所说的位置,或者 `memguard(9)` 确实拥有我们描述的 API,你将建立更强的直觉。 -Keep a second terminal open to your test VM, where you will load the -`bugdemo` driver, trigger bugs, and watch the output. If you can attach a -serial console to the VM, do so. A serial console is the most reliable way -to capture the tail end of a panic message before the machine reboots, and -we will use it in several labs. +保持第二个终端打开到你的测试虚拟机,在那里你将加载 `bugdemo` 驱动程序、触发 bug 并观察输出。如果可以给虚拟机连接串行控制台,请这样做。串行控制台是在机器重启前捕获 panic 消息尾部最可靠的方式,我们将在多个实验中使用它。 -Finally, keep your expectations calibrated. Kernel bugs are often not what -they appear to be at first. A use-after-free might first present itself as -a random data corruption in an unrelated subsystem. A deadlock might first -look like a slow system call. One of the most valuable skills this chapter -teaches is patience: gathering evidence before forming a theory, and -confirming the theory before committing to a fix. The tools help, but the -discipline is what separates a quick bug hunt from a long one. +最后,保持预期的校准。内核 bug 通常不是它们最初看起来的样子。释放后使用可能首先表现为不相关子系统中的随机数据损坏。死锁可能首先看起来像是一个缓慢的系统调用。本章教授的最有价值的技能之一是耐心:在形成理论之前收集证据,在承诺修复之前确认理论。工具有所帮助,但纪律才是区分快速 bug 猎杀和漫长排查的关键。 -With those expectations in place, let us begin by discussing when advanced -debugging is actually the right response to a problem. +带着这些预期,让我们开始讨论何时高级调试才是对问题的正确回应。 ## 1. 何时以及为何需要高级调试 -Most bugs in a driver can be solved without reaching for a crash dump or a -tracing framework. A careful reading of the code, an extra `printf`, a -second look at the return value of a function, a glance at `dmesg`: these -together resolve the majority of defects a driver author encounters. If you -can see the problem, reproduce it cheaply, and hold the relevant code in -your head, the simplest tool is the right tool. +驱动程序中的大多数 bug 无需借助崩溃转储或跟踪框架即可解决。仔细阅读代码、添加一个额外的 `printf`、重新检查函数的返回值、查看 `dmesg`——这些方法加在一起就能解决驱动程序作者遇到的大部分缺陷。如果你能看到问题、能低成本地重现它、并且能在脑中保持相关代码的清晰印象,那么最简单的工具就是正确的工具。 -Advanced debugging exists for the bugs that do not yield to that approach. -It is the toolkit we reach for when the problem is rare, when it appears -far from its cause, when it only shows up under specific timing, when the -driver hangs rather than crashes, or when the symptom is corruption rather -than failure. Those bugs share a common property: they require evidence -you cannot easily collect by reading code, and they require control over -the kernel's execution that a normal user process does not have. +高级调试是为那些无法通过上述方法解决的 bug 而存在的。它是我们在以下情况下才会动用的工具箱:问题很罕见、问题的表现远离其根源、只在特定的时序下才会出现、驱动程序挂起而不是崩溃、或者症状是数据损坏而不是功能失败。这些 bug 有一个共同特征:它们需要你无法通过阅读代码轻松收集的证据,并且需要对内核执行过程的控制权——而这是普通用户进程所不具备的。 ### 需要比printf更多工具的Bug -The first class of bug that demands advanced tooling is the bug that -destroys the evidence of its own cause. A use-after-free is the canonical -example. The driver frees an object, then some later code, possibly in a -different function or a different thread, reads or writes that memory. -By the time the crash happens, the free has long since occurred, the -memory has been reused for something unrelated, and the backtrace at the -point of the crash points to the victim, not the culprit. A `printf` -added at the crash site will faithfully print the nonsense it sees. It -will not tell you who freed the memory or when. +第一类需要高级工具的 bug 是会销毁自身成因证据的 bug。释放后使用(use-after-free)是典型例子。驱动程序释放了一个对象,然后一些后续代码——可能在不同的函数或不同的线程中——读取或写入了那块内存。等到崩溃发生时,释放操作早已完成,内存已被重新用于无关的用途,崩溃点的回溯指向的是受害者而非罪魁祸首。在崩溃点添加 `printf` 会忠实地打印出它看到的乱码,但不会告诉你谁释放了内存或何时释放的。 -A second class is the bug that only appears under concurrency. Two threads -race for a lock. One of them takes the lock in the wrong order, deadlocking -against another thread that took the same locks in the reverse order. The -system goes quiet, and the bug leaves no message on the console. Adding -`printf` calls to the locking path often perturbs the timing just enough to -make the bug disappear, a frustrating property that Heisenbug enthusiasts -are familiar with. Static lock order checking, which FreeBSD provides -through `WITNESS`, exists precisely because this class of bug is hard to -find any other way. +第二类是只在并发条件下才出现的 bug。两个线程竞争一把锁。其中一个以错误的顺序获取了锁,与另一个以相反顺序获取相同锁的线程发生死锁。系统安静下来,bug 没有在控制台留下任何消息。在加锁路径中添加 `printf` 调用往往会干扰时序,恰好使 bug 消失——这是 Heisenbug 爱好者熟悉的令人沮丧的特性。FreeBSD 通过 `WITNESS` 提供的静态锁序检查之所以存在,正是因为这类 bug 很难通过其他方式发现。 -A third class is the bug that cannot be observed at all in user space. The -driver corrupts a kernel data structure on one code path, and the -consequence shows up many minutes later in an unrelated subsystem. The -process that triggers the corruption is long gone by the time anything -goes wrong. The only way to correlate cause and effect is to capture the -full kernel state at the moment of the panic and walk it offline with -`kgdb`, or to trace the kernel continuously with DTrace so that the -suspicious event leaves a trail. +第三类是在用户空间完全无法观察的 bug。驱动程序在某条代码路径上损坏了一个内核数据结构,其后果在许多分钟后才在不相关的子系统中显现。触发损坏的进程在出问题时早已消失。将原因与结果关联起来的唯一方法是在 panic 的瞬间捕获完整的内核状态并用 `kgdb` 离线遍历,或者用 DTrace 持续跟踪内核,让可疑事件留下痕迹。 -A fourth class is the bug that only appears on hardware you cannot attach a -debugger to, or in production configurations you cannot directly instrument. -The driver runs on a customer's machine, it crashes once a week, and nobody -wants your development workstation physically plugged into it. The tool for -this situation is the crash dump: a snapshot of kernel memory written to -disk at the moment of panic, carried to a safe environment, and analyzed -there. `dumpon(8)` configures where the dump goes, `savecore(8)` retrieves -it after the reboot, and `kgdb` reads it offline. +第四类是只出现在你无法附加调试器的硬件上、或无法直接插桩的生产配置中的 bug。驱动程序运行在客户的机器上,每周崩溃一次,没有人希望你把开发工作站物理连接到上面。这种情况下的工具就是崩溃转储:在 panic 时写入磁盘的内核内存快照,可以被转移到安全环境中进行分析。`dumpon(8)` 配置转储的写入位置,`savecore(8)` 在重启后取回转储,`kgdb` 离线读取。 -Each of these bug classes has its own tool in the FreeBSD debugging -toolkit. The rest of the chapter introduces them in turn. The point of this -opening section is simply to set expectations: we are not about to learn a -single technique that replaces `printf`. We are learning a family of -techniques, each suited to a particular kind of difficulty. +这些 bug 类别中的每一个在 FreeBSD 调试工具箱中都有对应的工具。本章其余部分将逐一介绍它们。本节开头的目的是设定预期:我们不是要学习一种取代 `printf` 的单一技术,而是要学习一族技术,每一种适用于特定类型的困难。 ### 高级工具的成本 -Advanced debugging is not free. Each of the techniques we will study -carries some combination of build-time cost, run-time cost, and -disciplinary cost. +高级调试不是免费的。我们将学习的每一种技术都带有构建时成本、运行时成本和纪律成本的某种组合。 -Build-time cost is the easiest to describe. `INVARIANTS` and `WITNESS` -make the kernel slower because they add checks that a production kernel -skips. `DEBUG_MEMGUARD` makes certain allocations dramatically slower -because it replaces them with full-page mappings that are unmapped on -free. A debug kernel built with `makeoptions DEBUG=-g` is several times -larger than a release kernel because every function carries full debug -information. None of these costs matter on a development machine, where -correctness is worth orders of magnitude more than speed. All of them -matter in production. +构建时成本最容易描述。`INVARIANTS` 和 `WITNESS` 会使内核变慢,因为它们添加了生产内核会跳过的检查。`DEBUG_MEMGUARD` 会使某些分配大幅变慢,因为它用完整的页面映射替换分配并在释放时取消映射。使用 `makeoptions DEBUG=-g` 构建的调试内核比发布版内核大好几倍,因为每个函数都携带完整的调试信息。在开发机器上这些成本无关紧要,因为正确性的价值比速度高出几个数量级。但在生产环境中它们全部举足轻重。 -Run-time cost applies to the tools you enable in a running kernel. DTrace -probes that are disabled cost essentially nothing, but an enabled probe -still runs on every hit of the instrumented function. `ktr(9)` entries -are very cheap but not free. A verbose tracing session can generate -enough log output to fill a disk. A `kdb` session pauses the entire -kernel, which on a machine people are using is a disaster. Each tool has -a run-time budget, and part of the discipline of this chapter is knowing -what that budget is. +运行时成本适用于你在运行中的内核里启用的工具。已禁用的 DTrace 探针基本上不花什么成本,但启用的探针在每次命中被插桩函数时仍会执行。`ktr(9)` 条目非常便宜但并非免费。一个详细的跟踪会话可以产生足够填满磁盘的日志输出。`kdb` 会话会暂停整个内核,这对有人正在使用的机器来说是一场灾难。每种工具都有一个运行时预算,本章的纪律之一就是了解那个预算是多少。 -Disciplinary cost is the hardest to quantify but the easiest to -underestimate. Advanced debugging requires patience, careful note taking, -and a willingness to sit with incomplete information. It requires -resisting the urge to patch a visible symptom before you understand the -underlying defect. A crash that happens in module X almost never means -the bug is in module X. The reader who learns to collect evidence before -forming a theory will have an easier time with this chapter than the -reader who wants to commit a fix as quickly as possible. +纪律成本最难量化,但也最容易低估。高级调试需要耐心、认真的记录,以及与不完整信息共处的意愿。它要求你抵抗在理解底层缺陷之前就修补可见症状的冲动。发生在模块 X 中的崩溃几乎从来不意味着 bug 就在模块 X 中。学会在形成理论之前先收集证据的读者,在学习本章时会比急于尽快提交修复的读者轻松得多。 ### 决策框架 -With those costs in mind, here is a simple decision framework for -choosing your tool. If the bug is easy to reproduce and the cause is -likely visible in the nearby code, start with reading and with strategic -`printf` or `log(9)` statements. If the bug only appears under load or -concurrency, enable `INVARIANTS` and `WITNESS` and rebuild. If the bug -produces a panic, capture the dump and open it in `kgdb`. If the bug -involves memory corruption, enable `DEBUG_MEMGUARD` on the suspect -allocation type. If the bug involves a silent misbehavior rather than a -crash, add SDT probes and watch them with DTrace. If you need to -understand timing between events in an interrupt handler, use `ktr(9)`. -And if the bug is on a production machine, see Section 7 before doing -anything at all. +考虑到这些成本,以下是一个选择工具的简单决策框架。如果 bug 容易重现且原因可能在附近代码中可见,从阅读代码和策略性地放置 `printf` 或 `log(9)` 语句开始。如果 bug 只在负载或并发条件下出现,启用 `INVARIANTS` 和 `WITNESS` 并重新构建。如果 bug 产生了 panic,捕获转储并在 `kgdb` 中打开它。如果 bug 涉及内存损坏,对可疑的分配类型启用 `DEBUG_MEMGUARD`。如果 bug 表现为静默的错误行为而非崩溃,添加 SDT 探针并用 DTrace 观察它们。如果你需要理解中断处理程序中事件之间的时序,使用 `ktr(9)`。如果 bug 出现在生产机器上,在做任何事情之前先阅读第 7 节。 -We will spend the rest of the chapter teaching each of these techniques -in depth. The `bugdemo` driver we are about to meet gives us a safe place -to apply every one of them, with known bugs to hunt and known answers to -find. +本章其余部分将深入讲解每种技术。我们即将认识的 `bugdemo` 驱动程序为我们提供了一个安全的地方来应用每一种技术,有已知的 bug 可以追踪,有已知的答案可以寻找。 ### 认识bugdemo驱动 -The `bugdemo` driver is a small pseudo-device that we will use as our lab -subject throughout the chapter. It has no hardware to drive. It exposes a -device node at `/dev/bugdemo` and accepts a handful of `ioctl(2)` commands -that deliberately trigger different classes of bug: a null pointer -dereference, an unlocked access that `WITNESS` can catch, a -use-after-free, a memory leak, an infinite loop inside a spinlock, and so -on. Each ioctl is gated by a sysctl switch so that the driver can be -loaded safely on a development system without accidentally triggering -anything. +`bugdemo` 驱动程序是一个小型伪设备,我们将它作为本章的实验对象。它没有硬件需要驱动。它在 `/dev/bugdemo` 暴露一个设备节点,并接受少量 `ioctl(2)` 命令来故意触发不同类别的 bug:空指针解引用、`WITNESS` 可以捕获的无锁访问、释放后使用、内存泄漏、自旋锁内的无限循环等。每个 ioctl 都由一个 sysctl 开关控制,这样驱动程序可以在开发系统上安全加载而不会意外触发任何东西。 -We will introduce the driver properly in Lab 1, when we have the assertion -macros in hand. For now, keep in mind that every technique we study can be -demonstrated on `bugdemo` with a known starting point and a known answer. -That discipline, of reproducing bugs in a controlled setting, is itself -one of the most important skills this chapter aims to teach. +我们将在实验 1 中正式介绍这个驱动程序,届时我们已经掌握了断言宏。现在请记住,我们学习的每一种技术都可以在 `bugdemo` 上演示,有已知的起点和已知的答案。在受控环境中重现 bug——这种纪律本身就是本章旨在教授的最重要技能之一。 -Now we are ready to begin the toolkit proper, starting with the assertion -macros that catch bugs at the instant they happen. +现在我们已准备好正式开始工具箱的学习,从在 bug 发生瞬间就能捕获它们的断言宏开始。 ## 2. 使用KASSERT、panic及相关宏 -Defensive programming in user space often revolves around runtime checks -and careful error handling. Defensive programming in the kernel adds one -more tool: the assertion macro. An assertion states a condition that must -be true at a given point. If the condition is false, something is very -wrong, and the safest response is to stop the kernel immediately, before -the wrong state has a chance to spread. Assertions are the cheapest and -most effective debugging tool FreeBSD gives us, and they belong in every -serious driver. +用户空间中的防御性编程通常围绕运行时检查和谨慎的错误处理展开。内核中的防御性编程还多了一个工具:断言宏。断言声明了一个在给定位置必须为真的条件。如果条件为假,说明出现了严重问题,最安全的响应是立即停止内核,防止错误状态有机会扩散。断言是 FreeBSD 提供的最便宜、最有效的调试工具,它们属于每一个严肃的驱动程序。 -We will start with the two most important macros, `KASSERT(9)` and -`panic(9)`, look at a handful of useful companions, and then discuss when -each is appropriate. +我们将从两个最重要的宏 `KASSERT(9)` 和 `panic(9)` 开始,看看一些有用的伴生宏,然后讨论各自的适用场景。 -> **A note on line numbers.** When the chapter quotes code from -> `kassert.h`, `kern_shutdown.c`, or `cdefs.h`, the landmark is always -> the macro or function name. `KASSERT`, `kassert_panic`, `panic`, and -> `__dead2` will remain findable by those names in every FreeBSD 14.x -> tree even as the lines around them move. The sample backtrace you will -> see later, which quotes `file:line` pairs such as -> `kern_shutdown.c:400`, reflects a 14.3 tree at the time of writing and -> will not match line-for-line on a freshly updated system. Grep for the -> symbol rather than scroll to the number. +> **关于行号的说明。** 当本章引用 `kassert.h`、`kern_shutdown.c` 或 `cdefs.h` 中的代码时,定位标记始终是宏名或函数名。`KASSERT`、`kassert_panic`、`panic` 和 `__dead2` 在每一个 FreeBSD 14.x 源码树中都可以通过这些名字找到,即使它们周围的行已经移动。你后面将看到的示例回溯引用了 `kern_shutdown.c:400` 这样的 `file:line` 对,反映的是撰写时 14.3 源码树的情况,在新更新的系统上不会逐行匹配。请用 grep 搜索符号名而不是滚动到行号。 ### KASSERT:在生产环境中消失的检查 -`KASSERT` is the in-kernel equivalent of the user-space `assert()` macro, -but smarter. It takes a condition and a message. If the condition is -false, the kernel panics with the message. If the kernel was compiled -without the `INVARIANTS` option, the entire check disappears at compile -time and costs nothing at runtime. +`KASSERT` 是内核中对应于用户空间 `assert()` 宏的等价物,但更智能。它接受一个条件和一个消息。如果条件为假,内核以该消息触发 panic。如果内核在编译时没有启用 `INVARIANTS` 选项,整个检查在编译时就被消除,运行时不花费任何成本。 -The macro lives in `/usr/src/sys/sys/kassert.h`. In a FreeBSD 14.3 source -tree it looks like this: +这个宏位于 `/usr/src/sys/sys/kassert.h`。在 FreeBSD 14.3 源码树中它看起来是这样的: ```c #if (defined(_KERNEL) && defined(INVARIANTS)) || defined(_STANDALONE) @@ -346,67 +129,31 @@ tree it looks like this: #endif /* KERNEL && INVARIANTS */ ``` -Four details of this definition are worth pausing on. +这个定义中有四个细节值得仔细审视。 -First, the macro is defined differently depending on whether `INVARIANTS` -is set. If it is not, `KASSERT` expands to an empty `do { } while (0)` -block, which the compiler optimizes away entirely. A release kernel built -without `INVARIANTS` pays no runtime cost for `KASSERT` calls, no matter -how many the driver contains. This is the property that lets us write -generous assertions in development without worrying about production -performance. The `_STANDALONE` branch lets the same macro work in the -bootloader, where `INVARIANTS` may be absent but the check is still -desired. +第一,宏的定义方式取决于是否设置了 `INVARIANTS`。如果没有设置,`KASSERT` 展开为一个空的 `do { } while (0)` 块,编译器会将其完全优化掉。没有 `INVARIANTS` 的发布版内核无论驱动程序中包含多少 `KASSERT` 调用,都不承担任何运行时成本。这正是让我们在开发时可以慷慨地编写断言而无需担心生产性能的属性。`_STANDALONE` 分支让同一个宏也能在引导加载程序中工作,那里可能没有 `INVARIANTS` 但检查仍然是需要的。 -Second, the `__predict_false` hint tells the compiler that the condition -is almost always true. This improves code generation for the common path, -because the compiler will arrange the branch so that the hot path does -not take a jump. Defining `__predict_false` is one of the small -performance disciplines that keeps a debug kernel usable. +第二,`__predict_false` 提示告诉编译器该条件几乎总是为真。这改善了公共路径的代码生成,因为编译器会安排分支使得热路径不需要跳转。定义 `__predict_false` 是保持调试内核可用性的小性能纪律之一。 -Third, the body of a failing assertion calls `kassert_panic`, not `panic` -directly. This is an implementation detail for making assertion messages -easier to parse, but it matters when you see a panic message in practice: -`KASSERT` failures produce a distinctive prefix that we will recognize -later. +第三,失败断言的主体调用的是 `kassert_panic` 而非 `panic`。这是一个实现细节,目的是让断言消息更容易解析,但当你看到实际的 panic 消息时它很重要:`KASSERT` 失败会产生一个独特的前缀,我们后面会认出它。 -Fourth, notice that the `msg` argument is passed in double parentheses. -That is because the macro passes it directly to `kassert_panic`, which -has a `printf`-style signature. In practice you write: +第四,注意 `msg` 参数是用双层括号传递的。这是因为宏将其直接传递给 `kassert_panic`,后者具有 `printf` 风格的签名。在实践中你这样写: ```c KASSERT(ptr != NULL, ("ptr must not be NULL in %s", __func__)); ``` -The outer parentheses belong to the macro. The inner parentheses are the -argument list for `kassert_panic`. A beginner's mistake is to write -`KASSERT(ptr != NULL, "ptr is NULL")` with only one set of parentheses, -which will not compile. The double parentheses are the discipline that -reminds us a failing assertion will be formatted like a `printf`. +外层括号属于宏。内层括号是 `kassert_panic` 的参数列表。初学者的常见错误是只写一层括号 `KASSERT(ptr != NULL, "ptr is NULL")`,这无法编译。双层括号是一种纪律,提醒我们失败的断言将像 `printf` 一样格式化。 ### INVARIANTS and INVARIANT_SUPPORT -`INVARIANTS` is the kernel build option that controls whether `KASSERT` -is active. A debug kernel enables it. The `GENERIC-DEBUG` configuration -shipped with FreeBSD 14.3 enables it by including `std.debug`, which you -can see in `/usr/src/sys/conf/std.debug`. A release `GENERIC` kernel does -not enable it. +`INVARIANTS` 是控制 `KASSERT` 是否生效的内核构建选项。调试内核会启用它。FreeBSD 14.3 附带的 `GENERIC-DEBUG` 配置通过包含 `std.debug` 来启用它,你可以在 `/usr/src/sys/conf/std.debug` 中看到。发布版 `GENERIC` 内核不启用它。 -There is also a related option called `INVARIANT_SUPPORT`. `INVARIANT_SUPPORT` -compiles in the functions that assertions might call, without making them -mandatory. This allows loadable kernel modules that were built with -`INVARIANTS` to load into a kernel that was not built with `INVARIANTS`, as -long as `INVARIANT_SUPPORT` is present. For a driver author, the practical -upshot is this: if you build your module with `INVARIANTS`, make sure the -kernel you are loading it into has at least `INVARIANT_SUPPORT`. The -`GENERIC-DEBUG` kernel has both, which is one of the reasons we recommend -using it throughout development. +还有一个相关选项叫做 `INVARIANT_SUPPORT`。`INVARIANT_SUPPORT` 编译进断言可能调用的函数,但不使它们成为强制性的。这允许用 `INVARIANTS` 构建的可加载内核模块加载到没有用 `INVARIANTS` 构建的内核中,只要该内核有 `INVARIANT_SUPPORT`。对于驱动程序作者来说,实际意义在于:如果你用 `INVARIANTS` 构建模块,确保你要加载到的内核至少有 `INVARIANT_SUPPORT`。`GENERIC-DEBUG` 内核两者都有,这是我们推荐在整个开发过程中使用它的原因之一。 ### MPASS:带默认消息的KASSERT -Writing a message for every assertion can be tedious, especially for -simple invariants. FreeBSD provides `MPASS` as a shorthand for -`KASSERT(expr, ("Assertion expr failed at file:line"))`: +为每个断言都写一条消息可能很繁琐,特别是对于简单的不变式。FreeBSD 提供了 `MPASS` 作为 `KASSERT(expr, ("Assertion expr failed at file:line"))` 的简写: ```c #define MPASS(ex) MPASS4(ex, #ex, __FILE__, __LINE__) @@ -416,35 +163,21 @@ simple invariants. FreeBSD provides `MPASS` as a shorthand for KASSERT((ex), ("Assertion %s failed at %s:%d", what, file, line)) ``` -The four forms let you customize the message, the file, or both. The -simplest form, `MPASS(ptr != NULL)`, stringifies the expression itself -and embeds the location automatically. When the message can afford to be -terse, `MPASS` produces less visual clutter in the source. When the -message needs context a future reader will appreciate, prefer -`KASSERT` with a written message. +四种形式允许你自定义消息、文件,或两者兼有。最简单的形式 `MPASS(ptr != NULL)` 会自动将表达式字符串化并嵌入位置。当消息可以简明扼要时,`MPASS` 在源代码中产生的视觉杂乱更少。当消息需要未来读者会感谢的上下文时,优先使用带书面消息的 `KASSERT`。 -A sensible rule of thumb is that `MPASS` is for internal invariants that -should never happen and where the identity of the expression is -self-explanatory. `KASSERT` is for conditions where the failure mode -deserves a descriptive message. +一个合理的经验法则是:`MPASS` 用于不应该发生的内部不变式,且表达式的含义不言自明。`KASSERT` 用于失败模式值得描述性消息的条件。 ### CTASSERT:编译时断言 -Sometimes the condition you want to check can be decided at compile time. -`sizeof(struct foo) == 64`, for example, or `MY_CONST >= 8`. For those, -FreeBSD provides `CTASSERT`, also in `/usr/src/sys/sys/kassert.h`: +有时你想检查的条件可以在编译时决定。例如 `sizeof(struct foo) == 64` 或 `MY_CONST >= 8`。对于这些情况,FreeBSD 提供了 `CTASSERT`,同样位于 `/usr/src/sys/sys/kassert.h`: ```c #define CTASSERT(x) _Static_assert(x, "compile-time assertion failed") ``` -`CTASSERT` uses C11's `_Static_assert`. It produces a compile-time error -if the condition is false and has zero runtime cost because there is no -runtime involved. This is the ideal tool for structure layout checks that -must hold for the driver to be correct. +`CTASSERT` 使用 C11 的 `_Static_assert`。如果条件为假,它会产生编译时错误,并且没有任何运行时成本,因为没有运行时参与。这是结构体布局检查的理想工具——这些检查必须成立才能保证驱动程序正确。 -A typical use in the kernel is to guard a structure against accidental -size changes: +内核中的典型用法是保护结构体免受意外的大小变更: ```c struct bugdemo_command { @@ -456,52 +189,25 @@ struct bugdemo_command { CTASSERT(sizeof(struct bugdemo_command) == 16); ``` -If someone later adds a field without adjusting the size comment or -reordering thoughtfully, the build breaks immediately. This is far better -than finding out at runtime that the structure has grown and the ioctl -no longer matches user-space expectations. +如果后来有人添加了字段却没有调整大小注释或仔细重新排列,构建会立即中断。这远比在运行时才发现结构体增长了、ioctl 不再匹配用户空间期望要好得多。 ### panic:无条件停止 -Where `KASSERT` is a conditional check, `panic` is the unconditional -version. You call it when you have decided that continuing execution -would be worse than stopping: +`KASSERT` 是条件检查,而 `panic` 是无条件版本。当你判定继续执行比停止更糟糕时调用它: ```c void panic(const char *, ...) __dead2 __printflike(1, 2); ``` -The declaration lives in `/usr/src/sys/sys/kassert.h` and the implementation -in `/usr/src/sys/kern/kern_shutdown.c`. The `__dead2` attribute tells the -compiler that `panic` does not return, which lets it produce better code -downstream. The `__printflike(1, 2)` attribute tells it that the first -argument is a `printf`-style format string, so the compiler can type-check -the format against its arguments. +声明位于 `/usr/src/sys/sys/kassert.h`,实现在 `/usr/src/sys/kern/kern_shutdown.c`。`__dead2` 属性告诉编译器 `panic` 不会返回,这让它在下游产生更好的代码。`__printflike(1, 2)` 属性告诉编译器第一个参数是 `printf` 风格的格式字符串,这样编译器可以对格式与其参数进行类型检查。 -When would you use `panic` directly rather than `KASSERT`? Three common -situations. First, when the condition is so catastrophic that there is no -safe continuation even in a release kernel. Failing to allocate a soft -context during `attach`, for example, might be a `panic` rather than a -graceful cleanup if the driver has already been partially registered. -Second, when you want the message to appear even in non-debug builds, -because the event indicates a hardware or configuration failure that the -user must be told about. Third, as a placeholder during early development, -to make sure unreachable paths actually are unreachable, before you -replace the `panic` with a `KASSERT(0, ...)` in mature code. +什么时候应该直接使用 `panic` 而不是 `KASSERT`?三种常见情况。第一,当情况极其灾难性,即使在发布版内核中也没有安全的继续路径。例如,在 `attach` 期间分配 soft 上下文失败——如果驱动程序已经部分注册了,可能是 `panic` 而非优雅清理更合适。第二,当你希望消息即使在非调试构建中也出现,因为事件指示了用户必须知道的硬件或配置失败。第三,作为早期开发期间的占位符,确保不可达路径确实不可达,然后在代码成熟后将 `panic` 替换为 `KASSERT(0, ...)`。 -Some drivers in `/usr/src/sys/dev/` use `panic` sparingly. Reading a few -examples will give you a feel for the tone: a `panic` message says -something like "the controller returned an impossible status" or "we -reached a case the state machine claims cannot happen." It is not the -normal response to an I/O error. It is the response to an invariant that -has been broken so thoroughly that the driver cannot be trusted to -continue. +`/usr/src/sys/dev/` 中的一些驱动程序很少使用 `panic`。阅读几个例子会让你对基调有所感觉:`panic` 消息说的是类似"控制器返回了一个不可能的状态"或"我们到达了状态机声称不可能出现的情况"。它不是对 I/O 错误的正常响应。它是对一个已被严重破坏的不变式的响应——破坏到驱动程序不能被信任继续运行。 ### __predict_false and __predict_true -We saw `__predict_false` in the `KASSERT` definition. These two macros, -defined in `/usr/src/sys/sys/cdefs.h`, are compile-time hints to the -branch predictor: +我们在 `KASSERT` 定义中看到了 `__predict_false`。这两个宏定义在 `/usr/src/sys/sys/cdefs.h`,是给分支预测器的编译时提示: ```c #if __GNUC_PREREQ__(3, 0) @@ -513,26 +219,15 @@ branch predictor: #endif ``` -They do not change the semantics of the expression. They only tell the -compiler which outcome is more likely, which influences how the compiler -lays out the code. In a hot path, wrapping a likely-true condition in -`__predict_true` can improve cache behavior; wrapping a likely-false one -in `__predict_false` keeps the error-handling code off the fast path. +它们不改变表达式的语义。它们只告诉编译器哪种结果更可能,这会影响编译器的代码布局。在热路径中,用 `__predict_true` 包裹一个可能为真的条件可以改善缓存行为;用 `__predict_false` 包裹一个可能为假的条件则让错误处理代码不落在快速路径上。 -The first rule of using these macros is to be correct. If you predict -wrong, you slow the code down rather than speeding it up. The second rule -is to only use them in genuinely hot paths where the difference matters. -For most driver code, the compiler's default heuristics are fine, and -cluttering the code with predictions is more trouble than it is worth. +使用这些宏的第一条规则是正确。如果你预测错了,你会使代码变慢而不是变快。第二条规则是只在确实有影响的热路径中使用它们。对于大多数驱动程序代码,编译器的默认启发式就够了,在代码中添加预测杂乱无章,弊大于利。 ### 断言在驱动中的位置 -With these macros in hand, where do you actually put assertions? A few -patterns have proven useful in FreeBSD drivers. +有了这些宏,你实际上应该把断言放在哪里?在 FreeBSD 驱动程序中,几种模式已被证明是有用的。 -The first is at function entry, for non-trivial preconditions. A driver -function that expects to be called with a particular lock held is a -perfect candidate: +第一种是在函数入口处,用于非平凡的前置条件。一个期望在持有特定锁时被调用的驱动程序函数是完美的候选: ```c static void @@ -546,83 +241,43 @@ bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) } ``` -The `BUGDEMO_LOCK_ASSERT` is a macro convention many drivers adopt that -wraps a `mtx_assert(9)` or `sx_assert(9)` call. This pattern, where each -subsystem has its own `_ASSERT` macro that checks its own lock, scales -well across a large driver. +`BUGDEMO_LOCK_ASSERT` 是许多驱动程序采用的宏约定,它封装了 `mtx_assert(9)` 或 `sx_assert(9)` 调用。这种模式——每个子系统有自己的 `_ASSERT` 宏来检查自己的锁——在大型驱动程序中扩展性很好。 -The second pattern is at state transitions. If a driver state machine -has four valid states and an `attach` path that should only ever run in -state `INIT`, an assertion at the top of `attach` will catch any future -refactor that breaks that invariant: +第二种模式是在状态转换处。如果驱动程序状态机有四个有效状态,而 `attach` 路径应该只在 `INIT` 状态下运行,那么在 `attach` 顶部的断言将捕获任何未来破坏该不变式的重构: ```c KASSERT(sc->state == BUGDEMO_STATE_INIT, ("attach called in state %d", sc->state)); ``` -The third pattern is after subtle arithmetic. If a calculation should -produce a value in a known range, check: +第三种模式是在微妙的算术运算之后。如果一次计算应该产生一个已知范围内的值,检查它: ```c idx = (offset / PAGE_SIZE) & (SC_NRING - 1); KASSERT(idx < SC_NRING, ("idx %u out of range", idx)); ``` -This is especially valuable in ring buffer code, where an off-by-one -between producer and consumer can cause silent data corruption. +这在环形缓冲区代码中特别有价值,因为生产者和消费者之间的差一错误可能导致静默的数据损坏。 -The fourth pattern is for pointers that could be NULL but should not be. -If a function receives a pointer argument that is only valid when nonzero, -a single `KASSERT(ptr != NULL, ...)` at the top of the function catches -years of future misuse. +第四种模式是用于可能为 NULL 但不应为 NULL 的指针。如果函数接收一个只有非零时才有效的指针参数,在函数顶部的一个 `KASSERT(ptr != NULL, ...)` 可以捕获多年的未来误用。 ### 何时不应使用断言 -Assertions are not a replacement for error handling. The rule is: -`KASSERT` checks things that the programmer guarantees, not things the -environment guarantees. If a memory allocation with `M_NOWAIT` can fail -under memory pressure, you do not assert it succeeded. You check the -return value and handle the failure. If a user-space program passes a -structure larger than you expect, you return `EINVAL`, not `KASSERT(0)`. -The assertion is for internal consistency, not for external input. +断言不能替代错误处理。规则是:`KASSERT` 检查程序员保证的事情,而不是环境保证的事情。如果使用 `M_NOWAIT` 的内存分配在内存压力下可能失败,你不应该断言它成功了。你应该检查返回值并处理失败。如果用户空间程序传递了一个比你预期更大的结构体,你应该返回 `EINVAL`,而不是 `KASSERT(0)`。断言用于内部一致性,不用于外部输入。 -Another anti-pattern is using assertions for conditions that only hold in -certain configurations. `KASSERT(some_sysctl == default)` is wrong if -some_sysctl is user-tunable, because the assertion will fail on any -system that has tuned it. Check the configuration explicitly and handle -it, or assert only within the branch where the assumption actually holds. +另一种反模式是对只在某些配置中成立的条件使用断言。`KASSERT(some_sysctl == default)` 是错误的,如果 some_sysctl 是用户可调的,因为断言在任何调过它的系统上都会失败。应该显式检查配置并处理它,或者只在假设实际成立的分支内断言。 -A more subtle anti-pattern is using assertions as documentation. "This is -how it works, and it had better stay that way" is a tempting use of -`KASSERT`, but if the assertion only holds today and could reasonably -change tomorrow, you have created a future bug for someone who does not -remember your promise. Better to leave a comment that states the -assumption, and let the code evolve. Assertions should capture permanent -invariants, not temporary implementation choices. +一种更微妙的反模式是将断言用作文档。"这是它的工作方式,而且最好保持这样"是一种诱人的 `KASSERT` 用法,但如果断言只是今天成立而明天可能合理改变,你就为某个不记得你承诺的人创造了一个未来的 bug。最好留下一个说明假设的注释,让代码演进。断言应该捕获永久性的不变式,而不是临时的实现选择。 -### A Small Real-World Example +### 一个小型真实世界示例 -Let us see these ideas applied in real FreeBSD code. Open -`/usr/src/sys/dev/null/null.c` and look at a typical check near the read -handler. The driver is extremely simple, so there are few assertions, but -many drivers in `/usr/src/sys/dev/` use `KASSERT` liberally. For a richer -example, scan `/usr/src/sys/dev/uart/uart_bus_pci.c` or -`/usr/src/sys/dev/mii/mii.c`, where assertions at function entry catch -callers that do not hold the expected locks. +让我们看看这些想法在真实 FreeBSD 代码中的应用。打开 `/usr/src/sys/dev/null/null.c`,查看 read 处理程序附近的典型检查。该驱动程序极其简单,因此断言很少,但 `/usr/src/sys/dev/` 中的许多驱动程序大量使用 `KASSERT`。更丰富的示例可以浏览 `/usr/src/sys/dev/uart/uart_bus_pci.c` 或 `/usr/src/sys/dev/mii/mii.c`,那里的函数入口断言捕获了未持有期望锁的调用者。 -The consistency of this pattern across the tree is not accidental. It -reflects a cultural expectation that drivers will express their -invariants in code, not only in comments. When you adopt the same habit -in your own drivers, you join that culture. Your drivers will be easier -to port, easier to review, and much easier to debug when something -eventually goes wrong. +整个源码树中这种模式的一致性并非偶然。它反映了一种文化期望:驱动程序将在代码中而非仅在注释中表达其不变式。当你在自己的驱动程序中采用同样的习惯时,你就融入了这种文化。你的驱动程序将更容易移植、更容易审查,在最终出问题时也更容易调试。 -### A Quick Example: Adding Assertions to bugdemo +### 快速示例:为 bugdemo 添加断言 -Let us add a small set of assertions to an imagined `bugdemo` driver. -Assume we have a softc structure with a mutex, a state field, and a -counter, and an `ioctl` handler that takes a `struct bugdemo_command`. +让我们为一设想的 `bugdemo` 驱动程序添加一组断言。假设我们有一个包含互斥锁、状态字段和计数器的 softc 结构,以及一个接受 `struct bugdemo_command` 的 `ioctl` 处理程序。 ```c static int @@ -650,80 +305,35 @@ bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, } ``` -Four assertions, each catching a different class of future bug. The -first checks that the driver's private pointer is actually set, which is -easy to forget when `make_dev(9)` is called with `NULL` by mistake. The -second checks the driver state, which will fire if someone adds a code -path that can reach `ioctl` before `attach` has finished. The third -checks user-provided input is in range, though in a production context -this particular check would also be done as a real input validation that -returns an error, because `ioctl` is a public interface. The fourth, not -shown here but implied by `bugdemo_process`, asserts the lock is held. +四个断言,每一个捕获一类不同的未来 bug。第一个检查驱动程序的私有指针是否实际设置,这在 `make_dev(9)` 被误传 `NULL` 时很容易忘记。第二个检查驱动程序状态,如果有人添加了可以在 `attach` 完成前到达 `ioctl` 的代码路径,它就会触发。第三个检查用户提供的输入是否在范围内,不过在生上下文中,这个特定的检查也应作为返回错误的真正输入验证来完成,因为 `ioctl` 是公共接口。第四个(此处未显示但由 `bugdemo_process` 暗示)断言锁已被持有。 -These few lines express a lot of invariants. In a debug kernel, they -will catch real bugs the moment they happen. In a release kernel, they -disappear entirely. That is the bargain `KASSERT` offers, and taking it -is one of the best habits a driver author can cultivate. +这几行代码表达了大量不变式。在调试内核中,它们会在 bug 发生的瞬间捕获真正的 bug。在发布版内核中,它们完全消失。这就是 `KASSERT` 提供的契约,接受它是驱动程序作者能培养的最佳习惯之一。 -With this foundation in place, we can move on to what happens when an -assertion actually fires, which brings us to the panic path and the -crash dump. +有了这个基础,我们可以继续讨论断言实际触发时会发生什么,这将我们带到了 panic 路径和崩溃转储。 ## 3. 分析崩溃与崩溃转储 -When a `KASSERT` fails or `panic` is called, the kernel takes a series of -well-defined steps. Understanding those steps is the first part of making -sense of a crash. The second part is knowing what traces the kernel -leaves behind, and how to read them after the fact. This section walks -through both. +当 `KASSERT` 失败或 `panic` 被调用时,内核会执行一系列明确定义的步骤。理解这些步骤是理解崩溃的第一部分。第二部分是了解内核留下了什么痕迹,以及事后如何读取它们。本节将逐一讲解。 ### 崩溃时会发生什么 -A panic is the kernel's controlled shutdown in response to an -unrecoverable error. The exact sequence depends on the build options, -but a typical panic in a FreeBSD 14.3 kernel proceeds as follows. +panic 是内核对不可恢复错误的受控关闭。具体序列取决于构建选项,但 FreeBSD 14.3 内核中的典型 panic 过程如下。 -First, `panic()` or `kassert_panic()` is called with a message. The -message is formatted and written to the system log. If a serial console -is attached, it appears there immediately. If only a graphical console -is available, it appears on screen, though there is often too little time -to read a long trace before the machine reboots, which is one reason we -recommend a serial or virtual console during this chapter. +首先,`panic()` 或 `kassert_panic()` 被调用并传入一条消息。消息被格式化并写入系统日志。如果连接了串行控制台,消息会立即出现在那里。如果只有图形控制台可用,消息会显示在屏幕上,但在机器重启前通常没有足够的时间读取长跟踪信息,这是我们推荐在本章中使用串行或虚拟控制台的原因之一。 -Second, the kernel captures a backtrace of the panicking thread. You -will see this on the console as a list of function names with offsets. -The backtrace is the most valuable piece of information a panic -produces, because it tells you the chain of calls that led to the -failure. Reading it top-down shows you the function that called `panic`, -the function that called that one, and so on, back to the entry point. +其次,内核捕获恐慌线程的回溯。你将在控制台上看到一系列带有偏移量的函数名。回溯是 panic 产生的最有价值的信息,因为它告诉你导致失败的调用链。自顶向下阅读,它显示调用 `panic` 的函数、调用该函数的函数,以此类推,直到入口点。 -Third, if the kernel has been built with `KDB` enabled and a backend -such as `DDB`, the kernel enters the debugger. `DDB` is the in-kernel -debugger. It accepts commands directly on the console: `bt` to show a -backtrace, `show registers` to dump register state, `show proc` to show -process information, and so on. We will use `DDB` briefly in Section 4. -If `KDB` is not enabled, or if the kernel is configured to skip the -debugger on panic, the kernel moves on. +第三,如果内核在构建时启用了 `KDB` 并且有 `DDB` 等后端,内核进入调试器。`DDB` 是内核内调试器。它直接在控制台上接受命令:`bt` 显示回溯,`show registers` 转储寄存器状态,`show proc` 显示进程信息等。我们将在第 4 节中简要使用 `DDB`。如果 `KDB` 未启用,或内核配置为在 panic 时跳过调试器,内核继续下一步。 -Fourth, if a dump device is configured, the kernel writes a dump to it. -The dump is the entire contents of kernel memory, or at least the -portions marked as dumpable, serialized onto the dump device. This is -the crash dump that `savecore(8)` will retrieve after the reboot. +第四,如果配置了转储设备,内核向其写入转储。转储是内核内存的全部内容,或至少标记为可转储的部分,序列化到转储设备上。这就是 `savecore(8)` 在重启后将取回的崩溃转储。 -Fifth, the kernel reboots the machine, unless it has been asked to stop -at the debugger. After the reboot, when the system comes up, `savecore(8)` -runs and writes the dump to `/var/crash/vmcore.N` along with a textual -summary. You now have everything you need to analyze the crash offline. +第五,内核重启机器,除非它被要求停在调试器中。重启后,系统启动时 `savecore(8)` 运行并将转储写入 `/var/crash/vmcore.N`,同时生成一份文本摘要。现在你有了离线分析崩溃所需的一切。 -The whole sequence takes anywhere from a fraction of a second to a few -minutes, depending on how large the kernel is, how fast the dump device -is, and how configured the system is. On a development VM, dumping a -kernel of a few hundred megabytes to a virtual disk is typically a -matter of seconds. +整个过程从几分之一秒到几分钟不等,取决于内核大小、转储设备速度和系统配置。在开发虚拟机上,将几百兆字节的内核转储到虚拟磁盘通常只需要几秒钟。 ### 阅读崩溃消息 -A panic message in FreeBSD 14.3 looks something like this: +FreeBSD 14.3 中的 panic 消息看起来像这样: ```text panic: bugdemo: softc missing @@ -745,75 +355,43 @@ fast_syscall_common() at fast_syscall_common+0xf8 --- syscall (54, FreeBSD ELF64, sys_ioctl), rip = ..., rsp = ... ``` -Read this top to bottom. The first line is the panic message itself. The -`cpuid` and `time` lines are metadata; they are rarely useful for -debugging but occasionally help when reconciling multiple logs. The -`KDB: stack backtrace:` line marks the start of the trace. +从上到下阅读。第一行是 panic 消息本身。`cpuid` 和 `time` 行是元数据,对调试很少有用,但偶尔有助于比对多个日志。`KDB: stack backtrace:` 行标记跟踪的开始。 -The first few frames are the panic infrastructure itself: -`db_trace_self_wrapper`, `vpanic`, `panic`. These are always there on a -panic and can be skipped. The first interesting frame is `bugdemo_ioctl`, -which is where our driver called `panic`. The frames below that are the -path that got us to `bugdemo_ioctl`: `devfs_ioctl`, `vn_ioctl`, -`kern_ioctl`, `sys_ioctl`, `amd64_syscall`. This tells us that the -panic happened during an ioctl system call, which is already a useful -clue. The final line shows the syscall number (54, which is `ioctl`) -and the instruction pointer at entry. +前几帧是 panic 基础设施本身:`db_trace_self_wrapper`、`vpanic`、`panic`。这些在每次 panic 中都会出现,可以跳过。第一个有意义的帧是 `bugdemo_ioctl`,这是我们驱动程序调用 `panic` 的地方。下面的帧是到达 `bugdemo_ioctl` 的路径:`devfs_ioctl`、`vn_ioctl`、`kern_ioctl`、`sys_ioctl`、`amd64_syscall`。这告诉我们 panic 发生在 ioctl 系统调用期间,这已经是一个有用的线索。最后一行显示系统调用号(54,即 `ioctl`)和入口处的指令指针。 -The offsets (`+0x24`, `+0xc2`) are byte offsets into each function. On -their own they are not human-readable, but they let `kgdb` resolve the -exact line of source code when the debug kernel is available. +偏移量(`+0x24`、`+0xc2`)是每个函数中的字节偏移。它们本身不是人类可读的,但它们让 `kgdb` 在调试内核可用时能解析到确切的源代码行。 -Writing this kind of message down, or capturing the serial console log, -is the first thing you should do when a panic happens. If the machine -reboots too quickly to read, configure a serial console or a text-mode -virtual console where the history is retained. +记下这类消息,或捕获串行控制台日志,是 panic 发生时你应该做的第一件事。如果机器重启太快来不及阅读,请配置串行控制台或文本模式虚拟控制台以保留历史记录。 ### 配置转储设备 -For `savecore(8)` to have anything to retrieve, the kernel must know -where to write the dump. FreeBSD calls this the dump device, and -`dumpon(8)` is the utility that configures it. +要让 `savecore(8)` 有内容可以取回,内核必须知道把转储写到哪里。FreeBSD 称之为转储设备,`dumpon(8)` 是配置它的工具。 -There are two common ways to set this up. The simplest is a swap -partition. During install, `bsdinstall` typically creates a swap -partition large enough for kernel memory, and FreeBSD 14.3 automatically -configures it as the dump device if you enabled the relevant options. -You can check with: +有两种常见的设置方式。最简单的是使用交换分区。在安装过程中,`bsdinstall` 通常会创建一个足够大的交换分区来容纳内核内存,FreeBSD 14.3 会在你启用相关选项后自动将其配置为转储设备。你可以用以下命令检查: ```console # dumpon -l /dev/da0p3 ``` -If that command lists your swap device, you are good. If it says no -dump device is configured, you can set one manually: +如果该命令列出了你的交换设备,就可以了。如果它说没有配置转储设备,你可以手动设置: ```console # dumpon /dev/da0p3 ``` -To make this persistent across reboots, put it in `/etc/rc.conf`: +要使其在重启后持久化,将其放入 `/etc/rc.conf`: ```sh dumpdev="/dev/da0p3" dumpon_flags="" ``` -You can see the defaults for these variables in -`/usr/src/libexec/rc/rc.conf`, which is the authoritative source for -all default rc.conf values in the base system. Grep for `dumpdev=` -and `dumpon_flags=` to find the relevant block. +你可以在 `/usr/src/libexec/rc/rc.conf` 中看到这些变量的默认值,这是基本系统中所有默认 rc.conf 值的权威来源。用 grep 搜索 `dumpdev=` 和 `dumpon_flags=` 即可找到相关块。 -An alternative, introduced in modern FreeBSD, is to use a file-backed -dump. This avoids the need to dedicate a disk partition to dumps. See -`dumpon(8)` for the exact syntax; the short version is that you can -point `dumpon` at a file on a filesystem, and the kernel will dump into -it at panic time. File-backed dumps are convenient for development VMs -where you do not want to re-partition the disk. +另一种方法是使用现代 FreeBSD 引入的文件后备转储。这避免了专门为转储划分磁盘分区的需要。具体语法见 `dumpon(8)`;简而言之,你可以将 `dumpon` 指向文件系统上的一个文件,内核在 panic 时会转储到其中。文件后备转储对于不想重新分区的开发虚拟机很方便。 -A second rc.conf variable controls where `savecore(8)` puts retrieved -dumps: +第二个 rc.conf 变量控制 `savecore(8)` 将取回的转储放在哪里: ```sh dumpdir="/var/crash" @@ -821,19 +399,11 @@ savecore_enable="YES" savecore_flags="-m 10" ``` -The `-m 10` argument keeps only the most recent ten dumps, which is a -reasonable default. If you are chasing a rare bug, raise the number; if -disk space is tight, lower it. `savecore(8)` runs from `/etc/rc.d/savecore` -during boot, before most services are up, so your dump is preserved -before anything else touches `/var`. +`-m 10` 参数只保留最近的十个转储,这是一个合理的默认值。如果你在追踪一个罕见的 bug,增大这个数字;如果磁盘空间紧张,减小它。`savecore(8)` 在启动期间从 `/etc/rc.d/savecore` 运行,在大多数服务启动之前,所以你的转储在其他任何东西触及 `/var` 之前就已保存。 -### Enabling Dumps in the Kernel +### 在内核中启用转储 -For the kernel to be willing to write a dump, it must be built with the -right options. In FreeBSD 14.3, the `GENERIC` kernel is already -configured for the framework pieces. If you look at -`/usr/src/sys/amd64/conf/GENERIC` around the top of the file, you will -see something close to: +要让内核愿意写入转储,它必须用正确的选项构建。在 FreeBSD 14.3 中,`GENERIC` 内核已经配置了框架组件。如果你查看 `/usr/src/sys/amd64/conf/GENERIC` 文件顶部附近,会看到类似这样的内容: ```text options KDB @@ -842,46 +412,22 @@ options EKCD options DDB_CTF ``` -`KDB` is the kernel debugger framework. `KDB_TRACE` enables automatic -stack traces on panic. `EKCD` enables encrypted kernel crash dumps, -which is useful when dumps contain sensitive data. `DDB_CTF` tells the -build to include CTF type information for the debugger. Together these -options give a fully capable dumping kernel. +`KDB` 是内核调试器框架。`KDB_TRACE` 在 panic 时启用自动栈跟踪。`EKCD` 启用加密内核崩溃转储,当转储包含敏感数据时很有用。`DDB_CTF` 告诉构建系统为调试器包含 CTF 类型信息。这些选项共同提供了一个功能完备的转储内核。 -Notice what is *not* in `GENERIC`: `options DDB` and `options GDB` -themselves. The `KDB` framework is there, but the in-kernel debugger -backend (`DDB`) and the remote GDB stub (`GDB`) are added by -`std.debug`, which `GENERIC-DEBUG` includes. A plain `GENERIC` kernel -will still write a dump on panic, but if you drop to the console during -a live system, there is no `DDB` prompt to greet you. +注意 `GENERIC` 中*没有*什么:`options DDB` 和 `options GDB` 本身。`KDB` 框架在那里,但内核内调试器后端(`DDB`)和远程 GDB 桩(`GDB`)是由 `std.debug` 添加的,`GENERIC-DEBUG` 包含了它。普通的 `GENERIC` 内核仍然会在 panic 时写入转储,但如果你在运行的系统上进入控制台,不会有 `DDB` 提示符迎接你。 -If you are building your own kernel, either add the backends -explicitly or, simpler, start from `GENERIC-DEBUG`, which enables them -plus the debugging options we will need for the rest of the chapter. -`GENERIC-DEBUG` lives at `/usr/src/sys/amd64/conf/GENERIC-DEBUG` and is -just two lines: +如果你在构建自己的内核,要么显式添加后端,要么更简单地从 `GENERIC-DEBUG` 开始,它启用了后端以及本章其余部分需要的调试选项。`GENERIC-DEBUG` 位于 `/usr/src/sys/amd64/conf/GENERIC-DEBUG`,只有两行: ```text include GENERIC include "std.debug" ``` -The `std.debug` file in `/usr/src/sys/conf/std.debug` adds `DDB`, `GDB`, -`INVARIANTS`, `INVARIANT_SUPPORT`, `WITNESS`, `WITNESS_SKIPSPIN`, -`MALLOC_DEBUG_MAXZONES=8`, `ALT_BREAK_TO_DEBUGGER`, `DEADLKRES`, -`BUF_TRACKING`, `FULL_BUF_TRACKING`, `QUEUE_MACRO_DEBUG_TRASH`, and a -few subsystem-specific debug flags. Note that `DDB` and `GDB` themselves -come from `std.debug`, not from `GENERIC`; the release kernel enables -`KDB` and `KDB_TRACE` but leaves the backends out unless you opt in. -This is the recommended debug kernel for driver development and the -kernel we will assume in the rest of the chapter unless we say -otherwise. +`/usr/src/sys/conf/std.debug` 中的 `std.debug` 文件添加了 `DDB`、`GDB`、`INVARIANTS`、`INVARIANT_SUPPORT`、`WITNESS`、`WITNESS_SKIPSPIN`、`MALLOC_DEBUG_MAXZONES=8`、`ALT_BREAK_TO_DEBUGGER`、`DEADLKRES`、`BUF_TRACKING`、`FULL_BUF_TRACKING`、`QUEUE_MACRO_DEBUG_TRASH` 以及一些子系统特定的调试标志。注意 `DDB` 和 `GDB` 本身来自 `std.debug` 而非 `GENERIC`;发布版内核启用 `KDB` 和 `KDB_TRACE` 但不包含后端,除非你选择启用。这是推荐的驱动程序开发调试内核,除非另有说明,本章其余部分将假定使用此内核。 -### Retrieving the Dump with savecore +### 使用 savecore 取回转储 -After a panic and reboot, `savecore(8)` runs early in the boot -sequence. By the time you have a shell prompt, the dump is already in -`/var/crash/`: +panic 并重启后,`savecore(8)` 在启动序列早期运行。当你获得 shell 提示符时,转储已经在 `/var/crash/` 中了: ```console # ls -l /var/crash/ @@ -894,24 +440,11 @@ total 524288 -rw------- 1 root wheel 524288000 Apr 20 14:23 vmcore.last ``` -The `vmcore.N` file is the dump itself. The `info.N` file is a textual -summary of the panic, including the panic message, the backtrace, and -the kernel version. Always read `info.N` first. If the message and -backtrace are enough to identify the bug, you may not need to go -further. +`vmcore.N` 文件是转储本身。`info.N` 文件是 panic 的文本摘要,包括 panic 消息、回溯和内核版本。始终先读 `info.N`。如果消息和回溯足以识别 bug,你可能不需要进一步分析。 -A few common problems to watch for. If `ls` shows only `bounds` and -`minfree`, no dump has been captured yet. This usually means the dump -device is not configured or the kernel did not manage to write to it -before rebooting. Check `dumpon -l` and re-panic. If `savecore` logs -messages about a checksum mismatch, the dump was truncated, which -typically indicates the dump device was too small. If the machine -never panicked cleanly but simply rebooted, the kernel likely did not -have `KDB` enabled, so there was no dump machinery to invoke. +一些常见问题需要注意。如果 `ls` 只显示 `bounds` 和 `minfree`,说明尚未捕获转储。这通常意味着转储设备未配置或内核在重启前未能写入。检查 `dumpon -l` 并重新触发 panic。如果 `savecore` 记录了校验和不匹配的消息,转储被截断了,通常表示转储设备太小。如果机器从未干净地 panic 而只是简单重启,内核可能没有启用 `KDB`,因此没有转储机制可调用。 -The `info.N` file is short enough to read in full. It includes the -kernel version, the panic string, and the backtrace the kernel captured -at panic time. On FreeBSD 14.3 it looks something like this: +`info.N` 文件很短,可以完整阅读。它包含内核版本、panic 字符串和内核在 panic 时捕获的回溯。在 FreeBSD 14.3 上它看起来像这样: ```text Dump header from device: /dev/da0p3 @@ -930,39 +463,31 @@ Dump header from device: /dev/da0p3 Dump Status: good ``` -If the `Dump Status` is `good`, the dump is usable. If it says `bad`, -the dump was truncated or the checksum failed. +如果 `Dump Status` 为 `good`,转储可用。如果为 `bad`,转储被截断或校验失败。 ### 使用kgdb打开转储 -Once you have a dump, the next step is to open it with `kgdb`. `kgdb` is -FreeBSD's version of `gdb` specialized for kernel images. It needs three -things: the kernel image that produced the dump, the debug kernel image -that contains symbols, and the dump file itself. On most systems all -three are in predictable places: +有了转储后,下一步是用 `kgdb` 打开它。`kgdb` 是 FreeBSD 版本的 `gdb`,专门用于内核映像。它需要三样东西:产生转储的内核映像、包含符号的调试内核映像以及转储文件本身。在大多数系统上,这三者都在可预测的位置: -- The running kernel: `/boot/kernel/kernel` -- The debug kernel with full symbols: `/usr/lib/debug/boot/kernel/kernel.debug` -- The dump: `/var/crash/vmcore.N` +- 运行中的内核:`/boot/kernel/kernel` +- 带完整符号的调试内核:`/usr/lib/debug/boot/kernel/kernel.debug` +- 转储文件:`/var/crash/vmcore.N` -The simplest invocation is: +最简单的调用方式是: ```console # kgdb /boot/kernel/kernel /var/crash/vmcore.0 ``` -or equivalently: +或等价地: ```console # kgdb /usr/lib/debug/boot/kernel/kernel.debug /var/crash/vmcore.0 ``` -`kgdb` is a normal GDB session with kernel-specific tweaks. If your -kernel was built with `makeoptions DEBUG=-g` (which `GENERIC-DEBUG` -does), the debug symbols are included, and `kgdb` will be able to -resolve every frame to source code. +`kgdb` 是一个带有内核特定调整的普通 GDB 会话。如果你的内核是用 `makeoptions DEBUG=-g` 构建的(`GENERIC-DEBUG` 就是这样做的),调试符号会被包含在内,`kgdb` 将能够将每个帧解析到源代码。 -When `kgdb` starts, it automatically runs a few commands: +当 `kgdb` 启动时,它会自动运行一些命令: ```console (kgdb) bt @@ -979,8 +504,7 @@ When `kgdb` starts, it automatically runs a few commands: ... ``` -The top frame is the panic infrastructure. The interesting frame is -frame 5, `bugdemo_ioctl` at `bugdemo.c:142`. To jump to that frame: +顶部帧是 panic 基础设施。有意义的帧是第 5 帧,`bugdemo_ioctl`,位于 `bugdemo.c:142`。要跳转到该帧: ```console (kgdb) frame 5 @@ -989,112 +513,53 @@ frame 5, `bugdemo_ioctl` at `bugdemo.c:142`. To jump to that frame: 142 KASSERT(sc != NULL, ("bugdemo: softc missing")); ``` -`kgdb` prints the source line. From here you can inspect local -variables with `info locals`, look at `sc` directly with `print sc`, or -list the surrounding source with `list`: +`kgdb` 打印源代码行。从这里你可以用 `info locals` 检查局部变量,用 `print sc` 直接查看 `sc`,或用 `list` 列出周围的源代码: ```console (kgdb) print sc $1 = (struct bugdemo_softc *) 0x0 ``` -That tells us `sc` really is NULL, confirming the panic message. Now we -can work out why, which usually means walking up the stack to find -where `sc` should have been set: +这告诉我们 `sc` 确实是 NULL,确认了 panic 消息。现在我们可以追查为什么,这通常意味着沿栈向上查找 `sc` 应该在哪里被设置: ```console (kgdb) frame 6 ``` -and so on. The sequence of `frame N`, `print VAR`, `list` is the -bread-and-butter of `kgdb` analysis. It is the same conversation a -gdb user has with any crashing program, adapted to the kernel. +等等。`frame N`、`print VAR`、`list` 的序列是 `kgdb` 分析的基本功。这是任何 gdb 用户与任何崩溃程序进行的相同对话,适配到了内核。 ### 有用的kgdb命令 -Beyond `bt` and `frame`, a handful of commands cover most debugging -sessions. +除了 `bt` 和 `frame`,少量命令即可覆盖大多数调试会话。 -- `info threads` lists all threads in the dumped system. In a modern - kernel this can be hundreds of entries. Each has a number and a - state. -- `thread N` switches to a specific thread, as if that thread had been - the one that panicked. This is essential when a deadlock has - happened and the panicking thread is not the one holding the - problematic lock. -- `bt full` prints a backtrace with local variables at each frame. - This is often the fastest way to see the state of a function - involved in the panic. -- `info locals` shows local variables in the current frame. -- `print *SOMETHING` dereferences a pointer and prints the contents of - the structure it points to. -- `list` shows the source around the current line; `list FUNC` shows - the source of a function by name. +- `info threads` 列出转储系统中的所有线程。在现代内核中这可能有数百个条目。每个都有编号和状态。 +- `thread N` 切换到特定线程,就好像该线程是 panic 的那个。当发生死锁且 panic 线程不是持有问题锁的线程时,这是必不可少的。 +- `bt full` 打印带每帧局部变量的回溯。这通常是查看 panic 涉及函数状态的最快方式。 +- `info locals` 显示当前帧中的局部变量。 +- `print *SOMETHING` 解引用指针并打印其指向结构的内容。 +- `list` 显示当前行周围的源代码;`list FUNC` 按名称显示函数的源代码。 -There are many more, documented in `gdb(1)`, but these are the ones a -driver author reaches for most often. +还有很多,记录在 `gdb(1)` 中,但这些是驱动程序作者最常使用的命令。 ### 在转储中遍历struct thread -A panic backtrace answers "where did the crash happen?" but it rarely -answers "who was doing what?" The kernel keeps a dense record of every -live thread in `struct thread`, and once a dump is open in `kgdb` we -can read that record directly. For a driver author the value is -concrete: the fields of `struct thread` tell you what job this thread -was performing when the kernel crashed, which lock it was waiting on, -which process it belonged to, and whether it was still inside your -code when the panic occurred. +panic 回溯回答了"崩溃在哪里发生?"但很少回答"谁在做什么?"。内核在 `struct thread` 中保存了每个活动线程的密集记录,一旦转储在 `kgdb` 中打开,我们就可以直接读取该记录。对驱动程序作者来说,价值是具体的:`struct thread` 的字段告诉你内核崩溃时该线程正在执行什么任务、它在等待什么锁、它属于哪个进程,以及 panic 发生时它是否仍在你的代码中。 -`struct thread` is defined in `/usr/src/sys/sys/proc.h`. It is a large -structure, so rather than read every field, we focus on a small set -that matters most for driver debugging. In `kgdb` the quickest way to -see those fields is to take the current thread and dereference it: +`struct thread` 定义在 `/usr/src/sys/sys/proc.h` 中。它是一个很大的结构,因此我们不必阅读每个字段,而是聚焦于对驱动程序调试最重要的小部分字段。在 `kgdb` 中查看这些字段的最快方式是取当前线程并解引用它: ```console (kgdb) print *(struct thread *)curthread ``` -On the panicking CPU `curthread` is already correct, but you can also -reach a specific thread from the `info threads` listing. `kgdb` numbers -every thread sequentially. Once you know the number, `thread N` -switches context, and from there `print *$td` (or `print *(struct -thread *)0xADDR` if you have the raw address) prints the structure. +在 panic 的 CPU 上 `curthread` 已经是正确的,但你也可以从 `info threads` 列表中到达特定线程。`kgdb` 为每个线程顺序编号。知道编号后,`thread N` 切换上下文,然后用 `print *$td`(或者如果有原始地址,用 `print *(struct thread *)0xADDR`)打印结构。 -The fields to know are these. `td_name` is a short, readable name for -the thread, often set by `kthread_add(9)` or by the userspace program -that spawned it. When a driver creates its own kernel thread, this is -the name that shows up. `td_tid` is the numeric thread identifier the -kernel assigns; `ps -H` in userspace shows the same number. `td_proc` -is a pointer to the owning process, which gives us access to the -larger `struct proc` for more context. `td_flags` carries the `TDF_*` -bit field that records scheduler and debugger state; the definitions -live next to the structure in `/usr/src/sys/sys/proc.h`, and many -panics can be partially explained by reading those bits. `td_lock` is -the spin mutex that currently protects this thread's scheduler state. -It is almost always a CPU-local lock in a running kernel; in a dump, -a `td_lock` that points to an unexpected address is a strong hint -that something corrupted the scheduler view of this thread. +需要了解的字段如下。`td_name` 是线程的简短可读名称,通常由 `kthread_add(9)` 或生成它的用户空间程序设置。当驱动程序创建自己的内核线程时,这就是显示出来的名称。`td_tid` 是内核分配的数字线程标识符;用户空间中的 `ps -H` 显示相同的数字。`td_proc` 是指向所属进程的指针,这使我们能够访问更大的 `struct proc` 获取更多上下文。`td_flags` 携带 `TDF_*` 位字段,记录调度器和调试器状态;定义位于 `/usr/src/sys/sys/proc.h` 中结构旁边,许多 panic 可以通过读取这些位来部分解释。`td_lock` 是当前保护此线程调度器状态的自旋互斥锁。在运行的内核中它几乎总是 CPU 本地锁;在转储中,`td_lock` 指向意外地址是某物损坏了此线程调度器视图的强烈暗示。 -Two more fields are decisive when the panic involves sleeping or -waiting. `td_wchan` is the "wait channel," the kernel address the -thread is sleeping on. `td_wmesg` is a short human-readable string -describing why (for example, `"biord"` for a thread waiting on a buf -read, or `"select"` for a thread inside `select(2)`). If the panic -happened while threads were sleeping, these two fields tell you what -each thread was waiting for. `td_state` is the TDS_* state value -(defined just below `struct thread`); it tells you whether the thread -was running, runnable, or inhibited at the moment of the crash. +当 panic 涉及睡眠或等待时,另外两个字段是决定性的。`td_wchan` 是"等待通道",线程正在其上睡眠的内核地址。`td_wmesg` 是描述原因的简短人类可读字符串(例如 `"biord"` 表示等待 buf 读取的线程,或 `"select"` 表示在 `select(2)` 内部的线程)。如果 panic 时有线程正在睡眠,这两个字段告诉你每个线程在等待什么。`td_state` 是 TDS_* 状态值(定义在 `struct thread` 正下方);它告诉你线程在崩溃瞬间是正在运行、可运行还是被抑制的。 -For lock bugs specifically, `td_locks` counts the non-spin locks -currently held by the thread, and `td_lockname` records the name of -the lock the thread is currently blocked on, if any. If a thread -panics with a non-zero `td_locks`, that thread was holding one or -more sleep locks at the time of the crash: useful context when the -panic is a `mutex not owned` or `Lock (sleep mutex) ... is not -sleepable` message. +对于锁 bug,`td_locks` 计算线程当前持有的非自旋锁数量,`td_lockname` 记录线程当前阻塞的锁的名称(如果有的话)。如果一个线程在 panic 时 `td_locks` 非零,说明该线程在崩溃时持有一个或多个睡眠锁:当 panic 消息是 `mutex not owned` 或 `Lock (sleep mutex) ... is not sleepable` 时这是有用的上下文。 -A short `kgdb` session that pulls these fields out might look like -this: +一个提取这些字段的简短 `kgdb` 会话可能看起来像这样: ```console (kgdb) thread 42 @@ -1116,44 +581,17 @@ $7 = 0 $8 = "kernel" ``` -Reading this: thread 42 was a kernel thread called `bugdemo_worker`, -running when the panic hit, not sleeping on anything (`td_wmesg` is -NULL), and it was still holding exactly one sleep lock. The owning -process is the kernel proc with pid 0 and command name `kernel`, -which is the expected owner of kernel-only threads. The interesting -fact is `td_locks == 1`, because it tells us the thread held a lock -at panic time; a follow-up with `show alllocks` in DDB, or with -`show lockedvnods` if file locks are relevant, would pinpoint which. +解读如下:线程 42 是一个名为 `bugdemo_worker` 的内核线程,在 panic 发生时正在运行,没有在睡眠等待任何东西(`td_wmesg` 为 NULL),并且它仍持有一个睡眠锁。所属进程是 pid 为 0、命令名为 `kernel` 的内核进程,这是纯内核线程的预期持有者。有趣的事实是 `td_locks == 1`,因为它告诉我们该线程在 panic 时持有一把锁;后续用 DDB 中的 `show alllocks` 或在文件锁相关时用 `show lockedvnods` 可以精确定位是哪把锁。 ### 在转储中遍历struct proc -Each thread belongs to a `struct proc`, defined next to `struct -thread` in `/usr/src/sys/sys/proc.h__IC_1__struct proc` carries the -process-wide context: identity, credentials, address space, open -files, parent relationship. For driver bugs, a handful of these -fields are particularly useful. +每个线程属于一个 `struct proc`,定义在 `/usr/src/sys/sys/proc.h` 中 `struct thread` 旁边。`struct proc` 携带进程范围的上下文:身份、凭证、地址空间、打开的文件、父进程关系。对于驱动程序 bug,其中一些字段特别有用。 -`p_pid` is the process identifier, the same number userspace sees in -`ps`. `p_comm` is the process command name, truncated to `MAXCOMLEN` -bytes. Together they tell you which userspace process triggered the -kernel path that panicked. `p_state` is the PRS_* process state, -letting you distinguish a newly-forked process, a running one, and a -zombie. `p_numthreads` tells you how many threads this process has; -for a multithreaded userland program that called into your driver, -the count can be surprising. `p_flag` holds the P_* flag bits, which -encode properties like tracing, accounting, and single-threading; -`/usr/src/sys/sys/proc.h` documents each bit near the flag block. +`p_pid` 是进程标识符,与用户空间中 `ps` 看到的数字相同。`p_comm` 是进程命令名,截断为 `MAXCOMLEN` 字节。它们一起告诉你哪个用户空间进程触发了 panic 的内核路径。`p_state` 是 PRS_* 进程状态,让你区分新 fork 的进程、运行中的进程和僵尸进程。`p_numthreads` 告诉你这个进程有多少线程;对于一个调用了你的驱动的多线程用户程序,这个计数可能令人惊讶。`p_flag` 持有 P_* 标志位,编码了跟踪、记账和单线程等属性;`/usr/src/sys/sys/proc.h` 在标志块附近记录了每个位。 -Three pointers give you the larger context. `p_ucred` references the -process credentials, useful when the panic might be tied to a -privilege check your driver performed. `p_vmspace` points to the -address space, which matters when the panic involves a user pointer -that turned out to belong to an unexpected process. `p_pptr` points -to the parent process; walking this chain with `p_pptr->p_pptr` -eventually leads to `initproc`, the ancestor of every userspace -process. +三个指针为你提供更大的上下文。`p_ucred` 引用进程凭证,当 panic 可能与你驱动程序执行的权限检查有关时很有用。`p_vmspace` 指向地址空间,当 panic 涉及一个原来属于意外进程的用户指针时很重要。`p_pptr` 指向父进程;用 `p_pptr->p_pptr` 沿此链遍历最终到达 `initproc`,即每个用户空间进程的祖先。 -A short walk from a thread to its process looks like this in `kgdb`: +在 `kgdb` 中从线程到其进程的简短遍历如下: ```console (kgdb) set $p = curthread->td_proc @@ -1169,163 +607,65 @@ $12 = 4 $13 = 536871424 ``` -Now we know the panic happened while a userspace `devctl` process -with pid 3418 was running, that the process had four threads, and -that its flag bits decoded through the P_* constants in -`/usr/src/sys/sys/proc.h` will tell us whether it was being traced, -accounted for, or in the middle of an exec. The flag integer on its -own looks opaque, but in `kgdb` you can let the enum-like P_* macros -do the decoding by casting or by using `info macro P_TRACED`. +现在我们知道 panic 发生在一个 pid 为 3418 的用户空间 `devctl` 进程运行时,该进程有四个线程,其标志位通过 `/usr/src/sys/sys/proc.h` 中的 P_* 常量解码后会告诉我们它是否正在被跟踪、被记账或正处于 exec 中间。标志整数本身看起来是不透明的,但在 `kgdb` 中你可以通过类型转换或使用 `info macro P_TRACED` 让枚举般的 P_* 宏进行解码。 -For drivers that expose a character device, `p_fd` is also worth -knowing. It points to the file descriptor table of the process that -called into your driver, and in an advanced session you can walk it -to find which descriptor the call came in on. That is usually more -than a first-pass crash analysis needs, but the mechanism is worth -remembering for the rare bug that depends on how userspace had the -device open. +对于暴露字符设备的驱动程序,`p_fd` 也值得了解。它指向调用你驱动程序的进程的文件描述符表,在高级会话中你可以遍历它来找出调用是从哪个描述符进来的。这通常超出了首轮崩溃分析的需要,但这个机制值得记住,以应对那些依赖于用户空间如何打开设备的罕见 bug。 -Between `struct thread` and `struct proc`, you can reconstruct an -astonishing amount of context from a dump that at first glance only -shows a panic message and a backtrace. The cost is reading -`/usr/src/sys/sys/proc.h` once carefully; after that, the same -vocabulary is available to you in every debugging session for the -rest of your career. +通过 `struct thread` 和 `struct proc`,你可以从一个初看只有 panic 消息和回溯的转储中重建出惊人的大量上下文。代价是仔细阅读一次 `/usr/src/sys/sys/proc.h`;之后,同样的词汇在你余下职业生涯的每次调试会话中都可使用。 ### 对运行中的内核使用kgdb -So far we have treated `kgdb` as a post-mortem tool: open a dump, -explore it offline, think at your own pace. `kgdb` also has a second -mode, where it attaches to a running kernel through `/dev/mem` rather -than to a saved dump. This mode is capable, but it is also the most -easily misused tool in the whole debugging toolbox, so we will discuss -it with explicit warnings. +到目前为止我们一直将 `kgdb` 作为事后分析工具对待:打开转储、离线探索、按自己的节奏思考。`kgdb` 还有第二种模式,它通过 `/dev/mem` 而非保存的转储附加到运行中的内核。这种模式功能强大,但也是整个调试工具箱中最容易被误用的工具,所以我们将在明确警告下讨论它。 -The invocation looks almost identical to the post-mortem form, except -that the "core" is `/dev/mem`: +调用方式与事后形式几乎相同,只是"核心"是 `/dev/mem`: ```console # kgdb /boot/kernel/kernel /dev/mem ``` -What actually happens is that `kgdb` uses the libkvm library to read -kernel memory through `/dev/mem`. The interface is documented in -`/usr/src/lib/libkvm/kvm_open.3`, which makes the distinction clear: -the "core" argument can be either a file produced by `savecore(8)` -or `/dev/mem`, and in the latter case the currently running kernel -is the target. +实际发生的是 `kgdb` 使用 libkvm 库通过 `/dev/mem` 读取内核内存。该接口记录在 `/usr/src/lib/libkvm/kvm_open.3` 中,它明确区分了"核心"参数可以是 `savecore(8)` 产生的文件或 `/dev/mem`,在后一种情况下目标是当前运行的内核。 -This is genuinely useful. You can inspect global variables, walk lock -graphs, look at in-flight I/O, and confirm whether a sysctl you just -set has taken effect. You can do this without rebooting, without -interrupting service, and without having to reproduce a crash. On a -development system that is hosting a long-running test, it is often -the fastest way to answer "what is the driver actually doing right -now?" +这确实有用。你可以检查全局变量、遍历锁图、查看进行中的 I/O、确认你刚设置的 sysctl 是否生效。你无需重启、无需中断服务、无需重现崩溃就能做到这些。在托管长时间运行测试的开发系统上,这通常是回答"驱动程序现在到底在做什么?"的最快方式。 -The risks are real. First, the kernel is running while you are -reading. Data structures change under you. A linked list you start -walking may have an entry removed halfway through; a counter you -print may have been incremented between the moment you asked for it -and the moment `kgdb` printed it; a pointer you follow may be -reassigned before the dereference completes. Unlike a dump, you are -reading a moving target, and you will sometimes see states that are -transiently inconsistent. +风险是真实存在的。首先,内核在你读取时仍在运行。数据结构在你手下变化。你开始遍历的链表可能在中途被移除一个条目;你打印的计数器可能在你请求和 `kgdb` 打印之间被递增;你跟随的指针可能在解引用完成前被重新赋值。与转储不同,你在读取一个移动中的目标,有时你会看到瞬时不一致的状态。 -Second, `kgdb` on a live kernel is strictly read-only in practical -use. You can read memory, print structures, and walk data, but you -must not write to kernel memory through this path. The libkvm -interface does not provide locking or barriers, and an uncoordinated -write would race with the kernel itself. Treat every operation -through `/dev/mem` as inspection, never modification. If you want to -change running kernel state, use `sysctl(8)` or `sysctl(3)`, or -load a module, or use DDB from the console. Those mechanisms are -designed to coordinate with the rest of the kernel; raw writes -through `/dev/mem` are not. +其次,对运行中内核使用 `kgdb` 在实际使用中严格是只读的。你可以读取内存、打印结构、遍历数据,但你绝不能通过此路径写入内核内存。libkvm 接口不提供锁或屏障,不协调的写入会与内核本身竞争。将通过 `/dev/mem` 的每个操作视为检查,而非修改。如果你想改变运行中的内核状态,使用 `sysctl(8)` 或 `sysctl(3)`,或加载模块,或从控制台使用 DDB。这些机制被设计为与内核其余部分协调;通过 `/dev/mem` 的原始写入则不是。 -Third, the perturbation is not zero. Reading through `/dev/mem` can -cause TLB traffic, and on large structures the cost is measurable. -If you are also profiling, attribute the noise accordingly. +第三,干扰并非为零。通过 `/dev/mem` 读取会产生 TLB 流量,对大型结构来说成本是可测量的。如果你同时在做性能分析,请相应地归因噪声。 -Finally, access to `/dev/mem` requires root privilege, for obvious -reasons: anything that can read `/dev/mem` can read any secret the -kernel has ever held. On production systems, restricting this is a -security concern, and the policy around who may run `kgdb` against -a live kernel should reflect that. +最后,访问 `/dev/mem` 需要 root 权限,原因显而易见:能读取 `/dev/mem` 的任何东西都能读取内核曾经持有的任何秘密。在生产系统上,限制这种访问是一个安全问题,关于谁可以在运行中的内核上运行 `kgdb` 的策略应该反映这一点。 -Given those cautions, the guidance is straightforward. Prefer a crash -dump for any session where you want to take your time, where you -want to share the state with a colleague, or where consistency -matters. Prefer a live `kgdb` session for quick, read-only glances -at a running system where the question is small and the cost of -reboot would be high. When in doubt, take a dump with `sysctl -debug.kdb.panic=1` (if the system is expendable) or `dumpon` and a -deliberate triggering event, and do your analysis on the frozen -snapshot. The snapshot will still be there tomorrow; the running -kernel will not. +考虑到这些警告,指导原则是明确的。对于任何你想从容进行、想与同事共享状态、或一致性很重要的会话,优先使用崩溃转储。对于快速、只读地查看运行中系统的小问题,且重启成本很高时,优先使用实时 `kgdb` 会话。如有疑问,用 `sysctl debug.kdb.panic=1`(如果系统可消耗)或 `dumpon` 和一个有意触发事件来获取转储,然后在冻结的快照上做分析。快照明天还在;运行中的内核不会。 -### A Note on Symbols and Modules +### 关于符号和模块的说明 -When the panicking driver is a loadable module, `kgdb` also needs the -debug information for the module. If the module is in -`/boot/modules/bugdemo.ko` and was built with `DEBUG_FLAGS=-g`, the -debug symbols are embedded. `kgdb` will load them automatically when it -resolves frames in that module. +当 panic 的驱动程序是可加载模块时,`kgdb` 还需要该模块的调试信息。如果模块在 `/boot/modules/bugdemo.ko` 并且是用 `DEBUG_FLAGS=-g` 构建的,调试符号就嵌入在内。`kgdb` 在解析该模块中的帧时会自动加载它们。 -If the module lives somewhere nonstandard, you may need to tell `kgdb` -where to find its debug info: +如果模块位于非标准位置,你可能需要告诉 `kgdb` 在哪里找到其调试信息: ```console (kgdb) add-symbol-file /path/to/bugdemo.ko.debug ADDRESS ``` -where `ADDRESS` is the module's load address, which you can find in -`kldstat(8)` output. In practice this is rarely needed on a modern -FreeBSD system, because `kgdb` looks in the right places by default. +其中 `ADDRESS` 是模块的加载地址,你可以在 `kldstat(8)` 输出中找到。实际上这很少需要,因为现代 FreeBSD 系统上 `kgdb` 默认会查找正确的位置。 -What you do need to avoid is mixing kernels. If the running kernel and -the debug kernel came from different builds, symbols will not match -and `kgdb` will show confusing or wrong information. Rebuild both from -the same source tree, or keep matched pairs. On a development system -this is usually not a problem because you build and install both -together. +你确实需要避免的是混合内核。如果运行中的内核和调试内核来自不同的构建,符号将不匹配,`kgdb` 会显示令人困惑或错误的信息。从同一源码树重建两者,或保持匹配对。在开发系统上这通常不是问题,因为你同时构建和安装两者。 -### Closing Thoughts on Dumps +### 关于转储的结束语 -The crash dump is valuable because it preserves the kernel's -state at the moment of the panic. Unlike a running system, where -every read perturbs the state, a dump is a frozen snapshot. You can -examine it as long as you like, come back to it tomorrow, share it -with a colleague, or diff the state against the source. Even once you -have moved on to other bugs, a dump from an interesting failure is -worth keeping, because it is often the only record of that exact -sequence of events. +崩溃转储之所以有价值,是因为它保存了 panic 瞬间的内核状态。与运行中的系统不同——每次读取都会扰动状态——转储是一个冻结的快照。你可以随意检查它,明天再回来,与同事分享,或将状态与源代码进行对比。即使你已经转向其他 bug,来自有趣故障的转储也值得保留,因为它通常是那个确切事件序列的唯一记录。 -With panic mechanics and dump analysis behind us, we can move on to -the kernel configuration choices that make debugging actually -comfortable. That is the topic of Section 4. +有了 panic 机制和转储分析的基础,我们可以转向让调试真正舒适的内核配置选择。这是第 4 节的主题。 ## 4. 构建友好的调试内核环境 -Everything we have learned so far depends on having the right kernel -options enabled. A stock `GENERIC` kernel is a production configuration. -It is optimized for speed, ships no debug information, and does not -include the checks that catch many driver bugs. For the work of this -chapter, we want the opposite: a kernel that is slow but thorough, that -carries full debug symbols, and that actively looks for bugs rather than -trusting the driver to behave. FreeBSD calls this `GENERIC-DEBUG`, and -setting it up is the topic of this section. +到目前为止我们学到的所有内容都依赖于启用了正确的内核选项。标准的 `GENERIC` 内核是生产配置。它针对速度进行了优化,不发布调试信息,也不包含能捕获许多驱动程序 bug 的检查。对于本章的工作,我们需要相反的东西:一个虽然慢但彻底的内核,携带完整的调试符号,主动寻找 bug 而不是信任驱动程序会正常行为。FreeBSD 称之为 `GENERIC-DEBUG`,设置它是本节的主题。 -We will walk through building and installing a debug kernel, then look -at each of the interesting options in detail, including the debugger -backends (`DDB`, `GDB`), the invariant checks (`INVARIANTS`, `WITNESS`), -the memory debuggers (`DEBUG_MEMGUARD`, `DEBUG_REDZONE`), and the -console controls that let you enter the debugger from the keyboard. +我们将逐步介绍构建和安装调试内核,然后详细查看每个有趣的选项,包括调试器后端(`DDB`、`GDB`)、不变式检查(`INVARIANTS`、`WITNESS`)、内存调试器(`DEBUG_MEMGUARD`、`DEBUG_REDZONE`),以及让你从键盘进入调试器的控制台控制。 ### 构建GENERIC-DEBUG -On a FreeBSD 14.3 system with `/usr/src/` populated, building a debug -kernel is a three-command operation. From `/usr/src/`: +在有 `/usr/src/` 的 FreeBSD 14.3 系统上,构建调试内核是一个三步操作。从 `/usr/src/` 开始: ```console # make buildkernel KERNCONF=GENERIC-DEBUG @@ -1333,32 +673,20 @@ kernel is a three-command operation. From `/usr/src/`: # reboot ``` -The `buildkernel` step takes longer than a release build because debug -information is generated and many more checks are compiled in. On a -modest four-core VM it typically takes twenty to thirty minutes. -`installkernel` places the result in `/boot/kernel/` and keeps the -previous kernel in `/boot/kernel.old/`, which is a safety net if the -new kernel fails to boot. +`buildkernel` 步骤比发布版构建花费更长时间,因为需要生成调试信息并编译更多的检查。在适中的四核虚拟机上通常需要二十到三十分钟。`installkernel` 将结果放入 `/boot/kernel/` 并将之前的内核保留在 `/boot/kernel.old/`,这是新内核无法启动时的安全网。 -After reboot you can confirm the running kernel with `uname -v`: +重启后你可以用 `uname -v` 确认运行的内核: ```console # uname -v FreeBSD 14.3-RELEASE-p2 #0: ... ``` -The `#0` indicates a locally built kernel. You can also check that the -debug options are active by reading `sysctl debug` entries, which we -will return to shortly. +`#0` 表示这是一个本地构建的内核。你还可以通过读取 `sysctl debug` 条目来确认调试选项处于活动状态,我们稍后会回来讨论这一点。 ### GENERIC-DEBUG启用了什么 -As we saw in Section 3, `GENERIC-DEBUG` is a thin configuration that -simply includes `GENERIC` and `std.debug`. The interesting content is -in `std.debug`, which is worth reading in full because it documents the -kernel's opinion on what good debug options look like. In a FreeBSD -14.3 tree the file is at `/usr/src/sys/conf/std.debug`, and the core -options are: +正如我们在第 3 节中看到的,`GENERIC-DEBUG` 是一个精简配置,简单地包含 `GENERIC` 和 `std.debug`。有趣的内容在 `std.debug` 中,值得完整阅读,因为它记录了内核对好的调试选项的看法。在 FreeBSD 14.3 源码树中,该文件位于 `/usr/src/sys/conf/std.debug`,核心选项如下: ```text options BUF_TRACKING @@ -1376,75 +704,31 @@ options VERBOSE_SYSINIT=0 options ALT_BREAK_TO_DEBUGGER ``` -Plus a handful of subsystem-specific debug flags for networking, USB, -HID, and CAM that we do not need to dwell on. Let us look at each of -the driver-relevant options in turn. +还有一些网络、USB、HID 和 CAM 的子系统特定调试标志,我们不需要深入讨论。让我们依次查看每个与驱动相关的选项。 -Note one thing that `std.debug` does *not* contain: `makeoptions DEBUG=-g`. -That line lives in `GENERIC` itself, near the top of -`/usr/src/sys/amd64/conf/GENERIC`. A release `GENERIC` kernel is -already built with `-g`, because the release engineering process wants -the debug information available even when `INVARIANTS` and `WITNESS` -are off. `GENERIC-DEBUG` inherits this through its `include "GENERIC"`. +注意 `std.debug` *不*包含的一件事:`makeoptions DEBUG=-g`。那行在 `GENERIC` 本身中,位于 `/usr/src/sys/amd64/conf/GENERIC` 顶部附近。发布版 `GENERIC` 内核已经用 `-g` 构建,因为发布工程过程希望即使 `INVARIANTS` 和 `WITNESS` 关闭时调试信息也可用。`GENERIC-DEBUG` 通过其 `include "GENERIC"` 继承了这一点。 ### makeoptions DEBUG=-g -This passes `-g` to the compiler for every kernel file, producing a -kernel with full DWARF debug information. `kgdb` uses this debug -information to map from addresses back to source lines. Without `-g`, -`kgdb` can still show function names, but it cannot show the source -line where a crash happened, and `print someVariable` becomes -`print *(char *)0xffffffff...` with no symbolic names. +这将 `-g` 传递给编译器处理每个内核文件,产生一个带有完整 DWARF 调试信息的内核。`kgdb` 使用这些调试信息将地址映射回源代码行。没有 `-g`,`kgdb` 仍然可以显示函数名,但无法显示崩溃发生的源代码行,`print someVariable` 变成 `print *(char *)0xffffffff...`,没有符号名。 -The cost is that the kernel binary is larger. On amd64 a debug -`GENERIC-DEBUG` kernel is several times the size of a non-debug -`GENERIC` kernel. For a development VM this does not matter. For a -production system it is often the reason to keep debug information -in a separate file (`/usr/lib/debug/boot/kernel/kernel.debug`) while -the running kernel is stripped. +代价是内核二进制文件更大。在 amd64 上,调试版 `GENERIC-DEBUG` 内核是非调试 `GENERIC` 内核大小的数倍。对于开发虚拟机这不重要。对于生产系统,通常是将调试信息保留在单独的文件中(`/usr/lib/debug/boot/kernel/kernel.debug`),而运行中的内核是剥离过的。 -### INVARIANTS and INVARIANT_SUPPORT +### INVARIANTS 和 INVARIANT_SUPPORT -We met these in Section 2. `INVARIANTS` activates `KASSERT` and a -number of other runtime checks scattered through the kernel. Functions -throughout `/usr/src/sys/` have `#ifdef INVARIANTS` blocks that check -things like "this list is well-formed," "this pointer points into a -valid zone," or "this reference count is nonzero." With `INVARIANTS` -enabled, these checks fire at runtime. Without it, they are compiled -out. +我们在第 2 节中见过它们。`INVARIANTS` 激活 `KASSERT` 和散布在内核中的许多其他运行时检查。`/usr/src/sys/` 中的函数有 `#ifdef INVARIANTS` 块来检查诸如"此链表格式是否正确"、"此指针是否指向有效区域"或"此引用计数是否非零"之类的东西。启用 `INVARIANTS` 后,这些检查在运行时触发。没有它,它们被编译出去。 -The checks cost CPU cycles. As a rough order-of-magnitude figure on -typical FreeBSD 14.3-amd64 hardware, a busy `INVARIANTS` kernel runs -roughly five to twenty percent slower than a release kernel, and -sometimes more on allocation-heavy workloads. This is why `INVARIANTS` -is not enabled in `GENERIC`. For driver development, this overhead is -worth accepting in exchange for the bugs it catches. See Appendix F -for a reproducible workload that measures this ratio on your own -hardware. +这些检查消耗 CPU 周期。粗略估计,在典型的 FreeBSD 14.3-amd64 硬件上,繁忙的 `INVARIANTS` 内核比发布版内核大约慢百分之五到二十,在分配密集的工作负载上有时更多。这就是为什么 `INVARIANTS` 不在 `GENERIC` 中启用的原因。对于驱动程序开发,为了它捕获的 bug,这个开销是值得的。参见附录 F 获取在你自己硬件上测量此比例的可重现工作负载。 -`INVARIANT_SUPPORT` compiles in the helper routines that assertions -call, without activating the assertions in base kernel code. As noted -earlier, it allows modules built with `INVARIANTS` to load against -kernels without `INVARIANTS`. You almost always want both. +`INVARIANT_SUPPORT` 编译进断言调用的辅助例程,但不激活基础内核代码中的断言。如前所述,它允许用 `INVARIANTS` 构建的模块加载到没有 `INVARIANTS` 的内核中。你几乎总是需要两者。 ### WITNESS:锁顺序验证器 -`WITNESS` is one of the most effective debugging tools in the FreeBSD -arsenal. It tracks every lock operation and every lock dependency in -the kernel, and it fires a warning if it ever sees a lock order that -could deadlock. Because deadlocks are a class of bug that is extremely -hard to catch any other way, `WITNESS` is indispensable for any driver -that takes more than one lock. +`WITNESS` 是 FreeBSD 兵器库中最有效的调试工具之一。它跟踪内核中的每一次锁操作和每一个锁依赖,如果它看到可能导致死锁的锁序就会发出警告。因为死锁是一类极难通过其他方式捕获的 bug,`WITNESS` 对于任何获取多个锁的驱动程序都是不可或缺的。 -The way `WITNESS` works is worth understanding. Every time a thread -acquires a lock, `WITNESS` notes which other locks the thread already -holds. From these observations it builds a lock order graph: "lock A -has been seen held before lock B," and so on. If the graph ever -contains a cycle, that is a potential deadlock, and `WITNESS` prints -a warning on the console with backtraces for the offending -acquisitions. +`WITNESS` 的工作方式值得理解。每次线程获取锁时,`WITNESS` 记录该线程已经持有哪些其他锁。从这些观察中它构建一个锁序图:"锁 A 在锁 B 之前被持有过"等等。如果图中有环,那就是一个潜在的死锁,`WITNESS` 在控制台上打印带有违规获取回溯的警告。 -The output looks something like this: +输出看起来像这样: ```text lock order reversal: @@ -1457,46 +741,17 @@ stack backtrace: ... ``` -Read this as: your driver's `bugdemo_sc_mutex` was acquired first, and -then later another thread was observed taking `sysctl_lock` first and -`bugdemo_sc_mutex` second. This is a potential deadlock, because -enough concurrent activity could make the two threads wait for each -other. The fix is always the same: establish a consistent lock order -across all paths that take both locks, and stick to it. +解读如下:你的驱动程序的 `bugdemo_sc_mutex` 先被获取,然后后来观察到另一个线程先获取 `sysctl_lock` 再获取 `bugdemo_sc_mutex`。这是一个潜在的死锁,因为足够的并发活动可能使两个线程互相等待。修复方法始终相同:在所有获取两把锁的路径上建立一致的锁序,并坚持它。 -`WITNESS` is not cheap. It adds bookkeeping to every lock acquisition -and release. In our lab environment, on a busy kernel running a -lock-heavy workload, the overhead can approach twenty percent; the -exact figure varies with the amount of locking the workload does. But -the bugs it finds are the kind that destroy production uptime when -they slip through, so the investment is worth it in development. See -Appendix F for a reproducible workload that isolates this overhead -against a baseline kernel. +`WITNESS` 并不便宜。它为每次锁获取和释放添加簿记。在我们的实验环境中,在运行锁密集工作负载的繁忙内核上,开销可接近百分之二十;确切数字取决于工作负载的锁量。但它发现的 bug 是那种漏过去会摧毁生产运行时间的 bug,所以投资在开发中是值得的。参见附录 F 获取隔离此开销与基线内核的可重现工作负载。 -`WITNESS_SKIPSPIN` turns off `WITNESS` on spin mutexes. Spin locks are -typically short-lived and performance-critical, so checking them adds -overhead where it matters most. The default is to check them anyway, -but `std.debug` disables that check to keep the kernel usable. You can -re-enable it if you are specifically hunting spin-lock bugs. +`WITNESS_SKIPSPIN` 关闭自旋互斥锁上的 `WITNESS`。自旋锁通常寿命短且对性能关键,所以检查它们在最要紧的地方增加了开销。默认是检查它们,但 `std.debug` 禁用了该检查以保持内核可用。如果你专门追踪自旋锁 bug,可以重新启用它。 -### A Worked Race-Condition Walkthrough: Lock-Order Bug in bugdemo +### 一个实战竞态条件演练:bugdemo 中的锁序 Bug -Reading about `WITNESS` in the abstract is one thing; catching a real -lock-order reversal in a driver you wrote is another. This subsection -walks through a complete cycle: we introduce a deliberate ordering -bug into `bugdemo`, run it on a `GENERIC-DEBUG` kernel, read the -`WITNESS` report, and fix the bug. The walkthrough is short, but the -pattern repeats in every deadlock you will ever debug. +抽象地阅读 `WITNESS` 是一回事;在你编写的驱动程序中捕获一个真实的锁序反转是另一回事。本小节将完成一个完整循环:我们在 `bugdemo` 中引入一个故意的排序 bug,在 `GENERIC-DEBUG` 内核上运行它,阅读 `WITNESS` 报告,然后修复 bug。演练很短,但这个模式在你将来调试的每个死锁中都会重复。 -Assume our `bugdemo` driver has grown two locks as it gained features. -`sc_mtx` protects the per-unit state, and `cfg_mtx` protects a -configuration blob shared across units. Most of the driver already -takes them in the order "state first, config second," which is a -reasonable choice and which the author has followed in `bugdemo_ioctl` -and in the read/write entry points. But a recent sysctl handler, -written in a hurry, acquired the config lock first to validate a -value and then reached for the state lock to apply it. In source, -the two relevant excerpts look like this: +假设我们的 `bugdemo` 驱动程序随着功能增加而拥有了两把锁。`sc_mtx` 保护每个单元的状态,`cfg_mtx` 保护跨单元共享的配置数据。驱动程序的大部分代码已经按照"先状态、后配置"的顺序获取它们,这是一个合理的选择,作者在 `bugdemo_ioctl` 和读写入口点中遵循了这一点。但最近的一个 sysctl 处理程序写得匆忙,先获取了配置锁来验证值,然后才去获取状态锁来应用它。源代码中,相关的两段摘录如下: ```c /* bugdemo_ioctl: established ordering, state then config */ @@ -1518,20 +773,9 @@ mtx_unlock(&sc->sc_mtx); mtx_unlock(&cfg_mtx); ``` -Both paths individually are fine. The problem is that taken together -they form a cycle. If thread A enters `bugdemo_ioctl` and acquires -`sc_mtx`, and thread B concurrently enters `bugdemo_sysctl_set` and -acquires `cfg_mtx`, each thread now waits on the lock the other holds. -That is a classic AB-BA deadlock. It may not trigger on every run; it -depends on timing. `WITNESS` is the tool that refuses to wait for a -rare production failure to discover it. +两条路径单独看都没问题。问题在于它们合在一起形成了一个环。如果线程 A 进入 `bugdemo_ioctl` 并获取 `sc_mtx`,而线程 B 同时进入 `bugdemo_sysctl_set` 并获取 `cfg_mtx`,每个线程现在都在等待对方持有的锁。这就是经典的 AB-BA 死锁。它不一定在每次运行中都触发;取决于时序。`WITNESS` 就是那个拒绝等待罕见生产故障来发现它的工具。 -On a `GENERIC-DEBUG` kernel the reversal is caught the first time both -orderings are observed, even if no actual deadlock has occurred yet. -The console message has a specific shape. Using the format emitted by -`witness_output` in `/usr/src/sys/kern/subr_witness.c`, which prints -pointer, lock name, witness name, lock class, and source location for -each lock involved, the real report looks like this: +在 `GENERIC-DEBUG` 内核上,只要两种顺序都被观察到,反转就会被捕获,即使尚未发生实际死锁。控制台消息有特定的格式。使用 `/usr/src/sys/kern/subr_witness.c` 中 `witness_output` 打印的格式,它会为每个涉及的锁打印指针、锁名、见证名、锁类和源位置,真实的报告如下: ```text lock order reversal: @@ -1551,22 +795,9 @@ stack backtrace: ... ``` -Each `1st` and `2nd` line carries four pieces of information. The -pointer (`0xfffff80012345000`) is the address of the lock object in -kernel memory. The first string is the instance name, set when the -lock was initialized. The two strings in parentheses are the -`WITNESS` name for the lock class and the lock class itself, in this -case `sleep mutex`. The path and line are where the lock was last -acquired along this reversed ordering. The block after `lock order -... established at:` shows the earlier backtrace that first taught -`WITNESS` the now-violated ordering, and the final `stack backtrace` -shows the current call path that violates it. +每个 `1st` 和 `2nd` 行携带四条信息。指针(`0xfffff80012345000`)是锁对象在内核内存中的地址。第一个字符串是实例名称,在锁初始化时设置。括号中的两个字符串是锁类的 `WITNESS` 名称和锁类本身,在此例中是 `sleep mutex`。路径和行号是锁沿此反转顺序最后被获取的位置。`lock order ... established at:` 后面的块显示了首次教会 `WITNESS` 此(现在被违反的)顺序的早期回溯,最终的 `stack backtrace` 显示了违反它的当前调用路径。 -Reading all of that, the diagnosis is immediate. The driver has -established `sc_mtx -> cfg_mtx` in its normal paths, and -`bugdemo_sysctl_set` has just taken `cfg_mtx -> sc_mtx`. Both paths -are ours. The fix is to pick one ordering (here, the established one) -and rewrite the offending path to match: +读完所有这些,诊断是即刻的。驱动程序在其正常路径中建立了 `sc_mtx -> cfg_mtx` 的顺序,而 `bugdemo_sysctl_set` 刚刚采用了 `cfg_mtx -> sc_mtx` 的顺序。两条路径都是我们的。修复是选择一种顺序(这里是已建立的顺序),并重写违规路径以匹配: ```c /* bugdemo_sysctl_set: corrected to follow house ordering */ @@ -1577,42 +808,17 @@ mtx_unlock(&cfg_mtx); mtx_unlock(&sc->sc_mtx); ``` -If the locked region needs to be narrower, a common pattern is to -read state under `sc_mtx`, drop it, validate without holding any -lock, and then reacquire in the house order to apply. Either way, -the order is fixed at the driver level, not at the call site. A -useful habit is to document the order in a comment near the lock -declarations so future contributors do not have to rediscover it. +如果锁定区域需要更窄,一种常见的模式是在 `sc_mtx` 下读取状态、释放它、在无锁状态下验证,然后按照既定顺序重新获取以应用更改。无论哪种方式,顺序都在驱动级别固定,而非在调用站点。一个有用的习惯是在锁声明附近的注释中记录顺序,这样未来的贡献者就不必重新发现它。 -After the fix, rebuilding `bugdemo` on the same debug kernel and -rerunning the triggering test produces no further `WITNESS` output. -If a reversal reappears, `WITNESS` also supports querying the graph -interactively with `show all_locks` in DDB, which can show the -current state even without a full reversal report; for deeper -introspection, the source of `/usr/src/sys/kern/subr_witness.c` is -the authoritative explanation of both the bookkeeping and the -report format. +修复后,在同一调试内核上重建 `bugdemo` 并重新运行触发测试不会产生更多 `WITNESS` 输出。如果反转再次出现,`WITNESS` 还支持在 DDB 中用 `show all_locks` 交互式查询图,即使没有完整的反转报告也能显示当前状态;对于更深入的内省,`/usr/src/sys/kern/subr_witness.c` 的源代码是簿记和报告格式的权威解释。 -### The Same Bug Seen Through lockstat(1) +### 通过 lockstat(1) 看同一个 Bug -`WITNESS` tells you that an ordering is wrong. It does not tell you -how often each lock is actually contended, how long each acquisition -waits, or which callers are pushing on a given lock hardest. Those -are questions about contention, not correctness, and `lockstat(1)` is -the tool for them. +`WITNESS` 告诉你顺序是错误的。它不告诉你每把锁实际上被竞争的频率、每次获取等待多长时间、或哪些调用者对某把锁施加的压力最大。这些是关于竞争而非正确性的问题,`lockstat(1)` 就是回答它们的工具。 -`lockstat(1)` is a DTrace-backed profiler for kernel locks. It works -by instrumenting the entry and exit points of lock primitives and -reporting summaries, including spin time on adaptive mutexes, sleep -time on sx locks, and hold time when asked. The classical invocation -is `lockstat sleep N`, which gathers data for N seconds and then -prints a summary. +`lockstat(1)` 是一个基于 DTrace 的内核锁分析器。它通过在锁原语的入口和出口点插桩来工作,报告摘要信息,包括自适应互斥锁上的旋转时间、sx 锁上的睡眠时间,以及被请求时的持有时间。经典的调用方式是 `lockstat sleep N`,它收集 N 秒的数据然后打印摘要。 -If we run the buggy `bugdemo` under a workload that stresses both -paths (a small userspace program that opens several unit nodes and -simultaneously twiddles the sysctl in a tight loop), and profile with -`lockstat` for five seconds, the output on a FreeBSD system looks -roughly like this: +如果我们在施加压力于两条路径的工作负载下运行有 bug 的 `bugdemo`(一个打开多个单元节点并同时紧凑循环操作 sysctl 的用户空间小程序),并用 `lockstat` 分析五秒,FreeBSD 系统上的输出大致如下: ```console # lockstat sleep 5 @@ -1637,244 +843,101 @@ Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------------- ``` -Each table follows the same column convention: `Count` is how many -events of this type were seen, `indv` is the percentage of events in -this class, `cuml` is the running total, `rcnt` is the average -reference count (always 1 for mutexes), `nsec` is the average -duration in nanoseconds, and the last two columns identify the lock -instance and the caller. The header line `Adaptive mutex spin` -indicates contention that was resolved by a short spin; `Adaptive -mutex block` indicates contention that actually forced a thread to -sleep on the mutex. Those headers, and the column layout, are -standard `lockstat` output; the format is documented in -`/usr/src/cddl/contrib/opensolaris/cmd/lockstat/lockstat.1` along -with worked examples at the end of that man page. +每个表遵循相同的列约定:`Count` 是此类事件的观测数量,`indv` 是此类事件在该类别中的百分比,`cuml` 是累计百分比,`rcnt` 是平均引用计数(互斥锁始终为 1),`nsec` 是以纳秒为单位的平均持续时间,最后两列标识锁实例和调用者。标题行 `Adaptive mutex spin` 表示通过短时间旋转解决的竞争;`Adaptive mutex block` 表示实际迫使线程在互斥锁上睡眠的竞争。这些标题和列布局是标准的 `lockstat` 输出;格式记录在 `/usr/src/cddl/contrib/opensolaris/cmd/lockstat/lockstat.1` 中,该手册页末尾有实际示例。 -Two things are worth noting. First, both `bugdemo sc_mtx` and -`bugdemo cfg_mtx` appear in both directions of the table: the sysctl -path blocked on `sc_mtx` (line 1 of the block table), and the ioctl -path blocked on `cfg_mtx` (line 2). That is the contention signature -of the same ordering bug `WITNESS` reported, seen from the other -side. `WITNESS` told us the ordering was unsafe; `lockstat` tells us -that under this workload the unsafe ordering is also costing real -time. +有两点值得注意。首先,`bugdemo sc_mtx` 和 `bugdemo cfg_mtx` 都出现在表的两个方向中:sysctl 路径在 `sc_mtx` 上阻塞(阻塞表第 1 行),ioctl 路径在 `cfg_mtx` 上阻塞(第 2 行)。这就是同一排序 bug 的竞争特征,从另一面看到的。`WITNESS` 告诉我们顺序不安全;`lockstat` 告诉我们在此工作负载下不安全的顺序也在消耗真实时间。 -Second, after we apply the fix from the previous subsection, -`lockstat` becomes a validation tool: rerun with the same workload -and the `Adaptive mutex block` table should shrink dramatically, -because the mutual wait between the two paths is gone. If it does -not shrink, we have fixed the ordering but created a pure contention -problem, and the next step is to narrow the critical section rather -than to change the order. +其次,应用前一子节的修复后,`lockstat` 变成了一个验证工具:用相同工作负载重新运行,`Adaptive mutex block` 表应该大幅缩小,因为两条路径之间的相互等待消失了。如果不缩小,说明我们修复了顺序但创建了纯粹的竞争问题,下一步是缩小临界区而非改变顺序。 -Useful `lockstat` options beyond the default include `-H` to watch -hold events (how long locks are held, not just contended), `-D N` to -show only the top N rows per table, `-s 8` to include eight-frame -stack traces with each row, and `-f FUNC` to filter on a single -function. For driver work, `lockstat -H -s 8 sleep 10` while a -targeted test runs is a remarkably productive default. +有用的 `lockstat` 选项(除了默认)包括 `-H` 监视持有事件(锁被持有多长时间,而不仅仅是竞争)、`-D N` 每个表只显示前 N 行、`-s 8` 每行包含八帧栈跟踪、`-f FUNC` 过滤单个函数。对于驱动程序工作,在运行针对性测试时执行 `lockstat -H -s 8 sleep 10` 是一个极其高效的默认选择。 -### Reading WITNESS and lockstat Together +### 结合阅读 WITNESS 和 lockstat -`WITNESS` and `lockstat` are complementary. `WITNESS` is a -correctness tool: it detects bugs that will eventually produce a -deadlock, regardless of whether the current workload happens to hit -them. `lockstat` is a performance tool: it quantifies how much -current traffic is touching each lock and how long the traffic waits. -The same driver path often shows up in both, and the two views -together are frequently decisive. +`WITNESS` 和 `lockstat` 是互补的。`WITNESS` 是正确性工具:它检测最终会产生死锁的 bug,无论当前工作负载是否恰好命中它们。`lockstat` 是性能工具:它量化当前流量在多大程度上涉及每把锁以及流量等待多长时间。同一驱动路径经常出现在两者中,两个视图合在一起通常是决定性的。 -A useful discipline when a driver grows past its first lock is to -make both tools part of the routine. Run `GENERIC-DEBUG` during -development so `WITNESS` sees every new code path the moment it -executes. Periodically run `lockstat` on a realistic workload to see -whether any of your locks are becoming bottlenecks even when their -ordering is sound. A lock that passes `WITNESS` and shows low -`lockstat` contention is a lock you can mostly stop thinking about. -A lock that passes `WITNESS` but dominates `lockstat` output is a -performance problem waiting for a refactor, not a correctness bug. -A lock that fails `WITNESS` is a bug regardless of what `lockstat` -says. +当驱动程序的锁超过第一个时,一个有用的纪律是将两种工具都纳入常规。在开发期间运行 `GENERIC-DEBUG`,这样 `WITNESS` 在每个新代码路径执行的瞬间就能看到它。定期在现实工作负载上运行 `lockstat`,查看是否有任何锁正在成为瓶颈,即使其顺序是正确的。一把通过 `WITNESS` 且在 `lockstat` 中显示低竞争的锁,是你基本可以不用再担心的锁。一把通过 `WITNESS` 但在 `lockstat` 输出中占主导地位的锁,是等待重构的性能问题,而非正确性 bug。一把未通过 `WITNESS` 的锁,无论 `lockstat` 怎么说,都是一个 bug。 -With that framework in mind, we can continue looking at the other -debug-kernel options that surface different classes of bug. +带着这个框架,我们可以继续查看其他能暴露不同 bug 类别的调试内核选项。 ### MALLOC_DEBUG_MAXZONES -FreeBSD's kernel memory allocator (`malloc(9)`) groups similar -allocations into zones for speed. `MALLOC_DEBUG_MAXZONES=8` increases -the number of zones used by `malloc`, which spreads allocations across -more distinct memory regions. The practical effect is that -use-after-free and invalid free bugs are more likely to land in a -different zone than the original allocation, making them more -detectable. +FreeBSD 的内核内存分配器(`malloc(9)`)将类似的分组合并到区域中以加快速度。`MALLOC_DEBUG_MAXZONES=8` 增加了 `malloc` 使用的区域数量,将分配分散到更多不同的内存区域。实际效果是释放后使用和无效释放 bug 更可能落在与原始分配不同的区域中,使它们更容易被检测到。 -This is a low-cost option. It is always on in debug kernels. +这是一个低成本的选项。它在调试内核中始终启用。 ### ALT_BREAK_TO_DEBUGGER and BREAK_TO_DEBUGGER -These two options control how the user enters the kernel debugger from -the console. `BREAK_TO_DEBUGGER` enables the traditional -`Ctrl-Alt-Esc` or serial BREAK sequence. `ALT_BREAK_TO_DEBUGGER` -enables an alternative sequence, typed as `CR ~ Ctrl-B`, which is -useful over network consoles (ssh, virtio_console, and so on) where -sending a real BREAK is awkward. +这两个选项控制用户如何从控制台进入内核调试器。`BREAK_TO_DEBUGGER` 启用传统的 `Ctrl-Alt-Esc` 或串行 BREAK 序列。`ALT_BREAK_TO_DEBUGGER` 启用替代序列,输入为 `CR ~ Ctrl-B`,这在网络控制台(ssh、virtio_console 等)上发送真正的 BREAK 不方便时很有用。 -`GENERIC` ships with `BREAK_TO_DEBUGGER` enabled. -`GENERIC-DEBUG` adds `ALT_BREAK_TO_DEBUGGER`. If you are on a serial -console, either sequence will drop you into `DDB`. From `DDB` you can -inspect kernel state, set breakpoints, and optionally continue -execution or panic. +`GENERIC` 附带 `BREAK_TO_DEBUGGER` 启用。`GENERIC-DEBUG` 额外添加 `ALT_BREAK_TO_DEBUGGER`。如果你在串行控制台上,任一序列都可以将你送入 `DDB`。在 `DDB` 中你可以检查内核状态、设置断点,以及选择继续执行或 panic。 -This is an important convenience during development. A driver that -hangs the system without panicking can be investigated by dropping -into the debugger on command. +这在开发期间是一个重要的便利。一个挂起系统而不产生 panic 的驱动程序可以通过命令式进入调试器来调查。 ### DEADLKRES: The Deadlock Detector -`DEADLKRES` enables the deadlock resolver, which is a periodic thread -that watches for threads stuck in uninterruptible wait for too long. -If it finds any, it prints a warning and optionally panics. This -complements `WITNESS` by catching deadlocks that `WITNESS` did not -predict, which happens when the lock graph is not traversable -statically (for example, when locks are acquired by address through a -generic locking API). +`DEADLKRES` 启用死锁解析器,它是一个定期检查线程是否在不可中断等待中卡住过久的线程。如果发现这样的线程,它打印警告并可选择 panic。它补充了 `WITNESS`,捕获 `WITNESS` 未预测到的死锁,这在锁图无法静态遍历时发生(例如,当锁通过通用锁定 API 按地址获取时)。 -`DEADLKRES` has some false positives in practice, particularly for -long-lived operations like filesystem I/O under heavy load. Reading -the warning and deciding whether it is a real deadlock is part of the -debugging skill this chapter is teaching. +`DEADLKRES` 在实践中有一些误报,特别是对于在重负载下长时间运行的文件系统 I/O 操作。阅读警告并判断它是否是真正的死锁,是本章正在教授的调试技能的一部分。 ### BUF_TRACKING -`BUF_TRACKING` records a short history of operations on each buffer -in the buffer cache. When a corruption is found, the buffer's history -can be printed, showing which code paths touched it and in what order. -This is useful for storage driver bugs but less commonly needed in -other drivers. +`BUF_TRACKING` 记录缓冲区缓存中每个缓冲区操作的简短历史。当发现损坏时,可以打印缓冲区的历史,显示哪些代码路径以何种顺序触及了它。这对存储驱动程序 bug 很有用,但在其他驱动程序中较少需要。 ### QUEUE_MACRO_DEBUG_TRASH -The `queue(3)` macros (`LIST_`, `TAILQ_`, `STAILQ_`, and so on) are -used pervasively in the kernel for linked lists. When an element is -removed from a list, the usual behavior is to leave the element's -pointers alone. `QUEUE_MACRO_DEBUG_TRASH` overwrites them with -recognizable garbage values. Any later attempt to dereference those -pointers will crash in a recognizable way, rather than silently -corrupting the list. +`queue(3)` 宏(`LIST_`、`TAILQ_`、`STAILQ_` 等)在内核中被广泛用于链表。当元素从列表中移除时,通常的行为是保持元素的指针不变。`QUEUE_MACRO_DEBUG_TRASH` 用可识别的垃圾值覆盖它们。之后任何试图解引用这些指针的尝试都会以可识别的方式崩溃,而不是静默地损坏列表。 -This is a cheap option and catches a very common class of bug: -forgetting to remove an element from a list before freeing it, then -finding the list corrupted later. +这是一个便宜的选项,能捕获一类非常常见的 bug:在释放元素之前忘记将其从列表中移除,然后发现列表被损坏。 ### Memory Debuggers: DEBUG_MEMGUARD and DEBUG_REDZONE -Two more options that deserve attention are `DEBUG_MEMGUARD` and -`DEBUG_REDZONE`. They are not part of `std.debug` but are commonly -added for memory debugging sessions. +另外两个值得关注的选项是 `DEBUG_MEMGUARD` 和 `DEBUG_REDZONE`。它们不属于 `std.debug`,但通常用于内存调试会话。 -`DEBUG_MEMGUARD` is a specialized allocator that can be dropped in for -particular `malloc(9)` types. It backs each allocation with a separate -page or set of pages, marks the pages around the allocation as -inaccessible, and unmaps the allocation on free. Any access beyond -the bounds of the allocation, or any access after free, causes a -page fault that is trivial to diagnose. The trade-off is that every -allocation costs a full page of virtual memory plus kernel -bookkeeping, so you normally turn `DEBUG_MEMGUARD` on for one -specific malloc type at a time. +`DEBUG_MEMGUARD` 是一个专用分配器,可以替换特定 `malloc(9)` 类型的分配。它的想法很简单:不从 slab 中返回一块内存,而是返回由专用页面支持的内存。当内存被释放时,页面不归还到池中;它们被取消映射,因此任何后续访问都会触发页面错误。分配周围的页面也被标记为不可访问,因此任何超出分配边界的读取或写入也会触发错误。这将释放后使用、缓冲区越界和缓冲区下溢 bug 从静默的损坏者转变为立即 panic,并带有直接指向误用点的回溯。 -The relevant header is `/usr/src/sys/vm/memguard.h`, and the -configuration appears in `/usr/src/sys/conf/NOTES` on the -`options DEBUG_MEMGUARD` line. We will use `memguard(9)` in detail -in Section 6. +代价是每次分配现在至少消耗一个完整的虚拟内存页面(加上管理开销),每次释放都会消耗一个未映射的页面。因此,`memguard(9)` 通常一次只对一个 malloc 类型启用。 -`DEBUG_REDZONE` is a lighter-weight memory debugger that places -guard bytes before and after each allocation. When the allocation is -freed, the guard bytes are checked, and any corruption is reported. -It does not catch use-after-free but is very good at catching buffer -overruns and underruns. See the `options DEBUG_REDZONE` line in -`/usr/src/sys/conf/NOTES` for the configuration. +相关的头文件是 `/usr/src/sys/vm/memguard.h`,配置出现在 `/usr/src/sys/conf/NOTES` 中 `options DEBUG_MEMGUARD` 行。我们将在第 6 节详细使用 `memguard(9)`。 -Both `DEBUG_MEMGUARD` and `DEBUG_REDZONE` cost memory. For a debug -kernel on a development VM, both are often enabled. For a large -production server, neither is. +`DEBUG_REDZONE` 是一个更轻量的内存调试器,在每个分配前后放置保护字节。当分配被释放时,检查保护字节,如果被修改就报告损坏。它不捕获释放后使用,但非常擅长捕获缓冲区越界和下溢。参见 `/usr/src/sys/conf/NOTES` 中的 `options DEBUG_REDZONE` 行获取配置。 + +`DEBUG_MEMGUARD` 和 `DEBUG_REDZONE` 都消耗内存。对于开发虚拟机上的调试内核,两者通常都启用。对于大型生产服务器,两者都不启用。 ### KDB, DDB, and GDB Together -We have referenced these three options throughout this chapter. Let us -pin down the distinction, because it confuses many beginners. +我们在本章中多次引用了这三个选项。让我们澄清它们的区别,因为它让许多初学者感到困惑。 -`KDB` is the kernel debugger framework. It is the plumbing. It defines -entry points that the rest of the kernel calls when a panic or a -break-to-debugger event happens. It also defines an interface for -backends. +`KDB` 是内核调试器框架。它是管道。它定义了内核其余部分在 panic 或进入调试器事件发生时调用的入口点。它还为后端定义了接口。 -`DDB` and `GDB` are two such backends. `DDB` is the in-kernel -interactive debugger. When you hit `KDB_ENTER` and `DDB` is the -selected backend, you are dropped into an interactive prompt on the -console. `DDB` has a small set of commands: `bt`, `show`, `print`, -`break`, `step`, `continue`, and a few others. It is primitive but -self-contained: no other machine is needed. +`DDB` 和 `GDB` 是两个这样的后端。`DDB` 是内核内交互式调试器。当你触发 `KDB_ENTER` 且 `DDB` 是选定的后端时,你被投入控制台上的交互式提示符。`DDB` 有一小组命令:`bt`、`show`、`print`、`break`、`step`、`continue` 等等。它很原始但自包含:不需要其他机器。 -`GDB` is the remote backend. When you hit `KDB_ENTER` and `GDB` is the -selected backend, the kernel waits for a remote GDB client to attach -over a serial line or a network connection. The client runs on a -different machine and sends commands over a protocol called the GDB -remote serial protocol. This is much more flexible because you have -full `gdb` on the client side, but it requires a second machine (or -another VM) and a connection between the two. +`GDB` 是远程后端。当你触发 `KDB_ENTER` 且 `GDB` 是选定的后端时,内核等待远程 GDB 客户端通过串行线或网络连接附加。客户端在另一台机器上运行并通过称为 GDB 远程串行协议的协议发送命令。这更加灵活,因为客户端有完整的 `gdb`,但它需要第二台机器(或另一个虚拟机)和两者之间的连接。 -In practice, you enable both backends and switch between them at run -time. `sysctl debug.kdb.current_backend` names the active backend. -`sysctl debug.kdb.supported_backends` lists all compiled-in backends. -You can set `debug.kdb.current_backend` to `ddb` or `gdb` depending on -what kind of session you want. This is a useful convenience, because -the overhead of having both compiled in is negligible compared to the -benefit of flexibility. +在实践中,你启用两个后端并在运行时切换。`sysctl debug.kdb.current_backend` 命名活动后端。`sysctl debug.kdb.supported_backends` 列出所有编译进的后端。你可以根据想要的会话类型将 `debug.kdb.current_backend` 设置为 `ddb` 或 `gdb`。这是一个有用的便利,因为编译两者的开销与其灵活性的好处相比可以忽略不计。 -The KDB support in `GENERIC` is enough for most panics. We will use -`GDB` in Section 7 when we talk about remote debugging. +`GENERIC` 中的 KDB 支持足以应对大多数 panic。我们将在第 7 节讨论远程调试时使用 `GDB`。 ### KDB_UNATTENDED -One more option worth mentioning is `KDB_UNATTENDED`. This causes the -kernel to skip entry into the debugger on panic and go straight to the -dump and reboot. In production systems without anyone watching the -console, this is a sensible default; there is no point waiting -indefinitely for a debugger interaction that will never come. In -development, you usually want the opposite: to stay in `DDB` after a -panic so you can investigate before the state is lost to reboot. Set -this option via the `debug.debugger_on_panic` sysctl at runtime, or -`options KDB_UNATTENDED` in a kernel config. +还有一个值得一提的选项是 `KDB_UNATTENDED`。它使内核在 panic 时跳过进入调试器,直接进行转储和重启。在没有人在控制台旁的生产系统中,这是一个合理的默认值;等待一个永远不会到来的调试器交互毫无意义。在开发中,你通常想要相反的行为:在 panic 后留在 `DDB` 中,这样你可以在状态因重启而丢失之前进行调查。通过运行时 `sysctl debug.debugger_on_panic` 或内核配置中的 `options KDB_UNATTENDED` 设置此选项。 ### CTF and Debug Info Paths -One last piece of the debug environment is CTF, the Compact C Type -Format. CTF is a compressed representation of type information that -DTrace uses to understand kernel structures. `GENERIC` includes -`options DDB_CTF`, which tells the build to generate CTF information -for the kernel. On a debug kernel, CTF information lets DTrace print -structure fields by name instead of hex offsets, which makes its -output dramatically more useful. +调试环境的最后一个部分是 CTF,即紧凑 C 类型格式。CTF 是 DTrace 用来理解内核结构的类型信息的压缩表示。`GENERIC` 包含 `options DDB_CTF`,告诉构建系统为内核生成 CTF 信息。在调试内核上,CTF 信息让 DTrace 能用名称而非十六进制偏移量打印结构字段,使其输出实用性大幅提升。 -You can confirm CTF is present with `ctfdump`: +你可以用 `ctfdump` 确认 CTF 存在: ```console # ctfdump -t /boot/kernel/kernel | head ``` -If this produces output, the kernel has CTF. If not, either the build -did not include `DDB_CTF` or the CTF generation tool (`ctfconvert`) -was not installed. In FreeBSD 14.3 both are standard. +如果这产生输出,内核有 CTF。如果没有,要么构建没有包含 `DDB_CTF`,要么 CTF 生成工具(`ctfconvert`)未安装。在 FreeBSD 14.3 中两者都是标准的。 -For modules, you need to build with `WITH_CTF=1` in your environment -(or passed to `make`) to get CTF information for the module. This is -what lets DTrace understand the structures your driver defines. +对于模块,你需要在环境中设置 `WITH_CTF=1`(或传递给 `make`)来获取模块的 CTF 信息。这就是让 DTrace 理解你驱动程序定义的结构的方式。 ### Confirming Your Debug Kernel -When you first boot into a debug kernel, spend a minute verifying that -the options you care about are actually active. Useful sysctls: +当你首次启动调试内核时,花一分钟验证你关心的选项确实处于活动状态。有用的 sysctl: ```console # sysctl debug.kdb.current_backend @@ -1889,122 +952,67 @@ debug.ddb.capture.bufsize: 0 ... ``` -If these print sensible values, your debug kernel is wired up. If -`debug.kdb.supported_backends` lists only `ddb` but you expected -`gdb`, something in your configuration is off. Go back and check that -`options GDB` is in your kernel config or in `std.debug`. +如果这些打印出合理的值,你的调试内核就配置好了。如果 `debug.kdb.supported_backends` 只列出 `ddb` 但你期望有 `gdb`,你的配置有问题。回去检查 `options GDB` 是否在你的内核配置或 `std.debug` 中。 ### Running on Top of the Debug Kernel -With the debug kernel running, the rest of the chapter's techniques -become available. `KASSERT` actually fires. `WITNESS` actually -complains about lock orders. `DDB` is there when you press the -break-to-debugger sequence. Crash dumps include full debug information -that `kgdb` can use to show source lines. You have moved from a -kernel that trusts the driver to a kernel that actively helps you -prove your driver is correct. +在调试内核运行后,本章其余部分的技术就变得可用了。`KASSERT` 真正触发。`WITNESS` 真正抱怨锁序。`DDB` 在你按下进入调试器序列时就在那里。崩溃转储包含 `kgdb` 可以用来显示源代码行的完整调试信息。你从一个信任驱动程序的内核转向了一个主动帮助你证明驱动程序正确的内核。 -A small but meaningful consequence of running a debug kernel for -driver development is that you will see bugs in your driver much -earlier, before they reach the field, and you will have an easier -time fixing them when they do appear. The discipline of always -developing on a debug kernel, even when you are only writing simple -code, is one of the habits that separates casual hobbyist drivers -from drivers that are trustworthy enough for serious use. +在调试内核上进行驱动程序开发的一个虽小但有意义的后果是,你会更早地看到驱动程序中的 bug,在它们到达现场之前,而且当它们确实出现时你修复起来更容易。始终在调试内核上开发的纪律——即使你只是在写简单代码——是将随意的业余驱动程序与值得信赖的严肃驱动程序区分开的习惯之一。 -With the environment set up, we can move on to the next class of -tool: tracing. Unlike assertions, which catch failures, tracing -records what happens so you can understand the shape of a bug even -when it is not crashing. That is the topic of Section 5. +有了环境设置,我们可以转向下一类工具:跟踪。与捕获失败的断言不同,跟踪记录发生了什么,这样即使它没有崩溃你也能理解 bug 的形状。这是第 5 节的主题。 ## 5. 追踪驱动行为:DTrace、ktrace和ktr(9) -Assertions catch what is wrong. Tracing shows what is happening. When a -driver misbehaves without crashing, or when you need to understand the -precise order of events across multiple threads, tracing is usually the -right tool. FreeBSD offers three complementary tracing facilities for -kernel code: DTrace, `ktrace(1)`, and `ktr(9)`. Each has a different -sweet spot, and a driver author should know when to reach for which. +断言捕获出错的地方。跟踪显示正在发生什么。当驱动程序在不崩溃的情况下行为异常,或当你需要理解多个线程之间事件的精确顺序时,跟踪通常是正确的工具。FreeBSD 为内核代码提供了三种互补的跟踪工具:DTrace、`ktrace(1)` 和 `ktr(9)`。每一种有不同的最佳适用场景,驱动程序作者应该知道何时使用哪种。 -Chapter 33 introduced DTrace as a performance measurement tool. Here we -come back to it as a correctness debugging tool, because the same -framework that can aggregate hot functions can also follow a bug -through the kernel. We will also meet `ktr(9)`, the lightweight -in-kernel tracing ring, and `ktrace(1)`, which traces system calls from -user space. +第 33 章将 DTrace 作为性能测量工具进行了介绍。在这里我们将它作为正确性调试工具重新审视,因为同一个能聚合热函数的框架也能在内核中跟踪 bug。我们还将认识 `ktr(9)`,轻量级内核内跟踪环,以及 `ktrace(1)`,它从用户空间跟踪系统调用。 -### DTrace for Correctness Debugging +### DTrace 用于正确性调试 -DTrace is FreeBSD's production-grade dynamic tracing framework. It -works by letting you attach small scripts to probe points throughout -the kernel. A probe is a named point in the code that can be -instrumented. When a probe fires, the script runs. If the script has -useful things to record, it records them; if not, the probe is -effectively free. +DTrace 是 FreeBSD 的生产级动态跟踪框架。它通过让你将小程序附加到内核各处的探针点来工作。探针是代码中可被插桩的命名点。当探针触发时,脚本运行。如果脚本有有用的东西要记录,它就记录;如果没有,探针基本上是免费的。 -Chapter 33 used DTrace with the `profile` provider for CPU sampling. In -this chapter we will use different providers for different purposes: -`fbt` (function boundary tracing) to follow entry and exit from -functions, `sdt` (statically defined tracing) to fire at explicitly -placed probe points in our driver, and `syscall` to watch user-kernel -transitions. +第 33 章使用带 `profile` 提供者的 DTrace 进行 CPU 采样。在本章中,我们将使用不同的提供者用于不同目的:`fbt`(函数边界跟踪)跟踪函数的进入和退出、`sdt`(静态定义跟踪)在驱动程序中显式放置的探针点触发、`syscall` 观察用户-内核转换。 -Let us take these in turn. +让我们逐一来看。 ### fbt提供者 -The `fbt` provider gives you a probe at every function entry and exit -in the kernel. To list all fbt probes in our driver: +`fbt` 提供者为内核中的每个函数入口和退出提供了一个探针。要列出驱动程序中的所有 fbt 探针: ```console # dtrace -l -P fbt -m bugdemo ``` -Each function produces two probes, an `entry` and a `return`. You can -attach actions to either. A common first step in debugging a new bug -is simply to see what functions are being called: +每个函数产生两个探针,一个 `entry` 和一个 `return`。你可以为任何一个附加动作。调试新 bug 时常见的第一步是简单地查看哪些函数被调用: ```console dtrace -n 'fbt::bugdemo_*:entry { printf("%s\n", probefunc); }' ``` -This prints every entry into any function in the `bugdemo` module, -showing the order in which they are called. If you suspect a -particular function is or is not being reached, this one-liner will -tell you immediately. +这打印了 `bugdemo` 模块中任何函数的每次进入,显示了它们的调用顺序。如果你怀疑某个特定函数是否被到达或未被到达,这个一行命令会立即告诉你。 -For a deeper view, you can also record arguments. `fbt` probe arguments -are the function's parameters, accessible as `arg0`, `arg1`, etc.: +要更深入地查看,你还可以记录参数。`fbt` 探针参数就是函数的参数,可通过 `arg0`、`arg1` 等访问: ```console dtrace -n 'fbt::bugdemo_ioctl:entry { printf("cmd=0x%lx\n", arg1); }' ``` -Here `arg1` is the second parameter to `bugdemo_ioctl`, which is the -`ioctl` command number. You can watch the stream of ioctl calls in -real time. +这里 `arg1` 是 `bugdemo_ioctl` 的第二个参数,即 `ioctl` 命令号。你可以实时观察 ioctl 调用流。 -Exit probes let you see return values: +退出探针让你看到返回值: ```console dtrace -n 'fbt::bugdemo_ioctl:return { printf("rv=%d\n", arg1); }' ``` -On a return probe, `arg1` is the return value. A stream of `rv=0` -entries confirms success. A sudden `rv=22` (which is `EINVAL`) tells -you the driver rejected a call. By combining entry and return probes -you can match each call with its result. +在返回探针上,`arg1` 是返回值。一连串的 `rv=0` 确认成功。突然出现的 `rv=22`(即 `EINVAL`)告诉你驱动程序拒绝了一个调用。通过结合入口和返回探针,你可以将每个调用与其结果匹配。 ### SDT探针:静态定义追踪 -`fbt` is flexible but gives you function boundaries, not semantic -events. If you want a probe that fires at a specific point inside a -function, representing a specific event, you use SDT. SDT probes are -placed explicitly in the code. They cost essentially nothing when -disabled and produce exactly the information you want when enabled. +`fbt` 很灵活,但给你的是函数边界而非语义事件。如果你想要一个在函数内部特定点触发的探针,代表一个特定事件,你就使用 SDT。SDT 探针在代码中显式放置。禁用时它们几乎不花什么成本,启用时产生你想要的确切信息。 -In FreeBSD 14.3, SDT probes are defined using macros from -`/usr/src/sys/sys/sdt.h`. The key macros are: +在 FreeBSD 14.3 中,SDT 探针使用 `/usr/src/sys/sys/sdt.h` 中的宏定义。关键宏如下: ```c SDT_PROVIDER_DEFINE(bugdemo); @@ -2016,18 +1024,11 @@ SDT_PROBE_DEFINE3(bugdemo, , , cmd__done, "struct bugdemo_softc *", "int", "int"); ``` -The naming convention is `provider:module:function:name`. The leading -`bugdemo` is the provider. The two empty strings are the module and -function, which we leave empty for a driver-level probe. The trailing -name identifies the probe. The underscore-underscore convention in -probe names is a DTrace idiom that becomes a dash in the user-facing -name. +命名约定是 `provider:module:function:name`。开头的 `bugdemo` 是提供者。两个空字符串是模块和函数,我们为驱动程序级探针留空。末尾的名称标识探针。探针名称中的双下划线约定是 DTrace 的惯用法,在用户面对的名称中变成短划线。 -The numeric suffix on `SDT_PROBE_DEFINE` indicates how many arguments -the probe takes. The string arguments are the C type names of those -arguments, which DTrace uses for display. +`SDT_PROBE_DEFINE` 上的数字后缀表示探针接受多少个参数。字符串参数是这些参数的 C 类型名称,DTrace 用于显示。 -To fire a probe in the driver: +要在驱动程序中触发探针: ```c static void @@ -2041,37 +1042,27 @@ bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) } ``` -`SDT_PROBE2` and `SDT_PROBE3` fire the corresponding probe with the -given arguments. +`SDT_PROBE2` 和 `SDT_PROBE3` 用给定的参数触发相应的探针。 -Now in DTrace you can watch these probes: +现在在 DTrace 中你可以监视这些探针: ```console dtrace -n 'sdt:bugdemo::cmd-start { printf("op=%d\n", arg1); }' ``` -Notice the dash in `cmd-start`: DTrace converts the double -underscore in the name to a dash in the probe spec. `arg0` is the -softc, `arg1` is the op. +注意 `cmd-start` 中的短划线:DTrace 将名称中的双下划线转换为探针规范中的短划线。`arg0` 是 softc,`arg1` 是 op。 -SDT probes are particularly useful for state transitions. If your -driver has three states and you want to follow the sequence, define -probes at each transition and aggregate on them: +SDT 探针对于状态转换特别有用。如果你的驱动程序有三个状态而你想要跟踪序列,在每个转换处定义探针并对其进行聚合: ```console dtrace -n 'sdt:bugdemo::state-change { @[arg1, arg2] = count(); }' ``` -This counts how often each (from_state, to_state) pair occurs, -giving a distribution of the state machine's behavior during your -workload. +这计算每对 (from_state, to_state) 出现的频率,给出工作负载期间状态机行为的分布。 ### 使用DTrace追踪Bug -Consider a scenario. The `bugdemo` driver sometimes returns `EIO` -to user space, but you cannot tell from user space which code path -produced that error. With DTrace, you can walk backwards from the -return to the origin: +考虑一个场景。`bugdemo` 驱动程序有时向用户空间返回 `EIO`,但你无法从用户空间判断是哪条代码路径产生了该错误。使用 DTrace,你可以从返回值追溯到来源: ```console dtrace -n ' @@ -2083,12 +1074,9 @@ fbt::bugdemo_ioctl:return ' ``` -`arg1 == 5` checks for the return value 5, which is `EIO`. When the -return matches, `stack()` prints the kernel stack trace at the point -of the return. This tells you exactly which code path returned the -error. +`arg1 == 5` 检查返回值 5,即 `EIO`。当返回匹配时,`stack()` 打印返回点的内核栈跟踪。这告诉你确切是哪条代码路径返回了该错误。 -A more sophisticated version records the start time and duration: +更复杂的版本记录开始时间和持续时间: ```console dtrace -n ' @@ -2106,40 +1094,24 @@ fbt::bugdemo_ioctl:return ' ``` -This produces a latency distribution for the ioctl, which is useful -when a bug manifests as unusual latency. The `self->` notation is -DTrace's thread-local storage, scoped to the current thread. +这产生 ioctl 的延迟分布,当 bug 表现为异常延迟时很有用。`self->` 表示法是 DTrace 的线程本地存储,作用域限于当前线程。 -These scripts are not full programs; they are small observations -that you iterate on. The cycle of "add a probe, run the workload, -read the output, refine the probe" is one of DTrace's strengths. A -full debugging session might go through a dozen variations of a -script before the shape of the bug becomes clear. +这些脚本不是完整的程序;它们是你迭代的小型观察。"添加探针、运行工作负载、阅读输出、改进探针"的循环是 DTrace 的优势之一。一个完整的调试会话可能在 bug 的形状变得清晰之前经历十几种脚本变体。 ### 理解ktrace(1) -`ktrace(1)` is a different beast. It traces system calls made by a -user-space process, along with their arguments and return values. It -is not about the kernel's internal behavior; it is about the -interface between user space and the kernel. When a user-space tool -is using a driver and something odd happens, `ktrace(1)` is often -the first tool to reach for, because it shows exactly what the -process asked of the kernel. +`ktrace(1)` 是另一种不同的工具。它跟踪用户空间进程发出的系统调用及其参数和返回值。它不关注内核的内部行为;它关注的是用户空间与内核之间的接口。当用户空间工具在使用驱动程序时出现了奇怪的行为,`ktrace(1)` 通常是最先应该使用的工具,因为它准确显示了进程向内核请求了什么。 -To trace a program: +要跟踪一个程序: ```console # ktrace -t cnsi ./test_bugdemo # kdump ``` -`ktrace` writes a binary trace file (`ktrace.out` by default), and -`kdump` renders it as human-readable text. The `-t` flags select -what to trace: `c` for system calls, `n` for namei (pathname -lookups), `s` for signals, `i` for ioctls. For driver debugging, `i` -is the most directly useful. +`ktrace` 写入一个二进制跟踪文件(默认为 `ktrace.out`),`kdump` 将其渲染为人类可读的文本。`-t` 标志选择跟踪什么:`c` 表示系统调用、`n` 表示 namei(路径名查找)、`s` 表示信号、`i` 表示 ioctl。对于驱动程序调试,`i` 是最直接有用的。 -Sample output: +示例输出: ```text 5890 test_bugdemo CALL ioctl(0x3,BUGDEMO_TRIGGER,0x7fffffffe0c0) @@ -2148,50 +1120,31 @@ Sample output: 5890 test_bugdemo RET read 32/0x20 ``` -The process made two syscalls. An ioctl on file descriptor 3 with -command `BUGDEMO_TRIGGER` succeeded. A read on the same fd returned -32 bytes. If the test fails, the trace tells you exactly what the -kernel was asked for and what it returned. +进程进行了两个系统调用。一个在文件描述符 3 上的 ioctl,命令为 `BUGDEMO_TRIGGER`,成功了。一个在同一 fd 上的 read 返回了 32 字节。如果测试失败,跟踪告诉你内核被请求了什么以及它返回了什么。 -Notice that `ktrace(1)` does not show internal kernel behavior. For -that you need DTrace or `ktr(9)`. But `ktrace(1)` is the canonical -way to see user-space interactions, and combined with DTrace it -gives a complete picture. +注意 `ktrace(1)` 不显示内部内核行为。为此你需要 DTrace 或 `ktr(9)`。但 `ktrace(1)` 是查看用户空间交互的规范方式,与 DTrace 结合使用可以给出完整的图景。 -`ktrace(1)` can also be attached to a running process: +`ktrace(1)` 还可以附加到运行中的进程: ```console # ktrace -p PID ``` -and detached: +并可以分离: ```console # ktrace -C ``` -For a driver that is being used by a long-running daemon, this is -more practical than restarting the daemon under `ktrace`. +对于被长时间运行的守护进程使用的驱动程序,这比在 `ktrace` 下重启守护进程更实用。 ### ktr(9): Lightweight In-Kernel Tracing -`ktr(9)` is FreeBSD's in-kernel trace ring. It is a ring buffer of -trace entries that code can write to cheaply. Each entry includes a -timestamp, the CPU number, the thread pointer, a format string, and -up to six arguments. The ring is sized by the `KTR_ENTRIES` kernel -config option, and its contents can be dumped from `DDB` or from user -space. +`ktr(9)` 是 FreeBSD 的内核内跟踪环。它是一个代码可以低成本写入的跟踪条目环形缓冲区。每个条目包括时间戳、CPU 编号、线程指针、格式字符串和最多六个参数。环的大小由 `KTR_ENTRIES` 内核配置选项决定,其内容可以从 `DDB` 或用户空间转储。 -`ktr(9)` is the right tool when you need very fine-grained -information about timing or ordering, especially in an interrupt -context where `printf` is too slow. Because each entry is small and -writes are lock-free, `ktr(9)` can be used in hot paths without -distorting the behavior you are trying to observe. +当你需要关于时序或顺序的非常细粒度信息时,`ktr(9)` 是正确的工具,特别是在中断上下文中 `printf` 太慢的情况下。因为每个条目很小且写入是无锁的,`ktr(9)` 可以用在热路径中而不扭曲你试图观察的行为。 -The macros are in `/usr/src/sys/sys/ktr.h`. The common ones are -`CTR0` through `CTR6`, varying by how many arguments follow the -format string. Each macro takes a class mask as its first argument, -then the format string, then the values: +宏定义在 `/usr/src/sys/sys/ktr.h` 中。常用的有 `CTR0` 到 `CTR6`,按格式字符串后面跟多少个参数而不同。每个宏的第一个参数是类掩码,然后是格式字符串,然后是值: ```c #include @@ -2207,160 +1160,75 @@ bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) } ``` -`CTR2` writes a two-argument entry to the trace ring. `KTR_DEV` is -the class mask: the kernel decides at runtime whether entries for a -given class are recorded, based on `debug.ktr.mask`. At compile time, -`KTR_COMPILE` (the set of classes actually compiled in) controls -which calls are emitted at all. Classes that are not in `KTR_COMPILE` -disappear entirely, so you can leave calls in the source permanently -without paying for them when the class is disabled. +`CTR2` 向跟踪环写入一个双参数条目。`KTR_DEV` 是类掩码:内核在运行时根据 `debug.ktr.mask` 决定某类的条目是否被记录。编译时,`KTR_COMPILE`(实际编译进去的类集合)控制哪些调用被发射。不在 `KTR_COMPILE` 中的类完全消失,因此你可以将调用永久保留在源代码中而不在类被禁用时为它们付费。 -The classes are defined in `/usr/src/sys/sys/ktr_class.h`. Common -ones include `KTR_GEN` (general-purpose), `KTR_DEV` (device -drivers), `KTR_NET` (networking), and many more. For a driver, you -would typically pick `KTR_DEV` or, in larger subsystems, define a new -bit alongside the existing ones. +类定义在 `/usr/src/sys/sys/ktr_class.h` 中。常见的包括 `KTR_GEN`(通用)、`KTR_DEV`(设备驱动程序)、`KTR_NET`(网络)等等。对于驱动程序,你通常选择 `KTR_DEV`,或在较大的子系统中,在现有位旁边定义一个新位。 -To enable and view the trace ring: +要启用和查看跟踪环: ```console # sysctl debug.ktr.mask=0x4 # enable KTR_DEV (bit 0x04) # sysctl debug.ktr.entries ``` -and dump it with: +并用以下命令转储: ```console # ktrdump ``` -`ktrdump(8)` reads the kernel's trace buffer through `/dev/kmem` -and formats it. The output is a time-ordered list of entries with -timestamps, CPUs, threads, and messages. +`ktrdump(8)` 通过 `/dev/kmem` 读取内核的跟踪缓冲区并格式化它。输出是按时间排序的条目列表,包含时间戳、CPU、线程和消息。 -The beauty of `ktr(9)` is its low overhead. A trace entry is -essentially a handful of memory writes. You can leave them in the -code, compile them in to a debug kernel, and enable them at runtime -when you need them. They are especially valuable for interrupt -handler debugging, where `printf` would add milliseconds of delay -and actually change the behavior being measured. +`ktr(9)` 的美妙之处在于它的低开销。一个跟踪条目本质上是一小撮内存写入。你可以将它们留在代码中,编译进调试内核,在需要时在运行时启用。它们在中断处理程序调试中特别有价值,`printf` 在那里会增加毫秒级的延迟并实际改变被测量的行为。 ### 何时使用哪种工具 -With three tracing tools, the question is which to reach for first. +有了三种跟踪工具,问题是首先该使用哪种。 -Use DTrace when the bug is about what the kernel is doing, when you -need to aggregate across many events, when you need filtering, or -when the probes can be placed dynamically. DTrace is the most -capable of the three, but it requires a running kernel and a -reasonable rate of probe firings. +当 bug 是关于内核在做什么时使用 DTrace,当你需要跨多个事件聚合时、需要过滤时、或探针可以动态放置时使用它。DTrace 是三者中功能最强的,但它需要一个运行中的内核和合理的探针触发频率。 -Use `ktrace(1)` when the bug is about what user space is asking of -the kernel, when the symptom is a wrong return value or a sequence -of syscalls that does not match expectations. `ktrace(1)` is simple, -fast, and immediately shows the kernel-user boundary. +当 bug 是关于用户空间在向内核请求什么时使用 `ktrace(1)`,当症状是错误的返回值或不符合预期的系统调用序列时使用它。`ktrace(1)` 简单、快速,立即显示用户-内核边界。 -Use `ktr(9)` when you need the lowest possible overhead, when the -code you are tracing is in an interrupt handler, or when you want -persistent trace points that can be turned on in production with -minimal risk. `ktr(9)` is the most primitive of the three but also -the most durable. +当你需要尽可能低的开销时、当你跟踪的代码在中断处理程序中时、或当你想要可以在生产环境中以最小风险开启的持久跟踪点时使用 `ktr(9)`。`ktr(9)` 是三者中最原始的,但也是最耐用的。 -In practice, a debugging session often uses two or three. You might -start with `ktrace(1)` to see the syscall sequence, then add DTrace -probes to narrow down which driver function is misbehaving, then -add `ktr(9)` entries to nail down timing in the interrupt path. -Each tool answers a different question, and a full picture often -requires all three. +在实践中,调试会话通常使用两种或三种工具。你可能先用 `ktrace(1)` 查看系统调用序列,然后添加 DTrace 探针缩小哪个驱动函数行为异常,然后添加 `ktr(9)` 条目来确定中断路径中的时序。每种工具回答不同的问题,完整的图景通常需要全部三种。 ### Tracing and Production -A quick word on production. DTrace is production-safe in most -configurations; its design specifically includes safeguards against -infinite loops and against crashing the kernel from a bad probe. -You can run DTrace on a busy production server without bringing it -down. `ktr(9)` is also production-safe, with the caveat that -enabling verbose classes costs CPU. `ktrace(1)` writes to a file -and can grow unbounded if left unchecked; use with size limits. +关于生产环境的一句简短说明。DTrace 在大多数配置中是生产安全的;它的设计明确包含了防止无限循环和防止坏探针崩溃内核的安全措施。你可以在繁忙的生产服务器上运行 DTrace 而不会使其宕机。`ktr(9)` 也是生产安全的,但要注意启用详细类会消耗 CPU。`ktrace(1)` 写入文件,如果不加检查可以无限增长;使用时请注意大小限制。 -Contrast these with crash dumps, `DDB`, and `memguard(9)`, which -are development-only tools. The distinction matters because -Section 7 will return to the question of what is safe to do on a -production machine. For now, remember that tracing is among the -lightest-touch techniques we have, and that is why it is often the -right first step when diagnosing a live problem. +将这些与崩溃转储、`DDB` 和 `memguard(9)` 做对比,后者都是仅用于开发的工具。这个区别很重要,因为第 7 节将回到在生产机器上什么是安全的问题。现在请记住,跟踪是我们拥有的最轻量级的技术之一,这就是为什么它通常是诊断运行中问题的正确第一步。 -With tracing in hand, we can turn to the bugs that tracing and -assertions tend to miss: memory bugs that corrupt state without -producing clear symptoms until much later. That is the domain of -Section 6. +有了跟踪工具在手,我们可以转向跟踪和断言倾向于遗漏的 bug:那些在不产生明显症状的情况下损坏状态的内存 bug,直到很久之后才显现。这是第 6 节的领域。 ## 6. 查找内存泄漏与无效内存访问 -Memory bugs are the most treacherous bugs a driver author faces. They -are rarely visible at the moment they happen. They corrupt state -quietly, accumulate across many runs, and manifest much later in -ways that seem completely unrelated to the original defect. A -use-after-free might surface as a corrupted structure in a different -subsystem. A buffer overrun might overwrite the next allocation and -show up as a bogus field value several minutes later. A small leak -might drain memory over days until the kernel finally refuses an -allocation and the system locks up. +内存 bug 是驱动程序作者面临的最棘手的 bug。它们很少在发生时就能被发现。它们静静地损坏状态,在多次运行中累积,然后在很久以后以看似与原始缺陷完全无关的方式显现。释放后使用可能表现为不同子系统中损坏的结构。缓冲区越界可能覆盖下一个分配,在几分钟后才显示为伪造的字段值。小的泄漏可能经过数天耗尽内存,直到内核最终拒绝分配,系统锁定。 -FreeBSD provides a family of tools for these bugs: `memguard(9)` for -use-after-free and modify-after-free detection, `redzone` for buffer -overruns, guard pages in the VM layer, and sysctls that expose the -state of the kernel memory allocator. Used together, they can -transform a class of bug that was nearly impossible to find into a -class that crashes immediately at the moment of misuse. +FreeBSD 为这些 bug 提供了一系列工具:`memguard(9)` 用于释放后使用和释放后修改检测,`redzone` 用于缓冲区越界,VM 层的保护页,以及暴露内核内存分配器状态的 sysctl。配合使用,它们可以将一类几乎不可能找到的 bug 转化为一类在误用时立即崩溃的 bug。 -### Understanding the Kernel Memory Allocator +### 理解内核内存分配器 -To use these tools effectively we need a rough mental model of how -the kernel allocates memory. FreeBSD has two primary allocators, -both in `/usr/src/sys/kern/`: +要有效使用这些工具,我们需要对内核如何分配内存有一个粗略的心智模型。FreeBSD 有两个主要的分配器,都在 `/usr/src/sys/kern/` 中: -`kern_malloc.c` implements `malloc(9)`, the general-purpose allocator. -It is a thin wrapper over UMA, the Universal Memory Allocator, with -accounting by malloc type. Every allocation is charged to a -`struct malloc_type` (commonly declared with `MALLOC_DEFINE(9)`), -which lets the kernel track how much memory each subsystem has -used. +`kern_malloc.c` 实现了 `malloc(9)`,即通用分配器。它是 UMA(通用内存分配器)的薄封装,带有按 malloc 类型的记账。每次分配都计入一个 `struct malloc_type`(通常用 `MALLOC_DEFINE(9)` 声明),这让内核能跟踪每个子系统使用了多少内存。 -`subr_vmem.c` and `uma_core.c` implement the lower layers. UMA is a -slab allocator: it maintains per-CPU caches and central slabs, so -most allocations are very fast and contention-free. When a driver -calls `malloc(9)` or `uma_zalloc(9)`, what actually happens depends -on size, zone configuration, and cache state. +`subr_vmem.c` 和 `uma_core.c` 实现了较低的层次。UMA 是一个 slab 分配器:它维护每 CPU 缓存和中央 slab,所以大多数分配非常快且无竞争。当驱动程序调用 `malloc(9)` 或 `uma_zalloc(9)` 时,实际发生的事情取决于大小、区域配置和缓存状态。 -For debugging, the practical consequence is that a corrupted -allocation might look different depending on where it landed. The -same bug can produce different symptoms on different kernels or -under different loads, simply because the underlying memory layout -differs. +对于调试而言,实际后果是损坏的分配可能根据其落点的不同而呈现不同的外观。同一个 bug 在不同的内核或不同的负载下可能产生不同的症状,仅仅是因为底层内存布局不同。 -### sysctl vm and kern.malloc: Observing Allocation State +### sysctl vm 和 kern.malloc:观察分配状态 -Before reaching for memory debuggers, a useful first step is to -look at the live state of the allocator. Two sysctls are -particularly useful: +在动用内存调试器之前,一个有用的第一步是查看分配器的实时状态。两个 sysctl 特别有用: ```console # sysctl vm.uma # sysctl kern.malloc ``` -The first dumps per-zone statistics for UMA: how many items are -allocated, how many are free, how many failures have occurred, and -how many pages each zone is using. The output is long, but it is -text-searchable. If you suspect a leak in a particular driver type, -find its zone in the output and watch it grow. +第一个命令转储 UMA 的每区域统计:已分配多少项、空闲多少项、发生了多少次失败、每个区域使用了多少页。输出很长,但可以文本搜索。如果你怀疑某个特定驱动类型有泄漏,在输出中找到它的区域并观察其增长。 -The second dumps per-type statistics for `malloc(9)`. Each entry -shows the type name, the number of requests, the amount allocated, -and the high-water mark. Running the driver under a workload and -comparing before and after is a simple leak-detection technique -that requires no special tooling: +第二个命令转储 `malloc(9)` 的每类型统计。每个条目显示类型名称、请求数、已分配量和高水位标记。在负载下运行驱动程序并比较前后结果,是一种不需要特殊工具的简单泄漏检测技术: ```console # sysctl kern.malloc | grep bugdemo @@ -2369,11 +1237,9 @@ bugdemo: memuse = 0K ``` -Run a workload, re-query, and compare. If `inuse` rises and does -not fall after the workload finishes, something is leaking. +运行一个负载,再次查询,然后比较。如果 `inuse` 上升且在负载结束后不下降,说明有东西在泄漏。 -The related `vmstat(8)` command has a `-m` flag that presents the -same `malloc(9)` state in a more compact form: +相关的 `vmstat(8)` 命令有一个 `-m` 标志,以更紧凑的形式呈现相同的 `malloc(9)` 状态: ```console # vmstat -m | head @@ -2384,138 +1250,74 @@ same `malloc(9)` state in a more compact form: ... ``` -For ongoing monitoring during a workload: +用于在负载期间进行持续监控: ```console # vmstat -m | grep -E 'bugdemo|Type' ``` -gives you a periodic snapshot of a single type's footprint. +可以给你提供单个类型占用情况的周期性快照。 ### memguard(9):查找释放后使用 -`memguard(9)` is a special allocator that can replace `malloc(9)` -for a specific type. The idea is simple: instead of returning a -piece of memory from a slab, it returns memory backed by dedicated -pages. When the memory is freed, the pages are not returned to the -pool; they are unmapped, so any subsequent access faults. And the -pages around the allocation are left inaccessible, so any read or -write past the end of the allocation also faults. This turns -use-after-free, buffer overrun, and buffer underrun bugs from -silent corruptors into immediate panics with a backtrace that -points directly at the misuse. +`memguard(9)` 是一个特殊的分配器,可以替换特定类型的 `malloc(9)`。其想法很简单:不从 slab 中返回一块内存,而是返回由专用页面支持的内存。当内存被释放时,页面不归还到池中;它们被取消映射,因此任何后续访问都会触发页面错误。分配周围的页面也被标记为不可访问,因此任何超出分配边界的读取或写入也会触发错误。这将释放后使用、缓冲区越界和缓冲区下溢 bug 从静默的损坏者转变为立即 panic,并带有直接指向误用点的回溯。 -The cost is that each allocation now costs at least one full page -of virtual memory (plus management overhead), and every free -burns an unmapped page. For that reason, `memguard(9)` is typically -turned on for a single malloc type at a time, not for everything. +代价是每次分配现在至少消耗一个完整的虚拟内存页面(加上管理开销),每次释放都会消耗一个未映射的页面。因此,`memguard(9)` 通常一次只对一个 malloc 类型启用。 -The configuration involves two steps. First, the kernel must be -built with `options DEBUG_MEMGUARD`, which `std.debug` does not -enable by default. You add it to your kernel config: +配置涉及两个步骤。首先,内核必须用 `options DEBUG_MEMGUARD` 构建,`std.debug` 默认不启用此选项。你需要将其添加到内核配置中: ```text include "std.debug" options DEBUG_MEMGUARD ``` -and rebuild. +然后重新构建。 -Second, at runtime you tell `memguard` which malloc type to guard: +第二步,在运行时告诉 `memguard` 保护哪个 malloc 类型: ```console # sysctl vm.memguard.desc=bugdemo ``` -From that moment on, every allocation of type `bugdemo` goes -through `memguard`. Note the type string matches the name passed to -`MALLOC_DEFINE(9)` in the driver source. Typos here silently do -nothing. +从那一刻起,类型为 `bugdemo` 的每次分配都通过 `memguard` 进行。注意类型字符串要与驱动源代码中传给 `MALLOC_DEFINE(9)` 的名称匹配。此处的拼写错误会静默地什么都不做。 -You can also use `vm.memguard.desc=*` to guard everything, but as -noted, this is expensive. For a targeted bug hunt, guard only the -type you suspect. +你也可以使用 `vm.memguard.desc=*` 来保护所有内容,但如前所述,这很昂贵。对于有针对性的 bug 狩猎,只保护你怀疑的类型。 -### A memguard Session in Action +### memguard 实战会话 -Imagine `bugdemo` has a use-after-free bug: the driver frees a -buffer when its ioctl completes, but then an interrupt handler -reads from the same buffer a moment later. Without `memguard`, the -read usually succeeds because the slab allocator has not yet -reused the memory, or it returns some unrelated data that happens -to have replaced the buffer. The driver gets plausible-but-wrong -output, which corrupts some later state, which manifests much -later as a subtle bug. +假设 `bugdemo` 有一个释放后使用的 bug:驱动程序在 ioctl 完成时释放了一个缓冲区,但随后一个中断处理程序稍后又从同一缓冲区读取。没有 `memguard` 时,读取通常成功,因为 slab 分配器尚未重用该内存,或者它返回了一些碰巧替换了缓冲区的无关数据。驱动程序获得了看似合理但错误的输出,这会损坏某些后续状态,然后在很久以后才表现为一个微妙的 bug。 -With `memguard` enabled for the driver's malloc type, the same -sequence of events fires a page fault the instant the interrupt -handler dereferences the freed pointer. The fault produces a -panic with a backtrace through the interrupt handler. The panic -message identifies the faulting address as inside a `memguard` -region, and `kgdb` on the dump shows you exactly which function -dereferenced the freed memory. +当为该驱动的 malloc 类型启用 `memguard` 后,相同的事件序列会在中断处理程序解引用已释放指针的瞬间触发页面错误。该错误产生一个带有经过中断处理程序的回溯的 panic。panic 消息将错误地址标识为 `memguard` 区域内部,转储上的 `kgdb` 会准确显示哪个函数解引用了已释放的内存。 -Compare that to the days of detective work the bug would have -demanded without `memguard`, and you understand why this tool is -so valuable. +将该 bug 在没有 `memguard` 时需要数天的侦探工作与此对比,你就会理解为什么这个工具如此有价值。 -### redzone: Buffer Overrun Detection +### redzone:缓冲区越界检测 -`memguard` is heavyweight. For the narrower case of buffer -overruns and underruns, FreeBSD offers `DEBUG_REDZONE`, a lighter -debugger that adds a few guard bytes before and after each -allocation. When the allocation is freed, the guard bytes are -checked. If they have been modified, `redzone` reports the -corruption, including the stack at the time of allocation. +`memguard` 是重量级的。对于更窄的缓冲区越界和下溢情况,FreeBSD 提供了 `DEBUG_REDZONE`,一个更轻量的调试器,在每个分配前后添加几个保护字节。当分配被释放时,检查保护字节,如果被修改了,`redzone` 报告损坏,包括分配时的栈信息。 -`DEBUG_REDZONE` is added to the kernel config: +`DEBUG_REDZONE` 添加到内核配置中: ```text options DEBUG_REDZONE ``` -Unlike `memguard`, it is always active once compiled in, and it -applies to all allocations. Its overhead is memory, not time: -each allocation grows by a few bytes. +与 `memguard` 不同,它一旦编译进去就始终活跃,并适用于所有分配。它的开销是内存而非时间:每个分配增加几个字节。 -`redzone` does not catch use-after-free, because the memory it -guards is still within the original allocation. It does catch -writes that step past the intended buffer, which is a common class -of bug in drivers that compute offsets from user-provided sizes. +`redzone` 不捕获释放后使用,因为它保护的内存仍在原始分配之内。它确实能捕获越出预期缓冲区的写入,这是驱动程序中从用户提供的尺寸计算偏移量时常见的一类 bug。 -### Guard Pages in the VM Layer +### VM 层中的保护页 -A third mechanism, available independently of `memguard` and -`redzone`, is the use of guard pages around critical kernel -allocations. The VM system supports allocating a memory region -with inaccessible pages placed before and after it. Kernel thread -stacks use this mechanism: the page below each stack is -unmapped, so a runaway recursion faults instead of overwriting -the adjacent allocation. +第三种机制,独立于 `memguard` 和 `redzone`,是在关键内核分配周围使用保护页。VM 系统支持分配一个在前后放置不可访问页面的内存区域。内核线程栈使用这种机制:每个栈下面的页面是未映射的,因此失控的递归会触发页面错误而不是覆盖相邻分配。 -Drivers that allocate stack-like objects can use `kmem_malloc(9)` -with the right flags, or can set up guard pages manually through -`vm_map_find(9)`. In practice, driver code rarely does this -directly; the mechanism is more commonly used by subsystems that -manage their own memory regions. But it is useful to know that -the capability is there, because you may see it in kernel -messages and want to understand what it means. +分配栈式对象的驱动程序可以使用带正确标志的 `kmem_malloc(9)`,或通过 `vm_map_find(9)` 手动设置保护页。实际上,驱动代码很少直接这样做;这种机制更常被管理自己内存区域的子系统使用。但了解这种能力是有用的,因为你可能会在内核消息中看到它并想要理解它的含义。 -### Leak Detection in Practice +### 实践中的泄漏检测 -Leaks are the quietest class of memory bug. They produce no -crashes, no faults, no assertions. The only symptom is that -memory usage grows over time. FreeBSD gives you a few tools for -finding them. +泄漏是最安静的一类内存 bug。它们不产生崩溃、不产生页面错误、不产生断言失败。唯一的症状是内存使用量随时间增长。FreeBSD 提供了几种查找它们的工具。 -The first, as we saw, is `kern.malloc`. Snapshot before, run the -workload, snapshot after, and look for types whose `inuse` grew -and did not shrink. This is crude but effective for driver leaks. +第一种,正如我们看到的,是 `kern.malloc`。之前拍一张快照,运行负载,之后拍一张快照,寻找 `inuse` 增长且未缩小的类型。这对驱动程序泄漏来说虽粗糙但有效。 -The second is to add counters to your driver. If every allocation -bumps a `counter(9)` and every free decrements it, a lingering -positive value at unload time tells you the driver leaked -something. A companion sysctl exposes the counter for inspection: +第二种是在驱动程序中添加计数器。如果每次分配递增一个 `counter(9)`,每次释放递减它,那么卸载时残留的正值告诉你驱动程序泄漏了东西。配套的 sysctl 暴露计数器以供检查: ```c static counter_u64_t bugdemo_inflight; @@ -2535,14 +1337,9 @@ KASSERT(counter_u64_fetch(bugdemo_inflight) == 0, (long)counter_u64_fetch(bugdemo_inflight))); ``` -This idiom, counting inflight allocations explicitly, is useful -in any subsystem that owns a pool of objects. The assertion at -unload time fires if anything leaked, giving you an immediate -report at the moment you notice the leak, not hours later. +这种显式计算进行中分配的惯用法在任何拥有对象池的子系统中都很有用。卸载时的断言在任何东西泄漏时触发,在你注意到泄漏的瞬间就给你一个即时报告,而不是数小时之后。 -The third tool is DTrace. If you know which malloc type is -leaking but not why, a DTrace script can track every allocation -and every free, accumulating the difference per stack trace: +第三种工具是 DTrace。如果你知道哪个 malloc 类型在泄漏但不知道为什么,一个 DTrace 脚本可以跟踪每次分配和每次释放,按栈跟踪累积差异: ```console dtrace -n ' @@ -2560,241 +1357,102 @@ fbt::free:entry ' ``` -After a workload, comparing the two aggregations often reveals a -code path that allocates but never frees. The stack traces point -you directly to the offending call sites. +在运行一个负载后,比较两个聚合通常能揭示一个分配但从不释放的代码路径。栈跟踪直接指向有问题的调用点。 -### When Memory Bugs Hide +### 当内存 Bug 隐藏时 -Sometimes memory bugs do not match any of these patterns. The -symptom is a panic in an unrelated subsystem, with a backtrace -that seems impossible. The driver looks fine on review; its -allocations and frees appear balanced. Yet the kernel keeps -crashing with messages about corrupt lists or invalid pointers. +有时内存 bug 不匹配这些模式中的任何一种。症状是在不相关子系统中的 panic,回溯看起来不可能。审查时驱动程序看起来没问题;分配和释放看起来是平衡的。然而内核不断崩溃,消息是关于损坏的链表或无效指针。 -The usual cause in these cases is that the driver writes past -the end of a buffer into the next allocation. The next -allocation belongs to someone else; your overrun silently -corrupts that other subsystem's data. The crash happens when -the other subsystem next touches its corrupted data, which -might be soon or might be much later. +这些情况下的常见原因是驱动程序写过了缓冲区末尾,进入下一个分配。下一个分配属于别的子系统;你的越界写入静默地损坏了那个子系统的数据。崩溃发生在另一个子系统下次触及它被损坏的数据时,这可能很快,也可能很久以后。 -For this class of bug, the diagnostic is to enable -`DEBUG_REDZONE` and watch for warnings. When `redzone` reports -that guard bytes have been modified, the stack trace it prints -for the allocation is the allocation in question, and the code -that overran it is the code that was writing into that -allocation. `redzone`'s report tells you both ends of the bug. +对于这类 bug,诊断方法是启用 `DEBUG_REDZONE` 并观察警告。当 `redzone` 报告保护字节被修改时,它为分配打印的栈跟踪就是那个被讨论的分配,而越界写入的代码就是当时正在写入该分配的代码。`redzone` 的报告告诉你 bug 的两端。 -Another trick is to enable `MALLOC_DEBUG_MAXZONES=N` with a -large N. This spreads allocations across more zones, so a -driver's allocations are less likely to share a zone with -unrelated subsystems. If the symptom disappears or changes with -more zones, it is a strong hint that the bug involves cross- -zone corruption. +另一个技巧是启用带较大 N 值的 `MALLOC_DEBUG_MAXZONES=N`。这会将分配分散到更多区域,使驱动的分配不太可能与不相关的子系统共享区域。如果症状随更多区域而消失或变化,这是 bug 涉及跨区域损坏的强烈暗示。 -### Working With DDB on Memory Bugs +### 在内存 Bug 上使用 DDB -When the kernel panics on a memory bug, entering `DDB` can help -narrow down the cause. Useful `DDB` commands include: +当内核因内存 bug 而 panic 时,进入 `DDB` 可以帮助缩小原因范围。有用的 `DDB` 命令包括: -- `show malloc` dumps `malloc(9)` state. -- `show uma` dumps UMA zone state. -- `show vmochk` runs a consistency check on the VM object tree. -- `show allpcpu` shows per-CPU state. +- `show malloc` 转储 `malloc(9)` 状态。 +- `show uma` 转储 UMA 区域状态。 +- `show vmochk` 对 VM 对象树运行一致性检查。 +- `show allpcpu` 显示每 CPU 状态。 -These commands produce output that helps correlate a crash with -the state of the allocators at the moment of the crash. They do -not replace `kgdb` analysis, but they can be faster to consult -when you are already in `DDB`. +这些命令产生的输出有助于将崩溃与崩溃瞬间分配器的状态关联起来。它们不能替代 `kgdb` 分析,但在你已经处于 `DDB` 中时可以更快地查阅。 -### Reality Check on Memory Debuggers +### 内存调试器的现实检验 -`memguard`, `redzone`, and their relatives are effective. They are -also disruptive. They change allocator behavior, they slow the -kernel down, and some of them consume memory aggressively. -Leaving them on in production is not a good idea. +`memguard`、`redzone` 及其相关工具是有效的。但它们也具有破坏性。它们改变分配器行为、减慢内核速度,有些还大量消耗内存。在生产环境中让它们持续开启不是好主意。 -The right use is targeted. When a bug presents, enable the -appropriate debugger, reproduce the bug, capture the evidence, -and then turn the debugger off. Most of your driver development -happens on a kernel with `INVARIANTS` and `WITNESS` but without -`DEBUG_MEMGUARD`. `DEBUG_MEMGUARD` comes out when you are -actively chasing a memory bug and goes away when you are done. +正确的用法是有针对性的。当 bug 出现时,启用适当的调试器,重现 bug,捕获证据,然后关闭调试器。你大部分驱动程序开发都在带有 `INVARIANTS` 和 `WITNESS` 但不带 `DEBUG_MEMGUARD` 的内核上进行。`DEBUG_MEMGUARD` 在你积极追捕内存 bug 时拿出来,完成时收起来。 -One last consideration. Some memory debuggers, notably -`memguard`, change the observable behavior of the allocator in -ways that can mask bugs. If a driver depends on two allocations -being adjacent in memory (which it never should, but sometimes -does as an accidental invariant), `memguard` will break that -dependency and make the bug go away. This does not mean the bug -is fixed; it means the bug is now latent. Always re-test -without `memguard` after a fix, to make sure the fix is real and -not an artifact of the debugger's presence. +最后一点考虑。某些内存调试器,特别是 `memguard`,会以可能掩盖 bug 的方式改变分配器的可观察行为。如果驱动程序依赖两个分配在内存中相邻(它永远不应该这样做,但有时会作为意外不变式),`memguard` 会打破这种依赖并使 bug 消失。这并不意味着 bug 被修复了;它意味着 bug 现在是潜在的。始终在修复后不使用 `memguard` 重新测试,以确保修复是真实的而非调试器存在的假象。 ### 内存部分总结 -Memory bugs are the quiet killers of driver code. The patience -to find them is built on a small, focused set of tools. -`memguard(9)` catches use-after-free and buffer overrun -directly. `redzone` catches overruns with less overhead. The -`kern.malloc` and UMA sysctls expose the allocator state that -normal code cannot see. And the discipline of counting inflight -allocations in your own driver catches leaks at unload time. -Put these together, and a class of bug that used to take days -to find can be made to announce itself in minutes. +内存 bug 是驱动代码中的静默杀手。找到它们的耐心建立在一小套聚焦的工具之上。`memguard(9)` 直接捕获释放后使用和缓冲区越界。`redzone` 以更低的开销捕获越界。`kern.malloc` 和 UMA sysctl 暴露正常代码无法看到的分配器状态。在驱动程序自身中计算进行中分配的纪律在卸载时捕获泄漏。把这些放在一起,一类过去需要数天才能找到的 bug 可以在几分钟内自我暴露。 -With the major technical tools now covered, we turn to the -discipline of using them safely, particularly on systems where -other people are watching. That is the content of Section 7. +主要技术工具现已涵盖,我们可以转向安全使用它们的纪律,特别是在其他人正在关注的系统上。这是第 7 节的内容。 ## 7. 安全调试实践 -Every tool we have learned in this chapter has a cost, and every cost -has a context in which it is acceptable. A debug kernel on a -development VM is a small price for catching bugs early. The same -debug kernel on a production server is a disaster in slow motion. -Knowing which tools to reach for in which context is part of what -separates a competent driver author from a dangerous one. +本章学到的每一种工具都有成本,而每种成本都有其可接受的上下文。开发虚拟机上的调试内核是为尽早捕获 bug 付出的小代价。生产服务器上同样的调试内核则是一场慢动作灾难。知道在什么上下文中选择什么工具,是将胜任的驱动程序作者与危险的驱动程序作者区分开来的因素之一。 -This section collects the practices that keep you out of trouble: -the conventions for using each tool safely, the signs that you are -about to make a mistake, and the mindset that helps you work with -discipline when the stakes are high. +本节汇集了让你远离麻烦的实践:安全使用每种工具的惯例、你即将犯错的信号,以及在风险很高时帮助你有纪律地工作的心态。 ### 开发环境与生产环境的区分 -The most important distinction in safe debugging is between a -development system, where you can crash the kernel freely, and a -production system, where you cannot. +安全调试中最重要的区分是开发系统和生产系统之间的区分。开发系统上你可以随意使内核崩溃;生产系统上则不行。 -On a development system, everything in this chapter is fair game. -Deliberately trigger panics. Enable `DEBUG_MEMGUARD`. Load and -unload the driver repeatedly. Attach `kgdb` to the live kernel. -Run DTrace scripts that collect megabytes of data. The worst that -can happen is that you reboot the VM, which is measured in -seconds. +在开发系统上,本章的一切都是可以做的。故意触发 panic。启用 `DEBUG_MEMGUARD`。反复加载和卸载驱动程序。将 `kgdb` 附加到运行的内核上。运行收集数兆字节数据的 DTrace 脚本。最坏的情况不过是重启虚拟机,这只消几秒钟。 -On a production system, the opposite posture applies. You do not -enable debug options unless you have a specific, targeted reason. -You do not load experimental drivers. You do not run DTrace -scripts that might destabilize the probe framework. You do not -break into `DDB` on a live system. Every intervention is -preceded by a clear answer to "what do I do if this goes wrong?" +在生产系统上,则采取相反的态度。除非你有具体、有针对性的理由,否则不启用调试选项。不加载实验性驱动程序。不运行可能使探针框架不稳定的 DTrace 脚本。不在运行的系统上闯入 `DDB`。每次干预之前都要清楚回答"如果出了问题怎么办?" -The discipline of keeping these two environments separate is the -single most effective way to avoid accidentally breaking -production. Have a development VM, keep the production kernel on -a different partition, and never confuse the two. +保持这两种环境分离的纪律是避免意外破坏生产的最有效方法。准备一台开发虚拟机,将生产内核放在不同的分区上,永远不要混淆两者。 ### 在生产环境中安全的操作 -A surprising amount of the debugging toolkit is actually safe in -production, if used carefully. Here is a partial list. +令人惊讶的是,调试工具包中相当多的部分在生产环境中实际上是安全的,只要谨慎使用。以下是不完整的列表。 -DTrace scripts are generally safe in production. The DTrace -framework is specifically designed with safety guarantees: probe -actions cannot loop indefinitely, cannot allocate arbitrary -memory, and cannot dereference arbitrary pointers without -falling into a well-defined recovery path. You can run DTrace -aggregations on a busy server without bringing it down. The -caveats are that very high-frequency probes can consume -significant CPU (a probe on every packet in a network driver is -unlikely to be free), and that DTrace output can fill filesystem -space if not rate-limited. +DTrace 脚本在生产环境中通常是安全的。DTrace 框架在设计上明确包含了安全保证:探针动作不能无限循环、不能分配任意内存、不能在没有进入明确定义恢复路径的情况下解引用任意指针。你可以在繁忙的服务器上运行 DTrace 聚合而不会使其宕机。注意事项是极高频探针会消耗大量 CPU(网络驱动程序中每个包触发一次的探针不太可能是免费的),而且如果不限速,DTrace 输出可能填满文件系统空间。 -`ktrace(1)` on a specific process is safe, though it writes to a -file that grows unbounded. Set a size limit or watch the file. +`ktrace(1)` 对特定进程是安全的,不过它会写入一个无限增长的文件。设置大小限制或监视文件大小。 -`ktr(9)` is safe if the relevant classes are already compiled -in. Enabling a class through `sysctl debug.ktr.mask=` is safe. -Compiling in a new class requires a kernel rebuild, which is -a development activity. +`ktr(9)` 在相关类已编译进去时是安全的。通过 `sysctl debug.ktr.mask=` 启用类是安全的。编译新类需要重建内核,这是开发活动。 -Reading sysctls is always safe. `kern.malloc`, `vm.uma`, -`hw.ncpu`, `debug.kdb.*`, and all the others expose state -without changing anything. A production system with a sick -driver can be interrogated extensively through sysctl alone. +读取 sysctl 始终是安全的。`kern.malloc`、`vm.uma`、`hw.ncpu`、`debug.kdb.*` 以及所有其他 sysctl 暴露状态而不改变任何东西。一个有问题驱动的生产系统可以仅通过 sysctl 就进行大量探查。 ### 在生产环境中不安全的操作 -A shorter list, but an important one. +更短的列表,但很重要。 -Panics are unsafe. Deliberately crashing a production server is -only acceptable as a last resort when the server is already -irrecoverably damaged and a dump is the best path to -understanding the cause. `sysctl debug.kdb.panic=1` triggers an -immediate panic and dump. Do not do this lightly. +Panic 是不安全的。故意崩溃一台生产服务器只有在服务器已经不可恢复且转储是理解原因的最佳途径时才可接受。`sysctl debug.kdb.panic=1` 触发立即 panic 和转储。不要轻易这样做。 -Breaking into `DDB` on a production console is unsafe. The -entire kernel stops while you are in `DDB`. User processes -freeze. Network connections time out. Real-time work halts. -Unless the alternative is worse (often the case during a -catastrophic crash), stay out of `DDB` on production. +在生产控制台上闯入 `DDB` 是不安全的。当你在 `DDB` 中时整个内核停止。用户进程冻结。网络连接超时。实时工作停止。除非替代方案更糟(通常在灾难性崩溃期间是这种情况),否则不要在生产环境中进入 `DDB`。 -`DEBUG_MEMGUARD` on all allocation types is unsafe. Memory use -balloons. Performance drops sharply. Memory-intensive workloads -may fail outright. If you absolutely must use `memguard` in -production, scope it to one malloc type at a time and monitor -memory use. +对所有分配类型启用 `DEBUG_MEMGUARD` 是不安全的。内存使用量膨胀。性能急剧下降。内存密集型工作负载可能完全失败。如果你绝对必须在使用中环境使用 `memguard`,将范围限制为一次一个 malloc 类型并监控内存使用。 -Loadable kernel modules are a risk. Loading or unloading a -module touches kernel state. A buggy module can crash the -kernel at load time, unload time, or any time in between. On -production, load only modules that have been tested in the -development environment against the same kernel. +可加载内核模块是有风险的。加载或卸载模块会触及内核状态。有 bug 的模块可能在加载时、卸载时或其间任何时间使内核崩溃。在生产环境上,只加载在开发环境中针对相同内核测试过的模块。 -Overly aggressive DTrace scripts can destabilize the system. -Aggregations that record stack traces produce memory pressure. -Probes with side effects can interact with the workload in -unexpected ways. Run DTrace scripts with explicit time limits -and review the aggregations carefully before leaving them -running. +过于激进的 DTrace 脚本可能使系统不稳定。记录栈跟踪的聚合会产生内存压力。有副作用的探针可能与工作负载以意想不到的方式交互。运行 DTrace 脚本时设置明确的时间限制,并在让它们持续运行之前仔细审查聚合。 -### Capturing Evidence on Production Systems +### 在生产系统上捕获证据 -When something goes wrong in production and the bug is rare or -difficult to reproduce in development, the challenge is to -capture enough evidence to diagnose the problem, without -destabilizing the running service. Several strategies help. +当生产环境中出问题且 bug 罕见或在开发环境中难以重现时,挑战在于在不破坏运行服务的情况下捕获足够的证据来诊断问题。几种策略有所帮助。 -First, start with passive observation. `sysctl`, `vmstat -m`, -`netstat -m`, `dmesg`, and the various `-s` system statistics -commands can be run while the system is live and cost almost -nothing. If the bug produces symptoms visible in these reports, -capture the reports periodically. +首先,从被动观察开始。`sysctl`、`vmstat -m`、`netstat -m`、`dmesg` 以及各种 `-s` 系统统计命令可以在系统运行时执行且几乎不花任何成本。如果 bug 在这些报告中产生可见症状,定期捕获报告。 -Second, use DTrace with strict bounds. A script that runs for -sixty seconds and exits produces a snapshot without leaving a -standing risk. Aggregations are particularly well suited to -this style: they collect statistics over a window, print them, -and stop. +其次,使用有严格边界的 DTrace。运行六十秒然后退出的脚本产生一个快照而不留下持续风险。聚合特别适合这种风格:它们在一个时间窗口内收集统计、打印结果然后停止。 -Third, if a crash dump is needed and the system has not yet -crashed, the safest approach is to wait for the crash. Modern -dump mechanisms are designed to capture the kernel state at the -moment of panic; a dump triggered manually is useful only when -you know the system is already irrecoverable. +第三,如果需要崩溃转储但系统尚未崩溃,最安全的方法是等待崩溃发生。现代转储机制设计为在 panic 瞬间捕获内核状态;手动触发的转储只有在你知道系统已经不可恢复时才有用。 -Fourth, when a crash does happen, work on the dump, not the -live system. A reboot into a fresh kernel restores service, -while the dump remains available for offline analysis at -leisure. The discipline of "reboot fast, analyze later" is -often the right trade-off on production hardware. +第四,当崩溃确实发生时,在转储上工作,而非运行中的系统。重启到新内核恢复服务,而转储仍然可供闲暇时离线分析。"快速重启,稍后分析"的纪律在生产硬件上通常是正确的权衡。 -### Using log(9) Over printf for Diagnostics +### 使用 log(9) 代替 printf 进行诊断 -Throughout the chapter we have used `printf` as a shorthand for -kernel-side logging, which is how it is commonly presented in -textbooks. On a production system you should prefer `log(9)`, -which writes through the `syslogd(8)` facility rather than -directly to the console. The reasons are practical: console -output is unbuffered and slow, `log(9)` is rate-limited and -buffered, and `log(9)` ends up in `/var/log/messages` where it -is available to log-analysis tools. +贯穿本章我们一直将 `printf` 用作内核端日志记录的简写,这也是教科书中的常见呈现方式。在生产系统上你应该优先使用 `log(9)`,它通过 `syslogd(8)` 设施写入而非直接写入控制台。原因是实际的:控制台输出是无缓冲且缓慢的,`log(9)` 是限速且缓冲的,`log(9)` 最终进入 `/var/log/messages`,日志分析工具可以使用。 -The API is in `/usr/src/sys/sys/syslog.h` and -`/usr/src/sys/kern/subr_prf.c`. Usage: +API 位于 `/usr/src/sys/sys/syslog.h` 和 `/usr/src/sys/kern/subr_prf.c`。用法: ```c #include @@ -2802,14 +1460,9 @@ The API is in `/usr/src/sys/sys/syslog.h` and log(LOG_WARNING, "bugdemo: unexpected state %d\n", sc->state); ``` -The priority level (`LOG_DEBUG`, `LOG_INFO`, `LOG_NOTICE`, -`LOG_WARNING`, `LOG_ERR`, `LOG_CRIT`, `LOG_ALERT`, `LOG_EMERG`) -lets `syslogd` route messages differently. +优先级(`LOG_DEBUG`、`LOG_INFO`、`LOG_NOTICE`、`LOG_WARNING`、`LOG_ERR`、`LOG_CRIT`、`LOG_ALERT`、`LOG_EMERG`)让 `syslogd` 以不同方式路由消息。 -A common extension is rate-limited logging, so a sick driver -does not flood `/var/log/messages` with millions of entries per -second. FreeBSD provides the `ratecheck(9)` primitive that you -can wrap around your own `log` calls: +一种常见的扩展是限速日志,这样一个有问题的驱动程序不会以每秒数百万条的速度淹没 `/var/log/messages`。FreeBSD 提供了 `ratecheck(9)` 原语,你可以将其包装在自己的 `log` 调用周围: ```c #include @@ -2821,166 +1474,74 @@ if (ratecheck(&lastlog, &interval)) log(LOG_WARNING, "bugdemo: error (rate-limited)\n"); ``` -`ratecheck(9)` returns nonzero once per interval, suppressing -repeated logs in between. The technique is essential for any -driver that might observe the same error repeatedly. +`ratecheck(9)` 每个时间间隔返回一次非零值,在间隔之间抑制重复日志。这种技术对于可能反复观察同一错误的任何驱动程序来说都是必不可少的。 -### Do Not Mix Debug and Release Kernels in One Fleet +### 不要在集群中混合调试和发布版内核 -A subtle trap is to run a mix of debug and release kernels in a -production fleet. The intuition is that debug kernels give you -better diagnostics if a bug appears. The reality is that a debug -kernel performs noticeably worse than a release kernel, has -different memory usage, and can exhibit different timing. If a -bug is sensitive to those factors (and many concurrency bugs -are), running mixed kernels guarantees that your reproduction -environment does not match your production environment. +一个微妙的陷阱是在生产集群中运行混合的调试和发布版内核。直觉是调试内核在 bug 出现时能提供更好的诊断。现实是调试内核的性能明显低于发布版内核,有不同的内存使用,并可能表现出不同的时序。如果 bug 对这些因素敏感(许多并发 bug 正是如此),运行混合内核保证你的重现环境不匹配生产环境。 -The right approach is uniform: either the whole fleet runs -release kernels (and you debug on development hardware), or the -whole fleet runs debug kernels (and you accept the overhead). -Mixed deployments are a third option only for very controlled -experiments. +正确的做法是统一的:要么整个集群运行发布版内核(你在开发硬件上调试),要么整个集群运行调试内核(你接受开销)。混合部署仅在非常受控的实验中才是第三种选择。 -### Working With a Recovery Plan +### 制定恢复计划 -Before running any risky debugging action, know your recovery -plan. If the system hangs, how will you recover? Is there an IPMI -interface that can issue a hardware reset? Is there a second -administrator who can cycle the power if needed? How much data -loss is acceptable? +在执行任何有风险的调试操作之前,了解你的恢复计划。如果系统挂起,你将如何恢复?是否有可以发出硬件重置的 IPMI 接口?是否有另一位管理员可以在需要时循环电源?多少数据丢失是可接受的? -A good recovery plan is two steps. First, get the system back up -quickly. Second, capture the evidence (dump, logs) for offline -analysis. These two steps often involve different people or -different timescales, and thinking through both in advance -prevents panic in the moment. +一个好的恢复计划是两步。首先,快速让系统恢复运行。其次,捕获证据(转储、日志)供离线分析。这两步通常涉及不同的人或不同的时间尺度,提前想清楚这两步可以防止事到临头时的慌乱。 -### Keep a Debug Journal +### 保持调试日志 -When debugging a hard bug, a written record is invaluable. Each -entry should include: +在追踪一个棘手的 bug 时,书面记录是无价的。每条记录应包含: -- What hypothesis you were testing. -- What action you took. -- What result you observed. -- What the result rules in or out. +- 你在测试什么假设。 +- 你采取了什么行动。 +- 你观察到了什么结果。 +- 结果排除了什么或确认了什么。 -This sounds pedantic but is genuinely useful. A long debugging -session involves dozens of micro-hypotheses, and losing track of -which ones you have tested wastes enormous time. The written -record also helps when you come back to the bug after a weekend, -or when you hand it off to a colleague. +这听起来学究气,但确实有用。漫长的调试会话涉及数十个微假设,失去哪些已经测试过的跟踪会浪费大量时间。书面记录在你周末回来继续追查 bug 时、或将它交给同事时也有帮助。 -For a driver bug that goes across multiple systems, a shared -record (bug tracker, wiki, or an internal ticket) is even more -valuable. Each person who touches the bug can see what the -others have already tried, and no one reruns the same experiment -twice. +对于跨多个系统的驱动程序 bug,共享记录(bug 追踪器、wiki 或内部工单)更有价值。每个接触该 bug 的人都能看到其他人已经尝试了什么,没有人重复运行同一个实验。 -### Practicing on Your Own Drivers +### 在你自己的驱动程序上练习 -One habit that pays off over time is to keep a deliberately -buggy version of your driver around for practice. Every time -you find an interesting bug in real work, add a variant of it to -your practice driver. Then, periodically, run through the -practice driver with fresh eyes and make sure you can still -find the bugs using the tools of this chapter. This builds -muscle memory that is invaluable when a real bug appears under -time pressure. +一个长期有效的习惯是保留一个故意有 bug 的驱动程序版本用于练习。每次你在实际工作中发现一个有趣的 bug,将它的变体添加到练习驱动程序中。然后定期用新的眼光运行练习驱动程序,确保你仍然能用本章的工具找到那些 bug。这会建立肌肉记忆,在真正的时间压力下 bug 出现时是无价的。 -The `bugdemo` driver we have been using throughout this chapter -is one starting point for such a practice driver. Fork it, add -your own bugs, and use it to stay sharp. +我们贯穿本章一直在使用的 `bugdemo` 驱动程序就是这样一个练习驱动程序的起点。派生它,添加你自己的 bug,用它来保持敏锐。 -### Knowing When to Stop +### 知道何时停下来 -A final piece of safe debugging wisdom is knowing when to stop. -Not every bug needs to be hunted to the last instruction. If a -bug is rare, has a workaround, and the cost of finding its root -cause is measured in days, there is sometimes a case for -documenting the workaround and moving on. This is a judgment -call, not a rule, but the ability to make the call is part of -professional maturity. +安全调试智慧的最后一部分是知道何时停下来。并非每个 bug 都需要追查到最后一条指令。如果一个 bug 很罕见、有变通方法、且找到根因的成本以天计,有时有理由记录变通方法然后继续前进。这是一个判断,而非规则,但做出这种判断的能力是专业成熟度的一部分。 -The opposite mistake (declaring victory too early, accepting a -surface fix that does not address the underlying defect) is -also common. The symptom is a bug that keeps coming back in -new forms. When a "fix" does not produce a stable result, -something deeper is wrong, and more investigation is called for. +相反的错误(过早宣布胜利,接受不解决底层缺陷的表面修复)也很常见。症状是 bug 不断以新形式回来。当一个"修复"不能产生稳定的结果时,说明更深层的东西出了问题,需要更多调查。 -Between these extremes is the healthy zone where you invest -time proportional to the importance of the bug. Kernel -development rewards patience, but it also rewards pragmatism. -The tools of this chapter exist to make the investment -efficient, not to make every bug a multi-day research project. +在这两个极端之间是健康的区域,你投入与 bug 重要性成正比的时间。内核开发回报耐心,但也回报务实。本章的工具旨在使投入高效,而非让每个 bug 都成为耗时数天的研究项目。 -With safe practices established, we can turn to the last major -topic of the chapter: what to do after a debugging session -that found something serious, and how to make the driver more -resilient against the next time something similar goes wrong. +有了安全实践的建立,我们可以转向本章最后一个主要话题:在一次发现严重问题的调试会话之后该做什么,以及如何使驱动程序对下一次类似问题更具韧性。 ## 8. 调试会话后的重构:恢复与韧性 -A hard-won debugging victory is not the end of the work. Finding -the bug is finding evidence. The real question is: what does -the evidence tell us about the driver, and how should the driver -change in response? +来之不易的调试胜利不是工作的结束。找到 bug 是找到证据。真正的问题是:证据告诉了我们关于驱动程序的什么,驱动程序应该如何改变以回应? -A common failure mode is to patch the immediate symptom and move -on. The patch makes the test pass, the crash stop, the corruption -vanish. But the underlying weakness that allowed the bug in the -first place is still there, lurking. The next subtle change in -surrounding code, or the next new environment, finds the same -weakness and produces the next bug. +一种常见的失败模式是修补即时症状然后继续。补丁让测试通过、让崩溃停止、让损坏消失。但首先允许 bug 进入的底层弱点仍然在那里,潜伏着。周围代码的下一次微妙变化,或下一个新环境,会发现同样的弱点并产生下一个 bug。 -This section is about resisting that failure mode. We will walk -through a small set of techniques for using a debugging result to -strengthen the driver, not just to fix the particular bug. +本节就是关于抵制这种失败模式的。我们将走一小套技术,用调试结果来加强驱动程序,而不仅仅是修复特定的 bug。 ### 将Bug视为消息 -Every bug carries a message about the design. A use-after-free -says "the driver's ownership model for this buffer is unclear." -A deadlock says "the driver's lock order is not explicitly -documented or enforced." A memory leak says "the driver's -lifecycle for this object is incomplete." A panic in `attach` -says "the driver's error recovery during initialization is -weak." A race condition says "the driver's assumptions about -thread context are not strict enough." +每个 bug 都携带着关于设计的信息。释放后使用说的是"驱动程序对这个缓冲区的所有权模型不清晰"。死锁说的是"驱动程序的锁序没有显式记录或执行"。内存泄漏说的是"驱动程序对这个对象的生命周期管理不完整"。`attach` 中的 panic 说的是"驱动程序在初始化期间的错误恢复很弱"。竞态条件说的是"驱动程序对线程上下文的假设不够严格"。 -When you find a bug, spend a few minutes asking what the bug is -telling you about the design. The specific defect is usually a -symptom of a broader pattern, and understanding the pattern -makes future bugs easier to prevent. +当你找到一个 bug 时,花几分钟问问这个 bug 在告诉你关于设计的什么。具体的缺陷通常是更广泛模式的症状,理解模式使未来的 bug 更容易预防。 ### 加强不变量 -One concrete response to a bug is to add assertions that would -have caught it sooner. If a use-after-free was the bug, add a -`KASSERT` somewhere in the path that confirms the buffer is -still valid when used. If a lock order was violated, add a -`mtx_assert(9)` at the point where the violation occurred. If -a structure field was corrupted, add a `CTASSERT` on its -alignment or a runtime check on its value. +对 bug 的一种具体回应是添加能更早捕获它的断言。如果 bug 是释放后使用,在确认缓冲区使用时仍然有效的路径上添加 `KASSERT`。如果违反了锁序,在违反发生的点添加 `mtx_assert(9)`。如果结构字段被损坏,在其对齐上添加 `CTASSERT` 或对其值添加运行时检查。 -The goal is not to duplicate every check with an assertion, but -to convert each bug into one or two new invariants that make the -same class of bug impossible in the future. Over time, the -driver accumulates a set of defensive checks that reflect its -actual behavior, documented in code rather than in your head. +目标不是用断言复制每个检查,而是将每个 bug 转化为一两个新的不变式,使同一类 bug 在未来不可能发生。随着时间推移,驱动程序积累了一套反映其实际行为的防御性检查,以代码而非以你脑海中的方式记录。 -### Documenting the Ownership Model +### 记录所有权模型 -Another common response is to clarify documentation. Many bugs -arise because ownership of a resource (who allocated it, who is -responsible for freeing it, when is it safe to access) is -implicit. Writing a few lines of comment that explicitly state -the ownership rules makes the rules visible to the next reader, -and often forces you to confront cases where the rules were not -actually consistent. +另一种常见回应是澄清文档。许多 bug 的产生是因为资源所有权(谁分配了它、谁负责释放它、何时可以安全访问)是隐式的。写几行注释显式声明所有权规则使规则对下一个读者可见,并且经常迫使你面对规则实际上并不一致的情况。 -For example, a comment like: +例如,这样的注释: ```c /* @@ -2992,162 +1553,73 @@ For example, a comment like: struct bugdemo_buffer *sc_buffer; ``` -This comment is not decorative. It is a statement of the -invariants that the driver will enforce. If a future bug -violates the invariants, the comment is a reference point for -understanding what went wrong. +这条注释不是装饰性的。它是驱动程序将执行的不变式声明。如果未来的 bug 违反了这些不变式,注释就是理解出了什么问题的参考点。 -### Narrowing the API Surface +### 收窄 API 表面 -A third response is to narrow the API. If the bug was caused -because a function was called in a context where it should not -have been, can the function be made private, so that it is -only called from contexts where it is safe? If a state was -reached through a path that should not have existed, can the -state be made unreachable? +第三种回应是收窄 API。如果 bug 是因为函数在不应该被调用的上下文中被调用了,能否将函数设为私有,使它只在安全的上下文中被调用?如果某个状态通过不应该存在的路径到达了,能否使该状态不可达? -The principle is that every external entry point into a driver -is a surface for bugs. Reducing the surface, by making -functions internal, by hiding state behind accessors, by -combining related operations into atomic transactions, makes the -driver harder to misuse. +原则是驱动程序的每个外部入口点都是 bug 的攻击面。通过将函数设为内部函数、将状态隐藏在访问器后面、将相关操作合并为原子事务来减少表面,使驱动程序更难被误用。 -This is not about ideological minimalism. It is about recognizing -that surface area is proportional to bug risk, and that many bugs -can be prevented by the simple expedient of not exposing the -thing that was misused. +这不是关于教条式的极简主义。这是关于认识到表面积与 bug 风险成正比,许多 bug 可以通过不让暴露被误用的东西来预防。 -### Hardening the Unload Path +### 加固卸载路径 -Unload is a frequently underhardened path in drivers. The -attach path is usually well tested; the unload path is usually -not. This is a major source of bugs: a driver that works -perfectly in long-running use might crash on `kldunload`. +卸载是驱动程序中经常未被充分加固的路径。`attach` 路径通常测试良好;卸载路径通常则不然。这是 bug 的主要来源:一个在长期运行中完美工作的驱动程序可能在 `kldunload` 时崩溃。 -A good unload path satisfies several invariants. Every object -allocated in attach is freed. Every thread spawned by the -driver has exited. Every timer is cancelled. Every callout is -drained. Every taskqueue has finished its pending work. Every -device node is destroyed before the memory that supports it is -freed. +好的卸载路径满足几个不变式。在 `attach` 中分配的每个对象都被释放。驱动程序产生的每个线程都已退出。每个定时器都已取消。每个 callout 都已排干。每个 taskqueue 都已完成其待处理工作。每个设备节点在支持它的内存被释放之前都被销毁。 -After a bug in an unload path, audit the entire unload -function against this checklist. Each item is an invariant -that the driver should maintain, and violations are common. +在卸载路径出现 bug 后,对照此清单审计整个卸载函数。每一项都是驱动程序应维护的不变式,违反是常见的。 ### 韧性驱动的形态 -Putting these habits together, what does a resilient driver -look like? A few traits stand out. +把这些习惯放在一起,一个有韧性的驱动程序是什么样的?几个特征很突出。 -Its locking is explicit. Every shared data structure is -protected by a named lock, and every function that accesses -the structure has either an assertion that the lock is held or -a documented reason why the lock is not needed. Lock orders -are documented in comments at each site of multi-lock -acquisition. `WITNESS` produces no warnings during normal -operation. +它的加锁是显式的。每个共享数据结构都由一个命名的锁保护,访问该结构的每个函数要么有一个断言说锁已被持有,要么有一个文档说明为什么不需要锁。锁序在每次多锁获取处的注释中记录。`WITNESS` 在正常操作中不产生警告。 -Its error handling is complete. Every allocation has a -corresponding free. Every `attach` has a complete `detach`. Every -path through the code cleans up after itself on failure. -Partial states do not linger. The driver does not get stuck -in half-initialized or half-torn-down states. +它的错误处理是完整的。每次分配都有对应的释放。每个 `attach` 都有完整的 `detach`。代码中的每条路径在失败时都能自行清理。部分状态不会残留。驱动程序不会卡在半初始化或半拆除的状态。 -Its invariants are expressed in code. Preconditions are -checked with `KASSERT` at function entry. Structural -invariants are checked with `CTASSERT` at compile time. -State transitions are verified with explicit checks. +它的不变量以代码表达。前置条件在函数入口用 `KASSERT` 检查。结构不变量在编译时用 `CTASSERT` 检查。状态转换用显式检查验证。 -Its observability is built in. Counters expose allocation -and error rates. SDT probes fire at key events. Sysctls -expose enough state that an operator can inspect the driver -without a debugger. The driver tells you what it is doing. +它的可观测性是内置的。计数器暴露分配和错误率。SDT 探针在关键事件触发。sysctl 暴露足够的状态,使操作员无需调试器就能检查驱动程序。驱动程序告诉你它在做什么。 -Its error messages are useful. `log(9)` messages include -the subsystem name, the specific error, and enough context -to locate the problem. They are rate-limited. They do not -log spurious warnings that train the operator to ignore -them. +它的错误消息是有用的。`log(9)` 消息包含子系统名称、特定错误和足够的上下文来定位问题。它们是限速的。它们不会记录训练操作员忽略它们的虚假警告。 -These traits are not free. They take time to implement and -discipline to maintain. But once a driver has them, the cost -of future bugs drops dramatically, because bugs are caught -earlier, diagnosed more easily, and fixed more definitively. +这些特征不是免费的。它们需要时间来实现和纪律来维护。但一旦驱动程序拥有它们,未来 bug 的成本就会急剧下降,因为 bug 被更早捕获、更容易诊断、更确定地修复。 -### Revisiting the bugdemo Driver +### 重访 bugdemo 驱动程序 -By the end of the chapter's labs, we will have applied many -of these ideas to the `bugdemo` driver. What starts out as a -handful of deliberately broken code paths grows, through -iteration, into a driver with assertions at every key point, -counters on every operation, SDT probes on every interesting -event, and an unload path that passes scrutiny. The -trajectory is deliberately designed to mirror the trajectory -of a real driver as it matures. +到本章实验结束时,我们将对 `bugdemo` 驱动程序应用许多这样的想法。最初只有少数几个故意破坏的代码路径,通过迭代,逐渐成长为一个在每个关键点有断言、每个操作有计数器、每个有趣事件有 SDT 探针、卸载路径经得起审查的驱动程序。这个轨迹是刻意设计的,用于映射真实驱动程序的成熟轨迹。 -### Closing the Refactoring Loop +### 关闭重构循环 -A last thought on refactoring. Every time you modify a driver -in response to a bug, you are taking a small risk that the -modification introduces a new bug. This risk is unavoidable but -manageable. A few practices help. +关于重构的最后一个想法。每次你因 bug 而修改驱动程序,你都在承担修改引入新 bug 的小风险。这种风险不可避免但可控。几种做法有帮助。 -First, isolate the change. Make the smallest modification that -addresses the root cause, and commit it separately from -cosmetic changes. If something regresses, the blame is easy to -assign. +首先,隔离变更。做出解决根因的最小修改,并将其与外观性变更分开提交。如果出现回归,归因很容易。 -Second, add a test. If the bug was triggered by a specific -sequence of ioctls, add a small test program that runs that -sequence and verifies the correct result. Keep the test in your -repository. A test suite that grows with each bug becomes an -asset over years. +其次,添加测试。如果 bug 是由特定的 ioctl 序列触发的,添加一个运行该序列并验证正确结果的小测试程序。将测试保留在你的仓库中。随每个 bug 增长的测试套件会随着时间推移成为一项资产。 -Third, run the existing tests. If the driver has any automated -tests at all, run them after a fix. Surprisingly many -regressions are caught this way, even with a small test suite. +第三,运行现有测试。如果驱动程序有任何自动化测试,在修复后运行它们。令人惊讶的是,即使测试套件很小,这种方式也能捕获很多回归。 -Fourth, note the lesson. In your debug journal or commit -message, write a brief note about what the bug revealed about -the driver's design. The note is a gift to your future self, -who will encounter similar patterns. +第四,记录教训。在调试日志或提交消息中,简要记录 bug 揭示的驱动程序设计问题。这条记录是给未来自己的礼物,你以后会遇到类似的模式。 -With these habits in place, debugging becomes a cycle of -discovery rather than a string of firefights. Each bug teaches -something, each lesson strengthens the driver, and each -strengthened driver becomes easier to work with. The tools of -this chapter are the means by which that cycle turns. +有了这些习惯,调试变成了一个发现的循环而非一连串的救火。每个 bug 都教授一些东西,每个教训都加强驱动程序,每个加强的驱动程序都变得更容易使用。本章的工具就是使这个循环转动的手段。 -With the conceptual material behind us, we can move into the -hands-on lab section, where we will apply every technique in -the chapter to the `bugdemo` driver and see each one produce -a concrete result. +概念性内容已经讲完,我们可以进入动手实验部分,在那里我们将本章的每种技术应用到 `bugdemo` 驱动程序上,看每一种产生具体的结果。 -## Hands-on Labs +## 动手实验 -Each lab in this section is self-contained but builds on the -previous ones. They use the `bugdemo` driver, whose companion -source is under `examples/part-07/ch34-advanced-debugging/`. +本节中的每个实验都是独立的,但建立在前一个之上。它们使用 `bugdemo` 驱动程序,其配套源代码位于 `examples/part-07/ch34-advanced-debugging/`。 -Before starting, make sure you have a development FreeBSD 14.3 -VM where you can crash the kernel safely, a copy of the -FreeBSD source tree at `/usr/src/`, and the ability to attach -a serial or virtual console that preserves output across a -reboot. +开始之前,确保你有一个可以安全崩溃内核的开发用 FreeBSD 14.3 虚拟机,一份位于 `/usr/src/` 的 FreeBSD 源码树副本,以及能够附加保留跨重启输出的串行或虚拟控制台。 -### Lab 1: Adding Assertions to bugdemo +### 实验 1:为 bugdemo 添加断言 -In this lab we build the first version of `bugdemo` and add -assertions that catch internal inconsistencies. The goal is to -see `KASSERT`, `MPASS`, and `CTASSERT` working in practice. +在本实验中,我们构建 `bugdemo` 的第一个版本并添加捕获内部不一致性的断言。目标是看到 `KASSERT`、`MPASS` 和 `CTASSERT` 在实践中工作。 -**Step 1: Build and load the baseline driver.** +**步骤 1:构建并加载基准驱动程序。** -The baseline driver lives at -`examples/part-07/ch34-advanced-debugging/lab01-kassert/`. -It is a minimal pseudo-device with a single ioctl that triggers -a bug when instructed to. From the lab directory: +基准驱动程序位于 `examples/part-07/ch34-advanced-debugging/lab01-kassert/`。它是一个最小的伪设备,有一个 ioctl 在被指示时触发 bug。从实验目录执行: ```console $ make @@ -3155,25 +1627,22 @@ $ sudo kldload ./bugdemo.ko $ ls -l /dev/bugdemo ``` -If the device node appears, the driver loaded correctly. +如果设备节点出现,驱动程序加载成功。 -**Step 2: Run the test tool to confirm the driver works.** +**步骤 2:运行测试工具确认驱动正常工作。** -The lab also contains a small user-space program, -`bugdemo_test`, that opens the device and issues ioctls: +实验还包含一个小型用户空间程序 `bugdemo_test`,它打开设备并发出 ioctl: ```console $ ./bugdemo_test hello $ ./bugdemo_test noop ``` -Both should return success. Without any bugs triggered, the -driver behaves correctly. +两者都应返回成功。未触发任何 bug 时,驱动程序行为正确。 -**Step 3: Inspect the assertions in the source.** +**步骤 3:检查源代码中的断言。** -Open `bugdemo.c` and find the function `bugdemo_process`. You -will see something like this: +打开 `bugdemo.c`,找到 `bugdemo_process` 函数。你会看到类似这样的代码: ```c static void @@ -3188,96 +1657,74 @@ bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) } ``` -Each assertion documents an invariant. If any of them fires, -the kernel panics with a message identifying the broken -invariant. +每个断言记录一个不变式。如果其中任何一个触发,内核以标识被违反不变式的消息 panic。 -**Step 4: Trigger an assertion.** +**步骤 4:触发一个断言。** -The driver has an ioctl called `BUGDEMO_FORCE_BAD_OP` that -intentionally sets `cmd->op` to an out-of-range value before -calling `bugdemo_process`: +驱动程序有一个名为 `BUGDEMO_FORCE_BAD_OP` 的 ioctl,它在调用 `bugdemo_process` 之前故意将 `cmd->op` 设置为超出范围的值: ```console $ ./bugdemo_test force-bad-op ``` -With a debug kernel, this produces an immediate panic: +在调试内核上,这产生立即的 panic: ```text panic: bugdemo: op 255 out of range ``` -and the system reboots. On a release kernel (no `INVARIANTS`), -the `KASSERT` is compiled out and the driver continues on with -an out-of-range value. The difference is exactly the value of -having a debug kernel during development. +系统重启。在发布版内核(无 `INVARIANTS`)上,`KASSERT` 被编译出去,驱动程序带着超出范围的值继续执行。这种差异正是开发期间使用调试内核的价值。 -**Step 5: Confirm the assertion fires on the right line.** +**步骤 5:确认断言在正确的行触发。** -After the reboot, if a dump was captured, open it with `kgdb`: +重启后,如果捕获了转储,用 `kgdb` 打开它: ```console # kgdb /boot/kernel/kernel /var/crash/vmcore.last (kgdb) bt ``` -The backtrace will show `bugdemo_process`, and `frame N` to -that entry will show the assertion line. This is the end-to-end -chain: assertion fires, kernel panics, dump captures state, -kgdb identifies the code. +回溯将显示 `bugdemo_process`,`frame N` 到那个条目将显示断言行。这就是端到端链条:断言触发、内核 panic、转储捕获状态、kgdb 标识代码。 -**Step 6: Add your own assertion.** +**步骤 6:添加你自己的断言。** -Modify the driver to add an assertion that a counter is -nonzero in a specific code path. Rebuild, reload, and trigger -a case that makes the counter zero. Observe that your -assertion fires as expected. +修改驱动程序添加一个断言,在特定代码路径中计数器不为零。重建、重新加载、触发使计数器为零的情况。观察你的断言如期触发。 -**What this lab teaches.** The `KASSERT` macro is a live check, -not a theoretical one. It fires, it panics, it identifies the -code. The discipline of adding assertions is backed by a -discipline of testing that they fire when they should. +**本实验教授的内容。** `KASSERT` 宏是一个活的检查,而非理论的。它触发、它 panic、它标识代码。添加断言的纪律由测试它们应该触发时就触发的纪律支撑。 -### Lab 2: Capturing and Analyzing a Panic With kgdb +### 实验 2:使用 kgdb 捕获和分析 Panic -In this lab we focus on the post-mortem workflow. Starting from -a clean debug kernel, we trigger a panic, capture the dump, and -walk through it with `kgdb`. +在本实验中我们专注于事后分析工作流。从一个干净的调试内核开始,我们触发 panic、捕获转储并用 `kgdb` 遍历它。 -**Step 1: Confirm the dump device is configured.** +**步骤 1:确认转储设备已配置。** -On the VM, run: +在虚拟机上运行: ```console # dumpon -l ``` -If the output shows a device path (typically the swap -partition), you are ready. If not, configure one: +如果输出显示设备路径(通常是交换分区),你就准备好了。如果没有,配置一个: ```console # dumpon /dev/ada0p3 # replace with your swap partition # echo 'dumpdev="/dev/ada0p3"' >> /etc/rc.conf ``` -**Step 2: Confirm the debug kernel is running.** +**步骤 2:确认调试内核正在运行。** ```console # uname -v # sysctl debug.debugger_on_panic ``` -`debug.debugger_on_panic` should be `0` or `1` depending on -whether you want to pause at the debugger before the dump. -For automated lab work, `0` is easier; for interactive -exploration, `1` is educational. +`debug.debugger_on_panic` 应为 `0` 或 `1`,取决于你是否想在转储之前暂停在调试器。对于自动化实验工作,`0` 更方便;对于交互式探索,`1` 更有教学意义。 ```console # sysctl debug.debugger_on_panic=0 ``` -**Step 3: Load bugdemo and trigger a panic.** +**步骤 3:加载 bugdemo 并触发 panic。** ```console # kldload ./bugdemo.ko @@ -3287,11 +1734,9 @@ Dumping ... Rebooting ... ``` -The panic message, the dump notice, and the reboot all appear -on the console. Dump writing takes a few seconds on a VM with -virtual disk. +panic 消息、转储通知和重启都出现在控制台上。在带虚拟磁盘的虚拟机上转储写入需要几秒钟。 -**Step 4: After the reboot, inspect the saved dump.** +**步骤 4:重启后,检查保存的转储。** ```console # ls /var/crash/ @@ -3299,17 +1744,15 @@ bounds info.0 info.last minfree vmcore.0 vmcore.last # cat /var/crash/info.0 ``` -The `info.0` file summarizes the panic: the kernel version, the -message, and the initial backtrace captured before dumping. +`info.0` 文件汇总了 panic:内核版本、消息和转储前捕获的初始回溯。 -**Step 5: Open the dump in kgdb.** +**步骤 5:在 kgdb 中打开转储。** ```console # kgdb /boot/kernel/kernel /var/crash/vmcore.0 ``` -`kgdb` automatically runs a backtrace. Identify the frame that -is inside `bugdemo_ioctl` or `bugdemo_process`. Switch to it: +`kgdb` 自动运行回溯。识别在 `bugdemo_ioctl` 或 `bugdemo_process` 内部的帧。切换到它: ```console (kgdb) frame 5 @@ -3318,11 +1761,11 @@ is inside `bugdemo_ioctl` or `bugdemo_process`. Switch to it: (kgdb) print sc ``` -Observe that `sc` is NULL, confirming the panic message. +观察 `sc` 为 NULL,确认 panic 消息。 -**Step 6: Explore adjacent state.** +**步骤 6:探索相邻状态。** -From `kgdb`, examine the process that triggered the panic: +从 `kgdb` 中,检查触发 panic 的进程: ```console (kgdb) info threads @@ -3330,84 +1773,70 @@ From `kgdb`, examine the process that triggered the panic: (kgdb) proc # driver-specific helper for process state ``` -`proc` is a kernel-specific command that prints the current -process. Between these commands and `bt`, you can build a full -picture of the panic's context. +`proc` 是一个特定于内核的命令,打印当前进程。通过这些命令和 `bt`,你可以构建 panic 上下文的完整图景。 -**Step 7: Exit kgdb.** +**步骤 7:退出 kgdb。** ```console (kgdb) quit ``` -The dump remains on disk; you can reopen it anytime. +转储保留在磁盘上;你可以随时重新打开它。 -**What this lab teaches.** The full cycle of panic, dump, and -offline analysis is routine, not mysterious. A development VM -should be able to complete this cycle in under a minute. The -discipline is to practice it before the first real bug, so -that when you need it you are not learning the tool in a -hurry. +**本实验教授的内容。** panic、转储和离线分析的完整循环是常规操作,并不神秘。开发虚拟机应该能在不到一分钟内完成这个循环。纪律是在遇到第一个真正 bug 之前就练习它,这样当你需要它时你不需要匆忙学习工具。 -### Lab 3: Building GENERIC-DEBUG and Confirming Options Active +### 实验 3:构建 GENERIC-DEBUG 并确认选项激活 -This lab is about kernel configuration rather than code. The -aim is to walk through the full process of building, installing, -and validating a debug kernel. +本实验是关于内核配置而非代码。目标是走完构建、安装和验证调试内核的完整流程。 -**Step 1: Start from a fresh `/usr/src/`.** +**步骤 1:从一个干净的 `/usr/src/` 开始。** -If you have a source tree, update it. If not, install one with: +如果你有源码树,更新它。如果没有,安装一个: ```console # git clone --depth 1 -b releng/14.3 https://git.freebsd.org/src.git /usr/src ``` -**Step 2: Review the existing GENERIC-DEBUG config.** +**步骤 2:查看现有的 GENERIC-DEBUG 配置。** ```console $ ls /usr/src/sys/amd64/conf/GENERIC* $ cat /usr/src/sys/amd64/conf/GENERIC-DEBUG ``` -Observe that it is only two lines: `include GENERIC` and -`include "std.debug"`. Review `std.debug` next: +注意它只有两行:`include GENERIC` 和 `include "std.debug"`。接下来查看 `std.debug`: ```console $ cat /usr/src/sys/conf/std.debug ``` -Confirm the options we discussed: `INVARIANTS`, -`INVARIANT_SUPPORT`, `WITNESS`, and friends. +确认我们讨论过的选项:`INVARIANTS`、`INVARIANT_SUPPORT`、`WITNESS` 及其他。 -**Step 3: Build the kernel.** +**步骤 3:构建内核。** ```console # cd /usr/src # make buildkernel KERNCONF=GENERIC-DEBUG ``` -On a modest VM this takes twenty to forty minutes. The build -produces detailed output; if it stops with an error, investigate -and retry. +在适中的虚拟机上这需要二十到四十分钟。构建产生详细输出;如果因错误停止,调查并重试。 -**Step 4: Install the kernel.** +**步骤 4:安装内核。** ```console # make installkernel KERNCONF=GENERIC-DEBUG # ls -l /boot/kernel/kernel /boot/kernel.old/kernel ``` -The previous kernel is preserved in `/boot/kernel.old/` as a -recovery option. +之前的内核保留在 `/boot/kernel.old/` 中作为恢复选项。 -**Step 5: Reboot into the new kernel.** +**步骤 5:重启到新内核。** ```console # shutdown -r now ``` -After reboot, confirm: +重启后,确认: ```console $ uname -v @@ -3415,54 +1844,36 @@ $ sysctl debug.kdb.current_backend $ sysctl debug.kdb.supported_backends ``` -The backend should list both `ddb` and `gdb`. +后端应列出 `ddb` 和 `gdb` 两者。 -**Step 6: Confirm INVARIANTS is active.** +**步骤 6:确认 INVARIANTS 已激活。** -Build and load the lab01 `bugdemo.ko`, then trigger the out-of- -range op as in Lab 1. On a debug kernel, the panic fires. On a -release kernel, it does not. This round-trip confirms that -`INVARIANTS` is genuinely compiled in. +构建并加载实验 1 的 `bugdemo.ko`,然后像实验 1 那样触发超出范围的 op。在调试内核上,panic 触发。在发布版内核上,不会触发。这个往返确认 `INVARIANTS` 确实被编译进去了。 -**Step 7: Confirm WITNESS is active.** +**步骤 7:确认 WITNESS 已激活。** -The lab03 variant of `bugdemo` has a deliberate lock order -inversion, triggered by a specific ioctl. Load it, run the -triggering test, and watch for a `WITNESS` warning on the -console: +实验 3 变体的 `bugdemo` 有一个故意的锁序反转,由特定的 ioctl 触发。加载它,运行触发测试,在控制台上观察 `WITNESS` 警告: ```text lock order reversal: ... ``` -No panic is produced, just a warning. This is the expected -behavior: `WITNESS` detects potential deadlocks and reports -them, without forcing a system failure. +不产生 panic,只有警告。这是预期行为:`WITNESS` 检测潜在的死锁并报告它们,而不强制系统失败。 -**Step 8: Recover if the new kernel does not boot.** +**步骤 8:如果新内核无法启动则恢复。** -If your new kernel fails to boot for any reason, the FreeBSD -boot loader offers a recovery option. From the loader menu, -select "Boot Kernel" and then "kernel.old". Your previous -kernel boots, and you can investigate the debug kernel's -failure at leisure. +如果你的新内核因任何原因无法启动,FreeBSD 启动加载器提供恢复选项。从加载器菜单中,选择"Boot Kernel"然后选择"kernel.old"。你之前的内核启动,你可以从容地调查调试内核的故障。 -**What this lab teaches.** Building a debug kernel is not a -mysterious operation. It is a rebuild with different options -and a reboot. The hazards are predictable: long build times, -large binaries, and the need to keep the previous kernel -available as a fallback. +**本实验教授的内容。** 构建调试内核不是神秘的操作。它是用不同选项重新构建加重启。风险是可预测的:较长的构建时间、较大的二进制文件,以及需要保留之前的内核作为后备。 -### Lab 4: Tracing bugdemo With DTrace and ktrace +### 实验 4:使用 DTrace 和 ktrace 追踪 bugdemo -This lab exercises the three tracing tools we studied: DTrace -`fbt` probes, DTrace SDT probes, and `ktrace(1)`. +本实验练习我们学过的三种追踪工具:DTrace `fbt` 探针、DTrace SDT 探针和 `ktrace(1)`。 -**Step 1: Load a bugdemo variant with SDT probes.** +**步骤 1:加载带 SDT 探针的 bugdemo 变体。** -The `lab04-tracing` variant of bugdemo defines SDT probes at -key points: +`lab04-tracing` 变体的 bugdemo 在关键点定义了 SDT 探针: ```c SDT_PROVIDER_DEFINE(bugdemo); @@ -3470,38 +1881,38 @@ SDT_PROBE_DEFINE2(bugdemo, , , cmd__start, "struct bugdemo_softc *", "int"); SDT_PROBE_DEFINE3(bugdemo, , , cmd__done, "struct bugdemo_softc *", "int", "int"); ``` -Load it: +加载它: ```console # kldload ./bugdemo.ko ``` -**Step 2: List the probes.** +**步骤 2:列出探针。** ```console # dtrace -l -P sdt -n 'bugdemo:::*' ``` -You should see the `cmd-start` and `cmd-done` probes listed. +你应该看到 `cmd-start` 和 `cmd-done` 探针列出。 -**Step 3: Watch the probes fire.** +**步骤 3:观察探针触发。** -In one terminal: +在一个终端中: ```console # dtrace -n 'sdt:bugdemo::cmd-start { printf("op=%d\n", arg1); }' ``` -In another terminal: +在另一个终端中: ```console $ ./bugdemo_test noop $ ./bugdemo_test hello ``` -The first terminal shows each probe firing with its op value. +第一个终端显示每个探针及其 op 值触发。 -**Step 4: Measure latency per op.** +**步骤 4:测量每次操作的延迟。** ```console # dtrace -n ' @@ -3519,50 +1930,38 @@ sdt:bugdemo::cmd-done ' ``` -Run a workload of many ioctls, then Ctrl-C the DTrace. An -aggregation prints, showing a latency histogram per op. +运行大量 ioctl 的负载,然后 Ctrl-C 中止 DTrace。打印聚合结果,显示每种操作的延迟直方图。 -**Step 5: Use fbt to trace entries.** +**步骤 5:使用 fbt 追踪入口。** ```console # dtrace -n 'fbt::bugdemo_*:entry { printf("%s\n", probefunc); }' ``` -Trigger some ioctls from user space. The DTrace terminal shows -each entry, giving you a live view of the driver's flow. +从用户空间触发一些 ioctl。DTrace 终端显示每次入口,给你驱动程序流程的实时视图。 -**Step 6: Use ktrace to trace the user-space side.** +**步骤 6:使用 ktrace 追踪用户空间侧。** ```console $ ktrace -t ci ./bugdemo_test hello $ kdump ``` -Observe the ioctl calls visible in the kdump output. +观察 kdump 输出中可见的 ioctl 调用。 -**Step 7: Combine ktrace and DTrace.** +**步骤 7:结合 ktrace 和 DTrace。** -Run DTrace in one terminal, watching SDT probes, while running -ktrace in another on the user-space test. The two outputs, -read together, give a complete picture of the interaction from -user space to kernel and back. +在一个终端运行 DTrace,监视 SDT 探针,同时在另一个终端对用户空间测试运行 ktrace。两个输出一起阅读,给出从用户空间到内核再返回的交互完整图景。 -**What this lab teaches.** Tracing is not a single tool; it is a -family. DTrace is the richest, `ktrace(1)` is the simplest way -to see the user-kernel boundary, and combining them gives the -most complete view. +**本实验教授的内容。** 追踪不是单一工具;它是一个家族。DTrace 是最丰富的,`ktrace(1)` 是查看用户-内核边界最简单的方式,结合它们能给出最完整的视图。 -### Lab 5: Catching a Use-After-Free With memguard +### 实验 5:使用 memguard 捕获释放后使用 -This lab walks through a real memory debugging scenario. The -`lab05-memguard` variant of `bugdemo` contains a deliberate -use-after-free bug: under certain ioctl sequences, the driver -frees a buffer and then reads it from a callout. +本实验走完一个真实的内存调试场景。`lab05-memguard` 变体的 `bugdemo` 包含一个故意的释放后使用 bug:在特定 ioctl 序列下,驱动程序释放了一个缓冲区,然后从 callout 中读取它。 -**Step 1: Build a kernel with DEBUG_MEMGUARD.** +**步骤 1:构建带 DEBUG_MEMGUARD 的内核。** -Add `options DEBUG_MEMGUARD` to your `GENERIC-DEBUG` config, or -create a new config: +将 `options DEBUG_MEMGUARD` 添加到你的 `GENERIC-DEBUG` 配置中,或创建新配置: ```text include GENERIC @@ -3570,28 +1969,24 @@ include "std.debug" options DEBUG_MEMGUARD ``` -Rebuild and install as in Lab 3. +像实验 3 那样重新构建和安装。 -**Step 2: Load the lab05 bugdemo and enable memguard.** +**步骤 2:加载实验 5 的 bugdemo 并启用 memguard。** ```console # kldload ./bugdemo.ko # sysctl vm.memguard.desc=bugdemo ``` -The second command tells `memguard(9)` to guard all allocations -made with malloc type `bugdemo`. The exact type name comes from -the driver's `MALLOC_DEFINE` call. +第二个命令告诉 `memguard(9)` 保护所有 malloc 类型为 `bugdemo` 的分配。确切的类型名称来自驱动程序的 `MALLOC_DEFINE` 调用。 -**Step 3: Trigger the use-after-free.** +**步骤 3:触发释放后使用。** ```console $ ./bugdemo_test use-after-free ``` -The user-space call returns quickly. A moment later (when the -callout fires), the kernel panics with a page fault inside the -callout routine: +用户空间调用快速返回。稍后(当 callout 触发时),内核在 callout 例程内以页面错误 panic: ```text Fatal trap 12: page fault while in kernel mode @@ -3604,11 +1999,9 @@ bugdemo_callout() ... ``` -`memguard(9)` has converted a silent use-after-free into an -immediate page fault. The backtrace points directly at -`bugdemo_callout`. +`memguard(9)` 将一个静默的释放后使用转变为立即的页面错误。回溯直接指向 `bugdemo_callout`。 -**Step 4: Analyze the dump with kgdb.** +**步骤 4:用 kgdb 分析转储。** ```console # kgdb /boot/kernel/kernel /var/crash/vmcore.last @@ -3618,30 +2011,21 @@ immediate page fault. The backtrace points directly at (kgdb) print buffer ``` -The source line shows the read from `buffer`, and `buffer` is -a freed `memguard`-protected address. `kgdb` prints it as an -address that is no longer mapped. +源代码行显示从 `buffer` 的读取,而 `buffer` 是一个已释放的 `memguard` 保护的地址。`kgdb` 将其打印为一个不再映射的地址。 -**Step 5: Fix the bug and verify.** +**步骤 5:修复 bug 并验证。** -The fix is to cancel the callout before freeing the buffer. -Modify the driver source accordingly, rebuild, reload, and run -the same test. The panic no longer fires. Keep `memguard` -enabled during the verification, then disable it and re-test: +修复是在释放缓冲区之前取消 callout。相应地修改驱动程序源代码,重建、重新加载并运行相同的测试。panic 不再触发。在验证期间保持 `memguard` 启用,然后禁用它并重新测试: ```console # sysctl vm.memguard.desc= ``` -Both runs should succeed. If the release-mode run (without -`memguard`) still fails, the bug is not fully fixed. +两次运行都应成功。如果发布版模式运行(不带 `memguard`)仍然失败,说明 bug 未完全修复。 -**Step 6: Count inflight allocations.** +**步骤 6:计算进行中的分配。** -The lab also shows an alternative technique: counting inflight -allocations. Add a `counter(9)` to the driver, bump it on -allocate, decrement on free. At unload, assert that the counter -is zero: +实验还展示了一种替代技术:计算进行中的分配。在驱动程序中添加一个 `counter(9)`,分配时递增,释放时递减。卸载时断言计数器为零: ```c KASSERT(counter_u64_fetch(bugdemo_inflight) == 0, @@ -3649,49 +2033,41 @@ KASSERT(counter_u64_fetch(bugdemo_inflight) == 0, (long)counter_u64_fetch(bugdemo_inflight))); ``` -Unload without first freeing all buffers, observe the assertion -fire. +在未先释放所有缓冲区的情况下卸载,观察断言触发。 -**What this lab teaches.** `memguard(9)` is a specific tool for a -specific class of bug. When it applies, it turns hard bugs into -easy ones. Knowing when to reach for it is the practical skill. +**本实验教授的内容。** `memguard(9)` 是针对特定类别 bug 的特定工具。当它适用时,它将困难 bug 变成简单 bug。知道何时使用它是实用技能。 -### Lab 6: Remote Debugging With the GDB Stub +### 实验 6:使用 GDB 桩进行远程调试 -This lab demonstrates remote debugging over a virtual serial -port. It assumes you are using bhyve or QEMU with a serial -console exposed to the host. +本实验演示通过虚拟串行端口进行远程调试。假设你使用的是 bhyve 或 QEMU,串行控制台暴露给主机。 -**Step 1: Configure KDB and GDB in the kernel.** +**步骤 1:在内核中配置 KDB 和 GDB。** -Both should already be present in `GENERIC-DEBUG`. Confirm with: +两者应该已经在 `GENERIC-DEBUG` 中。用以下命令确认: ```console # sysctl debug.kdb.supported_backends ``` -**Step 2: Configure the serial console in the VM.** +**步骤 2:在虚拟机中配置串行控制台。** -In bhyve, add `-l com1,stdio` to the launch command, or -equivalent. In QEMU, use `-serial stdio` or `-serial pty`. The -goal is to have a virtual serial port accessible from the host. +在 bhyve 中,向启动命令添加 `-l com1,stdio` 或等价参数。在 QEMU 中,使用 `-serial stdio` 或 `-serial pty`。目标是拥有一个可从主机访问的虚拟串行端口。 -**Step 3: In the VM, switch to the GDB backend.** +**步骤 3:在虚拟机中,切换到 GDB 后端。** ```console # sysctl debug.kdb.current_backend=gdb ``` -**Step 4: In the VM, drop into the debugger.** +**步骤 4:在虚拟机中,进入调试器。** -Send the break-to-debugger sequence on the serial console, or -trigger a panic: +在串行控制台上发送进入调试器的序列,或触发 panic: ```console # sysctl debug.kdb.enter=1 ``` -The kernel halts. The serial console shows: +内核停止。串行控制台显示: ```text KDB: enter: sysctl debug.kdb.enter @@ -3700,316 +2076,192 @@ Stopped at kdb_enter+0x37: movq $0,kdb_why gdb> ``` -**Step 5: On the host, attach kgdb.** +**步骤 5:在主机上,附加 kgdb。** ```console $ kgdb /boot/kernel/kernel (kgdb) target remote /dev/ttyXX # the host-side serial device ``` -The host's `kgdb` connects to the kernel over the serial line. -You can now run full `kgdb` commands on the live kernel: -`bt`, `info threads`, `print`, `set variable`, and so on. +主机的 `kgdb` 通过串行线连接到内核。你现在可以在运行的内核上运行完整的 `kgdb` 命令:`bt`、`info threads`、`print`、`set variable` 等等。 -**Step 6: Set a breakpoint.** +**步骤 6:设置断点。** ```console (kgdb) break bugdemo_ioctl (kgdb) continue ``` -The VM resumes. In the VM, run `./bugdemo_test hello`. The -breakpoint fires, and `kgdb` on the host shows the state. +虚拟机恢复运行。在虚拟机中运行 `./bugdemo_test hello`。断点触发,主机上的 `kgdb` 显示状态。 -**Step 7: Detach cleanly.** +**步骤 7:干净地分离。** ```console (kgdb) detach (kgdb) quit ``` -In the VM, the kernel resumes running. +在虚拟机中,内核恢复运行。 -**What this lab teaches.** Remote debugging is a specialized but -valuable tool. It is most useful when you need live inspection -of a running kernel, particularly for intermittent bugs that -are hard to capture as dumps. +**本实验教授的内容。** 远程调试是一个专业但有价值的工具。当你需要对运行中的内核进行实时检查时最有用,特别是对于难以作为转储捕获的间歇性 bug。 ## 挑战练习 -The following challenges build on the labs. They are open-ended -by design: there are multiple valid approaches, and the point is -to practice choosing the right tool for each bug. +以下挑战建立在实验之上。它们被设计为开放式的:有多种有效的方法,重点是为每个 bug 练习选择正确的工具。 -### Challenge 1: Find the Silent Bug +### 挑战 1:找到静默 Bug -The `lab-challenges/silent-bug` variant of `bugdemo` contains a -bug that produces no crash and no error. Instead, a counter -sometimes reports the wrong value after a specific ioctl -sequence. Your task: +`lab-challenges/silent-bug` 变体的 `bugdemo` 包含一个不产生崩溃也不产生错误的 bug。相反,一个计数器在特定 ioctl 序列后有时报告错误的值。你的任务: -1. Write a test program that reproduces the bug. -2. Use DTrace to narrow down which function produces the wrong - counter value. -3. Fix the bug and verify that the DTrace signature disappears. +1. 编写一个重现该 bug 的测试程序。 +2. 使用 DTrace 缩小哪个函数产生了错误的计数器值。 +3. 修复 bug 并验证 DTrace 特征消失。 -Hint: the bug is a missing memory barrier, not a missing lock. -The symptom is cache coherence, not contention. +提示:bug 是缺少内存屏障,而非缺少锁。症状是缓存一致性,而非竞争。 -### Challenge 2: Hunt the Leak +### 挑战 2:猎捕泄漏 -The `lab-challenges/leaky-driver` variant leaks an object each -time a specific ioctl path is exercised. Your task: +`lab-challenges/leaky-driver` 变体在每次行使特定 ioctl 路径时泄漏一个对象。你的任务: -1. Confirm the leak using `vmstat -m` before and after a - workload. -2. Use DTrace to record every allocation and free of the leaked - object type, aggregated by stack. -3. Identify the code path that allocates without freeing. -4. Add a `counter(9)`-based inflight check to the driver and - verify that it fires when the buggy path is taken. +1. 使用 `vmstat -m` 在负载前后确认泄漏。 +2. 使用 DTrace 记录泄漏对象类型的每次分配和释放,按栈聚合。 +3. 标识分配但未释放的代码路径。 +4. 向驱动程序添加基于 `counter(9)` 的进行中检查,并验证它在错误路径被采用时触发。 -### Challenge 3: Diagnose the Deadlock +### 挑战 3:诊断死锁 -The `lab-challenges/deadlock` variant sometimes hangs when two -ioctls are run concurrently. Your task: +`lab-challenges/deadlock` 变体有时在两个 ioctl 并发运行时挂起。你的任务: -1. Reproduce the hang. -2. Attach to the hung kernel with `kgdb` (or drop into `DDB`). -3. Use `info threads` and `bt` on each stuck thread to - identify the lock ordering. -4. Determine the fix (reorder locks, or eliminate one of them). +1. 重现挂起。 +2. 用 `kgdb` 附加到挂起的内核(或进入 `DDB`)。 +3. 对每个卡住的线程使用 `info threads` 和 `bt` 标识锁序。 +4. 确定修复方案(重排锁序,或消除其中一个)。 -### Challenge 4: Read a Real Panic +### 挑战 4:阅读真实的 Panic -Load a kernel module you did not write (for example, one of the -USB class drivers or a filesystem module). Deliberately trigger -a bad interaction by sending malformed input from user space. -When it panics (or fails to), write up: +加载一个你没写过的内核模块(例如某个 USB 类驱动或文件系统模块)。通过从用户空间发送畸形输入故意触发一次不良交互。当它 panic(或未能 panic)时,写下: -1. The exact sequence that caused the symptom. -2. The backtrace or error observed. -3. Whether the module had assertions that would have caught the - problem earlier. -4. One suggestion for strengthening the module's invariants. +1. 导致症状的确切序列。 +2. 观察到的回溯或错误。 +3. 该模块是否有能更早捕获问题的断言。 +4. 一个关于加强该模块不变量的建议。 -### Challenge 5: Build Your Own bugdemo Variant +### 挑战 5:构建你自己的 bugdemo 变体 -Create a new variant of `bugdemo` that contains a bug you have -encountered in real-world code. Write a test program that -triggers the bug deterministically. Then, using any subset of -the techniques in this chapter, diagnose the bug from scratch. -Write up what you learned. The point is to practice the -conversion of "I recognize this pattern" into reproducible -teaching material. +创建一个 `bugdemo` 的新变体,包含你在真实代码中遇到过的 bug。编写一个确定性地触发该 bug 的测试程序。然后,使用本章技术的任何子集,从头诊断该 bug。写下你学到的内容。重点是练习将"我认出这个模式"转化为可重现的教学材料。 ## 常见问题故障排除 -Even the best tools run into problems in practice. This section -collects the issues you are most likely to hit and how to resolve -them. +即使最好的工具在实践中也会遇到问题。本节收集你最可能遇到的问题及其解决方法。 -### The Dump Is Not Being Captured +### 转储未被捕获 -After a panic, `/var/crash/` shows only `bounds` and `minfree`, -no `vmcore.N`. Possible causes: +panic 后,`/var/crash/` 只显示 `bounds` 和 `minfree`,没有 `vmcore.N`。可能的原因: -- **No dump device configured.** Run `dumpon -l` after a normal - boot. If it reports "no dump device configured," set one - with `dumpon /dev/DEVICE` and persist it in `/etc/rc.conf` - with `dumpdev=`. -- **Dump device too small.** A dump needs space equal to kernel - memory plus some overhead. A 1GB swap partition will not hold - a dump of an 8GB-memory machine. Enlarge the dump device or - use a compressed dump (`dumpon -z`). -- **savecore disabled.** Check `/etc/rc.conf` for - `savecore_enable="NO"`. Switch to `YES` and reboot. -- **Crash too severe.** If the panic itself prevents the dump - machinery from running, you may see no output at all. In that - case a serial console is essential to capture at least the - panic message. +- **未配置转储设备。** 正常启动后运行 `dumpon -l`。如果报告"no dump device configured",用 `dumpon /dev/DEVICE` 设置一个并在 `/etc/rc.conf` 中用 `dumpdev=` 持久化。 +- **转储设备太小。** 转储需要等于内核内存加一些开销的空间。1GB 的交换分区无法容纳 8GB 内存机器的转储。扩大转储设备或使用压缩转储(`dumpon -z`)。 +- **savecore 被禁用。** 检查 `/etc/rc.conf` 中的 `savecore_enable="NO"`。改为 `YES` 并重启。 +- **崩溃太严重。** 如果 panic 本身阻止转储机制运行,你可能完全看不到输出。这种情况下串行控制台对于至少捕获 panic 消息是必不可少的。 -### kgdb Says "No Symbols" +### kgdb 说"没有符号" -When opening a dump, `kgdb` prints "no debugging symbols found" -or similar. Possible causes: +打开转储时,`kgdb` 打印"no debugging symbols found"或类似信息。可能的原因: -- **Kernel built without `-g`.** Debug kernels include `-g` - automatically via `makeoptions DEBUG=-g`. Release kernels do - not. Either build a debug kernel or install the debug - symbols package if available. -- **Mismatch between kernel and dump.** If the dump came from a - different kernel than the one `kgdb` is loading, symbols will - not match. Use the exact kernel binary that was running at - the time of the panic. -- **Module symbols missing.** If the panic is inside a module - that was built without `-g`, `kgdb` shows addresses without - source lines for that module. Rebuild the module with - `DEBUG_FLAGS=-g`. +- **内核构建时没有 `-g`。** 调试内核通过 `makeoptions DEBUG=-g` 自动包含 `-g`。发布版内核不包含。要么构建调试内核,要么安装调试符号包(如果可用)。 +- **内核和转储不匹配。** 如果转储来自与 `kgdb` 加载的不同的内核,符号将不匹配。使用 panic 时正在运行的精确内核二进制文件。 +- **模块符号缺失。** 如果 panic 发生在没有用 `-g` 构建的模块内,`kgdb` 为该模块显示没有源代码行的地址。用 `DEBUG_FLAGS=-g` 重建模块。 -### DDB Freezes the System +### DDB 冻结系统 -Entering `DDB` intentionally halts the kernel. This is by -design, but on a production-like system it can look like a -hang. If you are in `DDB` and want to resume: +进入 `DDB` 有意地停止内核。这是设计如此,但在类生产系统上可能看起来像挂起。如果你在 `DDB` 中并想恢复: -- `continue` exits `DDB` and returns to the kernel. -- `reset` reboots immediately. -- `call doadump` forces a dump and then reboot. +- `continue` 退出 `DDB` 并返回内核。 +- `reset` 立即重启。 +- `call doadump` 强制转储然后重启。 -If you entered `DDB` accidentally, `continue` is almost always -the right action. +如果你不小心进入了 `DDB`,`continue` 几乎总是正确的操作。 -### A Module Refuses to Unload +### 模块拒绝卸载 -`kldunload bugdemo` returns `Device busy`. Causes: +`kldunload bugdemo` 返回 `Device busy`。原因: -- **Open file descriptors.** Something still has `/dev/bugdemo` - open. Use `fstat | grep bugdemo` to find processes and close - them. -- **Reference counts.** Another module references this one. - Unload that module first. -- **Pending work.** A callout or taskqueue is still scheduled. - Wait for it to drain, or make the driver explicitly cancel - and drain in its unload path. -- **Stuck thread.** A kernel thread spawned by the driver has - not exited. Terminate it from within the driver on unload. +- **打开的文件描述符。** 某些东西仍然持有 `/dev/bugdemo` 打开。使用 `fstat | grep bugdemo` 找到进程并关闭它们。 +- **引用计数。** 另一个模块引用了这个模块。先卸载那个模块。 +- **待处理工作。** 一个 callout 或 taskqueue 仍在计划中。等待它排干,或让驱动程序在卸载路径中显式取消和排干。 +- **卡住的线程。** 驱动程序产生的内核线程尚未退出。在卸载时从驱动程序内部终止它。 -### memguard Does Nothing +### memguard 不起作用 -`vm.memguard.desc=bugdemo` is set, but memguard does not seem -to be catching any bugs. Causes: +设置了 `vm.memguard.desc=bugdemo`,但 memguard 似乎没有捕获任何 bug。原因: -- **Wrong type name.** `vm.memguard.desc` must match a type - passed to `MALLOC_DEFINE(9)` exactly. If you set - `vm.memguard.desc=BugDemo` but the driver uses - `MALLOC_DEFINE(..., "bugdemo", ...)`, the names do not match. -- **Kernel not built with `DEBUG_MEMGUARD`.** The sysctl node - exists only if the option is compiled in. Check - `sysctl vm.memguard.waste` or similar; if it returns "unknown - oid," the feature is not compiled in. -- **Allocation path not traversed.** If the code path where - the bug lives does not actually use the guarded type, - `memguard` cannot catch it. Confirm the allocation type with - `vmstat -m`. +- **类型名称错误。** `vm.memguard.desc` 必须与传给 `MALLOC_DEFINE(9)` 的类型完全匹配。如果你设置了 `vm.memguard.desc=BugDemo` 但驱动使用 `MALLOC_DEFINE(..., "bugdemo", ...)`,名称不匹配。 +- **内核未用 `DEBUG_MEMGUARD` 构建。** sysctl 节点只在选项编译进来时存在。检查 `sysctl vm.memguard.waste` 或类似的;如果返回"unknown oid",该功能未编译进来。 +- **未遍历分配路径。** 如果 bug 所在的代码路径实际上不使用被保护的类型,`memguard` 无法捕获它。用 `vmstat -m` 确认分配类型。 -### DTrace Says "Probe Does Not Exist" +### DTrace 说"探针不存在" ```text dtrace: invalid probe specifier sdt:bugdemo::cmd-start: probe does not exist ``` -Causes: +原因: -- **Module not loaded.** SDT probes are defined by the module - that provides them. If the module is not loaded, the probes - do not exist. -- **Probe name mismatch.** The name in the source has double - underscores (`cmd__start`), but DTrace uses a single dash - (`cmd-start`). This is the conversion rule; the underscore - form appears in C, the dash form in DTrace. -- **Provider not defined.** If `SDT_PROVIDER_DEFINE(bugdemo)` - is missing or in a different file than `SDT_PROBE_DEFINE`, - the probes will not exist. +- **模块未加载。** SDT 探针由提供它们的模块定义。如果模块未加载,探针不存在。 +- **探针名称不匹配。** 源代码中的名称使用双下划线(`cmd__start`),但 DTrace 使用单短划线(`cmd-start`)。这是转换规则;下划线形式出现在 C 中,短划线形式出现在 DTrace 中。 +- **提供者未定义。** 如果 `SDT_PROVIDER_DEFINE(bugdemo)` 缺失或与 `SDT_PROBE_DEFINE` 在不同文件中,探针将不存在。 -### Kernel Builds Fail With Symbol Conflicts +### 内核构建因符号冲突失败 -When building a kernel with unusual option combinations, you -may see link errors like "multiple definition of X." Causes: +当用不寻常的选项组合构建内核时,你可能看到类似"multiple definition of X"的链接错误。原因: -- **Conflicting options.** Some options are mutually exclusive. - Review the option documentation in `/usr/src/sys/conf/NOTES`. -- **Stale objects.** Old build artifacts can interfere with - new builds. Try `make cleandir && make cleandir` in the - kernel build directory. -- **Tree inconsistency.** A partial update of `/usr/src/` can - leave headers and sources out of sync. Run a full `svnlite - update` or `git pull` and retry. +- **选项冲突。** 某些选项互斥。查看 `/usr/src/sys/conf/NOTES` 中的选项文档。 +- **过期对象。** 旧的构建产物可能干扰新的构建。尝试在内核构建目录中运行 `make cleandir && make cleandir`。 +- **源码树不一致。** `/usr/src/` 的部分更新可能使头文件和源码不同步。运行完整的 `svnlite update` 或 `git pull` 然后重试。 -### The System Boots Into the Old Kernel +### 系统启动到旧内核 -After `installkernel`, you reboot and `uname -v` shows the old -kernel. Causes: +`installkernel` 后重启,`uname -v` 显示旧内核。原因: -- **Boot entry not updated.** The default is `kernel`, which - points to the current kernel. If you installed with - `KERNCONF=GENERIC-DEBUG` but did not run `make - installkernel` cleanly, the old binary may still be in - place. Check `/boot/kernel/kernel` timestamp. -- **Wrong kernel selected in loader.** The FreeBSD loader - menu has a "Boot Kernel" option that can select between - available kernels. Pick the right one, or set - `kernel="kernel"` in `/boot/loader.conf`. -- **Boot partition unchanged.** On some systems the boot - partition is separate and needs a manual copy. Check that - you installed to the correct partition. +- **启动条目未更新。** 默认是 `kernel`,指向当前内核。如果你用 `KERNCONF=GENERIC-DEBUG` 安装但没有干净地运行 `make installkernel`,旧二进制可能仍在原位。检查 `/boot/kernel/kernel` 的时间戳。 +- **加载器中选择了错误的内核。** FreeBSD 加载器菜单有"Boot Kernel"选项,可以在可用内核之间选择。选择正确的,或在 `/boot/loader.conf` 中设置 `kernel="kernel"`。 +- **启动分区未更改。** 在某些系统上启动分区是独立的,需要手动复制。检查你是否安装到了正确的分区。 -### WITNESS Reports False Positives +### WITNESS 报告误报 -Sometimes `WITNESS` warns about a lock order that you know is -safe. Possible reasons and responses: +有时 `WITNESS` 警告一个你知道是安全的锁序。可能的原因和回应: -- **The order really is unsafe but harmless in practice.** - `WITNESS` reports potential deadlocks, not actual ones. A - cycle in the lock graph that is never exercised concurrently - is still a bug waiting to happen. Refactor the locking. -- **Locks are acquired by address.** Generic code that locks by - pointer can produce orders that depend on runtime data, not - static structure. See `witness(4)` for how to suppress - specific orders with `witness_skipspin` or manual overrides. -- **Multiple locks of the same type.** Acquiring two instances - of the same lock class is always a potential issue. Use - `mtx_init(9)` with a distinct type name per instance if you - need them treated as separate classes. +- **顺序确实不安全但在实践中无害。** `WITNESS` 报告潜在的死锁,而非实际的死锁。锁图中从未被并发行使的环仍然是等待发生的 bug。重构加锁。 +- **锁按地址获取。** 按指针加锁的通用代码可能产生取决于运行时数据而非静态结构的顺序。参见 `witness(4)` 了解如何使用 `witness_skipspin` 或手动覆盖来抑制特定顺序。 +- **同类型的多个锁。** 获取同一锁类的两个实例始终是潜在问题。如果你需要将它们视为单独的类,使用带不同类型名称的 `mtx_init(9)`。 -## Putting It All Together: A Debugging Session Walkthrough +## 综合运用:一次调试会话演练 -Before we wrap up, let us walk through a complete debugging -session that uses several of the techniques we have studied. The -scenario is fictional but realistic: a driver that sometimes -fails with a misleading error, and we track it down from first -symptom to root cause. +在结束之前,让我们走完一个使用我们学过的几种技术的完整调试会话。场景是虚构但真实的:一个驱动程序有时以误导性的错误失败,我们从首发症状追踪到根因。 -### The Symptom +### 症状 -A user reports that their program sometimes gets `EBUSY` from an -ioctl on `/dev/bugdemo`. The program always calls the ioctl in -the same way, and most of the time it works. Only under heavy -load does `EBUSY` appear, and then inconsistently. +一位用户报告他们的程序有时从 `/dev/bugdemo` 的 ioctl 得到 `EBUSY`。程序总是以相同方式调用 ioctl,大多数时候工作正常。只有在重负载下 `EBUSY` 才会出现,而且不一致。 -### Step 1: Collect Evidence +### 步骤 1:收集证据 -The first step is to observe the phenomenon without perturbing -it. We run the user's program under `ktrace(1)` to confirm the -symptom: +第一步是在不干扰现象的情况下观察它。我们在 `ktrace(1)` 下运行用户程序以确认症状: ```console $ ktrace -t ci ./user_program $ kdump | grep ioctl ``` -The output confirms that a specific ioctl returns `EBUSY` now -and then. No other user-space call misbehaves. This tells us the -bug is in the kernel's handling of that ioctl, not in the user -program's logic. +输出确认特定的 ioctl 有时返回 `EBUSY`。没有其他用户空间调用行为异常。这告诉我们 bug 在内核对该 ioctl 的处理中,而非用户程序的逻辑中。 -### Step 2: Form a Hypothesis +### 步骤 2:形成假设 -The error code `EBUSY` usually indicates a resource conflict. -Reading the driver source, we find that `EBUSY` is returned when -an internal flag indicates a previous operation is still in -progress. The flag is cleared by a callout that completes the -operation. +错误代码 `EBUSY` 通常表示资源冲突。阅读驱动程序源代码,我们发现 `EBUSY` 在内部标志指示前一个操作仍在进行时返回。该标志由完成操作的 callout 清除。 -Our hypothesis: under heavy load, the callout is delayed long -enough that a new ioctl arrives before the previous one has -completed. The driver was not designed to serialize such -requests, so it rejects the newcomer. +我们的假设是:在重负载下,callout 被延迟到足够长,以至于新的 ioctl 在前一个完成之前到达。驱动程序未设计为序列化此类请求,因此它拒绝了新的请求。 -### Step 3: Test the Hypothesis With DTrace +### 步骤 3:用 DTrace 测试假设 -We write a DTrace script that records the delay between -consecutive ioctls and the state of the busy flag at each entry: +我们编写一个 DTrace 脚本,记录连续 ioctl 之间的延迟和每次入口时忙碌标志的状态: ```console dtrace -n ' @@ -4027,15 +2279,11 @@ fbt::bugdemo_ioctl:return ' ``` -Running the user program under load, we observe that `EBUSY` -returns happen almost exclusively when the previous ioctl -completed more than 50 microseconds ago and the callout has not -fired yet. This corroborates the hypothesis. +在负载下运行用户程序,我们观察到 `EBUSY` 返回几乎专门发生在前一个 ioctl 完成超过 50 微秒且 callout 尚未触发时。这证实了假设。 -### Step 4: Confirm With SDT Probes +### 步骤 4:用 SDT 探针确认 -We add SDT probes around the busy flag manipulation and watch -them: +我们在忙碌标志操作周围添加 SDT 探针并观察它们: ```console dtrace -n ' @@ -4056,184 +2304,112 @@ sdt:bugdemo::reject-busy ' ``` -The trace shows a clear pattern: set, reject, reject, reject, -clear, set, clear. The clear is coming late because the callout -is competing for a shared taskqueue with other work. +跟踪显示了一个清晰的模式:设置、拒绝、拒绝、拒绝、清除、设置、清除。清除来得晚,因为 callout 在与其他工作竞争共享的 taskqueue。 -### Step 5: Identify the Fix +### 步骤 5:确定修复方案 -With the evidence gathered, the fix is clear. Either the driver -needs to serialize incoming ioctls instead of rejecting them (a -queue or a wait), or it needs to complete the previous operation -synchronously instead of via callout. +有了收集到的证据,修复方案很清楚。要么驱动程序需要序列化传入的 ioctl 而非拒绝它们(队列或等待),要么需要同步完成前一个操作而非通过 callout。 -We pick the queuing approach because it preserves the callout's -benefits. The driver accumulates pending requests and dispatches -them as the callout fires. Under light load, nothing changes. -Under heavy load, requests wait rather than failing. +我们选择排队方法,因为它保留了 callout 的好处。驱动程序累积待处理请求并在 callout 触发时分发它们。轻负载下没有任何变化。重负载下,请求等待而非失败。 -### Step 6: Implement and Verify +### 步骤 6:实现并验证 -We modify the driver. We run the user program under the original -workload. `EBUSY` no longer appears. The DTrace latency -distribution now shows a tail that reflects the queueing delay, -which is acceptable for this driver's use case. +我们修改驱动程序。在原始负载下运行用户程序。`EBUSY` 不再出现。DTrace 延迟分布现在显示反映排队延迟的尾部,这对该驱动的用例是可接受的。 -We also enable `DEBUG_MEMGUARD` on the driver's malloc type and -run the workload for a while, to make sure the queuing code does -not introduce memory bugs. No faults fire. +我们还在驱动的 malloc 类型上启用 `DEBUG_MEMGUARD` 并运行负载一段时间,以确保排队代码没有引入内存 bug。没有页面错误触发。 -Finally, we run the full test suite. Everything passes. The fix -is committed with a descriptive message that explains the root -cause, not just the symptom. +最后,我们运行完整的测试套件。一切通过。修复以解释根因而非仅仅症状的描述性消息提交。 -### Lessons From This Session +### 本次会话的教训 -Two things are worth noting. +有两点值得注意。 -First, the tools we used were relatively lightweight. No crash -dump was needed. No `DDB` was entered. The bug was diagnosed -through passive observation, DTrace, and careful reading. For -many driver bugs, this is the shape of a session: not a -dramatic panic but a systematic narrowing of hypotheses. +第一,我们使用的工具相对轻量。不需要崩溃转储。不需要进入 `DDB`。bug 是通过被动观察、DTrace 和仔细阅读来诊断的。对于许多驱动程序 bug,这就是会话的形态:不是戏剧性的 panic,而是系统性的假设缩小。 -Second, the fix addressed the root cause, not the symptom. A -surface fix might have been to increase the priority of the -callout's taskqueue. That would have reduced the frequency of -the bug without eliminating it. A more principled fix changes -the driver's contract from "reject if busy" to "queue and -serve." This is the refactoring mindset we discussed in Section -8: every bug is a message about the design. +第二,修复解决了根因而非症状。表面修复可能是提高 callout 的 taskqueue 优先级。那会降低 bug 的频率但不消除它。更原则性的修复将驱动程序的契约从"忙碌时拒绝"改为"排队并服务"。这就是我们在第 8 节讨论的重构心态:每个 bug 都是关于设计的信息。 -## Additional Techniques Worth Knowing +## 值得了解的附加技术 -The chapter has covered the core of FreeBSD's debugging -toolkit. A handful of additional techniques did not fit into the -main narrative but deserve mention, because you will eventually -encounter them. +本章涵盖了 FreeBSD 调试工具包的核心。少数附加技术不适合放在主线叙述中,但值得一提,因为你最终会遇到它们。 -### witness_checkorder With Manual Lists +### witness_checkorder 与手动列表 -`WITNESS` can be tuned. In `/usr/src/sys/kern/subr_witness.c` -there is a table of known-good lock orders that the kernel -recognizes. When building a driver that uses a subsystem locked -by an existing lock, adding the driver's own lock to this table -lets `WITNESS` verify the combined order across the driver and -the subsystem. +`WITNESS` 可以被调优。在 `/usr/src/sys/kern/subr_witness.c` 中有一个已知良好锁序的表,内核能识别它。在构建与由现有锁锁定的子系统交互的驱动程序时,将驱动程序自己的锁添加到此表让 `WITNESS` 能验证跨驱动程序和子系统的组合顺序。 -This is rarely needed in small drivers but becomes useful for -drivers that interact deeply with multiple subsystems. +这在小型驱动程序中很少需要,但对与多个子系统深度交互的驱动程序变得有用。 ### sysctl debug.ktr -Beyond just enabling and disabling `ktr(9)` classes, there are -additional controls: +除了启用和禁用 `ktr(9)` 类,还有额外的控制: -- `debug.ktr.clear=1` clears the buffer. -- `debug.ktr.verbose=1` sends trace entries to the console in - real time, in addition to the ring. -- `debug.ktr.stamp=1` adds timestamps to each entry. +- `debug.ktr.clear=1` 清除缓冲区。 +- `debug.ktr.verbose=1` 实时将跟踪条目发送到控制台,除了环之外。 +- `debug.ktr.stamp=1` 为每个条目添加时间戳。 -The combination of these is especially useful when you want to -watch a live trace without running `ktrdump(8)` repeatedly. +这些组合在你想要观看实时跟踪而不反复运行 `ktrdump(8)` 时特别有用。 -### DDB Commands Beyond bt +### 超越 bt 的 DDB 命令 -`DDB` has a rich set of commands that are sparsely documented. -A few are particularly useful for driver authors: +`DDB` 有丰富的命令集,文档稀疏。有几个对驱动程序作者特别有用: -- `show all procs` lists every process. -- `show lockedvnods` shows currently locked vnodes (useful for - storage driver bugs). -- `show mount` shows mounted filesystems. -- `show registers` dumps CPU registers. -- `break FUNC` sets a breakpoint. -- `step` and `next` advance one instruction or one line. -- `watch` sets a watchpoint on an address. +- `show all procs` 列出每个进程。 +- `show lockedvnods` 显示当前锁定的 vnode(对存储驱动程序 bug 有用)。 +- `show mount` 显示挂载的文件系统。 +- `show registers` 转储 CPU 寄存器。 +- `break FUNC` 设置断点。 +- `step` 和 `next` 推进一条指令或一行。 +- `watch` 在地址上设置观察点。 -The `help` command in `DDB` lists all available commands. -Reading the list once is a useful way to discover features you -did not know about. +`DDB` 中的 `help` 命令列出所有可用命令。阅读一次列表是发现你不知道的功能的有用方式。 -### Kernel Option KDB_TRACE +### 内核选项 KDB_TRACE -`KDB_TRACE` causes the kernel to print a stack trace on every -panic, even if the operator does not interact with the -debugger. This is useful in automated testing where nobody is -watching the console. It is already in `GENERIC`. +`KDB_TRACE` 使内核在每次 panic 时打印栈跟踪,即使操作员不与调试器交互。这在无人值守控制台的自动化测试中有用。它已在 `GENERIC` 中。 -### EKCD: Encrypted Kernel Crash Dumps +### EKCD:加密内核崩溃转储 -If kernel dumps contain sensitive data (process memory, -credentials, keys), the kernel can encrypt them at dump time. -The `EKCD` option enables this feature. A public key is loaded -at runtime with `dumpon -k`; the matching private key is used -at `savecore` time to decrypt. +如果内核转储包含敏感数据(进程内存、凭证、密钥),内核可以在转储时加密它们。`EKCD` 选项启用此功能。公钥在运行时用 `dumpon -k` 加载;匹配的私钥在 `savecore` 时用于解密。 -This matters on production systems where dumps might be -transported over untrusted channels. It does not matter on a -development VM. +这在转储可能通过不受信通道传输的生产系统上很重要。在开发虚拟机上不重要。 -### Lightweight Debug Output: bootverbose +### 轻量级调试输出:bootverbose -Another low-overhead option is `bootverbose`. Setting -`boot_verbose` in the loader or `bootverbose=1` in sysctl -causes many kernel subsystems to print additional diagnostic -information at boot. If your driver has not yet reached the -point where DTrace applies, `bootverbose` can help you see -what the driver is doing during `attach`. +另一个低开销选项是 `bootverbose`。在加载器中设置 `boot_verbose` 或在 sysctl 中设置 `bootverbose=1` 会导致许多内核子系统在启动时打印额外的诊断信息。如果你的驱动程序尚未到达 DTrace 适用的阶段,`bootverbose` 可以帮助你在 `attach` 期间看到驱动程序在做什么。 -The way to make your own driver honor `bootverbose` is to -check `bootverbose` in your probe or attach code: +让你自己的驱动程序遵循 `bootverbose` 的方式是在探测或 attach 代码中检查 `bootverbose`: ```c if (bootverbose) device_printf(dev, "detailed attach info: ...\n"); ``` -This is a well-established pattern in `/usr/src/sys/dev/` -drivers. +这是 `/usr/src/sys/dev/` 驱动程序中的成熟模式。 -## A Closer Look at DDB +## 深入了解 DDB -The in-kernel debugger, `DDB`, deserves more attention than we -have given it so far. Many driver authors use `DDB` only -reactively, when a panic lands them in it unexpectedly. With a -little practice, `DDB` is also a useful tool to enter -deliberately, for interactive inspection of a live kernel. +内核内调试器 `DDB` 值得比我们到目前为止给予的更多关注。许多驱动程序作者只在 panic 意外将他们投入其中时才被动使用 `DDB`。通过一点练习,`DDB` 也是可以主动进入的有用工具,用于交互式检查运行的内核。 -### Entering DDB +### 进入 DDB -There are several ways to enter `DDB`. We have seen some of -them already: +有几种进入 `DDB` 的方式。我们已经见过其中一些: -- By panic, if `debug.debugger_on_panic` is nonzero. -- By serial BREAK (or `Ctrl-Alt-Esc` on a keyboard console), - when `BREAK_TO_DEBUGGER` is compiled in. -- By the alternative sequence `CR ~ Ctrl-B`, when - `ALT_BREAK_TO_DEBUGGER` is compiled in. -- Programmatically, with `sysctl debug.kdb.enter=1`. -- From code, by calling `kdb_enter(9)`. +- 通过 panic,如果 `debug.debugger_on_panic` 非零。 +- 通过串行 BREAK(或键盘控制台上的 `Ctrl-Alt-Esc`),当编译了 `BREAK_TO_DEBUGGER` 时。 +- 通过替代序列 `CR ~ Ctrl-B`,当编译了 `ALT_BREAK_TO_DEBUGGER` 时。 +- 通过编程方式,使用 `sysctl debug.kdb.enter=1`。 +- 从代码中,通过调用 `kdb_enter(9)`。 -In development, the programmatic entry is the most -convenient. You can drop into `DDB` at a specific point in a -script without waiting for a panic. +在开发中,编程方式进入最方便。你可以在脚本中在特定点投入 `DDB` 而不等 panic。 -### DDB Prompts and Commands +### DDB 提示符和命令 -Once inside, `DDB` presents a prompt. The standard prompt is -simply `db>`. Commands are typed, followed by Enter. `DDB` has -a command history (press up-arrow on the serial console) and -tab-completion for many command names. +一旦进入,`DDB` 呈现提示符。标准提示符就是 `db>`。输入命令后按回车。`DDB` 有命令历史(在串行控制台上按上箭头)和许多命令名的 tab 补全。 -A useful first command is `help`, which lists categories of -commands. `help show` lists the many `show` subcommands. Most -exploration happens through `show`. +一个有用的第一个命令是 `help`,列出命令类别。`help show` 列出许多 `show` 子命令。大多数探索通过 `show` 完成。 -### Walking a Thread +### 遍历线程 -The most common diagnostic task in `DDB` is to walk a specific -thread. Start with `ps`, which lists all processes: +`DDB` 中最常见的诊断任务是遍历特定线程。从 `ps` 开始,列出所有进程: ```console db> ps @@ -4244,8 +2420,7 @@ db> ps 500 499 500 0 SL nanslp [...] user_program ``` -Pick the thread of interest. In `DDB`, switching to a thread -is done by the `show thread` command: +选择感兴趣的线程。在 `DDB` 中,通过 `show thread` 命令切换线程: ```console db> show thread 100012 @@ -4254,14 +2429,11 @@ db> show thread 100012 db> bt ``` -This walks the stack of that specific thread. A kernel deadlock -investigation typically involves walking each stuck thread to -see where it is waiting. +这遍历该特定线程的栈。内核死锁调查通常涉及遍历每个卡住的线程,看它在等待什么。 -### Inspecting Structures +### 检查结构 -`DDB` can dereference pointers and print structure fields if -the kernel was built with `DDB_CTF`. Example: +如果内核用 `DDB_CTF` 构建,`DDB` 可以解引用指针并打印结构字段。示例: ```console db> show proc 500 @@ -4269,99 +2441,57 @@ db> show malloc db> show uma ``` -Each of these prints a formatted view of the relevant kernel -state. `show malloc` gives a table of malloc types and their -current allocations. `show uma` does the same for UMA zones. -`show proc` shows a specific process in detail. +每个命令打印相关内核状态的格式化视图。`show malloc` 给出 malloc 类型及其当前分配的表。`show uma` 对 UMA 区域做同样的。`show proc` 详细显示特定进程。 -### Setting Breakpoints +### 设置断点 -`DDB` supports breakpoints. `break FUNC` sets a breakpoint at -the entry to a function. `continue` resumes execution. When the -breakpoint fires, the kernel returns to `DDB` and you can -inspect state at that point. +`DDB` 支持断点。`break FUNC` 在函数入口设置断点。`continue` 恢复执行。当断点触发时,内核返回 `DDB`,你可以检查该点的状态。 -This is the machinery that makes `DDB` a real debugger, not -just a crash inspector. With breakpoints you can pause the -kernel at a specific code location, examine arguments, and -decide whether to continue. +这是使 `DDB` 成为真正调试器而非仅是崩溃检查器的机制。使用断点你可以在特定代码位置暂停内核、检查参数,并决定是否继续。 -The catch is that a kernel paused in `DDB` really is paused. -While you are in `DDB`, no other thread runs. On a network -server, every client times out. On a desktop, the GUI freezes. -For local, development-VM debugging, this is fine. For any -remote or shared use, it is not. +注意事项是在 `DDB` 中暂停的内核确实是暂停的。当你在 `DDB` 中时,没有其他线程运行。在网络服务器上,每个客户端超时。在桌面上,GUI 冻结。对于本地开发虚拟机调试,这没问题。对于任何远程或共享使用,不行。 -### Scripting DDB +### 脚本化 DDB -`DDB` supports a simple scripting facility. You can define -named scripts that execute a sequence of `DDB` commands. -`script kdb.enter.panic=bt; show registers; show proc` makes -those three commands run automatically every time the debugger -enters due to a panic. This is useful for unattended dumps: -the scripted output appears on the console and in the dump, -giving you information without needing an interactive session. +`DDB` 支持简单的脚本功能。你可以定义命名脚本,执行一系列 `DDB` 命令。`script kdb.enter.panic=bt; show registers; show proc` 使这三个命令在每次因 panic 进入调试器时自动运行。这对无人值守的转储有用:脚本化输出出现在控制台和转储中,为你提供信息而无需交互式会话。 -The scripts are stored in kernel memory and can be configured -at boot via `/boot/loader.conf` or at runtime with `sysctl` -calls. See `ddb(4)` for the exact syntax. +脚本存储在内核内存中,可以在启动时通过 `/boot/loader.conf` 或运行时通过 `sysctl` 调用配置。参见 `ddb(4)` 获取确切语法。 -### Exiting DDB +### 退出 DDB -When you are done, `continue` exits `DDB` and the kernel -resumes. `reset` reboots. `call doadump` forces a dump and -reboot. `call panic` triggers a panic intentionally (useful -when you want a dump from the current state but did not reach -`DDB` via a panic). +完成后,`continue` 退出 `DDB`,内核恢复运行。`reset` 重启。`call doadump` 强制转储并重启。`call panic` 故意触发 panic(当你想从当前状态获取转储但不是通过 panic 到达 `DDB` 时有用)。 -For the developer practicing on a VM, `continue` is the one -command to remember. It brings the kernel back to life and -lets you keep working. +对于在虚拟机上练习的开发者,`continue` 是要记住的命令。它让内核恢复运行,让你继续工作。 -### DDB vs kgdb: When to Use Each +### DDB 与 kgdb:何时使用哪个 -`DDB` and `kgdb` overlap but are not interchangeable. +`DDB` 和 `kgdb` 有重叠但不可互换。 -Use `DDB` when the kernel is running (or paused on a specific -event) and you want to poke around. `DDB` runs inside the -kernel and has direct access to kernel memory and threads. It -is the right tool for quick state checks, for setting -breakpoints, and for stopping on specific events. +当内核正在运行(或暂停在特定事件上)而你想要到处看看时使用 `DDB`。`DDB` 在内核内部运行,直接访问内核内存和线程。它是快速状态检查、设置断点和在特定事件上停止的正确工具。 -Use `kgdb` on a crash dump, after the machine has rebooted. -`kgdb` has no access to a running system's threads, but it has -full gdb features for offline analysis: command history, -source browsing, scripting with Python, and so on. +当机器重启后在崩溃转储上使用 `kgdb`。`kgdb` 没有访问运行系统线程的能力,但它有完整的 gdb 功能用于离线分析:命令历史、源代码浏览、Python 脚本等等。 -For a live kernel that you cannot reboot, the GDB stub backend -of `KDB` bridges the gap: the kernel pauses, and `kgdb` on -another machine attaches over a serial line for full gdb -features on the live state. This is the most capable -combination but requires two machines (or VMs). +对于你不能重启的运行中内核,`KDB` 的 GDB 桩后端弥合了差距:内核暂停,另一台机器上的 `kgdb` 通过串行线附加,在实时状态上获得完整的 gdb 功能。这是最强大的组合,但需要两台机器(或虚拟机)。 -## Practical Worked Example: Following a Null Pointer +## 实战演练示例:跟踪空指针 -To pull the tools together, let us walk through one more -worked example. The symptom: `bugdemo` occasionally panics -with `page fault: supervisor read instruction` and a -backtrace through `bugdemo_read`. The panic address is low, -suggesting a null pointer dereference. +为了将工具整合在一起,让我们再走一个演练示例。症状是:`bugdemo` 偶尔以 `page fault: supervisor read instruction` 和经过 `bugdemo_read` 的回溯 panic。panic 地址很低,暗示空指针解引用。 -### Step 1: Capture the Dump +### 步骤 1:捕获转储 -After the panic, we confirm a dump was saved: +panic 后,我们确认转储已保存: ```console # ls -l /var/crash/ ``` -and open it: +并打开它: ```console # kgdb /boot/kernel/kernel /var/crash/vmcore.last ``` -### Step 2: Read the Backtrace +### 步骤 2:阅读回溯 ```console (kgdb) bt @@ -4373,15 +2503,14 @@ and open it: at /usr/src/sys/modules/bugdemo/bugdemo.c:185 ``` -The interesting frame is 8, `bugdemo_read`. The code at line -185 is: +有趣的帧是 8,`bugdemo_read`。第 185 行的代码是: ```c sc = dev->si_drv1; amt = MIN(uio->uio_resid, sc->buflen); ``` -### Step 3: Inspect the Variables +### 步骤 3:检查变量 ```console (kgdb) frame 8 @@ -4391,311 +2520,126 @@ $1 = (struct bugdemo_softc *) 0x0 $2 = (void *) 0x0 ``` -`si_drv1` is NULL on the dev. This is the private pointer that -`make_dev(9)` sets; it should have been set during attach. +`si_drv1` 在设备上为 NULL。这是 `make_dev(9)` 设置的私有指针;它应该在 attach 期间被设置。 -### Step 4: Walk Back +### 步骤 4:回溯 ```console (kgdb) print *dev ``` -We see the device structure. The name field says "bugdemo", -the flags look reasonable, but `si_drv1` is NULL. Something -cleared it. +我们看到设备结构。名称字段显示"bugdemo",标志看起来合理,但 `si_drv1` 是 NULL。有东西清除了它。 -### Step 5: Form a Hypothesis +### 步骤 5:形成假设 -In the source, `si_drv1` is set once, in `attach`, and it is -read in every `read`, `write`, and `ioctl` handler. It is -never explicitly cleared. However, in the unload path, the -device is destroyed with `destroy_dev(9)`, which returns -before pending handlers finish. If a `read` is in progress -when unload starts, the dev might be partially destroyed. +在源代码中,`si_drv1` 设置一次,在 `attach` 中,在每个 `read`、`write` 和 `ioctl` 处理程序中读取。它从未被显式清除。然而,在卸载路径中,设备用 `destroy_dev(9)` 销毁,它在待处理处理程序完成之前就返回了。如果卸载开始时有一个 `read` 正在进行,设备可能被部分销毁。 -### Step 6: Add an Assertion +### 步骤 6:添加断言 -A `KASSERT` at the top of `bugdemo_read` catches the case: +在 `bugdemo_read` 顶部的 `KASSERT` 捕获这种情况: ```c KASSERT(sc != NULL, ("bugdemo_read: no softc")); ``` -With this assertion in place, the next panic gives us the same -information without requiring a dump walk. We also know -immediately that the condition is real, not a random -corruption. +有了这个断言,下一次 panic 给我们相同的信息而不需要遍历转储。我们也立即知道条件是真实的,而非随机损坏。 -### Step 7: Fix the Bug +### 步骤 7:修复 Bug -The real fix is to make the unload path wait for pending -handlers before destroying the device. FreeBSD provides -`destroy_dev_drain(9)` for exactly this purpose. Using it: +真正的修复是让卸载路径在销毁设备之前等待待处理处理程序。FreeBSD 为此目的提供了 `destroy_dev_drain(9)`。使用它: ```c destroy_dev_drain(sc->dev); ``` -ensures that no read or write is in flight when the softc is -freed. +确保在 softc 被释放时没有 read 或 write 正在进行。 -### Step 8: Verify +### 步骤 8:验证 -Load the fixed driver. Run concurrent reads and unloads. The -panic does not reproduce. The `KASSERT` stays in the code as -a safety net for future refactoring. +加载修复后的驱动程序。并发运行 read 和 unload。panic 不再重现。`KASSERT` 留在代码中作为未来重构的安全网。 -### Takeaway +### 要点 -This workflow (capture, read, inspect, hypothesize, verify) -is the shape of most productive debugging sessions. Each tool -plays a small, specific role. The discipline is to gather -evidence before acting, and to leave assertions behind as -witnesses for the future. +这个工作流(捕获、阅读、检查、假设、验证)是大多数高效调试会话的形态。每个工具扮演一个小而具体的角色。纪律是在行动之前收集证据,并留下断言作为未来的见证。 ## 从第一天起让驱动可观测 -A theme running through this chapter is that the best time to -add debugging infrastructure is before you need it. A driver -that was designed with observability in mind is easier to -debug than a driver that was designed for speed alone. +贯穿本章的一个主题是添加调试基础设施的最佳时机是在你需要它之前。设计时就考虑可观测性的驱动程序比只为速度设计的驱动程序更容易调试。 -A few concrete habits support this. +一些具体的习惯支持这一点。 -### Name Every Allocator Type +### 为每个分配器类型命名 -`MALLOC_DEFINE(9)` requires a short and a long name. The short -name is what appears in `vmstat -m` output and in `memguard(9)` -targeting. Picking a descriptive name, unique to the driver, -makes later diagnosis easier. Never share a malloc type -between unrelated subsystems; the tooling cannot distinguish -them. +`MALLOC_DEFINE(9)` 需要一个短名称和一个长名称。短名称是出现在 `vmstat -m` 输出和 `memguard(9)` 目标中的名称。选择一个描述性的、驱动程序唯一的名称,使后续诊断更容易。永远不要在不相关的子系统之间共享 malloc 类型;工具无法区分它们。 -### Count Important Events +### 计数重要事件 -Every major event in a driver (open, close, read, write, -interrupt, error, state transition) is a candidate for a -`counter(9)`. Counters are cheap, they accumulate over time, -and they are exposed through sysctl. A driver with good -counters answers most "what is this thing doing" questions -without any additional tooling. +驱动程序中的每个主要事件(open、close、read、write、中断、错误、状态转换)都是 `counter(9)` 的候选。计数器很便宜,它们随时间累积,并通过 sysctl 暴露。拥有良好计数器的驱动程序无需任何额外工具就能回答大多数"这东西在做什么"的问题。 -### Declare SDT Probes +### 声明 SDT 探针 -Every state transition is a candidate for an SDT probe. -Unlike assertions or counters, probes cost nothing when -disabled. Leaving them in the source for the lifetime of the -driver is a net win: when a bug appears, DTrace can see the -event flow without requiring a rebuild. +每个状态转换都是 SDT 探针的候选。与断言或计数器不同,探针在禁用时没有成本。将它们保留在源代码中,伴随驱动程序的整个生命周期是净收益:当 bug 出现时,DTrace 可以看到事件流而无需重建。 -### Use Consistent Log Messages +### 使用一致的日志消息 -`log(9)` messages should follow a consistent format. A prefix -that identifies the driver, a specific error code or state, -and enough context to locate the problem are the essentials. -Avoid cleverness in log messages; a reader under time pressure -wants to know what happened, not to admire your prose. +`log(9)` 消息应遵循一致的格式。标识驱动程序的前缀、特定的错误代码或状态,以及足够的上下文来定位问题,这些是基本要素。避免在日志消息中耍小聪明;时间压力下的读者想知道发生了什么,而非欣赏你的文采。 -### Provide Useful Sysctls +### 提供有用的 sysctl -Every internal flag, every counter, every configuration value -should be exposed through sysctl unless there is a specific -reason not to. The reader who needs to debug your driver will -thank you; the reader who never needs to debug your driver -pays nothing for the exposure. +每个内部标志、每个计数器、每个配置值都应通过 sysctl 暴露,除非有特定原因不这样做。需要调试你驱动程序的人会感谢你;从不需要调试你驱动程序的人不为这种暴露付出任何代价。 -### Write Assertions As You Go +### 边写代码边写断言 -The best time to add a `KASSERT` is when the invariant is -fresh in your mind, which is while you are writing the code. -Going back later to sprinkle assertions is less effective -because you have forgotten some invariants and have -rationalized others as "obvious." +添加 `KASSERT` 的最佳时机是在不变式在你脑海中最清晰的时候,即你编写代码时。之后再回去撒断言效果较差,因为你已经忘记了一些不变式,并将其他一些合理化为"显而易见"。 -### Expose the State of the State Machine +### 暴露状态机的状态 -Every nontrivial driver has a state machine. Exposing the -current state through a sysctl, an SDT probe at each -transition, and a counter per state makes the state machine -visible to both humans and tools. This is particularly -important for asynchronous drivers, which is the subject of -the next chapter. +每个非平凡的驱动程序都有状态机。通过 sysctl 暴露当前状态、在每个转换处添加 SDT 探针、以及为每个状态设置计数器,使状态机对人和工具都可见。这对异步驱动程序特别重要,这是下一章的主题。 -### Test the Unload Path +### 测试卸载路径 -An underhardened unload path is a classic source of crashes. -In development, write a test that loads the driver, exercises -it briefly, and unloads it, repeatedly and under various -conditions. If the driver cannot sustain a hundred -load/unload cycles, it has bugs. +未充分加固的卸载路径是经典的崩溃来源。在开发中,编写一个测试,加载驱动程序、短暂使用它、然后卸载它,在各种条件下重复执行。如果驱动程序无法承受一百次加载/卸载循环,它就有 bug。 -These habits cost a little time in development and pay for -themselves many times over in debugging. A disciplined driver -author applies them all, even to drivers that look too simple -to need them. +这些习惯在开发中花费一点时间,但在调试中多次回本。有纪律的驱动程序作者把它们全部应用,即使对看起来太简单而用不上的驱动程序也是如此。 -## Real-World Reading List +## 实用阅读清单 -Every tool in this chapter is documented more completely in its own -man page or source file. That is good news: you do not have to carry -the whole toolbox in your head. When a bug points you at a specific -subsystem, opening the right man page or source file will almost -always take you further than any chapter can. The following list -gathers the references that matter most for this material, in the -order you are likely to need them. +本章中的每种工具在其自己的手册页或源文件中都有更完整的文档。这是好消息:你不必把整个工具箱装在脑子里。当 bug 将你引向特定子系统时,打开正确的手册页或源文件几乎总是比任何章节都走得更远。以下列表按照你可能需要它们的顺序,汇集了对本材料最重要的参考。 -The `witness(4)` man page is the first thing to read when -`GENERIC-DEBUG` starts printing lock order reversals and you want to -understand exactly what the output means, which `sysctl` controls -change behavior, and which counters you can inspect. It documents -the `debug.witness.*` sysctls, the `show all_locks` DDB command, and -the general approach `WITNESS` takes to bookkeeping. For the actual -implementation, `/usr/src/sys/kern/subr_witness.c` is the -authoritative source. Reading the structures it maintains and the -shape of its output functions (the ones that produce the "1st ... -2nd ..." lines you saw earlier in this chapter) removes most of the -mystery from a `WITNESS` report. The file is long, but the top -comment and the output-producing functions together cover most of -what a driver author needs to know. +`witness(4)` 手册页是当 `GENERIC-DEBUG` 开始打印锁序反转而你想要确切理解输出含义、哪些 `sysctl` 控制改变行为、以及哪些计数器可以检查时首先要阅读的。它记录了 `debug.witness.*` sysctl、`show all_locks` DDB 命令,以及 `WITNESS` 簿记的一般方法。对于实际实现,`/usr/src/sys/kern/subr_witness.c` 是权威来源。阅读它维护的结构和产生输出的函数(那些产生你之前在本章中看到的"1st ... 2nd ..."行的函数)消除了 `WITNESS` 报告中大部分的神秘感。该文件很长,但顶部注释和产生输出的函数加在一起涵盖了驱动程序作者需要了解的大部分内容。 -For lock profiling, `lockstat(1)` is documented in -`/usr/src/cddl/contrib/opensolaris/cmd/lockstat/lockstat.1`. The man -page ends with several worked examples whose output format matches -what you will see on your own systems, which makes it a useful -reference to keep open the first time you try `-H -s 8` on a real -workload. Because `lockstat(1)` is DTrace-backed, the `dtrace(1)` -man page is its natural companion; you can express the same queries -in raw D if you need flexibility the `lockstat` command-line flags -do not offer. +对于锁性能分析,`lockstat(1)` 记录在 `/usr/src/cddl/contrib/opensolaris/cmd/lockstat/lockstat.1` 中。手册页末尾有几个演练示例,其输出格式与你将在自己系统上看到的匹配,这使得它在你第一次在真实负载上尝试 `-H -s 8` 时是一个有用的参考。因为 `lockstat(1)` 是基于 DTrace 的,`dtrace(1)` 手册页是它的天然伴侣;你可以用原始 D 表达相同的查询,如果你需要 `lockstat` 命令行标志不提供的灵活性。 -For kernel debugger work, `ddb(4)` documents the in-kernel debugger -in full, including every builtin command, every script hook, and -every way to enter the debugger. When in doubt, read this page -before using a DDB command you have not tried before. For offline -post-mortem analysis, `kgdb(1)` on your installed FreeBSD system -documents the kernel-specific extensions over stock `gdb`. The -underlying access layer is in libkvm, described in -`/usr/src/lib/libkvm/kvm_open.3`, which explains both the dump and -the live-kernel modes you met in Section 3. +对于内核调试器工作,`ddb(4)` 完整记录了内核内调试器,包括每个内建命令、每个脚本钩子,以及每种进入调试器的方式。有疑问时,在使用你之前未尝试过的 DDB 命令之前阅读此页面。对于离线事后分析,你安装的 FreeBSD 系统上的 `kgdb(1)` 记录了在标准 `gdb` 之上的内核特定扩展。底层访问层在 libkvm 中,记录在 `/usr/src/lib/libkvm/kvm_open.3`,它解释了你在第 3 节中遇到的转储和运行中内核两种模式。 -Two smaller pointers are worth keeping in your reading queue. The -first is `/usr/src/share/examples/witness/lockgraphs.sh`, a tiny -shell script shipped in the base system that demonstrates how to -turn `WITNESS`'s accumulated lock-order graph into a visual diagram. -On a real driver, running it once gives you a picture of where your -locks sit relative to the rest of the kernel's lock hierarchy, and -it can be surprising. The second is the FreeBSD kernel source tree -itself: reading `/usr/src/sys/kern/kern_shutdown.c` (the panic and -dump path) and `/usr/src/sys/kern/kern_mutex.c` (the mutex -implementation that `WITNESS` instruments) grounds the whole -debugging workflow in the code that actually implements it. +两个较小的指针值得保留在你的阅读队列中。第一个是 `/usr/src/share/examples/witness/lockgraphs.sh`,一个随基本系统发布的小型 shell 脚本,演示了如何将 `WITNESS` 累积的锁序图转换为可视化图表。在真实驱动程序上运行一次就能给你一张你的锁相对于内核其余部分锁层次结构的位置图,这可能令人惊讶。第二个是 FreeBSD 内核源码树本身:阅读 `/usr/src/sys/kern/kern_shutdown.c`(panic 和转储路径)和 `/usr/src/sys/kern/kern_mutex.c`(`WITNESS` 插桩的互斥锁实现)将整个调试工作流建立在实际实现它的代码之上。 -Beyond the source tree, the FreeBSD Developers' Handbook and the -FreeBSD Architecture Handbook both contain longer-form articles on -kernel debugging. Both are shipped with the documentation set on -any FreeBSD system and kept up to date alongside the source. They -are worth browsing once, even if you do not read them end to end, -because they give names to patterns you will later recognize in -your own debugging sessions. +在源码树之外,FreeBSD 开发者手册和 FreeBSD 架构手册都包含关于内核调试的较长文章。两者都随任何 FreeBSD 系统上的文档集发布,并与源代码同步更新。它们值得浏览一次,即使你不从头读到尾,因为它们为你以后在自己的调试会话中会识别的模式赋予了名称。 -A final note on choosing references. Man pages age more slowly than -blog posts, and source comments age more slowly than man pages. -When two references disagree, trust the source, then the man page, -then the handbook, then everything else. That hierarchy has served -FreeBSD developers well for decades, and the habit will serve you -through the rest of this book and the rest of your career. +关于选择参考的最后一点。手册页比博客文章老化得更慢,源代码注释比手册页老化得更慢。当两个参考不一致时,信任源代码,然后是手册页,然后是手册,然后是其他一切。这个层次结构数十年来很好地服务了 FreeBSD 开发者,这个习惯将在本书的其余部分和你的职业生涯中为你服务。 ## 总结 -Advanced debugging is a patient craft. Each tool in this chapter -exists because someone, somewhere, faced a bug that could not be -found any other way. `KASSERT` exists because invariants that -live only in the programmer's head are not invariants. `kgdb` and -crash dumps exist because some bugs destroy the machine that -produced them. `DDB` exists because a frozen kernel cannot -explain itself through any other channel. `WITNESS` exists -because deadlocks are catastrophic in production and impossible -to debug after the fact. `memguard(9)` exists because silent -memory corruption was the hardest class of bug until someone -built a tool that made it loud. +高级调试是一门耐心的手艺。本章中的每种工具之所以存在,是因为某个人在某处遇到了无法通过其他方式找到的 bug。`KASSERT` 存在是因为只存在于程序员脑海中的不变式不是不变式。`kgdb` 和崩溃转储存在是因为有些 bug 会摧毁产生它们的机器。`DDB` 存在是因为冻结的内核无法通过其他任何渠道解释自己。`WITNESS` 存在是因为死锁在生产中是灾难性的而且在事后不可能调试。`memguard(9)` 存在是因为静默的内存损坏曾是最难的一类 bug,直到有人构建了一个让它变得响亮的工具。 -None of these tools replace understanding. A debugger cannot -tell you what your driver should do. A crash dump cannot tell -you the right locking discipline. DTrace cannot infer your -design. The tools are instruments; you are the player. The -music is the shape of the driver you are building. +这些工具都不能替代理解。调试器不能告诉你驱动程序应该做什么。崩溃转储不能告诉你正确的加锁纪律。DTrace 不能推断你的设计。工具是乐器;你是演奏者。音乐是你正在构建的驱动程序的形态。 -The habits that make this craft successful are small and -undramatic. Develop on a debug kernel. Add assertions for every -invariant you can articulate. Capture dumps routinely so you -can open them without ceremony. Keep a journal when you are -chasing something hard. Read the FreeBSD source when a -mechanism mystifies you. Reach for the lightest tool that will -answer your question, and graduate to heavier tools only when -the lighter ones come up short. +使这门手艺成功的习惯是微小而不引人注目的。在调试内核上开发。为你能表述的每个不变式添加断言。常规地捕获转储,这样你可以毫无仪式地打开它们。在追查困难的东西时保持日志。当某个机制困扰你时阅读 FreeBSD 源代码。选择能回答你问题的最轻量工具,只在更轻量的工具不足时才升级到更重的工具。 -Debugging is also a social craft. A bug that takes you a day -to find, written up clearly, can save another author a week. -Good commit messages, detailed test cases, and honest accounts -of what worked and what did not are contributions to the -common practice. The FreeBSD project's historical patience with -bug reports, its habit of capturing root causes in commit logs, -and its consistent use of `KASSERT` and `WITNESS` across -decades of drivers all stem from this collective habit of -treating bug hunting as a shared responsibility. +调试也是一门社交手艺。一个花了你一天才找到的 bug,写清楚后可以为另一个作者节省一周。好的提交消息、详细的测试用例、以及对什么有效什么无效的诚实记录,都是对公共实践的贡献。FreeBSD 项目对 bug 报告的历史耐心、在提交日志中捕获根因的习惯,以及数十年来在驱动程序中一致使用 `KASSERT` 和 `WITNESS`,都源于将 bug 狩猎视为共同责任的集体习惯。 -You now have the toolkit to participate. Load a debug kernel, -pick a driver in `/usr/src/sys/dev/` that interests you, and -read it with a debugger's eye. Where are the invariants? Where -are the assertions? Where is the locking discipline? Where -might a bug hide, and what tool would catch it? The exercise -sharpens the instincts the rest of this book has been building. +你现在有了参与其中的工具包。加载调试内核,在 `/usr/src/sys/dev/` 中选一个你感兴趣的驱动程序,用调试器的眼睛阅读它。不变式在哪里?断言在哪里?加锁纪律在哪里?bug 可能藏在哪里,什么工具能捕获它?这个练习磨砺本书其余部分一直在建立的直觉。 -In the next chapter, we will leave correctness behind and look -at how drivers handle asynchronous I/O and event-driven work: -the patterns by which a driver serves many users at once -without blocking, and the kernel facilities that make such -designs possible. The debugging skills you have gained here will -serve you well in that territory, because asynchronous code is -where subtle concurrency bugs tend to live. A driver with solid -assertions, a clean lock ordering verified by `WITNESS`, and a -set of SDT probes to trace its event flow is also a driver that -is much easier to reason about when its work is spread across -callbacks, timers, and kernel threads. +在下一章中,我们将把正确性放在一边,看看驱动程序如何处理异步 I/O 和事件驱动的工作:驱动程序一次为多个用户服务而不阻塞的模式,以及使这种设计成为可能的内核设施。你在这里获得的调试技能将在那个领域很好地为你服务,因为异步代码正是微妙并发 bug 倾向栖息的地方。一个有坚实断言、经 `WITNESS` 验证的干净锁序、以及一组 SDT 探针来跟踪其事件流的驱动程序,也是一个当其工作分散在回调、定时器和内核线程之间时更容易推理的驱动程序。 ## 通往第35章的桥梁:异步I/O与事件处理 -Chapter 35 picks up where this one leaves off. Synchronous code -is straightforward to reason about: a call arrives, the driver -does its work, the call returns. Asynchronous code is not: -callbacks fire at unpredictable times, events arrive out of -order, and the driver must manage state that persists across -many thread contexts. +第 35 章从本章结束的地方接续。同步代码容易推理:一个调用到达,驱动程序做它的工作,调用返回。异步代码则不然:回调在不可预测的时间触发,事件乱序到达,驱动程序必须管理跨越多个线程上下文持久存在的状态。 -The complexity of asynchronous drivers is exactly the kind of -complexity that benefits from the tools of this chapter. A -synchronous driver with a bug might crash at a predictable -place. An asynchronous driver with a bug might crash hours -later, in a callback that has no obvious connection to the -original misbehavior. `KASSERT` on the state at each callback -entry catches such bugs early. DTrace probes on each event -transition make the sequence visible. `WITNESS` detects the -deadlocks that arise naturally when multiple asynchronous paths -need to coordinate. +异步驱动程序的复杂性正是本章工具所擅长的那类复杂性。有 bug 的同步驱动程序可能在可预测的位置崩溃。有 bug 的异步驱动程序可能在数小时后在一个与原始误行为没有明显联系的回调中崩溃。在每个回调入口对状态使用 `KASSERT` 可以早早捕获这类 bug。在每个事件转换上使用 DTrace 探针使序列可见。`WITNESS` 检测当多个异步路径需要协调时自然产生的死锁。 -In the next chapter we will meet the building blocks of -asynchronous work in FreeBSD: `callout(9)` for deferred timers, -`taskqueue(9)` for background work, `kqueue(9)` for event -notification, and the patterns for using them correctly. We -will build a driver that serves many concurrent users without -blocking, and we will exercise the debugging techniques of this -chapter to keep that complexity under control. +在下一章中,我们将认识 FreeBSD 中异步工作的构建块:`callout(9)` 用于延迟定时器、`taskqueue(9)` 用于后台工作、`kqueue(9)` 用于事件通知,以及正确使用它们的模式。我们将构建一个为许多并发用户服务而不阻塞的驱动程序,并将运用本章的调试技术来控制那种复杂性。 -By the time you finish Chapter 35, you will have the full -synchronous and asynchronous toolkit: drivers that handle -traffic efficiently, scale to many users, maintain correctness -under concurrency, and can be debugged when something -nevertheless goes wrong. That combination is what it takes to -write drivers that survive in production. +到完成第 35 章时,你将拥有完整的同步和异步工具包:能高效处理流量、扩展到多用户、在并发下维护正确性、以及在出问题时能被调试的驱动程序。这种组合正是在生产环境中存活下来的驱动程序所需要的。 -See you in Chapter 35. +第 35 章见。 diff --git a/translations/zh_CN/chapters/part7/chapter-36.md b/translations/zh_CN/chapters/part7/chapter-36.md index be2a1a2..4a4b5db 100644 --- a/translations/zh_CN/chapters/part7/chapter-36.md +++ b/translations/zh_CN/chapters/part7/chapter-36.md @@ -1312,230 +1312,8 @@ bhyve PCI 直通是一种模拟形式,将真实硬件暴露给虚拟机,同 - 如果工作主要是文档(你部分逆向工程了设备并发布了寄存器映射),`freebsd-hackers@` 和相关论坛都适合。 发布让他人受益于你的工作。他们可以修复错误、添加功能或将其用作类似设备的起点。发布也让你受益:用户报告错误、建议改进、有时贡献补丁。一个发布的驱动程序会改进;一个私人驱动程序停滞。 -没有正确释放;这是分离路径中的错误,需要在进行进一步工作之前修复。 -### 6.9 干净卸载 - -分离路径至少与附加路径同等重要。可以加载但不能干净卸载的驱动程序是每次想测试更改时都需要重启的驱动程序,重启很快就会成为你工作的瓶颈。尽早花时间在干净的分离路径上会在开发速度上产生巨大回报。 - -```c -static int -mydev_detach(device_t dev) -{ - struct mydev_softc *sc = device_get_softc(dev); - - if (sc->sc_ih != NULL) - bus_teardown_intr(dev, sc->sc_irq, sc->sc_ih); - if (sc->sc_irq != NULL) - bus_release_resource(dev, SYS_RES_IRQ, - sc->sc_irid, sc->sc_irq); - if (sc->sc_mem != NULL) - bus_release_resource(dev, SYS_RES_MEMORY, - sc->sc_rid, sc->sc_mem); - mtx_destroy(&sc->sc_mtx); - return (0); -} -``` - -分配的每个资源都必须释放。注册的每个中断处理器都必须拆除。每个互斥锁都必须销毁。顺序是分配顺序的逆序,这是一条有用的通用规则。 - -### 6.10 第6节小结 - -最小驱动程序是一个基础。它做的事情很少,但正确地完成了那很少的事情。复位有效,标识符验证有效,资源分配正确,分离路径干净。从这个基础开始,每个后续功能都可以增量添加,并确信底层脚手架是健全的。 - -下一节将采用最小驱动程序并展示如何一次添加一个功能,在添加下一个之前总是确认每个新功能是正确的。该技术是增量开发的纪律应用于没有规范可参考的领域:我们不是根据规范进行验证,而是根据捕获和测量行为进行验证。结果是一样的:一个做我们相信它所做的事情的驱动程序,由证据而非希望支持。 - -## 7. 迭代扩展驱动程序并确认行为 - -第6节的最小驱动程序是真正驱动程序的种子。要将其成长为有用的东西,你需要一次添加一个功能,对于每个功能,你要确认运行驱动程序中该功能所做的与你在厂商驱动程序下观察到的设备行为相匹配。过程简单但要求严格:每个步骤都必须验证,每次验证都必须记录,每条记录都成为第11节将组装的伪数据手册的一部分。 - -本节介绍增量扩展的方法论。它不引入新的底层技术,因为底层技术与第4和第6节相同。它增加的是在不确定性下负责任地成长驱动程序的纪律。 - -### 7.1 一次一个功能的规则 - -规则就在名字里。添加一个功能,验证它有效,将结果提交到你的仓库,然后添加下一个功能。不要一次添加三个功能然后试图调试组合。不要在不验证的情况下添加功能并继续下一个。不要跳过提交,因为提交是让你在后续更改破坏以前有效的东西时可以回滚的东西。 - -这种纪律与测试驱动开发相同,有一个重要的适应:测试通常是第3节捕获的比较,而不是传统意义上的单元测试。"测试"是"当被调用执行操作 X 时,驱动程序产生与厂商驱动程序相同的寄存器访问序列"。比较是机械的,但它是真正的测试:序列要么匹配要么不匹配,失败告诉你某些东西已经改变。 - -网络控制器的典型功能序列可能是: - -1. 读取 MAC 地址。 -2. 设置 MAC 地址。 -3. 设置接收描述符环。 -4. 接收一个数据包。 -5. 设置发送描述符环。 -6. 发送一个数据包。 -7. 启用中断。 -8. 实现中断处理器。 -9. 启动链路。 -10. 关闭链路。 -11. 复位并从错误中恢复。 - -每个项目是一个离散的功能。每个项目建立在前面的项目之上。每个项目有明确的成功标准(操作要么有效要么无效)。每个项目都有第3节中对应的捕获,驱动程序的行为可以与之进行比较。 - -### 7.2 验证循环 - -对于每个新功能,验证循环是: - -1. 形成假设:此功能通过执行 X 来工作。 -2. 在驱动程序中实现该功能,带有记录每个寄存器访问的日志。 -3. 使用小型用户空间程序、sysctl 或任何你已连接的接口触发该功能。 -4. 捕获内核日志输出。 -5. 与第3节中相关的捕获进行比较。 -6. 如果它们匹配,声明功能已实现。 -7. 如果它们不匹配,识别差异并决定是你的实现错误还是你的假设错误。 - -循环很慢。单个功能可能需要循环几次,中间还有假设修订。但慢就是重点。每次迭代都是一个有意识的测试,带有有意识的预测和有意识的观察。经过多次迭代,已验证事实的主体稳步增长,错误信念存活到最终驱动程序中的机会迅速缩小。 - -### 7.3 与厂商比较的模式 - -与厂商驱动程序的比较对于这项工作如此核心,以至于它值得自己的讨论。模式如下。 - -你有第3节中厂商驱动程序执行操作 X 的捕获。捕获包含寄存器访问列表(对于内存映射设备)或 USB 传输(对于 USB 设备),每个都标有时间戳、地址或端点、方向和值。 - -你有你的驱动程序,启用日志,执行相同的操作 X。内核日志包含寄存器访问或 USB 传输列表,每个都标有时间戳、地址或端点、方向和值。 - -你比较两个列表。访问应该以相同的顺序、相同的地址或端点、相同的方向,值要么完全匹配,要么以你可以解释的方式不同(因为,例如,值包括序列号或时间戳,它们在运行之间自然不同)。 - -两个列表一致的地方,你的驱动程序正在做厂商驱动程序所做的。它们不一致的地方,你有差异需要调查。有些差异是良性的:你的驱动程序可能省略了厂商驱动程序出于某种内部原因执行的冗余寄存器读取,省略对设备行为没有影响。其他差异是真正的错误:你写入的值不正确、你错过的序列步骤、你没有意识到操作需要的寄存器。 - -与厂商比较的模式本质上是一种示例规范。操作 X 的规范是"厂商驱动程序在执行操作 X 时进行的访问序列"。当你的访问序列匹配时,你的实现符合规范。该技术并不完美:它无法检测影响设备内部状态但不影响访问序列的错误,它无法检测你写入值中的错误,如果这些值在厂商捕获中也在运行之间变化。但它捕捉绝大多数实现错误,并且它正好在它们发生的详细程度上捕捉它们。 - -### 7.4 记录每个发现的寄存器 - -随着你添加功能,你发现寄存器。你在任何功能中写入或读取的每个寄存器都是寄存器映射的一部分,每个都需要添加到你正在构建的伪数据手册中。 - -一种有用的技术是将伪数据手册作为驱动程序源代码旁边的单独 Markdown 文件维护,并在每次发现新事实时更新它。第11节将详细讨论伪数据手册的结构;现在,规则很简单:你学到的任何事实都不应该只留在驱动程序代码中。驱动程序代码是实现;伪数据手册是文档。它们服务于不同的目的,阅读其中任何一个的人都应该能够理解设备。 - -一个常见的错误是将文档推迟到项目"完成"。逆向工程项目很少在这个意义上完成。它们随时间达到越来越高的完整度水平,文档应该与实现一起增长。一个有二十个功能和一段话伪数据手册的驱动程序是等待发生的维护灾难,因为没有人可以在不重新发现你已经知道的一切的情况下扩展它。 - -### 7.5 当厂商驱动程序与自身不一致时 - -当厂商驱动程序在不同场合以不同方式执行同一操作时,会出现一个微妙的复杂情况。有时这是因为驱动程序对同一操作有多条代码路径,取决于设备状态或用户配置。有时是因为驱动程序有在特定条件下激活的可选行为。 - -当你遇到这种变化时,正确的反应是捕获更多,而不是放弃。在几种不同的起始条件下捕获操作并比较它们。如果你能识别出什么条件选择每个变体,你就学到了关于驱动程序逻辑的一些东西。如果变体在功能上等效(它们都达到相同的最终状态),你可以选择最简单的一个作为规范实现。如果它们在功能上不等效,设备可能有多种需要支持的操作模式。 - -有时变化只是非确定性:厂商驱动程序从计数器选择序列号,或使用时间戳,结果捕获在运行之间略有不同。非确定性是良性的,学习识别它(这样你可以忽略它)是比较捕获技能的一部分。 - -### 7.6 在假设分歧时分支驱动程序 - -当你有两个相互竞争的假设和一个可以区分它们的实验时,值得在 git 中分支你的驱动程序。为实验创建一个 Git 分支,实现更改,运行实验,观察结果,然后合并或丢弃该分支。分支是廉价的;你可以同时有几个假设测试分支在运行,当新实验看起来值得时可以回到任何一个。 - -分支纪律在实验需要大量代码更改时特别有价值。没有分支,你可能不愿意花一个小时编写最终会丢弃的实验代码。有了分支,实验代码存在于自己的分支中,你的主分支保持干净。如果实验成功,你合并。如果它失败,你丢弃。无论哪种方式,你都有干净的历史。 - -### 7.7 第7节小结 - -我们学习了如何通过一次一个功能实现、与捕获比较和文档化每个发现事实的纪律化循环,将最小驱动程序成长为更强大的驱动程序。机制很简单。纪律是要求严格的。回报是一个每个功能都有证据支持的驱动程序,其寄存器映射随成长而记录,其行为可以抵御任何未来的挑战。 - -下一节转向一个稍微不同的主题:如何在冒险对真实硬件运行驱动程序之前建立对它的信心。模拟、模拟设备和验证循环是让你安全发现错误的技术,在这种情况下内核崩溃或挂起只花费一次虚拟机重启,而不是在生产环境中成本可能高得多的情况。 - -## 8. 使用仿真工具验证假设 - -逆向工程工作在两种风险之间摇摆。第一种是错误风险:编写了做你认为它做的事情以外事情的代码。第二种是正确得太晚的风险:只在错误已经造成损害时才发现错误,当错误已经将设备驱动到不可恢复的状态,或当错误已经导致生产机器崩溃时。第一种风险是不可避免的;错误是工作固有的。第二种风险很大程度上是可避免的,避免它的方法是模拟。 - -模拟器是任何让你在没有附加真实设备的情况下运行驱动程序代码的东西。模拟器范围从简单的几个寄存器读取的模拟实现,到整个设备的全功能软件模拟,再到假装成为操作系统栈上方真实设备的虚拟化硬件环境。FreeBSD 提供了几种自然融入逆向工程工作流程的类模拟器工具。 - -本节介绍三种类型的模拟:在内核中编写的模拟设备、用于模拟 USB 设备的 USB 模板框架,以及用于在受控管理程序下运行未修改真实设备的 bhyve 直通。我们将看到每种模拟如何帮助你验证假设,每种在哪里最有用,以及如何将它们与前面几节的捕获和寄存器映射工作相结合。 - -### 8.1 内核空间模拟设备 - -最简单的模拟形式是一个小型内核模块,它暴露与真实设备相同的接口但在软件中实现它们。模拟模块作为现有总线子设备附加,分配一个软件支持的"寄存器区域",并在内核中运行的 C 代码中实现寄存器读写。 - -对于内存映射设备,模拟是这样工作的。真实驱动程序会从总线分配 `SYS_RES_MEMORY` 并使用 `bus_read_4` 和 `bus_write_4` 与设备通信,而模拟模块给驱动程序一个指向软件分配的字数组的指针。读取返回请求偏移处字的当前值。写入更新字并触发任何软件实现的副作用。副作用是模拟实现设备行为的方式:当驱动程序将"go"位写入控制寄存器时,模拟可能会内部启动一个 callout,在模拟处理时间后,更新状态寄存器以指示完成并触发模拟中断。 - -模拟很小,通常只有几百行代码,对于一个其真实驱动程序有几千行的设备。目的不是实现一切;目的是实现足够的功能,使驱动程序的行为可以独立测试。一个对模拟正确处理"命令发出、命令完成、结果返回"的驱动程序,至少已经证明其顶层排序是正确的,即使模拟无法测试当真实设备产生驱动程序未预期的值时会发生什么。 - -`examples/part-07/ch36-reverse-engineering/lab04-mock-device/` 中的配套文件包含一个演示这种模式的小型模拟设备。模拟实现了一个极小的"命令和状态"接口:有一个驱动程序写入的 `CMD` 寄存器、一个模拟在模拟延迟后更新的 `STATUS` 寄存器,以及一个驱动程序在状态指示完成后读取的 `DATA` 寄存器。模拟有意简化,但它展示了结构:定义寄存器地址、为它们分配后备存储、实现读写回调,并安排回调执行模拟设备所需的任何副作用逻辑。 - -### 8.2 拦截驱动程序访问 - -更复杂的模拟可以通过在总线空间层本身进行拦截来构建。FreeBSD 的 `bus_space(9)` API 使用不透明句柄,自定义总线空间实现可以拦截驱动程序执行的每次读写。拦截可以记录访问、修改值、返回预先安排的响应,或模拟任何其他行为。 - -这种技术在你想要针对模拟器测试已为真实设备编写的驱动程序、且对驱动程序本身做最小更改时很有用。驱动程序继续像往常一样使用 `bus_read_4` 和 `bus_write_4`。拦截层接收调用并根据需要将它们分发给真实设备或伪造它们。 - -这种技术在你想要以可以与第3节捕获比较的形式准确记录驱动程序在测试期间所做的工作时也很有用。拦截总线空间层可以产生具有与捕获文件相同结构的日志文件,准备直接比较。 - -实现这种拦截比简单模拟更复杂,因为必须提供完整的总线空间实现。该模式在 FreeBSD 源码中已建立。对这种技术的深入版本感兴趣的读者可以研究 `/usr/src/sys/x86/include/bus.h` 和相关文件中的架构特定总线空间后端;那里使用的函数指针表方法正是你用于拦截层的方法。 - -### 8.3 USB模板驱动 - -对于 USB 设备,FreeBSD 包含一种异常强大的模拟机制:USB 模板框架。模板框架让内核可以假装成一个 USB 设备,带有可编程的描述符集,通过在设备模式下暴露 USB 设备端点。相关源文件位于 `/usr/src/sys/dev/usb/template/`,框架包括几个常见设备类的现成模板: - -- `usb_template_audio.c` 用于 USB 音频设备。 -- `usb_template_kbd.c` 用于 USB 键盘。 -- `usb_template_msc.c` 用于 USB 大容量存储设备。 -- `usb_template_mouse.c` 用于 USB 鼠标。 -- `usb_template_modem.c` 用于 USB 调制解调器。 -- `usb_template_serialnet.c` 用于 USB 串行网络复合设备。 - -同一目录下的其他几个模板覆盖了其他类,包括 CDC 以太网(`usb_template_cdce.c`)、CDC EEM(`usb_template_cdceem.c`)、MIDI(`usb_template_midi.c`)、MTP(`usb_template_mtp.c`),以及多功能和电话复合设备(`usb_template_multi.c`、`usb_template_phone.c`)。浏览你自己系统上的目录以查看完整列表;随着贡献者添加新设备类,这个集合随时间扩展。 - -每个模板是 USB 设备的可编程描述:它声明是哪个类、暴露哪些端点、其描述符是什么样子。加载到在设备模式下运行的 USB 主机控制器(控制器假装成 USB 电缆的设备端)后,模板让主机看到一个与描述符匹配的 USB 设备。 - -对于逆向工程工作,模板有两个用途。第一个是作为探测测试基底:你可以编写一个模仿未知设备静态身份的 USB 设备描述符,并使用模板框架将其暴露给开发机。开发机的 USB 栈将探测描述符、附加驱动程序(你的,或者如果你的描述符冲突则是内核树内的驱动程序),你可以观察主机期望具有此身份的设备做什么。当你捕获了未知设备的描述符但无法将设备本身放到你的开发机上时,这种练习特别有价值;模板让你模拟主机会看到什么。 - -第二个用途是作为实现未知 USB 设备完整协议的软件模拟器基础。构建这样的模拟器是一项重大工作,但对于非常重要的逆向工程目标,这可能是测试驱动程序代码而不冒险使用真实硬件的唯一方法。模板提供描述符方面;你必须自己添加数据处理逻辑。 - -### 8.4 bhyve与直通 - -bhyve 是 FreeBSD 的原生管理程序,其 PCI 直通支持是逆向工程的有价值工具。相关代码位于 `/usr/src/usr.sbin/bhyve/pci_passthru.c`,内核侧使用 `ppt(4)` 驱动程序(`/usr/src/sys/amd64/vmm/io/ppt.c`)来声明设备并将其暴露给客户机。 - -直通工作流程是: - -1. 在宿主机上,将设备从任何内核树内驱动程序分离: - ```sh - $ sudo devctl detach pci0:0:18:0 - ``` -2. 配置 `ppt(4)` 声明设备,通过向 `/boot/loader.conf` 添加条目: - ```text - pptdevs="0/18/0" - ``` - 这需要重启才能生效,之后设备将被 `ppt(4)` 而非任何其他驱动程序声明。 -3. 启动一个通过直通传递设备的 bhyve 客户机: - ```sh - $ sudo bhyve -c 2 -m 2G \ - -s 0,hostbridge \ - -s 1,virtio-blk,disk.img \ - -s 5,passthru,0/18/0 \ - -s 31,lpc \ - -l com1,stdio \ - myguest - ``` - `-s 5,passthru,0/18/0` 参数告诉 bhyve 将宿主机上 0/18/0 处的 PCI 设备暴露给客户机,在那里它将出现在虚拟 PCI 总线上。 - -在客户机内部,设备行为像普通 PCI 设备。客户机中运行的厂商驱动程序可以像在裸机上一样访问它。从宿主机,你不能直接看到设备的寄存器访问,因为管理程序为客户机处理它们,但你可以使用 bhyve 的日志功能查看配置空间访问、中断路由和其他通过管理程序传递的操作。 - -对于逆向工程,bhyve 直通的价值在于它让你在受控环境中运行厂商驱动程序,在那里你可以捕获否则不可见的某些类型活动。它还让你在实验之间快照和恢复宿主机,这样如果实验出错你可以快速恢复。 - -一种特别有用的模式是在宿主机上开发你自己的驱动程序,设备从 `ppt(4)` 分离,并只在你想将驱动程序行为与厂商比较时才切换到客户机直通。切换需要更改 `pptdevs` 配置并重启,但与能够在同一硬件上运行两种实现的价值相比,不便很小。 - -### 8.5 已知返回状态的循环 - -一种简单但有效的模拟形式是具有已知返回状态的验证循环。其思想是在测试模式下,让驱动程序中的某些寄存器读取返回你指定的值,而不是来自设备的值。然后你运行驱动程序并观察它对每个手工选择的值做出什么响应。 - -例如,假设你想知道当设备返回意外的状态值时驱动程序会做什么。在生产环境中,设备可能永远不会产生这样的值,也没有明显的方法来测试这个路径。通过验证循环,你将状态寄存器的读取替换为返回你指定值序列的函数:0x00,然后 0x01,然后 0xff,然后回到 0x00。驱动程序表现得好像设备依次返回了这些值,你可以验证驱动程序在每种情况下的响应是否正确。 - -验证循环技术对于错误路径特别有价值。大多数错误条件在实际操作中很少见,通过等待它们自然发生来测试它们将需要永远。通过按需强制它们发生,你可以系统地测试错误路径。这种技术在精神上与成熟系统软件中使用的故障注入技术相同,只是适应到驱动程序本身是被测试工件的逆向工程上下文中。 - -### 8.6 仿真的局限 - -模拟 enormously 有价值,但它有局限性。模拟器实现的是模拟器对设备的理解,而不是设备本身。当模拟器和真实设备不同时,模拟器的测试通过而真实设备表现异常,你就了解到你对设备的理解在某个具体方面是不完整的。 - -正确的态度是将模拟视为一种查找特定类别错误(驱动程序逻辑错误、序列错误、错误处理错误)的方法,而不是驱动程序能在真实硬件上工作的保证。驱动程序对设备约定理解中的错误不会被共享相同误解的模拟器捕获。设备实际行为中与模拟器实现不同的错误根本不会被模拟器测试捕获。 - -组合才是答案。模拟器测试捕获它能捕获的错误。使用第 10 节安全技术谨慎、增量进行的真实设备测试捕获其余错误。两者结合远比单独任何一个都好。 - -### 8.7 第8节小结 - -我们已经看到了补充逆向工程工作流的模拟工具:小型内核空间模拟设备、USB 模板框架、bhyve 直通和具有已知返回状态的验证循环。每种工具解决问题的不同方面,它们共同让你在任何错误到达真实设备之前找到大量错误。 - -下一节从技术工作中退后一步,看看社会背景:逆向工程项目如何协作、在哪里找到已有成果以及如何发布你自己的发现。逆向工程的技术部分是可见的部分,但社区部分才是使工作持久的东西。一个文档完善且良好共享的驱动程序能够长久。一个快速编写但从未发布的驱动程序往往随其作者一起消失。 - -## 9. 逆向工程中的社区协作 - -逆向工程很少是单独的活动,即使看起来像是。几乎每个成功的逆向工程项目要么建立在已有成果之上,要么最终贡献给它。关心特定设备或特定设备系列的人群虽小但持久,学会找到并贡献那个社区是逆向工程师能做的最有效率的事情之一。 - -本节讨论如何找到已有成果、如何评估其可信度、如何在不产生法律或伦理问题的情况下利用它,以及如何以帮助他人的形式分享你自己的发现。这项工作不光鲜,但它正是使逆向工程成为生产性长期活动而非一系列不连贯努力的东西。 +### 9.5 在Markdown或Git中维护伪数据手册 ### 9.1 寻找已有成果 @@ -1628,8 +1406,7 @@ Git 跟踪是必不可少的。伪数据手册是一个活文档;随着新事 一般原则很简单,通过练习可以直接应用。 -> **Never write to an unknown register or send an unknown -> command without strong evidence that the operation is safe.** +> **永远不要在没有有力证据表明操作安全的情况下,向未知寄存器写入或发送未知命令。** 充分的证据可以来自多个来源,每个都值得单独讨论。 @@ -1647,14 +1424,7 @@ Git 跟踪是必不可少的。伪数据手册是一个活文档;随着新事 某些类别的操作危险到值得明确关注。这些是粗心写入可能永久损坏设备的操作,它们是永远不应该在没有充分证据的情况下执行的操作。 -**闪存写入。** 许多设备包含用于固件、配置、校准或设备标识符的闪存。对闪存的写入是不可逆的(或者充其量可以通过恢复备份来逆转)。意外写入闪存的驱动程序可能会损坏固件(使设备无法启动)、覆盖校准数据(使设备不准确或不可用)或更改设备标识(使其自身的固件无法识别)。 The patterns that trigger -flash writes vary by device, but they often involve specific -"unlock" sequences followed by writes to addresses that are -explicitly the flash region. If your captures show such a -sequence in a context where the user explicitly performed a -"firmware update" operation, do not replicate the sequence in -your driver unless you are explicitly implementing firmware -update. +**闪存写入。** 许多设备包含用于固件、配置、校准或设备标识符的闪存。对闪存的写入是不可逆的(或者充其量可以通过恢复备份来逆转)。意外写入闪存的驱动程序可能会损坏固件(使设备无法启动)、覆盖校准数据(使设备不准确或不可用)或更改设备标识(使其自身的固件无法识别)。触发闪存写入的模式因设备而异,但它们通常涉及特定的"解锁"序列,随后是对明确为闪存区域的地址的写入。如果你的捕获显示这样的序列出现在用户明确执行"固件更新"操作的上下文中,不要在你的驱动程序中复制该序列,除非你明确正在实现固件更新。 **影响非易失性状态的硬复位。** 大多数复位是将设备返回到初始内存状态的软复位。然而,有些复位也会清除非易失性状态:校准数据、配置、标识符编程。这些"恢复出厂设置"操作有时由触发软复位的同一个寄存器触发,但使用不同的位模式。只使用厂商驱动程序在附加时使用的软复位模式,不要实验你未见厂商驱动程序使用过的位模式。 @@ -1666,30 +1436,17 @@ update. **PHY 或 PLL 配置。** 包含自己的时钟生成的设备(特别是 PCI Express 设备)具有 PLL 配置,如果设置错误,可能会使设备完全无法通信。网络设备上的 PHY 配置有类似的陷阱。这些是必须完全遵循厂商驱动程序的子系统,因为通过任何进一步配置从错误设置恢复没有好方法。 -**Bus master enable on a misconfigured DMA address.** If you -enable bus mastering on a device that has a DMA address pointing -to a wild memory location, the device may read or write that -location and corrupt the host's memory. This is one of the few -ways a driver bug can crash the host through hardware action. -Always set up valid DMA mappings before enabling bus mastering, -and never enable bus mastering if you are not yet ready to manage -DMA. +**在 DMA 地址配置错误时启用总线主控。** 如果你在设备上启用总线主控,而设备的 DMA 地址指向一个无效的内存位置,设备可能会读取或写入该位置并损坏主机内存。这是驱动程序错误通过硬件操作导致主机崩溃的少数方式之一。始终在启用总线主控之前设置有效的 DMA 映射,如果你还没有准备好管理 DMA,永远不要启用总线主控。 这些类别并不详尽,但它们涵盖了损坏设备的最常见方式。一般教训是:尊重你尚未完全理解其后果的操作,不要对它们进行实验。 ### 10.3 软复位与看门狗定时器 -The constructive side of the safety discussion is what to do when -something does go wrong. The first technique is the soft reset. +安全讨论的建设性方面是当出现问题时该怎么办。第一种技术是软复位。 -A soft reset is the device's "I have got into a bad state, please -restart" mechanism. The pattern is the same as the reset you -implemented in Section 6: a write to the control register that -puts the device back into its known initial state. Used -conservatively, a soft reset can recover from many kinds of -problems without requiring intervention. +软复位是设备的"我已经进入糟糕状态,请重新启动"机制。模式与你在第 6 节中实现的复位相同:写入控制寄存器将设备放回其已知初始状态。保守使用时,软复位可以从许多类型的问题中恢复而无需干预。 -The pattern in code is straightforward: +代码中的模式很简单: ```c static void @@ -1702,14 +1459,9 @@ mydev_recover(struct mydev_softc *sc) } ``` -The recovery routine should be called from any code path that -detects something has gone wrong: a timeout, an error status, an -unexpected register value. The cost of an unnecessary reset is -small; the cost of an unrecovered error can be much larger. +恢复例程应该从任何检测到问题的代码路径中调用:超时、错误状态、意外的寄存器值。不必要的复位代价很小;未恢复错误的代价可能大得多。 -A watchdog timer is the next layer of defence. The driver -periodically checks that the device is making progress, and if -progress has stalled, it triggers a recovery. The pattern is: +看门狗定时器是下一层防御。驱动程序定期检查设备是否在取得进展,如果进展停滞,则触发恢复。模式如下: ```c static void @@ -1784,20 +1536,9 @@ mydev_set_field(struct mydev_softc *sc, bus_size_t off, ### 10.7 知道何时停止 -The hardest safety decision is sometimes the decision to stop. -When an experiment is not behaving as expected, when the device -is producing values you cannot explain, when your hypotheses are -all wrong and you do not yet have new ones, the temptation is to -keep poking until something becomes clear. Resist this temptation. -Stop, take a break, look at the captures again, talk to someone -else about what you have observed, and let the situation -clarify before you resume. +最困难的安全决策有时是停止的决策。当实验表现不符合预期,当设备产生你无法解释的值,当你的假设全部错误而你还没有新的假设时,诱惑是继续探索直到某些东西变得清晰。抵制这种诱惑。停下来,休息一下,重新查看捕获,与其他人讨论你观察到的内容,在恢复之前让情况明朗起来。 -The reason is that the moments of confusion are exactly the -moments when accidental damage is most likely. A clear mind is -careful about which writes are safe; a frustrated mind tries -things that look promising and discovers, too late, that one of -它们是破坏性的。 +原因是困惑的时刻正是意外损坏最可能发生的时刻。清醒的头脑会小心谨慎地判断哪些写入是安全的;沮丧的头脑会尝试看起来有希望的操作,然后太晚才发现其中一个是破坏性的。 短暂休息也让你的潜意识工作。许多最有用的逆向工程洞察在你做其他事情时到来:散步、睡觉、处理无关问题。大脑在被给予机会时有将观察整合为连贯理解的非凡能力。当工作停滞时强迫自己呆在键盘前通常产生不了有用的东西,有时会产生灾难。 @@ -1833,32 +1574,19 @@ things that look promising and discovers, too late, that one of FreeBSD 驱动程序应该至少有一个第 4 节的手册页,理想情况下还有内核开发者文档中的一节。手册页是为想知道驱动程序做什么以及如何配置它的用户准备的。开发者文档是为想要内部理解驱动程序的内核黑客准备的。 -The manual page follows the standard FreeBSD style. The relevant -manual page for `style(4)` documents the conventions, and the -manual pages for similar drivers are good examples to follow. -A typical driver manual page covers: +手册页遵循标准 FreeBSD 风格。`style(4)` 的相关手册页记录了约定,类似驱动程序的手册页是很好的参考示例。典型驱动程序手册页涵盖: -- The name of the driver and a one-line description. -- The synopsis showing how to load the driver in `loader.conf`. -- The description, explaining what hardware the driver supports - and what features it provides. -- The hardware support section, listing the specific devices the - driver works with. -- The configuration section, describing any sysctls or loader - variables the driver exposes. -- The diagnostics section, listing the messages the driver may - produce and what they mean. -- The see-also section, with cross-references. -- The history section, explaining when the driver appeared. -- The author section. +- 驱动程序名称和一行描述。 +- 显示如何在 `loader.conf` 中加载驱动程序的概要。 +- 描述驱动程序支持什么硬件和提供什么功能的说明部分。 +- 硬件支持部分,列出驱动程序适用的特定设备。 +- 配置部分,描述驱动程序暴露的任何 sysctl 或 loader 变量。 +- 诊断部分,列出驱动程序可能产生的消息及其含义。 +- 另见部分,带交叉引用。 +- 历史部分,说明驱动程序何时出现。 +- 作者部分。 -For a reverse-engineered driver, the description should be -honest about the driver's provenance: it was developed by reverse -engineering, the supported feature set is what was achievable -through that process, and certain corners of the device may -behave differently than the driver expects. Operators appreciate -honest documentation; vague claims of full support set up users -for confusion when they encounter unimplemented behaviour. +对于逆向工程驱动程序,描述部分应对驱动程序的来源诚实:它通过逆向工程开发,支持的功能集是通过该过程可实现的,设备的某些角落可能行为与驱动程序预期不同。操作员欣赏诚实的文档;模糊声称完全支持的文档在用户遇到未实现行为时只会造成困惑。 ### 11.3 伪数据手册结构 @@ -2028,106 +1756,31 @@ FreeBSD 内核使用宽松的 BSD 风格许可证。当你从另一个代码库 合同可以在版权法不适用的情境下约束你。逆向工程工作中出现的合同有三种:保密协议、最终用户许可协议和固件许可证。每种约束工作流程的不同部分。 **保密协议。** 一些厂商会分享详细文档以换取签署的 NDA。文档通常很优秀,但 NDA 通常禁止发布信息,有时是无限期的,有时带有 -liquidated damages attached. Signing an NDA about a device and -then writing an open-source driver for that same device is a -legal minefield: every register you document in a pseudo-datasheet, -every field name, every value, could be challenged later as a -disclosure. The safer choice is almost always to refuse the NDA -and work from publicly observable information. If you have -already signed one and then want to contribute an open driver, -the clean option is to recuse yourself from the observation work -and let a second author build the pseudo-datasheet from scratch, -using only sources you never touched under the agreement. +附带惩罚性赔偿条款。签署关于某个设备的保密协议,然后为同一设备编写开源驱动程序,是一个法律雷区:你在伪数据手册中记录的每一个寄存器、每一个字段名、每一个值,都可能后来被质疑为泄密。更安全的选择几乎总是拒绝签署保密协议,并从公开可观察的信息中开展工作。如果你已经签署了保密协议,然后又想贡献一个开放驱动程序,干净的做法是让你自己回避观察工作,让第二位作者从头构建伪数据手册,只使用你在协议下从未接触过的来源。 -**End-user licence agreements.** Many vendor-supplied drivers -and SDKs include an EULA that explicitly forbids reverse -engineering. The enforceability of such clauses varies across -jurisdictions, but the safer path is to avoid clicking "I agree" -in the first place. If you only ever touched the vendor driver as -a binary shipped on an installation image, without accepting an -online agreement, your position is stronger than if you signed up -for a developer programme and downloaded the SDK under an -agreement that forbade disassembly. Record which vendor materials -you consulted and under what terms. That record becomes part of -the provenance field in your pseudo-datasheet. +**最终用户许可协议。** 许多厂商提供的驱动程序和 SDK 包含明确禁止逆向工程的 EULA。此类条款在不同司法管辖区的可执行性各不相同,但更安全的路径是一开始就避免点击"我同意"。如果你只接触过作为安装镜像附带的二进制文件的厂商驱动程序,而没有接受在线协议,你的法律地位比注册开发者计划并在禁止反汇编的协议下下载 SDK 要强得多。记录你参考了哪些厂商材料以及在什么条款下参考的。该记录将成为伪数据手册中来源字段的一部分。 -**Firmware licences.** Many modern devices need a binary firmware -blob that the driver loads at attach time. The vendor usually -distributes that blob under a redistribution licence that is more -permissive than the surrounding driver code but still not fully -free. FreeBSD's `ports` tree has a well-established pattern of -packaging firmware blobs in dedicated `-firmware-kmod` ports so -that the kernel code stays BSD while the blob keeps its vendor -licence. You do not need to reverse-engineer the firmware itself; -you need to understand how the driver hands it to the device. The -legal framework for firmware is separate from the legal framework -for the driver, and both have to be satisfied independently. +**固件许可证。** 许多现代设备需要驱动程序在附加时加载的二进制固件映像。厂商通常在再分发许可证下分发该映像,该许可证比周围的驱动程序代码更宽松但仍然不是完全自由的。FreeBSD 的 `ports` 树有一个成熟的模式,即将固件映像打包在专门的 `-firmware-kmod` 端口中,这样内核代码保持 BSD 许可,而映像保留其厂商许可证。你不需要逆向工程固件本身;你需要理解驱动程序如何将固件交给设备。固件的法律框架与驱动程序的法律框架是分开的,两者都必须独立满足。 ### 12.4 净室实践 -Reading a GPL driver to learn what a device does, and then -writing BSD code that does the same thing, is a recognised -interoperability technique. United States courts have upheld it -in cases such as Sega v. Accolade and Sony v. Connectix, and -Article 6 of the European Union's Software Directive -(2009/24/EC) carves out reverse engineering specifically for -interoperability. But the legal protection depends on how you do -the work, not just on what you do. A driver that looks -line-for-line like the Linux original will not be protected by -the clean-room defence, because the record will show that no -clean room existed. +阅读 GPL 驱动程序以了解设备功能,然后编写做同样事情的 BSD 代码,是一种公认的互操作性技术。美国法院在 Sega 诉 Accolade 和 Sony 诉 Connectix 等案件中支持了这一做法,欧盟软件指令(2009/24/EC)第 6 条专门为互操作性目的规定了逆向工程豁免。但法律保护取决于你如何开展工作,而不仅仅取决于你做了什么。一个逐行看起来与 Linux 原版相同的驱动程序不会受到净室辩护的保护,因为记录将显示不存在净室。 -Good clean-room practice has two elements: structural separation -and structural documentation. +良好的净室实践有两个要素:结构分离和结构文档。 -Structural separation means that the person who reads the -other-platform driver, and the person who writes the FreeBSD -driver, are different activities. On a team of two, they are -literally different people. On a solo project, they are -different work sessions with different artifacts. The reader's -output is a pseudo-datasheet: a document in plain English that -describes registers, bit fields, command sequences, and quirks, -with no reference to the specific identifiers the other driver -used. The writer's input is that pseudo-datasheet, plus the -FreeBSD header files and driver examples. The writer never opens -the other-platform driver while the FreeBSD code is being -written. +结构分离意味着阅读其他平台驱动程序的人和编写 FreeBSD 驱动程序的人是不同的活动。在两人团队中,他们实际上是不同的人。在个人项目中,它们是产生不同制品的不同工作会话。阅读者的输出是一份伪数据手册:一份用自然语言描述寄存器、位字段、命令序列和特殊行为的文档,不引用其他驱动程序使用的特定标识符。编写者的输入是该伪数据手册,加上 FreeBSD 头文件和驱动程序示例。编写者在编写 FreeBSD 代码期间从不打开其他平台的驱动程序。 -Structural documentation means that the pseudo-datasheet records -where each fact came from. A register description might be -annotated "observed on wire with `usbdump(8)` on 2026-02-14" or -"inferred from vendor datasheet section 3.4" or "deduced from -Linux driver, reread into prose". That annotation is the record -that would, if ever needed, support the claim that your driver -was written from understanding rather than from copying. Patent -and copyright cases have sometimes turned on the quality of -exactly this kind of record, and maintaining it is not paranoia; -it is the same discipline that keeps the rest of your engineering -honest. +结构文档意味着伪数据手册记录每个事实的来源。寄存器描述可能被标注为"2026-02-14 通过 `usbdump(8)` 在线路上观察到"或"从厂商数据手册第 3.4 节推断"或"从 Linux 驱动程序推导,转写为文字"。该标注就是记录,如果需要的话,它将支持你的驱动程序是基于理解而非复制的声明。专利和版权案件有时正是基于此类记录的质量来裁决的,维护它不是偏执;它是让你其余工程工作保持诚实的同样纪律。 -In practice, the time cost of clean-room discipline is small once -the pseudo-datasheet habit from Section 11 is already part of -your workflow. The legal value is large, because it moves you -from "I hope this is not a problem" to "I can show how it was -done". +在实践中,一旦第 11 节的伪数据手册习惯已经成为你工作流程的一部分,净室纪律的时间成本是很小的。法律价值却很大,因为它将你从"我希望这不是问题"转移到"我可以展示它是如何完成的"。 ### 12.5 安全港 -It helps to know what is always safe, so that you can push the -uncertain cases through the structure of this section without -second-guessing every keystroke. The following activities are -defensible in every jurisdiction the FreeBSD project cares about, -and you can perform them without hesitation. +了解哪些活动总是安全的很有帮助,这样你就可以通过本节的结构处理不确定的情况,而不必对每次按键都犹豫不决。以下活动在 FreeBSD 项目关注的所有司法管辖区中都是可辩护的,你可以毫不犹豫地执行它们。 -**Reading code is always safe.** Whatever licence the -other-platform driver carries, reading it to learn how a device -works is not a copyright violation. It is sometimes called fair -use, sometimes called interoperability research; the label -depends on the jurisdiction, but the principle is stable in every -legal system that the FreeBSD project is likely to encounter. +**阅读代码总是安全的。** 无论其他平台的驱动程序携带什么许可证,阅读它来了解设备如何工作不是版权侵犯。它有时被称为合理使用,有时被称为互操作性研究;标签取决于司法管辖区,但原则在 FreeBSD 项目可能遇到的每个法律体系中都是稳定的。 -**Observing your own hardware is always safe.** Running a device -你拥有的设备在你拥有的机器上运行并记录总线上发生的事情,根据版权、合同或商业秘密法是不可诉的。你从 `usbdump(8)`、`pciconf(8)`、JTAG 探针和逻辑分析仪产生的记录是你自己的作品,你可以自由描述和发布它们。 +**观察你自己的硬件总是安全的。** 在你拥有的机器上运行你拥有的设备并记录总线上发生的事情,根据版权、合同或商业秘密法是不可诉的。你从 `usbdump(8)`、`pciconf(8)`、JTAG 探针和逻辑分析仪产生的记录是你自己的作品,你可以自由描述和发布它们。 **从理解编写总是安全的。** 如果你能用自己的语言在伪数据手册中描述设备,你就可以从该文档编写 FreeBSD 驱动程序而不受限制。编写是你自己的,源自关于设备的事实而非其他作者的表达。 @@ -2155,26 +1808,11 @@ legal system that the FreeBSD project is likely to encounter. **设备和历史。** MosChip MCS7820 和 MCS7840 是出现在廉价多端口 RS-232 适配器中的 USB 转串行桥接芯片。MCS7820 是双端口部件,MCS7840 是四端口部件,两种情况下 USB 接口在电气上是相同的。FreeBSD 驱动程序 `umcs` 由 Lev Serebryakov 于 2010 年编写,现在位于 `/usr/src/sys/dev/usb/serial/umcs.c`。配套头文件 `/usr/src/sys/dev/usb/serial/umcs.h` 详细说明了寄存器布局。 -**方法。** `umcs.c` 顶部的头注释对文档情况异常坦率。作者写道驱动程序支持 mos7820 和 mos7840 部件,并直接指出公开数据手册不包含芯片的完整编程信息。由 MosChip 技术支持在限制下分发的完整数据手册 -filled in some of the gaps, and a vendor-supplied reference -driver filled in the rest. The author's task was to write an -original BSD driver that behaved the same way the confirmed -information said it should, with the vendor driver used as an -observational check rather than as a source to copy. +**方法。** `umcs.c` 顶部的头注释对文档情况异常坦率。作者写道驱动程序支持 mos7820 和 mos7840 部件,并直接指出公开数据手册不包含芯片的完整编程信息。由 MosChip 技术支持在限制下分发的完整数据手册填补了一些空白,厂商提供的参考驱动程序填补了其余部分。作者的任务是编写一个原创的 BSD 驱动程序,其行为与已确认信息所指示的一致,厂商驱动程序用作观察检查而非复制来源。 -The cleanest place to see this discipline at work is the -port-count detection inside the attach routine. A program that -drives a USB-to-serial chip must know whether the chip has two -ports or four, because the user-visible device nodes and the -internal data structures depend on that count. The datasheet -prescribes one method, the vendor driver uses another, and -experiments on real hardware show that the datasheet's method is -unreliable. +了解这种纪律的最佳位置是 attach 例程中的端口计数检测。驱动 USB 转串口芯片的程序必须知道芯片有两个端口还是四个端口,因为用户可见的设备节点和内部数据结构都取决于该计数。数据手册规定了一种方法,厂商驱动程序使用了另一种方法,而在真实硬件上的实验表明数据手册的方法不可靠。 -**Code.** In `/usr/src/sys/dev/usb/serial/umcs.c`, the function -`umcs7840_attach` performs the detection. The inline comment -records the problem in plain text, and the code records the -chosen workaround. The relevant fragment reads: +**代码。** 在 `/usr/src/sys/dev/usb/serial/umcs.c` 中,函数 `umcs7840_attach` 执行检测。内联注释以纯文本记录了问题,代码记录了选择的变通方案。相关片段如下: ```c /* @@ -2189,95 +1827,23 @@ umcs7840_get_reg_sync(sc, MCS7840_DEV_REG_GPIO, &data); if (data & MCS7840_DEV_GPIO_4PORTS) { ``` -The register involved is `MCS7840_DEV_REG_GPIO`, defined at -offset 0x07 in `/usr/src/sys/dev/usb/serial/umcs.h`. The header -is equally candid about its status. The register block as a whole -is annotated with a note explaining that the registers are -documented only in the full datasheet, which can be requested -from MosChip technical support, and the GPIO register -specifically is commented as holding the GPIO_0 and GPIO_1 bits -that are undocumented in the public datasheet. A longer note -further down the header explains that `GPIO_0` must be grounded -on two-port boards and pulled up on four-port boards, and that -the convention is enforced by board designers rather than by the -chip itself. The single-bit flag `MCS7840_DEV_GPIO_4PORTS`, -defined as `0x01`, is what the attach routine tests against the -value returned by `umcs7840_get_reg_sync`. +涉及的寄存器是 `MCS7840_DEV_REG_GPIO`,在 `/usr/src/sys/dev/usb/serial/umcs.h` 中定义为偏移 0x07。头文件对其状态同样坦诚。寄存器块整体上有一个注释,解释这些寄存器仅在完整数据手册中有文档记录,而完整数据手册需要向 MosChip 技术支持请求获取,GPIO 寄存器特别被注释为保存公开数据手册中未文档化的 GPIO_0 和 GPIO_1 位。头文件更下方的一条更长注释解释了 `GPIO_0` 在双端口板上必须接地,在四端口板上必须上拉,该约定由电路板设计者而非芯片本身强制执行。单位标志 `MCS7840_DEV_GPIO_4PORTS` 定义为 `0x01`,是 attach 例程用来与 `umcs7840_get_reg_sync` 返回的值进行测试的标志。 -What makes this a good study is that the code records the story. -A reader who finds the driver fifteen years after it was written -can reconstruct the reasoning: the datasheet said one thing, the -vendor driver did another, the real hardware was tested, and the -chosen method is explained in the comment. No one has to -rediscover the same dead end. +使这成为一个优秀案例的原因是代码记录了完整的故事。在驱动程序编写十五年后发现它的读者可以重建推理过程:数据手册说了一件事,厂商驱动程序做了另一件事,在真实硬件上进行了测试,选择的方法在注释中做了解释。没有人需要重新发现相同的死胡同。 -**Ethical and legal context.** The author had two classes of -source available: the restricted full datasheet, which MosChip -distributes on request, and the vendor reference driver, which -ships with the chip evaluation kit. Both are proprietary in the -sense that they are not freely redistributable, and neither can -be copied into an open-source driver. What you can do is learn -from them, and then write your own code against the information -they contain. The `umcs` comment does exactly that. It names the -behaviour the vendor driver exhibits, it names the experiment -that confirmed the behaviour on real hardware, and the code it -produces is original BSD-licensed prose. The copyright block at -the top of the source file identifies Lev Serebryakov as the sole -author. This is a textbook clean-room outcome: the driver -benefits from vendor information without importing vendor code. +**伦理和法律背景。** 作者有两类来源可用:受限的完整数据手册(MosChip 按请求分发)和厂商参考驱动程序(随芯片评估套件提供)。两者都是专有的,因为它们不能自由再分发,两者都不能复制到开源驱动程序中。你可以做的是从中学习,然后根据它们包含的信息编写自己的代码。`umcs` 注释正是这样做的。它命名了厂商驱动程序展示的行为,命名了在真实硬件上确认该行为的实验,它产生的代码是原创的 BSD 许可作品。源文件顶部的版权块将 Lev Serebryakov 标识为唯一作者。这是教科书式的净室结果:驱动程序受益于厂商信息而不导入厂商代码。 -**Modern replication.** If you were writing `umcs` today, the -workflow would be the same, with better tooling. You would -capture a `usbdump(8)` trace of the vendor driver's attach -sequence to see the exact GPIO read, you would run the same read -on your own hardware across known two-port and four-port boards, -and you would record the discrepancy between the datasheet and -the observed behaviour in your pseudo-datasheet with a clear -provenance line for each source. The driver would then implement -the observed method, with a comment identical in spirit to the -one Lev Serebryakov wrote. The technique has not changed; the -tools around it have improved. +**现代复现。** 如果你今天要编写 `umcs`,工作流程将是相同的,只是工具更好。你将捕获厂商驱动程序 attach 序列的 `usbdump(8)` 跟踪以查看确切的 GPIO 读取,你将在已知的双端口和四端口板上运行相同的读取,并将在伪数据手册中记录数据手册与观察行为之间的差异,每个来源都有清晰的来源行。然后驱动程序将实现观察到的行为,带有与 Lev Serebryakov 所写的精神相同的注释。技术没有改变;围绕它的工具已经改进。 ### 13.3 案例研究2:`axe`驱动与缺失的IPG初始化 -**Device and history.** The ASIX AX88172 is a USB 1.1 Ethernet -adapter chip, and the AX88178 and AX88772 are its USB 2.0 -descendants. Cheap Ethernet dongles based on these parts have -been common since the early 2000s, and the FreeBSD driver, -`axe`, lives at `/usr/src/sys/dev/usb/net/if_axe.c`. The original -code was written by Bill Paul between 1997 and 2003, and the -AX88178 and AX88772 support was backported from OpenBSD by -J. R. Oldroyd in 2007. The register header lives alongside the -driver at `/usr/src/sys/dev/usb/net/if_axereg.h`. +**设备与历史。** ASIX AX88172 是一款 USB 1.1 以太网适配器芯片,AX88178 和 AX88772 是其 USB 2.0 后继产品。基于这些芯片的廉价以太网适配器自 2000 年代初就很常见,FreeBSD 驱动程序 `axe` 位于 `/usr/src/sys/dev/usb/net/if_axe.c`。原始代码由 Bill Paul 在 1997 年至 2003 年间编写,AX88178 和 AX88772 支持由 J. R. Oldroyd 于 2007 年从 OpenBSD 回移。寄存器头文件与驱动程序并列位于 `/usr/src/sys/dev/usb/net/if_axereg.h`。 -**Approach.** The top-of-file comment block in -`/usr/src/sys/dev/usb/net/if_axe.c` reads, in part, that there -is information missing from the chip manual which the driver must -know in order for the chip to function at all. The author lists -two specific facts. A bit must be set in the RX control register -or the chip will receive no packets at all. The three -inter-packet-gap registers must all be initialised, or the chip -will send no packets at all. Neither of these requirements -appears in the public datasheet, and both were established by -reading the vendor's Linux driver and observing the chip on real -hardware. +**方法。** `/usr/src/sys/dev/usb/net/if_axe.c` 中文件顶部的注释块部分内容写道,芯片手册中缺少驱动程序为了让芯片正常工作必须了解的信息。作者列出了两个具体事实。必须在 RX 控制寄存器中设置某一位,否则芯片将完全无法接收数据包。三个帧间间隔寄存器都必须初始化,否则芯片将完全无法发送数据包。这两个要求都没有出现在公开数据手册中,两者都是通过阅读厂商的 Linux 驱动程序和在真实硬件上观察芯片而确立的。 -The story of the IPG registers is especially clear. Inter-packet -gap is a standard Ethernet concept: the transmitter must wait a -minimum number of bit times between frames, and the exact number -depends on the link speed. A silicon designer has several ways -to expose IPG to software, and the AX88172 chose to expose three -distinct registers that the driver must write during -initialisation. The datasheet names the registers but says -nothing about the need to program them, so a naïve driver -following only the datasheet would leave them at their reset -values and find that the chip, mysteriously, refuses to transmit. +IPG 寄存器的故事特别清晰。帧间间隔是以太网中的一个标准概念:发送器在帧之间必须等待最少的比特时间数,具体数量取决于链路速度。芯片设计师有多种向软件暴露 IPG 的方式,AX88172 选择暴露三个独立的寄存器,驱动程序必须在初始化期间写入它们。数据手册命名了这些寄存器,但对需要编程它们一事只字未提,因此仅遵循数据手册的朴素驱动程序会将其保持在复位值,然后发现芯片神秘地拒绝传输。 -**Code.** The initialisation sequence appears inside the function -`axe_init` in `/usr/src/sys/dev/usb/net/if_axe.c`. A short helper -called `axe_cmd` provides the standard way to issue a -vendor-specific USB control request, and `axe_init` calls it -once for each IPG write. The relevant branch reads: +**代码。** 初始化序列出现在 `/usr/src/sys/dev/usb/net/if_axe.c` 的 `axe_init` 函数中。一个名为 `axe_cmd` 的短小辅助函数提供了发出厂商特定 USB 控制请求的标准方式,`axe_init` 为每个 IPG 写入调用一次。相关分支如下: ```c if (AXE_IS_178_FAMILY(sc)) { @@ -2292,498 +1858,197 @@ if (AXE_IS_178_FAMILY(sc)) { } ``` -The two branches expose a second piece of reverse-engineering -information that is invisible in the datasheet. On the older -AX88172, each of the three IPG values is programmed as an -independent command: `AXE_172_CMD_WRITE_IPG0`, -`AXE_172_CMD_WRITE_IPG1`, and `AXE_172_CMD_WRITE_IPG2`, defined -in `/usr/src/sys/dev/usb/net/if_axereg.h`. On the newer AX88178 -and AX88772, a single command writes all three at once by packing -them into the same control request: -`AXE_178_CMD_WRITE_IPG012`. The two opcodes have the same -numeric value; the AX88178 reused the opcode slot that the -AX88172 used for writing a single IPG register, and expanded its -semantics to cover all three. A driver that treated the two chip -families as interchangeable would corrupt the IPG programming on -one of them. The only way to distinguish the families is the -macro `AXE_IS_178_FAMILY(sc)`, and the need for that macro is -itself a finding of the reverse-engineering work. +两个分支暴露了在数据手册中不可见的第二块逆向工程信息。在较旧的 AX88172 上,三个 IPG 值中的每一个作为独立命令编程:`AXE_172_CMD_WRITE_IPG0`、`AXE_172_CMD_WRITE_IPG1` 和 `AXE_172_CMD_WRITE_IPG2`,定义在 `/usr/src/sys/dev/usb/net/if_axereg.h` 中。在较新的 AX88178 和 AX88772 上,单个命令通过将三个值打包到同一个控制请求中来一次写入全部三个:`AXE_178_CMD_WRITE_IPG012`。两个操作码具有相同的数值;AX88178 重用了 AX88172 用于写入单个 IPG 寄存器的操作码槽位,并将其语义扩展为覆盖全部三个。将两个芯片系列视为可互换的驱动程序会破坏其中一个的 IPG 编程。区分两个系列的唯一方法是宏 `AXE_IS_178_FAMILY(sc)`,而对该宏的需求本身就是逆向工程工作的发现。 -**Ethical and legal context.** The axe driver has a long history, -and its provenance is recorded in the copyright block. Bill Paul -wrote the original driver against the AX88172, and the comments -show that his information came from a mix of the public datasheet -and observational work. J. R. Oldroyd's AX88178 support was -ported from OpenBSD's sibling driver, which is BSD-licensed and -directly compatible with FreeBSD. That port was legally -straightforward: the code came from a permissive source tree, and -the copyright block was preserved across the move. The -reverse-engineering notes about IPG and RX-control were carried -along with the code, so the finding itself is documented forever -in the driver's header. +**伦理和法律背景。** axe 驱动程序有着悠久的历史,其来源记录在版权块中。Bill Paul 针对 AX88172 编写了原始驱动程序,注释显示他的信息来自公开数据手册和观察工作的混合。J. R. Oldroyd 的 AX88178 支持从 OpenBSD 的姊妹驱动程序移植,该驱动程序是 BSD 许可的,与 FreeBSD 直接兼容。该移植在法律上很直接:代码来自宽松的源码树,版权块在移动过程中被保留。关于 IPG 和 RX 控制的逆向工程注释随代码一起携带,因此发现本身被永远记录在驱动程序头中。 -What did not happen is as informative as what did. The axe driver -does not import code from the Linux `asix_usb` driver, even -though that driver was available when Bill Paul was writing the -FreeBSD equivalent. Linux uses the GPL, and pasting from it would -have made axe unshippable under the kernel's licence rules. -Reading it for understanding is exactly what Bill Paul did, and -the FreeBSD driver is his own writing throughout. +没有发生的事情与已经发生的事情同样有信息价值。axe 驱动程序不导入 Linux `asix_usb` 驱动程序的代码,即使该驱动程序在 Bill Paul 编写 FreeBSD 等效物时已经可用。Linux 使用 GPL,从中粘贴会使 axe 无法在内核的许可证规则下发布。阅读它来理解正是 Bill Paul 所做的,而 FreeBSD 驱动程序从头到尾是他自己的编写。 -**Modern replication.** If you were writing axe today, you would -start by loading the Linux driver on a Linux test machine and -running `usbdump(8)` on a FreeBSD machine that shared the same -USB hub, so that you could capture the vendor driver's attach -sequence without needing to read a single line of GPL code. The -`usbdump(8)` output would show the three IPG writes directly, -because they travel on the wire as visible USB control transfers. -You would record the observation in your pseudo-datasheet, cite -the packet-capture file for provenance, and implement the writes -in your own driver. The comment above `axe_init` would read very -much like the one Bill Paul originally wrote. +**现代复现。** 如果你今天要编写 axe,你将从在 Linux 测试机上加载 Linux 驱动程序并在共享同一 USB 集线器的 FreeBSD 机器上运行 `usbdump(8)` 开始,这样你就可以捕获厂商驱动程序的 attach 序列而无需阅读一行 GPL 代码。`usbdump(8)` 输出将直接显示三个 IPG 写入,因为它们作为可见的 USB 控制传输在线路上传输。你将在伪数据手册中记录观察结果,引用 pcap 文件作为来源,并在你自己的驱动程序中实现这些写入。`axe_init` 上方的注释读起来将与 Bill Paul 最初写的非常相似。 ### 13.4 共同经验 -Reading the two drivers together surfaces a handful of lessons -that are worth naming explicitly. +阅读两个驱动程序可以发现一些值得明确指出的共同经验。 -**The comment is the audit trail.** In both `umcs` and `axe`, the -header and inline comments are the place where the -reverse-engineering story is preserved. Without those comments, a -future maintainer staring at `MCS7840_DEV_REG_GPIO` or at -`AXE_178_CMD_WRITE_IPG012` would have no way to know where the -information came from or why the driver does what it does. In -both cases the author took the extra minute to write down the -reasoning, and the result is a driver that remains maintainable -fifteen or twenty years after it was written. The author's -pseudo-datasheet, in each case, was partly absorbed into the -comments and partly preserved in the structure of the header -file. That absorption is what makes the code readable today. +**注释就是审计跟踪。** 在 `umcs` 和 `axe` 中,头注释和内联注释是保存逆向工程故事的地方。没有这些注释,盯着 `MCS7840_DEV_REG_GPIO` 或 `AXE_178_CMD_WRITE_IPG012` 的未来维护者将无法知道信息来自哪里或驱动程序为什么这样做。在两种情况下,作者都花了额外的一分钟写下推理过程,结果是一个在编写十五或二十年后仍然可维护的驱动程序。作者的伪数据手册在每种情况下都部分被吸收到注释中,部分保留在头文件的结构中。这种吸收正是代码今天仍然可读的原因。 -**Observation wins over documentation.** Both drivers trust -observation over the datasheet when the two disagree. `umcs` -trusts the experimentally verified GPIO read over the datasheet's -MODE-register method, and `axe` trusts the observation that the -chip refuses to transmit without IPG programming over the -datasheet's silence on the subject. This is not a rejection of -documentation; both authors read the datasheets carefully. It is -a recognition that a datasheet is a description of the intended -behaviour, and the chip's actual behaviour is what the driver has -to match. +**观察胜过文档。** 当观察与数据手册不一致时,两个驱动程序都信任观察而非数据手册。`umcs` 信任经过实验验证的 GPIO 读取而非数据手册的 MODE 寄存器方法,`axe` 信任芯片在没有 IPG 编程时拒绝传输的观察而非数据手册在该主题上的沉默。这不是对文档的排斥;两位作者都仔细阅读了数据手册。这是对数据手册描述的是预期行为的认识,而芯片的实际行为才是驱动程序必须匹配的。 -**Licence discipline is not an afterthought.** Both drivers -respect the licence of the sources they drew on. `umcs` uses a -proprietary reference driver as an observational check without -copying from it. `axe` imports AX88178 and AX88772 support from -OpenBSD, which is licence-compatible, and stays clear of the -Linux `asix_usb` driver, which is not. Neither driver includes -code that the FreeBSD project would have had to strip out during -review, and neither needed a lawyer's review before it was -committed. The habits from Section 12 were already part of how -the authors worked. +**许可证纪律不是事后想法。** 两个驱动程序都尊重它们所借鉴来源的许可证。`umcs` 将专有参考驱动程序用作观察检查而不从中复制。`axe` 从许可证兼容的 OpenBSD 导入 AX88178 和 AX88772 支持,并远离许可证不兼容的 Linux `asix_usb` 驱动程序。两个驱动程序都不包含 FreeBSD 项目在审查期间必须剥离的代码,两个都不需要律师审查就可以提交。第 12 节的习惯已经成为作者工作方式的一部分。 -**The work is reproducible.** Everything both drivers did can be -reproduced today with modern tools. `usbdump(8)`, `usbconfig(8)`, -and the bus-space tracing techniques from earlier in the chapter -would give you the same information that the original authors -had to gather by hand, and the pseudo-datasheet habit from -Section 11 would give you a cleaner audit trail than a set of -inline comments. The drivers you write for obscure hardware today -will be better documented than the drivers from 2007 and 2010, -because the techniques have matured. The spirit of the work, -however, is the same. +**工作是可复现的。** 两个驱动程序所做的一切都可以用现代工具复现。`usbdump(8)`、`usbconfig(8)` 和本章前面的总线空间跟踪技术将为你提供与原始作者必须手工收集的相同信息,第 11 节的伪数据手册习惯将为您提供比一组内联注释更清晰的审计跟踪。你今天为冷门硬件编写的驱动程序将比 2007 年和 2010 年的驱动程序文档更完善,因为技术已经成熟。然而,工作的精神是相同的。 ### 13.5 第13节小结 -Two case studies have shown what a disciplined -reverse-engineering effort looks like when it has been absorbed -into the FreeBSD tree. In both cases the author identified a -specific gap in the public documentation, confirmed the correct -behaviour through observation, recorded the finding in a comment -that is still readable today, and wrote original code under a -licence compatible with FreeBSD. The drivers work, the code is -maintainable, and the legal record is clean. +两个案例研究展示了有纪律的逆向工程工作被吸收到 FreeBSD 源码树后的样子。在两种情况下,作者都识别了公开文档中的特定空白,通过观察确认了正确行为,将发现记录在至今仍然可读的注释中,并在与 FreeBSD 兼容的许可证下编写了原创代码。驱动程序可以工作,代码可维护,法律记录干净。 -With the legal framework from Section 12 and the worked examples -from Section 13 in place, you now have both the principles and a -set of precedents to draw on. The remaining sections of the -chapter give you hands-on practice with the techniques that the -case studies illustrate, challenge exercises to push your -understanding further, troubleshooting notes for the common ways -the work can go wrong, and a closing bridge to Chapter 37. +有了第 12 节的法律框架和第 13 节的实际案例,你现在拥有了可借鉴的原则和先例。本章剩余部分为你提供了案例研究所展示技术的动手实践、扩展理解的挑战练习、常见工作失误的故障排除笔记,以及通向第 37 章的过渡桥梁。 ## 动手实验 -The labs in this chapter give you safe, repeatable practice with -the techniques the chapter has covered. None of them touches real -unknown hardware in a way that could damage anything; the -"unknown device" in the labs is either a software mock or a -benign region of memory that you control. Treat each lab as a -chance to internalise one specific technique before adding it to -your kit. +本章的实验为你提供了安全、可重复地练习本章所涵盖技术的机会。没有任何实验以可能损坏任何东西的方式接触真实的未知硬件;实验中的"未知设备"要么是软件模拟,要么是你控制的无害内存区域。将每个实验视为在将特定技术加入你的工具箱之前内化它的机会。 -The companion code lives in -`examples/part-07/ch36-reverse-engineering/`. Each lab subfolder -has its own `README.md` with step-by-step instructions, and the -code is organised so that you can build and run each lab -independently of the others. As with earlier chapters, type the -code yourself the first time you work through a lab; the -companion files are there as a reference and as a known-good -version to compare against. +配套代码位于 `examples/part-07/ch36-reverse-engineering/`。每个实验子文件夹都有自己的 `README.md`,包含分步说明,代码组织使你可以独立于其他实验构建和运行每个实验。与前面章节一样,第一次完成实验时请自己输入代码;配套文件作为参考和已知正确版本供你比较。 ### 实验1:识别设备并转储描述符 -This lab is the simplest possible reverse-engineering exercise. -You will use `pciconf(8)` and `usbconfig(8)` to enumerate every -device on your FreeBSD system and to dump the static descriptors -of one device of your choice. The output of the lab is a small -text file that records, for one specific device, every public -fact that the kernel can tell you about it. +这个实验是最简单的逆向工程练习。你将使用 `pciconf(8)` 和 `usbconfig(8)` 枚举 FreeBSD 系统上的每个设备,并转储你选择的一个设备的静态描述符。实验的输出是一个小型文本文件,记录了一个特定设备内核能告诉你的每一个公开事实。 -Steps: +步骤: -1. Run `sudo pciconf -lvc` and save the output. Note any device - that appears as `noneN@...`, indicating that no in-tree driver - has claimed it. -2. Run `sudo usbconfig` and save the output. Pick one USB device - that you understand (a USB stick, for example) and that you - own physically. -3. Run `sudo usbconfig -d ugen0.X dump_device_desc` and - `sudo usbconfig -d ugen0.X dump_curr_config_desc` for the - chosen device, where `ugen0.X` is the device's `usbconfig` - identifier. -4. Open the captured output and identify each field: bDeviceClass, - idVendor, idProduct, bMaxPacketSize0, bNumConfigurations, the - endpoint descriptors, and so on. -5. Write a one-page summary identifying the device's identity, its - class, its endpoints, and any notable features. +1. 运行 `sudo pciconf -lvc` 并保存输出。注意任何显示为 `noneN@...` 的设备,这表示没有内核树内驱动程序声明了它。 +2. 运行 `sudo usbconfig` 并保存输出。选择一个你理解的 USB 设备(例如 USB 存储盘)并且你实际拥有的。 +3. 运行 `sudo usbconfig -d ugen0.X dump_device_desc` 和 `sudo usbconfig -d ugen0.X dump_curr_config_desc` 来转储所选设备的描述符,其中 `ugen0.X` 是设备的 `usbconfig` 标识符。 +4. 打开捕获的输出并识别每个字段:bDeviceClass、idVendor、idProduct、bMaxPacketSize0、bNumConfigurations、端点描述符等。 +5. 编写一页摘要,识别设备的身份、其类别、其端点以及任何值得注意的特性。 -The lab is intentionally easy. The point is to internalise the -shape of the static-identity capture before applying it to a -device whose identity is genuinely unknown. +实验有意设计得很简单。重点是在将静态身份捕获应用于真正未知的设备之前,内化其形式。 ### 实验2:捕获USB初始化序列 -This lab moves from static identity to dynamic behaviour. You -will use `usbdump(8)` to capture the initialisation sequence of a -USB device, save the capture, and explore it in Wireshark. +本实验从静态身份转向动态行为。你将使用 `usbdump(8)` 捕获 USB 设备的初始化序列,保存捕获,并在 Wireshark 中探索它。 -Steps: +步骤: -1. Identify a USB device that you can attach and detach freely (a - USB stick is a good choice, because you can unplug and replug - it without consequence). -2. Run `sudo usbdump -i usbus0 -w stick-init.pcap` to start - capturing on the USB bus the device is attached to. Use the - correct bus number for your system; `usbconfig` will tell you - which bus the device is on. -3. With `usbdump` running, plug in the device. Wait for it to be - recognised by the kernel. Then unplug it. -4. Stop `usbdump` with Control-C. -5. Open the resulting pcap file in Wireshark. You should see a - series of USB transfers corresponding to enumeration: the - GET_DESCRIPTOR requests for the device, configuration, and - string descriptors, the SET_ADDRESS request, the - SET_CONFIGURATION request, and so on. -6. Identify each transfer and write down what it does. Compare - the captured device descriptor against the output of - `usbconfig dump_device_desc` from Lab 1; they should match - field for field. +1. 识别一个你可以自由附加和分离的 USB 设备(USB 存储盘是一个好选择,因为你可以毫无后果地拔插它)。 +2. 运行 `sudo usbdump -i usbus0 -w stick-init.pcap` 开始在设备附加的 USB 总线上捕获。使用你系统的正确总线号;`usbconfig` 会告诉你设备在哪条总线上。 +3. 在 `usbdump` 运行时,插入设备。等待内核识别它。然后拔出它。 +4. 用 Control-C 停止 `usbdump`。 +5. 在 Wireshark 中打开生成的 pcap 文件。你应该看到一系列对应枚举的 USB 传输:设备、配置和字符串描述符的 GET_DESCRIPTOR 请求、SET_ADDRESS 请求、SET_CONFIGURATION 请求等。 +6. 识别每个传输并写下它的作用。将捕获的设备描述符与实验 1 中 `usbconfig dump_device_desc` 的输出进行比较;它们应该逐字段匹配。 -This lab is the foundation of all USB reverse engineering. Every -USB device you ever investigate will go through an enumeration -sequence at attach time, and being able to read the enumeration -sequence is the entry point to understanding what the device is -doing. +本实验是所有 USB 逆向工程的基础。你将来研究的每个 USB 设备在附加时都会经过枚举序列,能够阅读枚举序列是理解设备在做什么的入口。 ### 实验3:构建安全的寄存器探测模块 -This lab introduces the kernel-side tool that you will use for -register-map work in real projects. You will build a small kernel -module called `regprobe` that allocates a memory resource on a -device of your choosing and exposes a sysctl that dumps the -contents of the resource. No writes are performed. +本实验介绍了你在真实项目中用于寄存器映射工作的内核侧工具。你将构建一个名为 `regprobe` 的小型内核模块,它在你选择的设备上分配内存资源,并暴露一个转储资源内容的 sysctl。不执行任何写入。 -Steps: +步骤: -1. Build the `regprobe` module from - `examples/part-07/ch36-reverse-engineering/lab03-register-map/`. -2. Identify a PCI device on your system that you do not need for - anything else. A spare network card or any unused PCI device - is ideal. (Do not use the device that backs your console or - your storage.) -3. Detach the in-tree driver from the device with - `sudo devctl detach `. -4. Use the operating procedures in the lab's README to attach - `regprobe` to the device. -5. Read the dump sysctl multiple times, with a few seconds - between each read. Compare the dumps and identify which words - are stable and which words are changing. -6. Reattach the in-tree driver with `sudo devctl attach `. +1. 从 `examples/part-07/ch36-reverse-engineering/lab03-register-map/` 构建 `regprobe` 模块。 +2. 识别你系统中不需要用于其他用途的 PCI 设备。备用网卡或任何未使用的 PCI 设备是理想选择。(不要使用支持你控制台或存储的设备。) +3. 使用 `sudo devctl detach ` 从设备分离内核树内驱动程序。 +4. 使用实验 README 中的操作步骤将 `regprobe` 附加到设备。 +5. 多次读取转储 sysctl,每次间隔几秒。比较转储并识别哪些字是稳定的、哪些字在变化。 +6. 使用 `sudo devctl attach ` 重新附加内核树内驱动程序。 -The lab demonstrates two things: that a read-only probe is safe, -and that even a read-only probe can reveal interesting structure -in a device's register space. The dynamic words are most likely -counters or status registers; the stable words are most likely -configuration registers or identifiers. +实验演示了两件事:只读探测是安全的,而且即使是只读探测也能揭示设备寄存器空间中有趣的结构。动态变化的字最可能是计数器或状态寄存器;稳定的字最可能是配置寄存器或标识符。 ### 实验4:编写和驱动模拟设备 -This lab introduces the simulation side of the workflow. You will -build a small kernel module that simulates a tiny "command and -status" device entirely in software, and a small user-space test -program that drives the simulated device through its sysctls. +本实验介绍了工作流程中的模拟部分。你将构建一个完全在软件中模拟小型"命令和状态"设备的内核模块,以及一个通过 sysctl 驱动模拟设备的小型用户空间测试程序。 -Steps: +步骤: -1. Build the `mockdev` module from - `examples/part-07/ch36-reverse-engineering/lab04-mock-device/`. -2. Load the module with `sudo kldload ./mockdev.ko`. -3. Use the test program (also in the lab folder) to send a few - commands to the mock device. -4. Observe the kernel log to see the commands being processed and - the simulated status updates. -5. Modify the mock device to introduce a deliberate error: have - it report failure for one specific command code. Verify that - the test program detects the failure correctly. -6. Modify the test program to use a watchdog: if the mock device - does not complete a command within a timeout, the program - should report a failure rather than hanging. +1. 从 `examples/part-07/ch36-reverse-engineering/lab04-mock-device/` 构建 `mockdev` 模块。 +2. 使用 `sudo kldload ./mockdev.ko` 加载模块。 +3. 使用测试程序(也在实验文件夹中)向模拟设备发送几个命令。 +4. 观察内核日志以查看命令被处理和模拟状态更新。 +5. 修改模拟设备以引入一个故意的错误:让它对某个特定命令代码报告失败。验证测试程序是否正确检测到失败。 +6. 修改测试程序以使用看门狗:如果模拟设备在超时时间内未完成命令,程序应报告失败而非挂起。 -The lab teaches the structure of mock-based testing in a setting -where the mock is small enough to understand fully. In real -projects, mocks become more complex, but the structure is the -same. +实验在模拟足够小到完全理解的设置中教授基于模拟的测试结构。在真实项目中,模拟变得更复杂,但结构是相同的。 ### 实验5:构建安全探测包装器 -This lab consolidates the safety techniques from Section 10. You -will build a small library of safe probing wrappers (read-modify- -write-verify, timeout-protected operations, automatic recovery on -failure) and use them to perform an experiment on the mock device -from Lab 4. +本实验整合了第 10 节的安全技术。你将构建一个小型安全探测包装器库(读-改-写-验证、超时保护操作、失败时自动恢复),并使用它们在实验 4 的模拟设备上执行实验。 -Steps: +步骤: -1. Open the `safeprobe` lab folder. -2. Read the wrapper library carefully. Notice how each operation - is protected by a timeout, how each register write is followed - by a readback, and how failures are reported clearly. -3. Build the wrapper library and the example driver that uses it. -4. Load the mock device from Lab 4. -5. Run the example driver against the mock device. Observe how - the wrappers report the operations they perform. -6. Modify the mock device to inject a failure (an unexpected - readback value, for example). Verify that the wrappers detect - the failure and report it clearly, rather than letting the - driver continue with corrupt state. +1. 打开 `safeprobe` 实验文件夹。 +2. 仔细阅读包装器库。注意每个操作如何受超时保护,每个寄存器写入如何后跟回读验证,以及失败如何被清晰报告。 +3. 构建包装器库和使用它的示例驱动程序。 +4. 加载实验 4 的模拟设备。 +5. 对模拟设备运行示例驱动程序。观察包装器如何报告它们执行的操作。 +6. 修改模拟设备以注入一个失败(例如意外的回读值)。验证包装器是否检测到失败并清晰报告,而不是让驱动程序以损坏状态继续。 -This lab teaches the safety wrappers as a tool you can apply to -your own drivers. The cost of using them is small; the -information they produce when something goes wrong is large. +本实验将安全包装器教授为你可以应用于自己驱动程序的工具。使用它们的代价很小;当出现问题时它们产生的信息量很大。 ### 实验6:编写伪数据手册 -This lab is the documentation-side equivalent of the technique -labs. You will take the mock device from Lab 4 and write a -pseudo-datasheet for it, following the structure from Section 11. +本实验是技术实验在文档方面的等价物。你将采用实验 4 的模拟设备并为其编写伪数据手册,遵循第 11 节的结构。 -Steps: +步骤: -1. Open the pseudo-datasheet template in - `examples/part-07/ch36-reverse-engineering/lab06-pseudo-datasheet/`. -2. Read the template carefully and understand the structure. -3. Examine the mock device's source code to learn its register - layout, command set, and behaviour. -4. Fill in the template with the mock device's information, - following the structure: identity, provenance, resources, - register map, buffer layouts, command interface, initialisation, - operating patterns, quirks, open questions, references. -5. Save the result as a Markdown file alongside the mock device's - source. +1. 打开 `examples/part-07/ch36-reverse-engineering/lab06-pseudo-datasheet/` 中的伪数据手册模板。 +2. 仔细阅读模板并理解其结构。 +3. 检查模拟设备的源代码以了解其寄存器布局、命令集和行为。 +4. 用模拟设备的信息填写模板,遵循结构:身份、来源、资源、寄存器映射、缓冲区布局、命令接口、初始化、操作模式、特性和勘误、未解决问题、参考资料。 +5. 将结果保存为与模拟设备源代码并列的 Markdown 文件。 -The mock device is small enough that the pseudo-datasheet can be -complete in an hour or two. The exercise teaches you the structure -of the document and the level of detail that each section -deserves. When you later write a pseudo-datasheet for a real -device, you will already know how to organise the information, -even though the information itself will be much more extensive. +模拟设备足够小,伪数据手册可以在一两小时内完成。练习教你文档的结构以及每节应有的详细程度。当你后来为真实设备编写伪数据手册时,你已经知道如何组织信息,即使信息本身会更加丰富。 ## 挑战练习 -The challenge exercises stretch the techniques from the labs into -larger, more open-ended investigations. None of them requires -exotic hardware; they all use either real common devices or the -mock devices from the labs. Take your time with them. The labs -have given you the techniques; the challenges give you the -practice of applying them in less guided settings. +挑战练习将实验中的技术扩展到更大、更开放的研究中。没有任何挑战需要特殊硬件;它们都使用真实的常见设备或实验中的模拟设备。慢慢来。实验给了你技术;挑战给了你在较少引导的环境中应用它们的实践。 ### 挑战1:分类未知捕获 -The companion files include a small set of pcap captures of an -unknown device's USB traffic. Open the captures in Wireshark. By -analysis alone, identify: +配套文件包含一小组未知设备 USB 流量的 pcap 捕获。在 Wireshark 中打开捕获。仅通过分析,识别: -- The device's vendor and product identifiers. -- The device class (HID, mass storage, vendor-specific, and so - on). -- The device's endpoint layout (which endpoints, of which types, - in which directions). -- The general shape of the device's data flow (does it appear to - use bulk transfers, control transfers, interrupt transfers). -- Any obvious patterns in the data (periodic transfers, command - and response, continuous streaming). +- 设备的厂商标识符和产品标识符。 +- 设备类别(HID、大容量存储、厂商特定等)。 +- 设备的端点布局(哪些端点、什么类型、什么方向)。 +- 设备数据流的总体形状(是否使用批量传输、控制传输、中断传输)。 +- 数据中任何明显的模式(周期性传输、命令和响应、连续流)。 -Write a one-paragraph summary of what kind of device the captures -came from and what protocol it appears to use. The captures are -labelled with the answer in a file you should not look at until -you have written your own answer; compare and reflect. +写一段话总结捕获来自什么类型的设备以及它似乎使用什么协议。捕获附有答案标签的文件,在你写出自己的答案之前不应查看;比较并反思。 ### 挑战2:扩展模拟设备 -Take the mock device from Lab 4 and extend it to support a -multi-byte data transfer through a small ring buffer. The ring -buffer should have a producer pointer that the mock advances when -data is "produced" (you can simulate this with a callout that -generates synthetic data at a fixed rate), a consumer pointer -that the driver advances when data is consumed, and a "queue -size" register that the driver can read to learn the ring's -capacity. +采用实验 4 的模拟设备并将其扩展为支持通过小型环形缓冲区的多字节数据传输。环形缓冲区应有一个生产者指针(模拟在"生产"数据时前进,你可以通过以固定速率生成合成数据的 callout 来模拟)、一个消费者指针(驱动程序在消费数据时前进)和一个驱动程序可以读取以了解环形容量的"队列大小"寄存器。 -Write a small driver that: +编写一个小型驱动程序: -1. Identifies the mock device. -2. Reads the queue-size register to learn the ring capacity. -3. Periodically reads the producer pointer to learn how many new - entries are available. -4. Reads each new entry and prints it to the kernel log. -5. Updates the consumer pointer after processing each entry. +1. 识别模拟设备。 +2. 读取队列大小寄存器以了解环形容量。 +3. 定期读取生产者指针以了解有多少新条目可用。 +4. 读取每个新条目并打印到内核日志。 +5. 在处理每个条目后更新消费者指针。 -The exercise practises the ring-buffer-recognition skill from -Section 5 in a setting where you control both sides. The -challenge is to write the driver so that it correctly handles -both the empty-ring case (no new entries) and the full-ring case -(more entries than the driver has consumed). +练习在你控制两侧的设置中练习第 5 节的环形缓冲区识别技能。挑战是编写一个能正确处理空环情况(无新条目)和满环情况(条目数超过驱动程序已消费量)的驱动程序。 ### 挑战3:仅从行为检测设备身份 -The mock device from Lab 4 has, in its companion code, a "mystery -mode" that disables the identifier register and changes some of -its behaviour to disguise its identity. Without reading the mock -device's source code, write a small driver that: +实验 4 的模拟设备在其配套代码中有一个"神秘模式",禁用标识符寄存器并更改一些行为以伪装其身份。在不阅读模拟设备源代码的情况下,编写一个小型驱动程序: -1. Probes the mystery-mode mock device. -2. Performs a series of safe register reads. -3. Observes the device's response to a small set of test - operations. -4. Identifies which of three known device identities the mock - matches, based purely on the observed behaviour. +1. 探测神秘模式模拟设备。 +2. 执行一系列安全的寄存器读取。 +3. 观察设备对一组小型测试操作的响应。 +4. 仅基于观察到的行为,识别模拟设备匹配三种已知设备身份中的哪一种。 -The challenge teaches the higher-level skill of fingerprinting a -device from behaviour rather than from explicit identifiers. -Real devices sometimes hide their identity for compatibility -reasons (presenting themselves as a more common chip), and -identifying them by behaviour is the only way to support them -correctly. +挑战教授从行为而非显式标识符指纹识别设备的高级技能。真实设备有时出于兼容性原因(伪装成更常见的芯片)隐藏其身份,通过行为识别它们是正确支持它们的唯一方法。 ### 挑战4:为你拥有的设备编写文档 -Pick a piece of USB hardware that you own and that does not have -particularly sensitive functionality. A USB game controller, a -webcam, a USB-to-serial adapter, a USB Wi-Fi adapter. Write a -pseudo-datasheet for it, using only what you can learn through -`usbconfig`, `usbdump`, and Wireshark. +选择一件你拥有的、功能不太敏感的 USB 硬件。USB 游戏控制器、网络摄像头、USB 转串口适配器、USB Wi-Fi 适配器。仅使用你通过 `usbconfig`、`usbdump` 和 Wireshark 能学到的内容,为其编写伪数据手册。 -The challenge requires you to apply, in sequence, every technique -from the chapter: identification, capture, observation, hypothesis, -documentation. The result is a real artifact: a pseudo-datasheet -for a real device. Many such pseudo-datasheets have grown into -community projects that produced production drivers; yours might -be the next one. +挑战要求你按顺序应用本章的每项技术:识别、捕获、观察、假设、文档化。结果是一个真实的制品:一个真实设备的伪数据手册。许多这样的伪数据手册已经成长为产生生产驱动程序的社区项目;你的可能是下一个。 ## 动手练习:你自己的观测 -The labs have given you controlled practice against software mocks -and known-good devices, and the challenges have asked you to apply -those techniques to slightly less structured targets. The case -studies in Section 13 walked you through reverse engineering work -that has long since been absorbed into the FreeBSD tree. What none -of those has asked you to do is to sit down with a device of your -own choosing, observe it cold, map what you see onto interface and -endpoint structures, and sketch the beginning of a driver from -scratch. That is what this exercise does, and it is the closest -this chapter can bring you to the work the `umcs` and `axe` authors -did at the start of their projects. +实验已经让你对软件模拟和已知设备进行了受控练习,挑战练习要求你将这些技术应用于结构稍少的目标。第 13 节的案例研究带你浏览了早已被吸收到 FreeBSD 源码树中的逆向工程工作。以上这些都没有要求你坐下来选择一个自己的设备,从零开始冷观察它,将你看到的内容映射到接口和端点结构,并从头开始勾勒驱动程序的雏形。这就是本练习要做的,也是本章能让你最接近 `umcs` 和 `axe` 作者在其项目开始时所做工作的方式。 -Treat the exercise as a capstone rather than another lab. It does -not introduce a new technique; it asks you to combine the -techniques you have already practised into a single self-directed -session, using a device you physically own and tools from the -FreeBSD base system. The goal is not a shippable driver. The goal -is a faithful short record of what you observed, a skeleton file -that compiles and attaches cleanly, and a list of the questions -your observation did not answer. If you finish with those three -artefacts, the exercise has worked as intended. +将本练习视为顶点而非又一个实验。它不引入新技术;它要求你将已经练习过的技术组合成一个自主引导的会话,使用你物理拥有的设备和 FreeBSD 基本系统中的工具。目标不是可发布的驱动程序。目标是忠实的简短观察记录、一个能编译并干净附加的骨架文件,以及你的观察未能回答的问题列表。如果你最终有了这三样制品,练习就达到了预期目的。 ### 开始之前:伦理门槛 -Because this exercise touches a real device that you own, the -legal and ethical framework from Sections 1 and 12 applies to it -directly, and it applies before the first command runs. Work -through the short checklist below, in order. Do not proceed until -every item has a clear answer. +因为本练习接触你拥有的真实设备,第 1 和第 12 节的法律和伦理框架直接适用于此,并在第一个命令运行之前就适用。按顺序完成下面的简短清单。每一项都应有明确答案后才可继续。 -1. **Pick a device you own outright.** The exercise is not a - licence to probe equipment you have borrowed, rented, or been - granted limited access to. The device must be yours, and it - must be a device you are willing to see briefly misbehave under - observation. A working rule is that if you would not feel - comfortable unplugging the device in the middle of normal +1. **选择你完全拥有的设备。** 本练习不是探查你借用、租用或获得有限访问权限的设备的许可。设备必须是你的,并且是你愿意看到在观察下短暂异常的设备。一个实用规则是:如果你不乐意在正常运行期间拔掉设备,它就不是本练习的好候选。 operation, it is not a good candidate for this exercise. -2. **Pick a device whose firmware and protocol are not - vendor-protected.** Good targets are simple class-compliant USB - devices that implement an open specification. A USB HID - keyboard or mouse, a USB-to-serial adapter built around a - commodity chip, a class-compliant USB audio interface, or a - small USB-attached LED enclosure with a straightforward - vendor-specific protocol are all reasonable choices. Rule out - anything whose firmware is known to be DRM-encumbered, anything - whose protocol is covered by a non-disclosure agreement that you - have signed, and anything whose vendor driver ships under an - end-user licence that specifically forbids the kind of - observation described here. When a device is ambiguous, set it - aside and pick something else. The exercise is about technique, - not about probing any specific piece of hardware. +2. **选择固件和协议不受厂商保护的设备。** 好的目标是实现开放规范的简单类兼容 USB 设备。USB HID 键盘或鼠标、围绕商用芯片构建的 USB 转串口适配器、类兼容的 USB 音频接口,或带有简单厂商特定协议的小型 USB LED 外壳都是合理的选择。排除固件已知受 DRM 保护的设备、协议受你签署的保密协议约束的设备、以及厂商驱动程序附带的最终用户许可明确禁止此处描述的观察类型的设备。当设备有歧义时,放在一边选择其他。练习关乎技术,不关乎探查任何特定硬件。 -3. **Observe only, do not import.** Everything the walkthrough - asks you to do is passive observation of traffic on a bus you - control, followed by writing your own code against your own - notes. That stays firmly inside the clean-room framework from - Section 12. The moment you move from observation to copying - vendor firmware, pasting vendor driver source, or redistributing - a binary blob you did not author, you leave that framework and - enter a space where the answer depends on the licence of the - specific material. Do not cross that line inside the exercise. - If you later want to carry the work toward a real driver, - revisit Sections 9 and 12 and work through the licensing - questions carefully before you do. +3. **仅观察,不导入。** 演练要求你做的一切都是对你控制的总线上流量的被动观察,然后根据你自己的笔记编写自己的代码。这牢固地处于第 12 节的净室框架之内。当你从观察转向复制厂商固件、粘贴厂商驱动程序源代码或再分发你不是作者的二进制映像时,你就离开了该框架,进入答案取决于特定材料许可证的空间。不要在练习中越过那条线。如果你后来想将工作推向真正的驱动程序,在这样做之前重新阅读第 9 和第 12 节并仔细处理许可证问题。 -4. **Defer to the chapter's existing guardrails.** The discipline - described in Sections 1 and 12 is the authoritative framework - for this project. If any step below appears to conflict with - those sections, treat the sections as correct and narrow the - step, not the other way around. The walkthrough here is a - concrete application of that framework, not an exception to it. +4. **遵从本章现有的护栏。** 第 1 和第 12 节描述的纪律是本项目的权威框架。如果下面任何步骤似乎与这些节冲突,将这些节视为正确的并缩小步骤的范围,而不是反过来。此处的演练是该框架的具体应用,而非其例外。 -With those four items settled, the observation can begin. The rest -of the exercise assumes that all four are cleared; if any of them -is uncertain, close this section and choose a different device. +解决了这四项后,观察就可以开始了。本练习的其余部分假设这四项都已清除;如果有任何一项不确定,关闭本节并选择不同的设备。 ### 步骤1:使用`usbconfig(8)`进行初始识别 -Attach the target device to your FreeBSD host and confirm that the -kernel has enumerated it: +将目标设备附加到你的 FreeBSD 主机并确认内核已枚举它: ```console $ sudo usbconfig list @@ -2791,129 +2056,63 @@ ugen0.1: <0x1022 XHCI root HUB> at usbus0, cfg=0 md=HOST spd=SUPER (5.0Gbps) pwr ugen0.2: at usbus0, cfg=0 md=HOST spd=FULL (12Mbps) pwr=ON (100mA) ``` -Note the `ugenB.D` coordinate of your device. That coordinate is -how every later `usbconfig` command will address it. +记下你设备的 `ugenB.D` 坐标。该坐标是后续所有 `usbconfig` 命令寻址设备的方式。 -Next, check which FreeBSD driver, if any, has claimed an interface -on the device: +接下来,检查 FreeBSD 驱动程序(如果有)是否已声明设备上的某个接口: ```console $ sudo usbconfig -d ugen0.2 show_ifdrv ``` -If a kernel driver already owns the interface, the output names -it. A device whose interface is claimed by an existing driver will -still respond to read-only descriptor queries, but you should not -run your own experimental code against it until you have detached -the existing driver with `devctl detach`. For a first pass, pick a -device whose interface is either unclaimed or whose claiming -driver you are willing to detach. +如果内核驱动程序已经拥有该接口,输出会命名它。接口被现有驱动程序声明的设备仍然会响应只读描述符查询,但在使用 `devctl detach` 分离现有驱动程序之前,不应针对它运行你自己的实验代码。作为第一轮,选择接口未被声明或其声明驱动程序你愿意分离的设备。 -Finally, dump the full descriptor tree and save it for later: +最后,转储完整的描述符树并保存以备后用: ```console $ sudo usbconfig -d ugen0.2 dump_all_desc > device-descriptors.txt ``` -The output lists the device descriptor, each configuration -descriptor, each interface descriptor, and each endpoint -descriptor. You will compare this file against your packet capture -in Step 3, and you will use it as the raw material for the short -pseudo-datasheet fragment at the end of the exercise. +输出列出设备描述符、每个配置描述符、每个接口描述符和每个端点描述符。你将在步骤 3 中将此文件与数据包捕获进行比较,并将其用作练习末尾简短伪数据手册片段的原始材料。 ### 步骤2:使用`usbdump(8)`进行数据包级观测 -Descriptors tell you what the device advertises about itself. To -see what the device actually does, capture the USB bus while the -device is used: +描述符告诉你设备关于自己的宣传信息。要查看设备实际做了什么,在使用设备时捕获 USB 总线: ```console $ sudo usbdump -i usbus0 -s 2048 -w trace.pcap ``` -The `-i usbus0` argument selects the USB bus to listen on; use the -bus number your device is attached to, as reported by `usbconfig -list`. The `-s 2048` argument caps each captured payload at 2048 -bytes, which is comfortably above the maximum packet size of any -full-speed or high-speed endpoint you are likely to encounter in -this exercise. The `-w trace.pcap` argument writes a binary pcap -file that Wireshark can open and dissect with the built-in USB -dissector. +`-i usbus0` 参数选择要监听的 USB 总线;使用你设备附加到的总线号,由 `usbconfig list` 报告。`-s 2048` 参数将每个捕获的有效载荷限制在 2048 字节,这远远高于你在此练习中可能遇到的任何全速或高速端点的最大数据包大小。`-w trace.pcap` 参数写入 Wireshark 可以用内置 USB 解析器打开和解析的二进制 pcap 文件。 -With `usbdump` running, exercise the device. For an HID keyboard, -press a few keys. For a USB-to-serial adapter, open the port from -another tool and send a handful of bytes in each direction. For a -USB LED enclosure, cycle the LED through its supported states. -Each action produces USB transfers on the bus, and every transfer -ends up in the capture. +在 `usbdump` 运行时,操作设备。对于 HID 键盘,按几个键。对于 USB 转串口适配器,从另一个工具打开端口并在每个方向发送少量字节。对于 USB LED 外壳,循环 LED 穿过其支持的状态。每个操作在总线上产生 USB 传输,每个传输最终都进入捕获。 -Stop `usbdump` with Control-C. A human-readable text record is -also useful while you are annotating transfers by hand, so re-run -the capture once with output redirected to a text file: +用 Control-C 停止 `usbdump`。在你手动标注传输时,人类可读的文本记录也很有用,所以用输出重定向到文本文件再运行一次捕获: ```console $ sudo usbdump -i usbus0 -s 2048 > trace.txt ``` -Keep both versions. The text form is easier to read line by line -and to annotate in a plain editor; the pcap form is easier to -navigate in Wireshark when you want to follow a specific flow. +保留两个版本。文本形式更容易逐行阅读和在纯文本编辑器中标注;pcap 形式在你想跟踪特定流时更容易在 Wireshark 中导航。 ### 步骤3:将描述符映射到接口和端点结构 -Open `device-descriptors.txt` alongside `trace.txt`. Work through -the descriptor dump and, for each interface descriptor, write -down: +打开 `device-descriptors.txt` 和 `trace.txt`。遍历描述符转储,为每个接口描述符写下: -- The device or interface class (`bInterfaceClass`), subclass - (`bInterfaceSubClass`), and protocol (`bInterfaceProtocol`). - Standard values are tabulated in the USB class specifications: - HID is class `0x03`, mass storage is class `0x08`, communications - device class is `0x02`, audio is class `0x01`, and - vendor-specific is class `0xFF`, among others. -- Each endpoint's address (`bEndpointAddress`), direction (the - high bit of the address: set means IN, clear means OUT), and - transfer type (the low two bits of `bmAttributes`: `0` control, - `1` isochronous, `2` bulk, `3` interrupt). -- Each endpoint's maximum packet size (`wMaxPacketSize`). +- 设备或接口类(`bInterfaceClass`)、子类(`bInterfaceSubClass`)和协议(`bInterfaceProtocol`)。标准值在 USB 类规范中列出:HID 是类 `0x03`,大容量存储是类 `0x08`,通信设备类是 `0x02`,音频是类 `0x01`,厂商特定是类 `0xFF` 等。 +- 每个端点的地址(`bEndpointAddress`)、方向(地址的高位:置位表示 IN,清除表示 OUT)和传输类型(`bmAttributes` 的低两位:`0` 控制、`1` 等时、`2` 批量、`3` 中断)。 +- 每个端点的最大数据包大小(`wMaxPacketSize`)。 -Simple devices typically expose one interface with a small number -of endpoints. A USB HID keyboard commonly has a single interrupt -IN endpoint that the host polls for key-state reports. A -USB-to-serial adapter commonly has a bulk IN endpoint for data -from the device, a bulk OUT endpoint for data to the device, and -uses the control endpoint for line-state commands. +简单设备通常暴露一个接口和少量端点。USB HID 键盘通常有一个主机轮询按键状态报告的中断 IN 端点。USB 转串口适配器通常有一个用于设备数据的大批量 IN 端点、一个用于发送设备数据的大批量 OUT 端点,并使用控制端点进行线路状态命令。 -Cross-check what you wrote down against the capture. Each endpoint -address you recorded in the descriptor dump should appear in -`trace.txt` as the source or destination of at least one transfer. -Each transfer type you recorded (bulk, interrupt, control) should -appear in the capture in the direction you expect. If the two -disagree, look again before you sketch any driver code; one of -the two observations is wrong and you want to find out which. +将你写下的内容与捕获进行交叉检查。你在描述符转储中记录的每个端点地址应该在 `trace.txt` 中作为至少一次传输的源或目的地出现。你记录的每种传输类型(批量、中断、控制)应该以你期望的方向出现在捕获中。如果两者不一致,在勾勒任何驱动程序代码之前再看一遍;两个观察中有一个是错误的,你想找出是哪个。 ### 步骤4:勾勒Newbus风格的驱动程序骨架 -With the device's identity, interfaces, and endpoints in hand, you -can sketch the outline of a driver that would attach to it. The -sketch is not a runnable driver. It is the scaffold into which you -would later drop real transfer setup, real data handling, and real -error handling. The point of producing it now is to confirm that -your observations are consistent enough to support a driver shape -at all. +有了设备的身份、接口和端点,你可以勾勒一个附加到它的驱动程序轮廓。草图不是可运行的驱动程序。它是你后来将真正的传输设置、真正的数据处理和真正的错误处理填入的脚手架。现在产生它的目的是确认你的观察足够一致,能够支撑一个驱动程序形状。 -Choose a short, lowercase Newbus identifier. The convention in the -FreeBSD USB tree is a brief lowercase string that echoes either -the chip family or the device function: `umcs` for the MosChip -serial bridge, `axe` for the ASIX Ethernet chip, `uftdi` for FTDI -adapters, `ukbd` for USB HID keyboards. Pick something that does -not collide with any name already in `/usr/src/sys/dev/usb/`. Your -local sketch can use a placeholder such as `myusb` until you -commit to a real name. +选择一个简短的小写 Newbus 标识符。FreeBSD USB 树中的约定是反映芯片系列或设备功能的简短小写字符串:`umcs` 代表 MosChip 串口桥、`axe` 代表 ASIX 以太网芯片、`uftdi` 代表 FTDI 适配器、`ukbd` 代表 USB HID 键盘。选择一个不与 `/usr/src/sys/dev/usb/` 中已有名称冲突的标识符。你的本地草图可以使用 `myusb` 等占位符,直到你确定一个真正的名称。 -The skeleton below is the minimum a USB driver needs, and it is -also what you will find in the companion file -`skeleton-template.c`: +下面的骨架是 USB 驱动程序所需的最小内容,也是你在配套文件 `skeleton-template.c` 中会找到的内容: ```c #include @@ -2981,261 +2180,102 @@ MODULE_DEPEND(myusb, usb, 1, 1, 1); MODULE_VERSION(myusb, 1); ``` -The `TODO` markers show where the observations from Steps 1 -through 3 feed into the driver. The vendor and product identifiers -come straight from the device descriptor you saved. The endpoint -allocation and transfer setup inside `myusb_attach` mirror the -endpoints you catalogued. In the full form of the driver, each -endpoint becomes an entry in a `struct usb_config` array whose -`.type` and `.direction` fields record what you observed: a bulk -IN endpoint uses `.type = UE_BULK` and `.direction = UE_DIR_IN`, -an interrupt IN endpoint uses `.type = UE_INTERRUPT` and -`.direction = UE_DIR_IN`, and so on. Existing drivers in -`/usr/src/sys/dev/usb/` are full of examples of the pattern; -`/usr/src/sys/dev/usb/serial/umcs.c` and -`/usr/src/sys/dev/usb/serial/uftdi.c` are both reasonable -references. +`TODO` 标记显示步骤 1 到 3 的观察如何输入到驱动程序中。厂商标识符和产品标识符直接来自你保存的设备描述符。`myusb_attach` 内部的端点分配和传输设置反映了你编目的端点。在驱动程序的完整形式中,每个端点成为 `struct usb_config` 数组中的一个条目,其 `.type` 和 `.direction` 字段记录了你的观察:大批量 IN 端点使用 `.type = UE_BULK` 和 `.direction = UE_DIR_IN`,中断 IN 端点使用 `.type = UE_INTERRUPT` 和 `.direction = UE_DIR_IN`,等等。`/usr/src/sys/dev/usb/` 中的现有驱动程序充满了这种模式的示例;`/usr/src/sys/dev/usb/serial/umcs.c` 和 `/usr/src/sys/dev/usb/serial/uftdi.c` 都是合理的参考。 -Do not try to fill in the transfer bodies yet. The goal at this -stage is a skeleton that compiles, loads, and attaches to your -device, and that prints a short message when it attaches and -another when it detaches. If the skeleton does those three things -cleanly, your observations were consistent. If it panics, refuses -to attach, or prints nonsense, the fault is almost always in the -descriptor mapping rather than in the skeleton itself; go back to -Step 3 and check the IN/OUT directions and the transfer types -before touching the code. +不要尝试现在填写传输主体。此阶段的目标是一个能编译、加载并附加到你的设备的骨架,在附加时打印一条短消息,在分离时打印另一条。如果骨架干净地完成了这三件事,你的观察就是一致的。如果它崩溃、拒绝附加或打印乱码,故障几乎总是在描述符映射而非骨架本身;回到步骤 3,在修改代码之前检查 IN/OUT 方向和传输类型。 ### 步骤5:写下你学到的内容 -Close the exercise by producing two short written artefacts to -keep alongside the descriptor dump, the trace file, and the driver -skeleton: +通过产生两个简短的书面制品来结束练习,与描述符转储、跟踪文件和驱动程序骨架一起保存: -1. A **pseudo-datasheet fragment**, following the structure from - Section 11. Identify the device, list its class and subclass, - list its endpoints with their transfer types, directions, and - maximum packet sizes, and note any behaviour you observed in - the capture that surprised you. Keep the fragment short. The - goal is to have something you could hand to a collaborator if - the two of you wanted to pick the work up later. +1. 一个**伪数据手册片段**,遵循第 11 节的结构。识别设备,列出其类和子类,列出其端点及其传输类型、方向和最大数据包大小,并记录你在捕获中观察到的任何令你惊讶的行为。保持片段简短。目标是产生一些如果你和合作者想稍后继续这项工作时可以交给他们的内容。 -2. A **list of open questions** you could not answer from - observation alone. Every honest reverse engineering session - ends with open questions, and writing them down is how you - avoid pretending to know things you do not. Typical entries - include a vendor-specific control request whose purpose is - unclear, a block of bytes inside a bulk transfer whose layout - is not obvious, or a descriptor field whose meaning depends on - a device state you have not yet seen. +2. 一个**未解决问题列表**,仅凭观察你无法回答。每个诚实的逆向工程会话都以未解决问题结束,写下它们是你避免假装知道你不知道的事情的方式。典型条目包括目的不明的厂商特定控制请求、大批量传输内部布局不明显的字节块,或含义取决于你尚未看到的设备状态的描述符字段。 -These two artefacts, together with `device-descriptors.txt`, -`trace.pcap`, `trace.txt`, and `skeleton-template.c`, make up the -output of the exercise. They are, at a smaller scale, the same -kind of output the `umcs` and `axe` authors would have produced -at the start of their own projects. +这两个制品连同 `device-descriptors.txt`、`trace.pcap`、`trace.txt` 和 `skeleton-template.c`,构成了练习的输出。它们在较小规模上与 `umcs` 和 `axe` 作者在自己项目开始时会产生的内容相同。 ### 关于范围的最后提醒 -Everything this exercise has asked you to do is passive -observation of traffic on your own bus, followed by writing your -own code against your own notes. That sits squarely inside the -clean-room tradition the chapter has described. If, after working -through the steps, you want to carry the work further toward a -shippable driver, stop and re-read Sections 9, 11, and 12 before -the next session. The techniques scale, but the legal and ethical -framework scales with them, and it is easier to apply early than -to unwind a commit later. The companion folder for this exercise, -at `examples/part-07/ch36-reverse-engineering/exercise-your-own/`, -collects a template walkthrough script, a skeleton source file -with the `TODO` markers shown above, and a short `README` that -gathers the safety notes in one place. +本练习要求你做的一切都是对你自己总线上流量的被动观察,然后根据你自己的笔记编写自己的代码。这牢固地处于本章描述的净室传统之内。如果你在完成步骤后想将工作进一步推向可发布的驱动程序,在下次会话之前停下来重新阅读第 9、11 和 12 节。技术可以扩展,但法律和伦理框架也随之扩展,早期应用比后来撤销提交更容易。本练习的配套文件夹位于 `examples/part-07/ch36-reverse-engineering/exercise-your-own/`,收集了模板演练脚本、带有上面所示 `TODO` 标记的骨架源文件以及将安全注意事项集中在一处的简短 `README`。 ## 常见错误与故障排除 -Reverse engineering has a small set of mistakes that nearly -everyone makes early on, and an equally small set of mistakes -that, even with experience, are easy to slip into. Recognising -them in advance shortens the painful learning curve significantly. +逆向工程有一小群几乎每个人早期都会犯的错误,以及同样一小群即使有经验也很容易滑入的错误。提前识别它们可以显著缩短痛苦的学习曲线。 ### 错误1:轻信第一个假设 -The most common mistake is to form a hypothesis early, then to -interpret every subsequent observation as supporting the -hypothesis, even when a more careful reading would suggest a -different explanation. Confirmation bias is human, and it is -particularly dangerous in reverse engineering because the -observations are noisy and the hypothesis space is large. +最常见的错误是早期形成一个假设,然后将每个后续观察解释为支持该假设,即使更仔细的阅读会建议不同的解释。确认偏见是人之常情,它在逆向工程中特别危险,因为观察是有噪声的,假设空间很大。 -The defence is the discipline of writing down each hypothesis -explicitly, designing a test that could falsify it, running the -test, and accepting the result honestly. If the test does not -falsify the hypothesis, the hypothesis survives, but it is not -yet "proven"; it is only "not yet refuted". The next test might -still kill it. +防御措施是明确写下每个假设、设计一个可以证伪它的测试、运行测试并诚实接受结果的纪律。如果测试没有证伪假设,假设存活,但它尚未被"证明";它只是"尚未被反驳"。下一个测试可能仍然会推翻它。 ### 错误2:跳过记录本 -The second most common mistake is to skip the notebook because -the keyboard is faster. The notebook feels like overhead. The -results, in the moment, seem clear. The patterns are obvious. -There is no need to write them down, because they will be -remembered. +第二常见的错误是因为打字更快而跳过记录本。记录本感觉像是开销。结果在当下看起来很清晰。模式很明显。没有必要写下来,因为它们会被记住。 -A week later, the patterns are not obvious. Another week later, -they are forgotten. A month later, the project has stalled -because nobody, including the author, can reconstruct what was -known. The notebook is what would have prevented this. Skip it -at your peril. +一周后,模式不再明显。又一周后,它们被遗忘了。一个月后,项目停滞了,因为没有人(包括作者自己)能重建当时已知的内容。记录本就是本可以防止这种情况的东西。跳过它后果自负。 ### 错误3:写入未知寄存器 -The third common mistake is to write to a register without -sufficient evidence that the write is safe. The temptation is -strong: you have a hypothesis, you want to test it, the test -involves a write, and what is the worst that could happen? -Section 10 has spelled out what can happen, but it is worth -repeating here. Devices can be permanently damaged by careless -writes, and the people who learn this from experience usually -learn it expensively. +第三常见的错误是在没有足够证据表明写入安全的情况下写入寄存器。诱惑很强:你有一个假设,你想测试它,测试涉及一次写入,最坏情况能怎样?第 10 节已经说明了可能发生什么,但值得在这里重申。粗心的写入可能永久损坏设备,从经验中学习这一点的人通常付出高昂的代价。 -The defence is the discipline of evidence-before-write. Before -performing a write, name the source of evidence that the write -is safe. If you cannot name a source, do not perform the write. +防御措施是证据先于写入的纪律。在执行写入之前,说出证据的来源以证明写入是安全的。如果你说不出来源,就不要执行写入。 ### 错误4:将厂商驱动视为完整 -A fourth common mistake is to assume that the vendor's driver -implements the full functionality of the device, and that -matching the vendor's driver is sufficient to support the device -fully. This is often wrong. Vendor drivers sometimes implement -only the subset of device functionality that the vendor's -products use; the full device may have features that the vendor's -driver never exercises. Conversely, the vendor's driver -sometimes contains workarounds for hardware bugs that you would -not need if you implemented the operations differently. +第四个常见错误是假设厂商驱动程序实现了设备的全部功能,并且匹配厂商驱动程序就足以完全支持设备。这通常是错误的。厂商驱动程序有时只实现厂商产品使用的设备功能子集;完整设备可能有厂商驱动程序从未使用的功能。反过来,厂商驱动程序有时包含你可能不需要的硬件错误变通方案(如果你以不同方式实现操作的话)。 -The defence is to read the vendor's driver as one source of -information among many, with the understanding that it represents -the vendor's choices, not the complete description of the -device. +防御措施是将厂商驱动程序视为众多信息来源之一,理解它代表的是厂商的选择,而非设备的完整描述。 ### 错误5:不测试卸载路径 -A fifth common mistake is to focus on the attach path, where -visible progress is made, and to neglect the detach path. The -result is a driver that loads and works, but cannot be unloaded -cleanly. Each test cycle then requires a reboot, which slows the -work down by an order of magnitude. +第五个常见错误是专注于可以看到进展的附加路径而忽视分离路径。结果是驱动程序可以加载和工作,但不能干净卸载。每次测试周期然后需要重启,这将工作速度降低了一个数量级。 -The defence is to write the detach path early, test it in every -build, and treat unload-time panics as serious bugs that block -further work. A driver that cannot be unloaded is, for practical -purposes, a driver that requires a reboot to test changes, and -that is not a productive way to work. +防御措施是早期编写分离路径、在每次构建中测试它,并将卸载时的崩溃视为阻碍进一步工作的严重错误。无法卸载的驱动程序在实际意义上是需要重启才能测试更改的驱动程序,这不是一种高效的工作方式。 ### 错误6:不保存捕获 -A sixth mistake is to throw away captures because they "did not -show anything new". They might not show anything new today. They -might show something important six weeks from now, when you have -learned enough to interpret them. Save every capture. Storage is -cheap. The captures themselves are part of the project's history, -and they are sometimes the only way to reconstruct what was -known at a given point. +第六个错误是因为捕获"没有显示任何新东西"而丢弃它们。它们今天可能没有显示任何新东西。六周后,当你学到了足够多的知识来解释它们时,它们可能显示重要的东西。保存每个捕获。存储很便宜。捕获本身是项目历史的一部分,它们有时是重建在给定时间点已知内容的唯一方式。 ### 错误7:独自工作 -A seventh mistake, particularly common in beginners, is to work -alone. Reverse engineering is much faster when there is at least -one other person to talk to about the work, even if that person -is not also a reverse engineer. The act of explaining what you -have observed, what you believe, and what you are about to test -forces clarity on the explanation, and clarity is what makes the -work go forward. +第七个错误在初学者中特别常见,就是独自工作。当至少有另一个人可以讨论工作时,逆向工程要快得多,即使那个人不是逆向工程师。解释你观察到的内容、你相信的内容以及你即将测试的内容的行为会强制澄清解释,而澄清正是推动工作前进的东西。 -If you do not have a colleague who is interested, find a community -that is. The mailing lists, IRC channels, and forums for the -device's family are full of people who understand the issues and -can sometimes provide the missing piece. The community-collaboration -side of Section 9 is not just about consuming prior work; it is -also about contributing to a discussion that helps everyone -involved. +如果你没有对此感兴趣的同事,找一个感兴趣的社区。该设备系列的邮件列表、IRC 频道和论坛充满了理解这些问题的人,有时可以提供缺失的那一块。第 9 节的社区协作方面不仅仅是消费已有成果;它也是参与帮助所有参与者的讨论。 ### 故障排除:驱动程序静默无操作 -Sometimes the driver loads, the device appears to attach, the -log says everything is fine, but no expected behaviour occurs. -The most common causes: +有时驱动程序加载、设备看起来已附加、日志说一切正常,但没有出现预期的行为。最常见的原因: -- The driver thinks it has set up an interrupt handler, but the - interrupt is not actually being delivered. Check `vmstat -i` to - see whether interrupts are arriving. If not, the interrupt - setup is wrong. -- The driver is reading the wrong register and seeing what looks - like a legitimate value. Compare against the `pciconf -r` or - `regprobe` output to verify that the values you are reading - match the values present in the device. -- The driver is using the wrong endianness for multi-byte values. - This is particularly common when reading values that look like - integers but are actually byte strings. -- The driver has a bug in its sequence: it performed step B - before step A, or it skipped a required step entirely. +- 驱动程序认为它已设置中断处理器,但中断实际上没有被传递。检查 `vmstat -i` 看中断是否到达。如果没有,中断设置有误。 +- 驱动程序读取了错误的寄存器并看到看起来合法的值。与 `pciconf -r` 或 `regprobe` 输出比较以验证你读取的值与设备中存在的值匹配。 +- 驱动程序对多字节值使用了错误的字节序。这在读取看起来像整数但实际是字节字符串的值时特别常见。 +- 驱动程序的序列有错误:在步骤 A 之前执行了步骤 B,或完全跳过了必要的步骤。 -The defence in each case is comparison against a known reference: -the captures from Section 3, the `regprobe` dump, the working -vendor driver. When the driver does not behave as expected, the -question is: where does its behaviour first diverge from the -reference? +每种情况下的防御措施是与已知参考比较:第 3 节的捕获、`regprobe` 转储、正常工作的厂商驱动程序。当驱动程序行为不符合预期时,问题是:它的行为在哪里首次偏离了参考? ### 故障排除:驱动程序卸载时崩溃 -A panic on unload usually indicates that the driver freed -something prematurely or kept a reference to something the kernel -has destroyed. +卸载时的崩溃通常表明驱动程序过早释放了某些东西或保留了对内核已销毁内容的引用。 -The most common causes: +最常见的原因: -- A callout was not drained before the softc was freed. Check - that every `callout_init` is matched by `callout_drain` in the - detach path. -- A taskqueue task was still pending when the taskqueue was - destroyed. Check that every `taskqueue_enqueue` is matched by - `taskqueue_drain` in the detach path. -- An interrupt handler was not torn down before the IRQ resource - was released. The order matters: tear down the handler with - `bus_teardown_intr`, then release the resource with - `bus_release_resource`. -- A character device node was not destroyed before the softc was - freed. Use `destroy_dev_drain` if there is any chance the - device might still be open. +- callout 在 softc 被释放之前没有被排干。检查每个 `callout_init` 在分离路径中都有匹配的 `callout_drain`。 +- taskqueue 任务在 taskqueue 被销毁时仍然待处理。检查每个 `taskqueue_enqueue` 在分离路径中都有匹配的 `taskqueue_drain`。 +- 中断处理器在 IRQ 资源被释放之前没有被拆除。顺序很重要:先用 `bus_teardown_intr` 拆除处理器,然后用 `bus_release_resource` 释放资源。 +- 字符设备节点在 softc 被释放之前没有被销毁。如果设备可能仍然处于打开状态,使用 `destroy_dev_drain`。 -These are the same patterns we discussed in Chapter 35 for -asynchronous drivers; reverse-engineered drivers face the same -issues, with the additional complication that you may not yet -fully understand which resources are in use at unload time. +这些与我们第 35 章异步驱动程序讨论的模式相同;逆向工程驱动程序面临相同的问题,还有一个额外的复杂因素是你可能尚未完全理解卸载时哪些资源在使用中。 ### 故障排除:行为在不同运行之间不一致 -Sometimes the device behaves differently from one run to the -next, even though nothing has changed in the driver. The causes -are usually one of: +有时设备在不同运行之间行为不同,即使驱动程序没有任何变化。原因通常是以下之一: -- The device contains state that is not reset between runs. - Investigate what the device's reset actually clears, and what - it leaves alone. -- The driver has a race condition that produces different - outcomes depending on timing. -- The device is sensitive to environmental conditions - (temperature, voltage) that vary slightly between runs. -- A second driver, or a userland program, is also accessing the - device and interfering with your investigation. +- 设备包含在运行之间未重置的状态。调查设备的复位实际清除了什么、保留了什么。 +- 驱动程序有竞态条件,根据时序产生不同结果。 +- 设备对运行之间略有变化的环境条件(温度、电压)敏感。 +- 第二个驱动程序或用户空间程序也在访问设备,干扰了你的调查。 -Distinguishing these causes requires careful, repeated runs with -each variable controlled. Reverse engineering against a device -whose behaviour is not deterministic is significantly harder than -the deterministic case, and identifying the source of the -non-determinism is itself part of the work. +区分这些原因需要控制每个变量的仔细、重复运行。对行为不确定的设备进行逆向工程比确定的情况困难得多,识别非确定性的来源本身就是工作的一部分。 ## 总结