Introduction to VFIO

Virtual function i/o (vfio) #.

  • Introduced to replace the old-fashioned KVM PCI device assignment (virtio).
  • Userspace driver interface
  • Use IOMMU (AMD IOMMU, Intel VT-d, etc)
  • Full PCI interrupt, MMIO and I/O port access, PCI configuration space access support
  • Take an abstract view of a device : to support anything!

VFIO Device Filer descriptor #

located in /dev/vfio

vfio_list

Each divided into regions

  • Each region maps to a device resource (MMIO BAR, IO BAR, PCI configuration space)

VFIO_DEVICE_GET_INFO ( /linux/include/uapi/linux/vfio.h:186~204 )

VFIO_DEVICE_GET_REGION_INFO ( /linux/include/uapi/vfio.h:206~230 )

VFIO_DEVICE_GET_IRQ_INFO ( /linux/include/uapi/vfio.h:291~333 )

vfio_regionmap

  • vfio_pci_ioctl() function is implemented in /linux/drivers/vfio/pci/vfio_pci.c:545 .

VFIO-PCI Device Driver Structure #

Mainly focus on vfio-pci

Implementation is in /linux/drviers/vfio/pci . Main driver code is vfio_pci.c . This kernel module is compiled as vfio_pci , and we load the module as modprobe vfio-pci for VFIO based PCI-passthrough.

Main kernel module file is vfio_pci.c . When Linux kernel initializes this module, vfio_pci_init() is called.

Also when loading the kernel module, vfio_pci_probe() function is called. This is a part of kernel module operation data structure static struct pci_driver vfio_pci_driver .

Here, VFIO PCI device structure is mapped to pdev , which represents the actual PCI device.

To use VFIO, we pass a kind of parameter to QEMU, like -device vfio-pci,host=01:00.0,bus=root.1.addr=00.0,multifunction=on,x-vga=on The above option is for passing a GPU ( 01:00.0 ) to a virtual machine.

When QEMU opens a VFIO device driver to load the device, vfio_pci_open() is called. This function is a part of operations struct static const struct vfio_device_ops vfio_pci_ops .

A presentation says vfio-iommu-type1 works with x86 style guest mapping, but the implementation uses POWER SPAPR.

In probing the kernel module, vfio_pci_ops is mapped to the VFIO device. This data structure contains the following operations.

Device information can be passed via vfio_pci_ioctl() , as said earlier. To read and write a data, vfio_pci_read() and vfio_pci_write() functions are used. These functions are wrappers of vfio_pci_rw() ( /linux/drivers/vfio/pci/vfio_pci.c:985,994 ).

vfio_pci_rw() is defined right above vfio_pci_read() , which calls

  • vfio_pci_config_rw (defined in /linux/drivers/vfio/pci/vfio_pci_config.c:1678 )
  • vfio_pci_bar_rw (defined in /linux/drivers/vfio/pci/vfio_pci_rdwr.c:116 )
  • vfio_pci_vga_rw (defined in /linux/drivers/vfio/pci/vfio_pci_rdwr.c:183 )

in terms of the index passed to the function.

For GPU, vfio_pci_rw() is mostly called with the index 7 (= VFIO_PCI_CONFIG_REGION_INDEX ) and 8 (= VFIO_PCI_VGA_REGION_INDEX ). Small number of calls are done with index 0 (= VFIO_PCI_BAR0_REGION_INDEX ). Note that each index can be found in /linux/include/uapi/linux/vfio.h:418 .

After a VM starts execution, it communicates with a PCI device via QEMU ( vfio_pci_read_config() and vfio_pci_write_config() ) and KVM VFIO device driver ( vfio_pci_rw() ).

References #

  • Alex Williamson. An Introduction to PCI Device Assignment with VFIO . [Online] . Aug 2016.
  • Alex Williamson. VFIO: PCI device assignment breaks free of KVM . [Online] . 2011.

VFIO - “Virtual Function I/O” 1 ¶

Many modern systems now provide DMA and interrupt remapping facilities to help ensure I/O devices behave within the boundaries they’ve been allotted. This includes x86 hardware with AMD-Vi and Intel VT-d, POWER systems with Partitionable Endpoints (PEs) and embedded PowerPC systems such as Freescale PAMU. The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment. In other words, this allows safe 2 , non-privileged, userspace drivers.

Why do we want that? Virtual machines often make use of direct device access (“device assignment”) when configured for the highest possible I/O performance. From a device and host perspective, this simply turns the VM into a userspace driver, with the benefits of significantly reduced latency, higher bandwidth, and direct use of bare-metal device drivers 3 .

Some applications, particularly in the high performance computing field, also benefit from low-overhead, direct device access from userspace. Examples include network adapters (often non-TCP/IP based) and compute accelerators. Prior to VFIO, these drivers had to either go through the full development cycle to become proper upstream driver, be maintained out of tree, or make use of the UIO framework, which has no notion of IOMMU protection, limited interrupt support, and requires root privileges to access things like PCI configuration space.

The VFIO driver framework intends to unify these, replacing both the KVM PCI specific device assignment code as well as provide a more secure, more featureful userspace driver environment than UIO.

Groups, Devices, and IOMMUs ¶

Devices are the main target of any I/O driver. Devices typically create a programming interface made up of I/O access, interrupts, and DMA. Without going into the details of each of these, DMA is by far the most critical aspect for maintaining a secure environment as allowing a device read-write access to system memory imposes the greatest risk to the overall system integrity.

To help mitigate this risk, many modern IOMMUs now incorporate isolation properties into what was, in many cases, an interface only meant for translation (ie. solving the addressing problems of devices with limited address spaces). With this, devices can now be isolated from each other and from arbitrary memory access, thus allowing things like secure direct assignment of devices into virtual machines.

This isolation is not always at the granularity of a single device though. Even when an IOMMU is capable of this, properties of devices, interconnects, and IOMMU topologies can each reduce this isolation. For instance, an individual device may be part of a larger multi- function enclosure. While the IOMMU may be able to distinguish between devices within the enclosure, the enclosure may not require transactions between devices to reach the IOMMU. Examples of this could be anything from a multi-function PCI device with backdoors between functions to a non-PCI-ACS (Access Control Services) capable bridge allowing redirection without reaching the IOMMU. Topology can also play a factor in terms of hiding devices. A PCIe-to-PCI bridge masks the devices behind it, making transaction appear as if from the bridge itself. Obviously IOMMU design plays a major factor as well.

