Notes about virtio-9p
什么是9P?
9P(Plan 9 File System Protocol)是一种网络文件系统协议。它最初是为贝尔实验室的Plan 9 from Bell Labs分布式操作系统而设计的。
其核心思想是:“将所有资源都表示为文件”。在 Plan 9 中,不仅是磁盘上的数据,包括进程、设备、网络接口、甚至窗口系统接口,都被统一抽象为文件系统中的文件。9P 就是用来访问这些”文件”的协议。
9P核心特性与设计哲学
简单与精简
- 9P 的消息类型非常少(大约 10 种左右,如 
Tversion,Tauth,Tattach,Tclunk,Twalk,Topen,Tread,Twrite,Tstat,Twstat),协议本身简洁明了。 - 这种简单性使得其实现轻量,开销小。
 
分层与状态性
- 9P 是一个有状态的协议。客户端首先通过 
Tattach消息与服务器建立一个”会话”,获取一个根文件句柄(fid)。 - 随后,客户端通过 
Twalk消息在这个根句柄的基础上”遍历”路径,逐步获取目标文件的句柄。 - 这种基于 
fid的交互模式,非常类似于在本地文件系统中使用文件描述符。 
传输无关性
- 9P 协议定义的是消息格式和语义,并不关心底层传输介质。
 - 它可以运行在多种传输层之上,最常见的是 TCP/IP,也可以是 Unix Domain Socket,甚至是 serial port connections。
 
在虚拟化场景下,virtio-9p就是这个传输通道!而virtio-9p就是本文要介绍的内容。
virtio-9p usage
通过virtio-9p(也称为 9pfs)功能,宿主机可以将一个目录直接”共享”给虚拟机。虚拟机内的客户端可以挂载这个 9P 文件系统,从而实现宿主机与虚拟机之间高效的文件共享。
virtio-9p architecture

The following figure shows the basic structure of the 9pfs implementation in QEMU.

The 9P transport driver is the communication channel between host system and guest system.
virtio transport driver: The 9p virtio transport driver uses e.g. a virtual PCI device and ontop the virtio protocol to transfer the 9p messages between clients (guest systems) and 9p server (host system). virtio-9p-device.c
参考资料: