This is a record of getting KVM PCI passthrough working on Gentoo.

I’ve more or less worked through the machines I have around me; only a Mac and a workstation are left. The Mac is too heavy to carry every day, and the workstation has plenty of PCIe slots and enough CPU lanes, so I figured I’d tinker with PCI passthrough: hand a GPU, a USB card and a sound card to a Windows VM and use it as a drawing machine.

Environment

First, the environment and how I’m splitting up the resources. My workstation is a very old ThinkStation S20, configured as follows:

Model CPU Memory Disk GPU USB expansion card Sound card
ThinkStation S20 X5670 8G * 3 PCIE SSD 800G 500G * 1 12TB *2 GT 620 Quadro K2000 Unbranded PCI 2.0 expansion card SB CA10300 and onboard audio

This hardware meets the basic requirements for PCI passthrough. If you want to try PCI passthrough yourself, make sure your hardware supports the following:

  • CPU support for VT-d (Intel) or AMD-Vi (AMD)
  • Two GPUs (if your CPU has integrated graphics and the motherboard can output from it, one is enough; otherwise you need two discrete GPUs)
  • IOMMU support (IOMMU groups the devices on the motherboard; passthrough takes devices from the host group by group)

The plan is to create a Windows VM and pass the K2000, the Sound Blaster card and the PCI 2.0 expansion card through to it, using it as a daily drawing machine. (Or swap in a macOS VM later.) For disks, I’ll give the VM 200G of SSD space and attach the rest as network disks.

Preparing the Environment

Getting the pieces for the VM ready, such as the KVM environment and installation media. I chose Gentoo for the host.

Deploying KVM

First, run this to check whether your machine supports virtualization:

grep --color -E "vmx|svm" /proc/cpuinfo

If you don’t see output like the following, check whether virtualization is enabled in the BIOS, or look up your CPU on Intel Ark to see whether it supports virtualization.

flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 popcnt aes lahf_lm epb pti tpr_shadow vnmi flexpriority ept vpid dtherm ida arat

Make sure the following kernel options are enabled:

[*] Virtualization  --->
    <*>   Kernel-based Virtual Machine (KVM) support

On an Intel CPU, make sure the following option is built as a module or included in the kernel:

[*] Virtualization  --->
       KVM for Intel processors support

On an AMD CPU, make sure the following option is built as a module or included in the kernel:

[*] Virtualization  --->
       KVM for AMD processors support

Building QEMU also needs the vhost-net USE flag, and enabling this kernel option is recommended:

[*] Virtualization  --->
    <*>   Host kernel accelerator for virtio net

For advanced networking support:

Device Drivers  --->
    [*] Network device support  --->
        [*]   Network core driver support
        <*>   Universal TUN/TAP device driver support

I’m going with a bridged network here, so these options need to be enabled as well:

[*] Networking support  --->
        Networking options  --->
            <*> The IPv6 protocol
            <*> 802.1d Ethernet Bridging

After changing these kernel options, rebuild and install the kernel, then boot into it.

make -j12 && make modules_install && make install && grub-mkconfig -o /boot/grub/grub.cfg && reboot

Once rebooted, we can install QEMU. There are two ways to add the USE flags we need.

USE="spice usb usbredir vhost-net" emerge qemu

Or write the flags to a file. Create and edit /etc/portage/package.use/qemu:

app-emulation/qemu spice usb usbredir vhost-net

Then install QEMU:

emerge qemu

Next we need a toolkit for managing VMs (libvirt):

emerge app-emulation/libvirt

Start libvirt and enable it at boot:

/etc/init.d/libvirtd start
rc-update add libvirtd default

Bridge setup: my VM needs to reach other servers on the LAN, so I chose a bridged network. To make the bridge easier to manage, I also need one more tool here:

emerge bridge-utils

To support UEFI in the VM, install the package that provides UEFI boot for virtual machines:

emerge sys-firmware/edk2-ovmf

A plain Windows install may not find the disk, so you also need:

emerge app-emulation/virtio-win

If you want a GUI management interface, install virt-manager:

emerge virt-manager

Configuring libvirt

Installing a VM with UEFI support takes some extra configuration. Edit /etc/libvirt/qemu.conf and add the following:

nvram = [
    "/usr/share/edk2-ovmf/OVMF_CODE.fd:/usr/share/edk2-ovmf/OVMF_VARS.fd",
    "/usr/share/edk2-ovmf/OVMF_VARS.secboot.fd:/usr/share/edk2-ovmf/OVMF_VARS.fd"
]

Change /usr/share/qemu/firmware/50-edk2-x86_64-secure.json to the following:

{
    "description": "UEFI firmware for x86_64, with Secure Boot and SMM",
    "interface-types": [
        "uefi"
    ],
    "mapping": {
        "device": "flash",
        "executable": {
            "filename": "/usr/share/edk2-ovmf/OVMF_CODE.fd",
            "format": "raw"
        },
        "nvram-template": {
            "filename": "/usr/share/edk2-ovmf/OVMF_VARS.fd",
            "format": "raw"
        }
    },
    "targets": [
        {
            "architecture": "x86_64",
            "machines": [
                "pc-q35-*"
            ]
        }
    ],
    "features": [
        "acpi-s3",
        "amd-sev",
        "requires-smm",
        "secure-boot",
        "verbose-dynamic"
    ],
    "tags": [

    ]
}

Restart libvirtd

/etc/init.d/libvirtd restart

Configuring the Bridged Network

There are two ways to configure the network: hand it to NetworkManager, or create a bridge directly in config files. I’ll cover both.

  1. Config files

Edit /etc/conf.d/net:

bridge_br0="enp6s0"
# this enp6s0 is my physical NIC, replace it with yours
# Bridge static config
config_br0="10.0.0.10 netmask 255.255.255.0"
routes_br0="default via 10.0.0.1"

bridge_forward_delay_br0=0
bridge_hello_time_br0=1000

bridge_stp_state_br0=1

Create a symlink

ln -s /etc/init.d/net.lo /etc/init.d/net.br0

Start the bridge interface

rc-service net.br0 start

Add it to boot

rc-update add net.br0 default

Verify

brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.70f39503c843       yes             enp6s0

The bridge interface is now configured.

  1. NetworkManager First create a bridge device
nmcli con add type bridge ifname br0 con-name br0

Add a bridge-slave interface:

nmcli con add type bridge-slave ifname enp6s0 master br0

Configure STP (to prevent bridge loops)

nmcli con modify br0 bridge.stp yes

Assign an IP to br0

nmcli con mod br0 ipv4.method manual ipv4.addresses "10.0.0.10/24" ipv4.gateway 10.0.0.1 ipv4.dns 114.114.114.114 connection.autoconnect yes
nmcli con up br0

Verify

brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.70f39503c843       yes             enp6s0

Enabling IOMMU on the Host

Enabling IOMMU on the host only takes some kernel boot parameters. Edit /etc/default/grub, find GRUB_CMDLINE_LINUX= and change it to:

GRUB_CMDLINE_LINUX="iommu=pt intel_iommu=on pcie_acs_override=downstream,multifunction vfio_iommu_type1.allow_unsafe_interrupts=1"

Both pcie_acs_override and allow_unsafe_interrupts trade security for compatibility: the first forcibly splits IOMMU groups, the second relaxes interrupt isolation. Only use them when device groups really can’t be separated, and be careful in production.

Then update GRUB and reboot:

grub-mkconfig -o /boot/grub/grub.cfg&& reboot

After boot, check the kernel log with dmesg:

dmesg | grep 'IOMMU enabled'
[    0.251621] DMAR: IOMMU enabled

You can see IOMMU is now enabled here.

Reserving Devices on the Host

To reserve devices on the host we need to change the kernel again, this time using VFIO (which hands device I/O and DMA to userspace).

Device Drivers --->
  <*> VFIO Non-Privileged userspace driver framework --->
      [*]   VFIO No-IOMMU support ----
      <*>   VFIO support for PCI devices
      [*]     VFIO PCI support for VGA devices
      < >   Mediated device driver framework

Build “VFIO support for PCI devices” however you like; I built it into the kernel directly and pass parameters through GRUB. Then build the new kernel:

make -j12 && make modules_install && make install && grub-mkconfig -o /boot/grub/grub.cfg && reboot

After rebooting, let’s find the devices we need. A script makes it quick to find them:

#!/bin/bash
shopt -s nullglob
for g in /sys/kernel/iommu_groups/*; do
    echo "IOMMU Group ${g##*/}:"
    for d in $g/devices/*; do
        echo -e "\t$(lspci -nns ${d##*/})"
    done;
done;

Save it to a file and run it, then pick the information we need out of the output and note it down. Here’s a sound card group: the card sits in a group of its own, so we remember the vendor:device ID at the end, 8086:3a3e.

IOMMU Group 16:
        00:1b.0 Audio device [0403]: Intel Corporation 82801JI (ICH10 Family) HD Audio Controller [8086:3a3e]

Further down we see:

IOMMU Group 17:
        00:1c.0 PCI bridge [0604]: Intel Corporation 82801JI (ICH10 Family) PCI Express Root Port 1 [8086:3a40]
        00:1c.4 PCI bridge [0604]: Intel Corporation 82801JI (ICH10 Family) PCI Express Root Port 5 [8086:3a48]
        04:00.0 PCI bridge [0604]: Tundra Semiconductor Corp. Tsi381 PCIe to PCI Bridge [10e3:8111] (rev 02)
        05:00.0 Multimedia audio controller [0401]: Creative Labs CA0108/CA10300 [Sound Blaster Audigy Series] [1102:0008]
        06:00.0 Ethernet controller [0200]: Broadcom Inc. and subsidiaries NetXtreme BCM5755 Gigabit Ethernet PCI Express [14e4:167b] (rev 02)