Therefore, while for the most part an IOMMU may have device level granularity, any system is susceptible to reduced granularity. The IOMMU API therefore supports a notion of IOMMU groups. A group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO.

While the group is the minimum granularity that must be used to ensure secure user access, it’s not necessarily the preferred granularity. In IOMMUs which make use of page tables, it may be possible to share a set of page tables between different groups, reducing the overhead both to the platform (reduced TLB thrashing, reduced duplicate page tables), and to the user (programming only a single set of translations). For this reason, VFIO makes use of a container class, which may hold one or more groups. A container is created by simply opening the /dev/vfio/vfio character device.

On its own, the container provides little functionality, with all but a couple version and extension query interfaces locked away. The user needs to add a group into the container for the next level of functionality. To do this, the user first needs to identify the group associated with the desired device. This can be done using the sysfs links described in the example below. By unbinding the device from the host driver and binding it to a VFIO driver, a new VFIO group will appear for the group as /dev/vfio/$GROUP, where $GROUP is the IOMMU group number of which the device is a member. If the IOMMU group contains multiple devices, each will need to be bound to a VFIO driver before operations on the VFIO group are allowed (it’s also sufficient to only unbind the device from host drivers if a VFIO driver is unavailable; this will make the group available, but not that particular device). TBD - interface for disabling driver probing/locking a device.

Once the group is ready, it may be added to the container by opening the VFIO group character device (/dev/vfio/$GROUP) and using the VFIO_GROUP_SET_CONTAINER ioctl, passing the file descriptor of the previously opened container file. If desired and if the IOMMU driver supports sharing the IOMMU context between groups, multiple groups may be set to the same container. If a group fails to set to a container with existing groups, a new empty container will need to be used instead.

With a group (or groups) attached to a container, the remaining ioctls become available, enabling access to the VFIO IOMMU interfaces. Additionally, it now becomes possible to get file descriptors for each device within a group using an ioctl on the VFIO group file descriptor.

The VFIO device API includes ioctls for describing the device, the I/O regions and their read/write/mmap offsets on the device descriptor, as well as mechanisms for describing and registering interrupt notifications.

VFIO Usage Example ¶

Assume user wants to access PCI device 0000:06:0d.0:

This device is therefore in IOMMU group 26. This device is on the pci bus, therefore the user will make use of vfio-pci to manage the group:

Binding this device to the vfio-pci driver creates the VFIO group character devices for this group:

Now we need to look at what other devices are in the group to free it for use by VFIO:

This device is behind a PCIe-to-PCI bridge 4 , therefore we also need to add device 0000:06:0d.1 to the group following the same procedure as above. Device 0000:00:1e.0 is a bridge that does not currently have a host driver, therefore it’s not required to bind this device to the vfio-pci driver (vfio-pci does not currently support PCI bridges).

The final step is to provide the user with access to the group if unprivileged operation is desired (note that /dev/vfio/vfio provides no capabilities on its own and is therefore expected to be set to mode 0666 by the system):

The user now has full access to all the devices and the iommu for this group and can access them as follows:

VFIO User API ¶

Please see include/linux/vfio.h for complete API documentation.

VFIO bus driver API ¶

VFIO bus drivers, such as vfio-pci make use of only a few interfaces into VFIO core. When devices are bound and unbound to the driver, the driver should call vfio_register_group_dev() and vfio_unregister_group_dev() respectively:

The driver should embed the vfio_device in its own structure and call vfio_init_group_dev() to pre-configure it before going to registration and call vfio_uninit_group_dev() after completing the un-registration. vfio_register_group_dev() indicates to the core to begin tracking the iommu_group of the specified dev and register the dev as owned by a VFIO bus driver. Once vfio_register_group_dev() returns it is possible for userspace to start accessing the driver, thus the driver should ensure it is completely ready before calling it. The driver provides an ops structure for callbacks similar to a file operations structure:

Each function is passed the vdev that was originally registered in the vfio_register_group_dev() call above. This allows the bus driver to obtain its private data using container_of(). The open/release callbacks are issued when a new file descriptor is created for a device (via VFIO_GROUP_GET_DEVICE_FD). The ioctl interface provides a direct pass through for VFIO_DEVICE_* ioctls. The read/write/mmap interfaces implement the device region access defined by the device’s own VFIO_DEVICE_GET_REGION_INFO ioctl.

PPC64 sPAPR implementation note ¶

This implementation has some specifics:

On older systems (POWER7 with P5IOC2/IODA1) only one IOMMU group per container is supported as an IOMMU table is allocated at the boot time, one table per a IOMMU group which is a Partitionable Endpoint (PE) (PE is often a PCI domain but not always).

Newer systems (POWER8 with IODA2) have improved hardware design which allows to remove this limitation and have multiple IOMMU groups per a VFIO container.

The hardware supports so called DMA windows - the PCI address range within which DMA transfer is allowed, any attempt to access address space out of the window leads to the whole PE isolation.

PPC64 guests are paravirtualized but not fully emulated. There is an API to map/unmap pages for DMA, and it normally maps 1..32 pages per call and currently there is no way to reduce the number of calls. In order to make things faster, the map/unmap handling has been implemented in real mode which provides an excellent performance which has limitations such as inability to do locked pages accounting in real time.

According to sPAPR specification, A Partitionable Endpoint (PE) is an I/O subtree that can be treated as a unit for the purposes of partitioning and error recovery. A PE may be a single or multi-function IOA (IO Adapter), a function of a multi-function IOA, or multiple IOAs (possibly including switch and bridge structures above the multiple IOAs). PPC64 guests detect PCI errors and recover from them via EEH RTAS services, which works on the basis of additional ioctl commands.

So 4 additional ioctls have been added:

