设备驱动程序

设备驱动程序

2024 南京大学《操作系统:设计与实现》
设备驱动程序

回顾:I/O 设备

一个能与 CPU 交换数据的接口/控制器

  • 寄存器被映射到地址空间

center

操作系统:Everything is a file

  • 只需要一个 struct file_operations 的实现
2024 南京大学《操作系统:设计与实现》
设备驱动程序

设备驱动程序

一个 struct file_operations 的实现

  • 把系统调用 “翻译” 成与设备能听懂的数据
    • 就是一段普通的内核代码

例子

  • devfs 中的 “虚拟” 文件
    • /dev/pts/[x] - pseudo terminal
    • /dev/zero, /dev/null (实现), /dev/random, ...
  • procfs 中的 “虚拟文件”
2024 南京大学《操作系统:设计与实现》
设备驱动程序

驱动 Nuclear Launcher

center

我们也可以实现一个

  • 把对 /dev/nuke0 “路由” 我们的 file_operations
  • 向 GPIO 的 memory-mapped address 写入正确的电平
  • (当然,我们只是模拟一下)
2024 南京大学《操作系统:设计与实现》
设备驱动程序

配置设备

设备不仅仅是数据,还有配置

  • 打印机的卡纸、清洁、自动装订……
    • 一台几十万的打印机可不是那么简单 😂
  • 键盘的跑马灯、重复速度、宏编程……
  • 磁盘的健康状况、缓存控制……

两种实现方法

  • 控制作为数据流的一部分 (ANSI Escape Code)
  • 提供一个新的接口 (request-response)
2024 南京大学《操作系统:设计与实现》
设备驱动程序

ioctl

The ioctl() system call manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g., terminals) may be controlled with ioctl() requests. The argument fd must be an open file descriptor.

“非数据” 的设备功能几乎全部依赖 ioctl

  • “Arguments, returns, and semantics of ioctl() vary according to the device driver in question”
2024 南京大学《操作系统:设计与实现》
设备驱动程序

ioctl (cont'd)

堆叠的 💩

  • 设备的复杂性是无法降低的
    • “就是有那么多功能”
    • UNIX 的负担:复杂的 “hidden specifications”
      • 另一个负担:procfs

例子

  • 终端:为什么 libc 能 “智能” 实现 buffer mode?
  • 网卡,GPU,……
  • KVM Device
2024 南京大学《操作系统:设计与实现》