This is the case you least want: the extra sound card I added shares a group with the NIC and other PCIe ports. Fortunately, the onboard sound card is on its own. Next, the extra USB card:

IOMMU Group 19:
        00:1e.0 PCI bridge [0604]: Intel Corporation 82801 PCI Bridge [8086:244e] (rev 90)
        07:0d.0 USB controller [0c03]: NEC Corporation OHCI USB Controller [1033:0035] (rev 43)
        07:0d.1 USB controller [0c03]: NEC Corporation OHCI USB Controller [1033:0035] (rev 43)
        07:0d.2 USB controller [0c03]: NEC Corporation uPD72010x USB 2.0 Controller [1033:00e0] (rev 04)

And the most important part, the GPUs:

IOMMU Group 21:
        01:00.0 VGA compatible controller [0300]: NVIDIA Corporation GK107GL [Quadro K2000] [10de:0ffe] (rev a1)
        01:00.1 Audio device [0403]: NVIDIA Corporation GK107 HDMI Audio Controller [10de:0e1b] (rev a1)
IOMMU Group 22:
        02:00.0 VGA compatible controller [0300]: NVIDIA Corporation GF119 [GeForce GT 620 OEM] [10de:1049] (rev a1)
        02:00.1 Audio device [0403]: NVIDIA Corporation GF119 HDMI Audio Controller [10de:0e08] (rev a1)

Append the following to the GRUB_CMDLINE_LINUX line in the GRUB config:

vfio-pci.ids=8086:3a3e,8086:244e,1033:0035,1033:00e0,10de:0ffe,10de:0e1b

Update GRUB and reboot:

grub-mkconfig -o /boot/grub/grub.cfg

If your second GPU has a monitor attached, you’ll see boot hang once it reaches the PCI devices being taken over, while the other monitor boots into the system.

Deploying the VM

In this section we’ll deploy a Windows 10 VM.

Prerequisites:

  • Windows 10 image
  • Quadro GPU driver

With those ready, we can start installing. First, create a VM disk:

qemu-img create -f qcow2 /etc/libvirt/storage/windows10.qcow2 200G

If you have SELinux enabled, don’t forget to change the SELinux booleans:

setsebool -P virt_use_vfio=on
setsebool -P virt_use_sysfs=on

Install the Windows 10 VM

sudo virt-install --virt-type=kvm \
--name=windows10 \
--memory=8192 \
--vcpus=6 \
--boot uefi \
--machine q35 \
--cpu=host-passthrough \
--file=/etc/libvirt/storage/windows10.qcow2 \
--cdrom=/etc/libvirt/storage/iso/windows10.iso \
--os-variant win10 \
--network bridge=br0,model=e1000 \
--graphics=vnc,password=passwd,listen=0.0.0.0,port=5900

The VNC password in the example is passwd. Change it once installation is done, and don’t leave it exposed on a public port.

Then connect over VNC and install:

I’ll skip the Windows installation steps.

Adding the PCI Devices

Only one step left before it works: adding the PCI devices. Shut down the VM, then add the matching PCI devices.

List the host devices with nodedev-list.

virsh nodedev-list --tree |grep pci

Find the addresses that correspond to our devices and note them down

  +- pci_0000_00_01_0
  |   +- pci_0000_01_00_0
  |   +- pci_0000_01_00_1

If these are our GPU’s addresses, we need to remember both, since they have to be assigned to the VM together

pci_0000_01_00_0
pci_0000_01_00_1

We can dump the XML with virsh’s nodedev-dumpxml subcommand

virsh nodedev-dumpxml pci_0000_01_00_0

Pick out the parts we need from the output

bus='1'
slot='0'
function='0'

Edit the VM XML:

virsh edit windows10

The GPU’s audio function must be passed through as well, so add both:

<hostdev mode='subsystem' type='pci' managed='yes'>
  <source>
    <address domain='0x0000' bus='0x01' slot='0x00' function='0x0'/>
  </source>
</hostdev>
<hostdev mode='subsystem' type='pci' managed='yes'>
  <source>
    <address domain='0x0000' bus='0x01' slot='0x00' function='0x1'/>
  </source>
</hostdev>

Do the same for the USB card and sound card, replacing bus, slot and function with the values from nodedev-dumpxml.

Don’t remove VNC just yet. Boot the VM, install the NVIDIA driver over VNC, then shut it down. Run virsh edit windows10 again, delete the <graphics> and <video> sections, save and boot. The display should now come from the passed-through GPU.

The result:

References