VFIO_IOMMU_SPAPR_TCE_GET_INFO returns the size and the start of the DMA window on the PCI bus. VFIO_IOMMU_ENABLE enables the container. The locked pages accounting is done at this point. This lets user first to know what the DMA window is and adjust rlimit before doing any real job. VFIO_IOMMU_DISABLE disables the container. VFIO_EEH_PE_OP provides an API for EEH setup, error detection and recovery.

The code flow from the example above should be slightly changed:

There is v2 of SPAPR TCE IOMMU. It deprecates VFIO_IOMMU_ENABLE/ VFIO_IOMMU_DISABLE and implements 2 new ioctls: VFIO_IOMMU_SPAPR_REGISTER_MEMORY and VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY (which are unsupported in v1 IOMMU).

PPC64 paravirtualized guests generate a lot of map/unmap requests, and the handling of those includes pinning/unpinning pages and updating mm::locked_vm counter to make sure we do not exceed the rlimit. The v2 IOMMU splits accounting and pinning into separate operations:

VFIO_IOMMU_SPAPR_REGISTER_MEMORY/VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY ioctls receive a user space address and size of the block to be pinned. Bisecting is not supported and VFIO_IOMMU_UNREGISTER_MEMORY is expected to be called with the exact address and size used for registering the memory block. The userspace is not expected to call these often. The ranges are stored in a linked list in a VFIO container.

VFIO_IOMMU_MAP_DMA/VFIO_IOMMU_UNMAP_DMA ioctls only update the actual IOMMU table and do not do pinning; instead these check that the userspace address is from pre-registered range.

This separation helps in optimizing DMA for guests.

sPAPR specification allows guests to have an additional DMA window(s) on a PCI bus with a variable page size. Two ioctls have been added to support this: VFIO_IOMMU_SPAPR_TCE_CREATE and VFIO_IOMMU_SPAPR_TCE_REMOVE. The platform has to support the functionality or error will be returned to the userspace. The existing hardware supports up to 2 DMA windows, one is 2GB long, uses 4K pages and called “default 32bit window”; the other can be as big as entire RAM, use different page size, it is optional - guests create those in run-time if the guest driver supports 64bit DMA.

VFIO_IOMMU_SPAPR_TCE_CREATE receives a page shift, a DMA window size and a number of TCE table levels (if a TCE table is going to be big enough and the kernel may not be able to allocate enough of physically contiguous memory). It creates a new window in the available slot and returns the bus address where the new window starts. Due to hardware limitation, the user space cannot choose the location of DMA windows.

VFIO_IOMMU_SPAPR_TCE_REMOVE receives the bus start address of the window and removes it.

VFIO was originally an acronym for “Virtual Function I/O” in its initial implementation by Tom Lyon while as Cisco. We’ve since outgrown the acronym, but it’s catchy.

“safe” also depends upon a device being “well behaved”. It’s possible for multi-function devices to have backdoors between functions and even for single function devices to have alternative access to things like PCI config space through MMIO registers. To guard against the former we can include additional precautions in the IOMMU driver to group multi-function PCI devices together (iommu=group_mf). The latter we can’t prevent, but the IOMMU should still provide isolation. For PCI, SR-IOV Virtual Functions are the best indicator of “well behaved”, as these are designed for virtualization usage models.

As always there are trade-offs to virtual machine device assignment that are beyond the scope of VFIO. It’s expected that future IOMMU technologies will reduce some, but maybe not all, of these trade-offs.

In this case the device is below a PCI bridge, so transactions from either function of the device are indistinguishable to the iommu:

The Linux Kernel

Quick search, table of contents.

  • Groups, Devices, and IOMMUs
  • VFIO Usage Example
  • VFIO User API
  • VFIO bus driver API
  • PPC64 sPAPR implementation note
  • Show Source

VFIO Device Passthrough Principles (1)

To ensure that I/O devices run within the boundaries they've been allotted, many modern systems provide DMA and interrupt remapping facilities, such as AMD-Vi and Intel VT-d on the x86 platform. Virtual Function I/O (VFIO) is a framework that securely exposes device I/O, interrupt, and DMA capabilities to userspace so that user-mode drivers can be used to implement the functions of devices. It is used to provide direct device access to VMs to obtain higher device I/O performance.

The key for implementing user-mode drivers is how to expose the DMA capability to userspace in a secure and controllable manner. IOMMU can restrict device access to memory. A malicious device cannot read or write the physical memory directly but through an I/O virtual address (IOVA) only after IOMMU mapping. In this way, memory access security is ensured.

VFIO Kernel Components #

The following lists main VFIO kernel components, which provide a unified access interface layer (the VFIO interface layer) for userspace through device files.

  • VFIO container
  • VFIO device

The VFIO interface layer encapsulates the vfio_iommu_driver and vfio_pci modules, which interact with the underlying IOMMU and PCI drivers respectively. vfio_iommu_driver provides the IOMMU remapping driver for VFIO to perform DMA remapping. The remapping is mainly completed by vfio_iommu_type1 , which uses the IOMMU capability of managing I/O page tables to perform I/O remapping. vfio_pci encapsulates the PCI driver and works with user-mode programs to implement user-mode device configuration space simulation, base address register (BAR) space redirection, and interrupt remapping.

The following shows the relationship between the container, group, and device. A container can be regarded as a physical resource set, and each container can have multiple groups. A group is the minimum hardware granularity for the IOMMU to implement DMA isolation. A group may contain one or more devices, depending on the IOMMU topology of hardware.

For details about the relationship between the container, group, device, and IOMMU, see the vfio.txt file.

VFIO Container #

A container manages memory resources and is related to the IOMMU, DMA, and address space. You can open the device file /dev/vfio/vfio to obtain the file descriptor corresponding to the container, and specific implementations of the VFIO device file operations are included in the kernel file vfio/vfio.c . ioctl is used to obtain IOMMU information. VFIO sends IOMMU-related operations in userspace to the underlying vfio_iommu driver. The following lists the interfaces provided by VFIO ioctl .

  • Obtaining the API version
  • Setting the IOMMU type, for example, VFIO_TYPE1_IOMMU
  • Obtaining IOMMU information
  • Allocating space and performing DMA mapping

VFIO Group #

