September 21, 2024 · linux software

virtiofs Filesystem Sharing with libvirt

virtiofs is a relatively new protocol that allows virtual machines to read and write files directly from the host, and replaces the older 9pfs protocol. It is supported in both Debian 11+ and Ubuntu 22.04+. This guide explains the setup of a virtiofs share.

Host Configuration

Some distributions (e.g. Ubuntu 24.04) may require the installation of the virtiofs daemon: sudo apt install virtiofsd. Start by inserting the <memoryBacking> block in your VM config as shown below:

<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
  <name>cloud</name>
  <uuid>37a22876-d8fe-40ee-8bae-ebc64db7cb24</uuid>
  <memory unit='GB'>2</memory>
...
  <memoryBacking>
    <source type='memfd'/>
    <access mode='shared'/>
  </memoryBacking>
...
</domain>

Next, insert the following <filesystem> block under <devices>. The source defines the directory to be shared from the host. The target is simply a unique string that is used to identify the share inside the guest. Here, the cache is disabled as it can cause stale data to be returned.

<domain>
...
  <devices>
  ...
    <filesystem type='mount' accessmode='passthrough'>
      <driver type='virtiofs' queue='1024'/>
      <source dir='/rust/backups'/>
      <target dir='rust_backups'/>
      <binary>
        <cache mode='none'/>
      </binary>
    </filesystem>
  </devices>
</domain>

Don't forget to redefine the config and perform a full stop-start cycle of the VM.

Guest Configuration

Add the following line to /etc/fstab to automatically mount the virtiofs share on boot:

rust_backups    /rust/backups   virtiofs        rw,noatime,_netdev,nofail

The first field is the target as defined above, the second field is the mount location inside the guest.

References

Adapted from libvirt.org with some changes.