简介

主要需求是透传主机目录至虚机内部使用,9p virtio可以提供该能力,9p的官方介绍如下:

With QEMU’s 9pfs you can create virtual filesystem devices (virtio-9p-device) and expose them to guests, which essentially means that a certain directory on host machine is made directly accessible by a guest OS as a pass-through file system by using the 9P network protocol for communication between host and guest, if desired even accessible, shared by several guests simultaniously.

This section details the steps involved in setting up VirtFS (Plan 9 folder sharing over Virtio - I/O virtualization framework) between the guest and host operating systems. The instructions are followed by an example usage of the mentioned steps.

This page is focused on user aspects like setting up 9pfs, configuration, performance tweaks. For the developers documentation of 9pfs refer to Documentation/9p instead.

See also Documentation/9p_root_fs for a complete HOWTO about installing and configuring an entire guest system ontop of 9p as root fs.

使用方法

Libvirt层面

  1. 在host OS上面创建新的目录和在这个目录里面创建一个文件
1
2
root@kvm:~# mkdir /tmp/shared
root@kvm:~# touch /tmp/shared/file
  1. 在停止KVM的实例后,添加下面的配置
1
2
3
4
5
6
7
8
9
10
11
12
root@kvm:~# virsh edit kvm1
...
<devices>
...
<filesystem type='mount' accessmode='passthrough'>
<source dir='/tmp/shared'/>
<target dir='tmp_shared'/>
</filesystem>
...
</devices>
...
Domain kvm1 XML configuration edited.
  1. 启动VM虚拟机:
1
2
root@kvm:~# virsh start kvm1
Domain kvm1 started
  1. 执行以下命令连接控制台
1
2
3
4
5
6
7
8
9
root@kvm:~# virsh console kvm1
Connected to domain kvm1
Escape character is ^]

Debian GNU/Linux 8 debian ttyS0

debian login: root
Password:
...
  1. 虚机内部,确保9p和virtio内存驱动已经加载
1
2
3
4
5
root@debian:~# lsmod | grep 9p
9pnet_virtio 17006 0
9pnet 61632 1 9pnet_virtio
virtio_ring 17513 3 virtio_pci,virtio_balloon,9pnet_virtio
virtio 13058 3 virtio_pci,virtio_balloon,9pnet_virtio
  1. 虚机内部,挂载共享的目录到/mnt
1
root@debian:~# mount -t 9p -o trans=virtio tmp_shared /mnt
  1. 虚机内部,列出刚刚挂载的东西
1
2
root@debian:~# mount | grep tmp_shared
tmp_shared on /mnt type 9p (rw,relatime,sync,dirsync,trans=virtio)
  1. 虚机内部,查看下我们在第一步创建的文件是否能看的到
1
2
3
4
5
root@debian:~# ls -la /mnt/
total 8
drwxr-xr-x 2 root root 4096 Mar 23 11:25 .
drwxr-xr-x 22 root root 4096 Mar 22 16:28 ..
-rw-r--r-- 1 root root 0 Mar 23 11:25 file

常见问题

VM启动失败:’virtio-9p-pci’ is not a valid device model name

解决方法: 需要重新编译 qemu, 编译时添加额外的 configure 参数 –enable-virtfs,可参考文档《Libvirt研发:Qemu编译》

1
2
3
4
# 1. 安装依赖
yum install -y libcap-devel libattr-devel

# 2. ../configure 编译时,增加--enable-virtfs参数

VM挂载失败:mount: unknown filesystem type ‘9p’

解决方法: 虚机的内核不支持‘9p’文件系统,需要重新编译内核,enable 9p功能。

可通过如下方法检测虚机内核是否支持9p,以下输出结果表示不支持。

1
2
[root@k104 ~]# cat /boot/config-$(uname -r) | grep -i 9p
# CONFIG_NET_9P is not set

编译内核时,添加如下配置至config文件内

1
2
3
4
5
6
7
CONFIG_NET_9P=y
CONFIG_NET_9P_VIRTIO=y
CONFIG_NET_9P_DEBUG=y (Optional)
CONFIG_9P_FS=y
CONFIG_9P_FS_POSIX_ACL=y
CONFIG_PCI=y
CONFIG_VIRTIO_PCI=y

参考文档