A group is the minimum hardware granularity for the IOMMU to implement DMA isolation. The group to which a device belongs depends on the IOMMU and the physical structure of the device. During device passthrough, all devices in a group are allocated to a VM. That is, multiple groups and their devices belong to one container. In this way, DMA isolation can be implemented, preventing a device in a container from obtaining data in another container through DMA attacks.

For a PCI device (for example, 0000:06:0d.0:😃, you can obtain its iommu_group in the sys directory through readlink . In the following example, the PCI device is in the IOMMU group whose ID is 26.

The device is mounted to the PCI bus. You can use vfio-pci to manage the group by unbinding the PCI device from the original driver and writing the ID to the new vfio-pci path. A character device for the group will be created.

After the device is bound to VFIO, a new group ID is generated in the /dev/vfio/ directory. You can use the ID to obtain group information and perform the following operations:

  • Querying the group status and checking whether all devices are bound to the VFIO driver
  • Setting the container of the group
  • Allocating a file descriptor to the device based on the BDF (Bus:Device.Function) of the device

VFIO Device #

To support both the platform and PCI devices, VFIO provides struct vfio_device to describe VFIO devices and points device_data to struct vfio_pci_device . Different from a physical device, a device that is an independent piece of hardware forms an IOMMU group. For a multi-function device, multiple functions are interconnected and can access data of each other; therefore, they must be placed in a group.

After the device descriptor is obtained through the BDF of the device and the ioctl operation on the group, the kernel operation structure vfio_pci_ops of vfio_pci corresponding to the descriptor can be used. This ops structure is registered with the PCI device when the vfio_pci_probe function of the vfio_pci device driver is invoked. During the probe, the device is added to the corresponding group. The vfio_pci_ioctl function is an important device operation in vfio_pci . It provides the following interfaces:

  • VFIO_DEVICE_GET_INFO : Obtains device information, including the number of regions and IRQs.
  • VFIO_DEVICE_GET_REGION_INFO : Obtains the vfio_region information, including the regions of the configuration space and BAR space.
  • VFIO_DEVICE_GET_IRQ_INFO : Obtains device interrupt information.
  • VFIO_DEVICE_SET_IRQS : Completes interrupt-related settings.
  • VFIO_DEVICE_RESET : Resets the device.
  • VFIO_DEVICE_GET_PCI_HOT_RESET_INFO : Obtains the hot reset information of the PCI device.
  • VFIO_DEVICE_PCI_HOT_RESET : Sets hot reset for the PCI device.
  • VFIO_DEVICE_IOEVENTFD : Sets ioeventfd.

To expose device capabilities to userspace, ensure the device configuration space can be directly accessed and device interrupts can be processed by user-mode programs. For a PCI device, the configuration space is a VFIO region, which corresponds to a block of MMIO memory. DMA remapping enables the device configuration space to be directly accessed from userspace, and interrupt remapping enables user-mode drivers to process device interrupts.

Container, Group, and Device Binding #

  • VFIO_SET_IOMMU : Binds a container to an IOMMU.

The VFIO container is bound to the IOMMU by invoking VFIO_SET_IOMMU through ioctl in user mode. Once the binding is complete, all groups managed by the container and their devices are attached to the IOMMU, which means that an I/O page table is created for the devices to complete initialization.

  • VFIO_GROUP_SET_CONTAINER : Binds a group to a container.

VFIO provides an interface for user-mode programs to specify the container to which a group is bound. The binding operation records the group in the linked list of the container for management. If vfio_iommu_driver has been set, the group is attached and then the I/O page table of devices in the group is initialized.

  • The binding between a device and a group depends on the physical topology of the device and IOMMU.

The implementation of VFIO kernel components is closely related to the IOMMU and device model of the Linux kernel. Three VFIO concepts (container, group, and device) are abstracted to encapsulate the Linux kernel components. This article describes the basic VFIO concepts using user-mode interfaces of VFIO. To expose a physical device to userspace through the VFIO driver, the following steps re required:

  • Unbind the device from the original driver and then bind the device to the VFIO driver. The VFIO driver specifies a group for the device depending on the physical topology of the device and IOMMU.
  • After the binding is complete, user-mode drivers can obtain the VFIO container through /dev/vfio/vfio , set the vfio_iommu_driver type, and indirectly access the IOMMU through the container to complete DMA mapping.
  • Then, you can use /dev/vfio/%group_id to obtain the group to which the device belongs and use ioctl to add all devices in the group to the container.
  • Then, the file descriptor of the VFIO device can be obtained by using the group ID and device BDF, and the configuration space and IRQ information of the device can be accessed by using the interface provided by VFIO. In this way, physical devices can be accessed from userspace.

VFIO device passthrough has several key issues. For example, how to access the I/O address space of a passthrough device, and how to complete interrupt remapping and DMA remapping to enable user-mode drivers to access physical devices.

References #

  • https://www.kernel.org/doc/Documentation/vfio.txt
  • https://kernelgo.org/vfio-introduction.html

How likely are you to recommend the openEuler Community to others?

The Linux Kernel

Quick search.

  • Development process
  • Submitting patches
  • Code of conduct
  • Maintainer handbook
  • All development-process docs
  • General information for driver authors
  • Early Userspace
  • Kernel Connector
  • Bus-Independent Device Accesses
  • Device Frequency Scaling
  • Buffer Sharing and Synchronization (dma-buf)
  • Component Helper for Aggregate Drivers
  • The io_mapping functions
  • Ordering I/O writes to memory-mapped addresses
  • The Userspace I/O HOWTO
  • VFIO Mediated devices
  • VFIO - “Virtual Function I/O”
  • Acceptance criteria for vfio-pci device specific driver variants
  • Bus-level documentation
  • Subsystem-specific APIs
  • Licensing rules
  • Writing documentation
  • Development tools
  • Testing guide
  • Hacking guide
  • Fault injection
  • Livepatching
  • Administration
  • Build system
  • Reporting issues
  • Userspace tools
  • Userspace API
  • Firmware and Devicetree
  • CPU architectures
  • Unsorted documentation
  • Translations
  • Show Source

VFIO - “Virtual Function I/O” 1 ¶

Many modern systems now provide DMA and interrupt remapping facilities to help ensure I/O devices behave within the boundaries they’ve been allotted. This includes x86 hardware with AMD-Vi and Intel VT-d, POWER systems with Partitionable Endpoints (PEs) and embedded PowerPC systems such as Freescale PAMU. The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment. In other words, this allows safe 2 , non-privileged, userspace drivers.

Why do we want that? Virtual machines often make use of direct device access (“device assignment”) when configured for the highest possible I/O performance. From a device and host perspective, this simply turns the VM into a userspace driver, with the benefits of significantly reduced latency, higher bandwidth, and direct use of bare-metal device drivers 3 .

Some applications, particularly in the high performance computing field, also benefit from low-overhead, direct device access from userspace. Examples include network adapters (often non-TCP/IP based) and compute accelerators. Prior to VFIO, these drivers had to either go through the full development cycle to become proper upstream driver, be maintained out of tree, or make use of the UIO framework, which has no notion of IOMMU protection, limited interrupt support, and requires root privileges to access things like PCI configuration space.

The VFIO driver framework intends to unify these, replacing both the KVM PCI specific device assignment code as well as provide a more secure, more featureful userspace driver environment than UIO.

Groups, Devices, and IOMMUs ¶

Devices are the main target of any I/O driver. Devices typically create a programming interface made up of I/O access, interrupts, and DMA. Without going into the details of each of these, DMA is by far the most critical aspect for maintaining a secure environment as allowing a device read-write access to system memory imposes the greatest risk to the overall system integrity.

To help mitigate this risk, many modern IOMMUs now incorporate isolation properties into what was, in many cases, an interface only meant for translation (ie. solving the addressing problems of devices with limited address spaces). With this, devices can now be isolated from each other and from arbitrary memory access, thus allowing things like secure direct assignment of devices into virtual machines.

This isolation is not always at the granularity of a single device though. Even when an IOMMU is capable of this, properties of devices, interconnects, and IOMMU topologies can each reduce this isolation. For instance, an individual device may be part of a larger multi- function enclosure. While the IOMMU may be able to distinguish between devices within the enclosure, the enclosure may not require transactions between devices to reach the IOMMU. Examples of this could be anything from a multi-function PCI device with backdoors between functions to a non-PCI-ACS (Access Control Services) capable bridge allowing redirection without reaching the IOMMU. Topology can also play a factor in terms of hiding devices. A PCIe-to-PCI bridge masks the devices behind it, making transaction appear as if from the bridge itself. Obviously IOMMU design plays a major factor as well.

Therefore, while for the most part an IOMMU may have device level granularity, any system is susceptible to reduced granularity. The IOMMU API therefore supports a notion of IOMMU groups. A group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO.

While the group is the minimum granularity that must be used to ensure secure user access, it’s not necessarily the preferred granularity. In IOMMUs which make use of page tables, it may be possible to share a set of page tables between different groups, reducing the overhead both to the platform (reduced TLB thrashing, reduced duplicate page tables), and to the user (programming only a single set of translations). For this reason, VFIO makes use of a container class, which may hold one or more groups. A container is created by simply opening the /dev/vfio/vfio character device.

On its own, the container provides little functionality, with all but a couple version and extension query interfaces locked away. The user needs to add a group into the container for the next level of functionality. To do this, the user first needs to identify the group associated with the desired device. This can be done using the sysfs links described in the example below. By unbinding the device from the host driver and binding it to a VFIO driver, a new VFIO group will appear for the group as /dev/vfio/$GROUP, where $GROUP is the IOMMU group number of which the device is a member. If the IOMMU group contains multiple devices, each will need to be bound to a VFIO driver before operations on the VFIO group are allowed (it’s also sufficient to only unbind the device from host drivers if a VFIO driver is unavailable; this will make the group available, but not that particular device). TBD - interface for disabling driver probing/locking a device.

Once the group is ready, it may be added to the container by opening the VFIO group character device (/dev/vfio/$GROUP) and using the VFIO_GROUP_SET_CONTAINER ioctl, passing the file descriptor of the previously opened container file. If desired and if the IOMMU driver supports sharing the IOMMU context between groups, multiple groups may be set to the same container. If a group fails to set to a container with existing groups, a new empty container will need to be used instead.

With a group (or groups) attached to a container, the remaining ioctls become available, enabling access to the VFIO IOMMU interfaces. Additionally, it now becomes possible to get file descriptors for each device within a group using an ioctl on the VFIO group file descriptor.

The VFIO device API includes ioctls for describing the device, the I/O regions and their read/write/mmap offsets on the device descriptor, as well as mechanisms for describing and registering interrupt notifications.

VFIO Usage Example ¶

Assume user wants to access PCI device 0000:06:0d.0:

This device is therefore in IOMMU group 26. This device is on the pci bus, therefore the user will make use of vfio-pci to manage the group:

Binding this device to the vfio-pci driver creates the VFIO group character devices for this group:

Now we need to look at what other devices are in the group to free it for use by VFIO:

This device is behind a PCIe-to-PCI bridge 4 , therefore we also need to add device 0000:06:0d.1 to the group following the same procedure as above. Device 0000:00:1e.0 is a bridge that does not currently have a host driver, therefore it’s not required to bind this device to the vfio-pci driver (vfio-pci does not currently support PCI bridges).

The final step is to provide the user with access to the group if unprivileged operation is desired (note that /dev/vfio/vfio provides no capabilities on its own and is therefore expected to be set to mode 0666 by the system):

The user now has full access to all the devices and the iommu for this group and can access them as follows:

IOMMUFD and vfio_iommu_type1 ¶

IOMMUFD is the new user API to manage I/O page tables from userspace. It intends to be the portal of delivering advanced userspace DMA features (nested translation 5 , PASID 6 , etc.) while also providing a backwards compatibility interface for existing VFIO_TYPE1v2_IOMMU use cases. Eventually the vfio_iommu_type1 driver, as well as the legacy vfio container and group model is intended to be deprecated.

The IOMMUFD backwards compatibility interface can be enabled two ways. In the first method, the kernel can be configured with CONFIG_IOMMUFD_VFIO_CONTAINER, in which case the IOMMUFD subsystem transparently provides the entire infrastructure for the VFIO container and IOMMU backend interfaces. The compatibility mode can also be accessed if the VFIO container interface, ie. /dev/vfio/vfio is simply symlink’d to /dev/iommu. Note that at the time of writing, the compatibility mode is not entirely feature complete relative to VFIO_TYPE1v2_IOMMU (ex. DMA mapping MMIO) and does not attempt to provide compatibility to the VFIO_SPAPR_TCE_IOMMU interface. Therefore it is not generally advisable at this time to switch from native VFIO implementations to the IOMMUFD compatibility interfaces.

Long term, VFIO users should migrate to device access through the cdev interface described below, and native access through the IOMMUFD provided interfaces.

VFIO Device cdev ¶

Traditionally user acquires a device fd via VFIO_GROUP_GET_DEVICE_FD in a VFIO group.

With CONFIG_VFIO_DEVICE_CDEV=y the user can now acquire a device fd by directly opening a character device /dev/vfio/devices/vfioX where “X” is the number allocated uniquely by VFIO for registered devices. cdev interface does not support noiommu devices, so user should use the legacy group interface if noiommu is wanted.

The cdev only works with IOMMUFD. Both VFIO drivers and applications must adapt to the new cdev security model which requires using VFIO_DEVICE_BIND_IOMMUFD to claim DMA ownership before starting to actually use the device. Once BIND succeeds then a VFIO device can be fully accessed by the user.

VFIO device cdev doesn’t rely on VFIO group/container/iommu drivers. Hence those modules can be fully compiled out in an environment where no legacy VFIO application exists.

So far SPAPR does not support IOMMUFD yet. So it cannot support device cdev either.

vfio device cdev access is still bound by IOMMU group semantics, ie. there can be only one DMA owner for the group. Devices belonging to the same group can not be bound to multiple iommufd_ctx or shared between native kernel and vfio bus driver or other driver supporting the driver_managed_dma flag. A violation of this ownership requirement will fail at the VFIO_DEVICE_BIND_IOMMUFD ioctl, which gates full device access.

Device cdev Example ¶

Assume user wants to access PCI device 0000:6a:01.0:

This device is therefore represented as vfio0. The user can verify its existence:

Then provide the user with access to the device if unprivileged operation is desired:

Finally the user could get cdev fd by:

An opened cdev_fd doesn’t give the user any permission of accessing the device except binding the cdev_fd to an iommufd. After that point then the device is fully accessible including attaching it to an IOMMUFD IOAS/HWPT to enable userspace DMA:

VFIO User API ¶

Please see include/uapi/linux/vfio.h for complete API documentation.

VFIO bus driver API ¶

VFIO bus drivers, such as vfio-pci make use of only a few interfaces into VFIO core. When devices are bound and unbound to the driver, Following interfaces are called when devices are bound to and unbound from the driver:

The driver should embed the vfio_device in its own structure and use vfio_alloc_device() to allocate the structure, and can register @init/@release callbacks to manage any private state wrapping the vfio_device:

vfio_register_group_dev() indicates to the core to begin tracking the iommu_group of the specified dev and register the dev as owned by a VFIO bus driver. Once vfio_register_group_dev() returns it is possible for userspace to start accessing the driver, thus the driver should ensure it is completely ready before calling it. The driver provides an ops structure for callbacks similar to a file operations structure:

Each function is passed the vdev that was originally registered in the vfio_register_group_dev() or vfio_register_emulated_iommu_dev() call above. This allows the bus driver to obtain its private data using container_of().

PPC64 sPAPR implementation note ¶

This implementation has some specifics:

On older systems (POWER7 with P5IOC2/IODA1) only one IOMMU group per container is supported as an IOMMU table is allocated at the boot time, one table per a IOMMU group which is a Partitionable Endpoint (PE) (PE is often a PCI domain but not always).

Newer systems (POWER8 with IODA2) have improved hardware design which allows to remove this limitation and have multiple IOMMU groups per a VFIO container.

The hardware supports so called DMA windows - the PCI address range within which DMA transfer is allowed, any attempt to access address space out of the window leads to the whole PE isolation.

PPC64 guests are paravirtualized but not fully emulated. There is an API to map/unmap pages for DMA, and it normally maps 1..32 pages per call and currently there is no way to reduce the number of calls. In order to make things faster, the map/unmap handling has been implemented in real mode which provides an excellent performance which has limitations such as inability to do locked pages accounting in real time.

According to sPAPR specification, A Partitionable Endpoint (PE) is an I/O subtree that can be treated as a unit for the purposes of partitioning and error recovery. A PE may be a single or multi-function IOA (IO Adapter), a function of a multi-function IOA, or multiple IOAs (possibly including switch and bridge structures above the multiple IOAs). PPC64 guests detect PCI errors and recover from them via EEH RTAS services, which works on the basis of additional ioctl commands.

So 4 additional ioctls have been added:

VFIO_IOMMU_SPAPR_TCE_GET_INFO returns the size and the start of the DMA window on the PCI bus. VFIO_IOMMU_ENABLE enables the container. The locked pages accounting is done at this point. This lets user first to know what the DMA window is and adjust rlimit before doing any real job. VFIO_IOMMU_DISABLE disables the container. VFIO_EEH_PE_OP provides an API for EEH setup, error detection and recovery.

The code flow from the example above should be slightly changed:

There is v2 of SPAPR TCE IOMMU. It deprecates VFIO_IOMMU_ENABLE/ VFIO_IOMMU_DISABLE and implements 2 new ioctls: VFIO_IOMMU_SPAPR_REGISTER_MEMORY and VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY (which are unsupported in v1 IOMMU).

PPC64 paravirtualized guests generate a lot of map/unmap requests, and the handling of those includes pinning/unpinning pages and updating mm::locked_vm counter to make sure we do not exceed the rlimit. The v2 IOMMU splits accounting and pinning into separate operations:

VFIO_IOMMU_SPAPR_REGISTER_MEMORY/VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY ioctls receive a user space address and size of the block to be pinned. Bisecting is not supported and VFIO_IOMMU_UNREGISTER_MEMORY is expected to be called with the exact address and size used for registering the memory block. The userspace is not expected to call these often. The ranges are stored in a linked list in a VFIO container.

VFIO_IOMMU_MAP_DMA/VFIO_IOMMU_UNMAP_DMA ioctls only update the actual IOMMU table and do not do pinning; instead these check that the userspace address is from pre-registered range.

This separation helps in optimizing DMA for guests.

sPAPR specification allows guests to have an additional DMA window(s) on a PCI bus with a variable page size. Two ioctls have been added to support this: VFIO_IOMMU_SPAPR_TCE_CREATE and VFIO_IOMMU_SPAPR_TCE_REMOVE. The platform has to support the functionality or error will be returned to the userspace. The existing hardware supports up to 2 DMA windows, one is 2GB long, uses 4K pages and called “default 32bit window”; the other can be as big as entire RAM, use different page size, it is optional - guests create those in run-time if the guest driver supports 64bit DMA.

VFIO_IOMMU_SPAPR_TCE_CREATE receives a page shift, a DMA window size and a number of TCE table levels (if a TCE table is going to be big enough and the kernel may not be able to allocate enough of physically contiguous memory). It creates a new window in the available slot and returns the bus address where the new window starts. Due to hardware limitation, the user space cannot choose the location of DMA windows.

VFIO_IOMMU_SPAPR_TCE_REMOVE receives the bus start address of the window and removes it.

VFIO was originally an acronym for “Virtual Function I/O” in its initial implementation by Tom Lyon while as Cisco. We’ve since outgrown the acronym, but it’s catchy.

“safe” also depends upon a device being “well behaved”. It’s possible for multi-function devices to have backdoors between functions and even for single function devices to have alternative access to things like PCI config space through MMIO registers. To guard against the former we can include additional precautions in the IOMMU driver to group multi-function PCI devices together (iommu=group_mf). The latter we can’t prevent, but the IOMMU should still provide isolation. For PCI, SR-IOV Virtual Functions are the best indicator of “well behaved”, as these are designed for virtualization usage models.

As always there are trade-offs to virtual machine device assignment that are beyond the scope of VFIO. It’s expected that future IOMMU technologies will reduce some, but maybe not all, of these trade-offs.

In this case the device is below a PCI bridge, so transactions from either function of the device are indistinguishable to the iommu:

Nested translation is an IOMMU feature which supports two stage address translations. This improves the address translation efficiency in IOMMU virtualization.

PASID stands for Process Address Space ID, introduced by PCI Express. It is a prerequisite for Shared Virtual Addressing (SVA) and Scalable I/O Virtualization (Scalable IOV).

IMAGES

  1. [2016] An Introduction to PCI Device Assignment with VFIO by Alex Williamson

    an introduction to pci device assignment with vfio

  2. PCI Device passthrough on Harvester : tobilehman.com

    an introduction to pci device assignment with vfio

  3. Introduction to VFIO · Better Tomorrow with Computer Science

    an introduction to pci device assignment with vfio

  4. QEMU Virtual Machine PCIe Device Passthrough Using vfio-pci

    an introduction to pci device assignment with vfio

  5. Features/VT-d

    an introduction to pci device assignment with vfio

  6. Introduction to VFIO · Better Tomorrow with Computer Science

    an introduction to pci device assignment with vfio

VIDEO

  1. Lecture 17: Hannah Arendt's Introduction her book On Revolution

  2. PowerBasic Projects

  3. PCI DSS Assignment 2

  4. GPU passthrough with bhyve

  5. Assignment 1

  6. PCI HVAC Program Introduction

COMMENTS

  1. [2016] An Introduction to PCI Device Assignment with VFIO by Alex

    VFIO is a Linux kernel userspace driver framework used by QEMU to make devices directly assignable to virtual machines. This model replaces the now deprecate...

  2. Introduction to VFIO · Better Tomorrow with Computer Science

    Apr 27, 2017. research linux pcie. Virtual Function I/O (VFIO) Introduced to replace the old-fashioned KVM PCI device assignment (virtio). Userspace driver interface. Use IOMMU (AMD IOMMU, Intel VT-d, etc) Full PCI interrupt, MMIO and I/O port access, PCI configuration space access support. Take an abstract view of a device: to support anything ...

  3. An Introduction to PCI Device Assignment with VFIO

    Sometimes VFIO users are befuddled that they aren't able to separate devices between host and guest or multiple guests due to IOMMU grou... VFIO GPU How To series, part 3 - Host configuration For my setup I'm using a Fedora 21 system with the virt-preview yum repos to get the latest QEMU and libvirt support along with Gerd Ho...

  4. VFIO driver analysis

    This is from Alex's talk An Introduction to PCI Device Assignment with VFIO. VFIO decomposes the physical device as a set of userspace API and recomposes the physical device's resource to a virtual device in qemu. ... Here 'dev' is the physical device. 'ops' is 'vfio_pci_ops', 'group' is get or created right now, 'group ...

  5. VFIO

    The VFIO driver framework intends to unify these, replacing both the KVM PCI specific device assignment code as well as provide a more secure, more featureful userspace driver environment than UIO. ... Binding this device to the vfio-pci driver creates the VFIO group character devices for this group: $ lspci -n -s 0000:06:0d.0 06:0d.0 0401: ...

  6. Introduction to VFIO · Better Tomorrow with Computer Science Graphics

    Virtual Function I/O (VFIO) # Introduced toward replace the old-fashioned KVM PCI device assignment (virtio). Userspace driver interface Use IOMMU (AMD IOMMU, Intel VT-d, etc) Full PCI cancel, MMIO and I/O port accessories, PCI configuration space access support Take an abstract view of a device: to assistance anything! VFIO Device Filter descriptor # located in /dev/vfio Each divided into ...

  7. VFIO Device Assignment Quirks

    Device file ioctls provide introspection of region and interrupt capabilities; Device interrupts are programmed through ioctls and delivered via eventfd; QEMU consumes the VFIO API. Recomposing the physical device to a virtual device. For further details: KVM Forum 2016: "An Introduction to PCI Device Assignment with VFIO" Quirks What are Quirks

  8. LinuxCon Beijing 2018: VFIO Device Assignment Quirks, and how to avoid

    Device file ioctls provide introspection of region and interrupt capabilities; Device interrupts programmed through ioctls and delivered via eventfd; QEMU consumes the VFIO API. Recomposing the physical device to a virtual device. For further details: KVM Forum 2016: "An Introduction to PCI Device Assignment with VFIO" Device Assignment ...

  9. PDF VFIO: A user's perspective

    15 Alex Williamson x86 only, PCI only, KVM only VFIO supports a modular IOMMU interface IOMMU API (type1) implemented POWER (SPAPR) under development VFIO supports a modular device interface PCI (vfio-pci) implemented VFIO has no KVM dependencies Used only for acceleration Non-x86 guests on x86 host work today ppc g3beige - Big Endian driver test platform!

  10. PDF Kernel-based Virtual Machine

    Kernel-based Virtual Machine

  11. VFIO Device Passthrough Principles (1)

    After the device descriptor is obtained through the BDF of the device and the ioctl operation on the group, the kernel operation structure vfio_pci_ops of vfio_pci corresponding to the descriptor can be used. This ops structure is registered with the PCI device when the vfio_pci_probe function of the vfio_pci device driver is invoked. During ...

  12. PDF VFIO Device Assignment Quirks and How to Avoid Them in Your Hardware

    redhat VFIO Device Assignment Quirks and how to avoid them in your hardware Alex Williamson / [email protected]. A quick VFIO refresher redhat. VFIO: A userspace driver interface. container Devices are decomposed into a userspace API redhat. QEMU consumes the VFIO API vrie, group2 group container Recomposing the physical device to a ...

  13. Setting up PCI devices for VFIO pass-through

    Before you begin: The preferred method for setting up PCI devices is to configure them for automatic management with libvirt, see the information about configuring VFIO pass-through devices in KVM Virtual Server Management, SC34-2752.This management includes a dynamic host preparation. The tasks that follow describe a fallback method that applies only to PCI devices that are not managed by ...

  14. PDF File:01x04-Alex Williamson-An Introduction to PCI Device Assignment

    File:01x04-Alex Williamson-An Introduction to PCI Device Assignment with VFIO.pdf. File. : 01x04-Alex Williamson-An Introduction to PCI Device Assignment with VFIO.pdf. Size of this JPG preview of this PDF file: 800 × 450 pixels. Original file ‎ (2,666 × 1,500 pixels, file size: 12.93 MB, MIME type: application/pdf, 118 pages)

  15. VFIO

    This device is behind a PCIe-to-PCI bridge 4, therefore we also need to add device 0000:06:0d.1 to the group following the same procedure as above.Device 0000:00:1e.0 is a bridge that does not currently have a host driver, therefore it's not required to bind this device to the vfio-pci driver (vfio-pci does not currently support PCI bridges).

  16. Slides

    An Introduction to PCI Device Assignment with VFIO. By Alex Williamson. Qemu as a USB-MTP responder. By Bandan Das. CPU hotplug support in QEMU. By Bharata B Rao. ... Design of Vhost-pci. By Wei Wang. VMBus (Hyper-V) devices in QEMU/KVM.

  17. Platform Device Assignment to KVM-on-ARM Virtual Machines via VFIO

    VFIO (Virtual Function I/O) is a Linux kernel infrastructure that allows to leverage the capabilities of modern IOMMUs to drive a device directly from user space without any additional specialized kernel driver being involved. When used by QEMU/KVM, a device can be assigned to a guest VM, allowing to transparently handle all aspects of communication with the device, including DMA mapping, MMIO ...

  18. VFIO resource

    introduction [2016] An Introduction to PCI Device Assignment with VFIO [2012] VFIO: A User's Perspective (2012) LWN - Safe device assignment with VFIO. other intro [2016] IBM LTC China - VFIO introduction [2013] IBM LTC China - VFIO 簡介. More. Documentation/vfio.txt. vfio 内核实现分析 (1) ~ (7) Kernel Patches¶ (2012, linux-v3.6) 1st ...

  19. Virtual I/O Internals

    Figure 1: Binding devices to the vfio-pci driver results in VFIO group nodes. Opening the file "/dev/vfio/vfio" creates a VFIO Container. Figure 2: The interrupt routine IOCTL ... [2016] An Introduction to PCI Device Assignment with VFIO by Alex Williamson - slides [2017] Scalable I/O Virtualization by Kevin Tian

  20. GitHub

    An Introduction to PCI Device Assignment with VFIO; VFIO Device Assignment Quirks, How to use Them and How to Avoid Them; Martin Polednik - Red Hat Helping Users Maximize VM Performance; Neo Jia & Kirti Wankhede - NVIDIA vGPU on KVM - A VFIO Based Framework; Communities Reddit /r/vfio; Level1Techs; Red Hat vfio-users; KVM Forum

  21. An Introduction to PCI Device Assignment with VFIO by Alex ...

    This is a subreddit to discuss all things related to VFIO and gaming on virtual machines in general. Members Online • madnark. ADMIN MOD An Introduction to PCI Device Assignment with VFIO by Alex Williamson Resource Share Sort by: Best. Open comment sort options. Best. Top. New. Controversial. Old. Q&A. Add a Comment ...

  22. PDF VGA Assignment Using VFIO Alex Williamson

    11 Alex Williamson QEMU & VFIO QEMU creates guest mappings to each region PCI config region mapped to guest Bus/Slot/Func Some emulation in QEMU, some in VFIO BARs & ROM mapped to emulated BAR address in/out or read/write to BAR mapping results in read/write to VFIO device file descriptor mmap support for sufficiently sized MMIO BARs VFIO signals interrupts via eventfd

  23. An Introduction to PCI Device Assignment with VFIO by Alex ...

    An Introduction to PCI Device Assignment with VFIO by Alex Williamson #46. Open ... Open An Introduction to PCI Device Assignment with VFIO by Alex Williamson #46. nxnfufunezn opened this issue Sep 8, 2016 · 0 comments Labels. arch/virt long OS. Comments. Copy link Owner. nxnfufunezn commented Sep 8, 2016. Duration: 50 min