2 * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
3 * Author: Alex Williamson <alex.williamson@redhat.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * Derived from original vfio:
10 * Copyright 2010 Cisco Systems, Inc. All rights reserved.
11 * Author: Tom Lyon, pugs@cisco.com
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/device.h>
17 #include <linux/eventfd.h>
18 #include <linux/file.h>
19 #include <linux/interrupt.h>
20 #include <linux/iommu.h>
21 #include <linux/module.h>
22 #include <linux/mutex.h>
23 #include <linux/notifier.h>
24 #include <linux/pci.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/slab.h>
27 #include <linux/types.h>
28 #include <linux/uaccess.h>
29 #include <linux/vfio.h>
30 #include <linux/vgaarb.h>
31 #include <linux/nospec.h>
33 #include "vfio_pci_private.h"
35 #define DRIVER_VERSION "0.2"
36 #define DRIVER_AUTHOR "Alex Williamson <alex.williamson@redhat.com>"
37 #define DRIVER_DESC "VFIO PCI - User Level meta-driver"
39 static char ids[1024] __initdata;
40 module_param_string(ids, ids, sizeof(ids), 0);
41 MODULE_PARM_DESC(ids, "Initial PCI IDs to add to the vfio driver, format is \"vendor:device[:subvendor[:subdevice[:class[:class_mask]]]]\" and multiple comma separated entries can be specified");
43 static bool nointxmask;
44 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
45 MODULE_PARM_DESC(nointxmask,
46 "Disable support for PCI 2.3 style INTx masking. If this resolves problems for specific devices, report lspci -vvvxxx to linux-pci@vger.kernel.org so the device can be fixed automatically via the broken_intx_masking flag.");
48 #ifdef CONFIG_VFIO_PCI_VGA
49 static bool disable_vga;
50 module_param(disable_vga, bool, S_IRUGO);
51 MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
54 static bool disable_idle_d3;
55 module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
56 MODULE_PARM_DESC(disable_idle_d3,
57 "Disable using the PCI D3 low power state for idle, unused devices");
59 static inline bool vfio_vga_disabled(void)
61 #ifdef CONFIG_VFIO_PCI_VGA
69 * Our VGA arbiter participation is limited since we don't know anything
70 * about the device itself. However, if the device is the only VGA device
71 * downstream of a bridge and VFIO VGA support is disabled, then we can
72 * safely return legacy VGA IO and memory as not decoded since the user
73 * has no way to get to it and routing can be disabled externally at the
76 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
78 struct vfio_pci_device *vdev = opaque;
79 struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
80 unsigned char max_busnr;
83 if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
84 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
85 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
87 max_busnr = pci_bus_max_busnr(pdev->bus);
88 decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
90 while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
92 pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
93 pci_is_root_bus(tmp->bus))
96 if (tmp->bus->number >= pdev->bus->number &&
97 tmp->bus->number <= max_busnr) {
99 decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
107 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
109 return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
112 static void vfio_pci_probe_mmaps(struct vfio_pci_device *vdev)
114 struct resource *res;
116 struct vfio_pci_dummy_resource *dummy_res;
118 INIT_LIST_HEAD(&vdev->dummy_resources_list);
120 for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
121 res = vdev->pdev->resource + bar;
123 if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
126 if (!(res->flags & IORESOURCE_MEM))
130 * The PCI core shouldn't set up a resource with a
131 * type but zero size. But there may be bugs that
132 * cause us to do that.
134 if (!resource_size(res))
137 if (resource_size(res) >= PAGE_SIZE) {
138 vdev->bar_mmap_supported[bar] = true;
142 if (!(res->start & ~PAGE_MASK)) {
144 * Add a dummy resource to reserve the remainder
145 * of the exclusive page in case that hot-add
146 * device's bar is assigned into it.
148 dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
149 if (dummy_res == NULL)
152 dummy_res->resource.name = "vfio sub-page reserved";
153 dummy_res->resource.start = res->end + 1;
154 dummy_res->resource.end = res->start + PAGE_SIZE - 1;
155 dummy_res->resource.flags = res->flags;
156 if (request_resource(res->parent,
157 &dummy_res->resource)) {
161 dummy_res->index = bar;
162 list_add(&dummy_res->res_next,
163 &vdev->dummy_resources_list);
164 vdev->bar_mmap_supported[bar] = true;
168 * Here we don't handle the case when the BAR is not page
169 * aligned because we can't expect the BAR will be
170 * assigned into the same location in a page in guest
171 * when we passthrough the BAR. And it's hard to access
172 * this BAR in userspace because we have no way to get
173 * the BAR's location in a page.
176 vdev->bar_mmap_supported[bar] = false;
180 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
181 static void vfio_pci_disable(struct vfio_pci_device *vdev);
184 * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
185 * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
186 * If a device implements the former but not the latter we would typically
187 * expect broken_intx_masking be set and require an exclusive interrupt.
188 * However since we do have control of the device's ability to assert INTx,
189 * we can instead pretend that the device does not implement INTx, virtualizing
190 * the pin register to report zero and maintaining DisINTx set on the host.
192 static bool vfio_pci_nointx(struct pci_dev *pdev)
194 switch (pdev->vendor) {
195 case PCI_VENDOR_ID_INTEL:
196 switch (pdev->device) {
197 /* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
200 case 0x1580 ... 0x1581:
201 case 0x1583 ... 0x158b:
202 case 0x37d0 ... 0x37d2:
212 static int vfio_pci_enable(struct vfio_pci_device *vdev)
214 struct pci_dev *pdev = vdev->pdev;
219 pci_set_power_state(pdev, PCI_D0);
221 /* Don't allow our initial saved state to include busmaster */
222 pci_clear_master(pdev);
224 ret = pci_enable_device(pdev);
228 /* If reset fails because of the device lock, fail this path entirely */
229 ret = pci_try_reset_function(pdev);
230 if (ret == -EAGAIN) {
231 pci_disable_device(pdev);
235 vdev->reset_works = !ret;
236 pci_save_state(pdev);
237 vdev->pci_saved_state = pci_store_saved_state(pdev);
238 if (!vdev->pci_saved_state)
239 pr_debug("%s: Couldn't store %s saved state\n",
240 __func__, dev_name(&pdev->dev));
242 if (likely(!nointxmask)) {
243 if (vfio_pci_nointx(pdev)) {
244 dev_info(&pdev->dev, "Masking broken INTx support\n");
248 vdev->pci_2_3 = pci_intx_mask_supported(pdev);
251 pci_read_config_word(pdev, PCI_COMMAND, &cmd);
252 if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
253 cmd &= ~PCI_COMMAND_INTX_DISABLE;
254 pci_write_config_word(pdev, PCI_COMMAND, cmd);
257 ret = vfio_config_init(vdev);
259 kfree(vdev->pci_saved_state);
260 vdev->pci_saved_state = NULL;
261 pci_disable_device(pdev);
265 msix_pos = pdev->msix_cap;
270 pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
271 pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
273 vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
274 vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
275 vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
277 vdev->msix_bar = 0xFF;
279 if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
280 vdev->has_vga = true;
283 if (vfio_pci_is_vga(pdev) &&
284 pdev->vendor == PCI_VENDOR_ID_INTEL &&
285 IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
286 ret = vfio_pci_igd_init(vdev);
288 dev_warn(&vdev->pdev->dev,
289 "Failed to setup Intel IGD regions\n");
294 if (pdev->vendor == PCI_VENDOR_ID_NVIDIA &&
295 IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
296 ret = vfio_pci_nvdia_v100_nvlink2_init(vdev);
297 if (ret && ret != -ENODEV) {
298 dev_warn(&vdev->pdev->dev,
299 "Failed to setup NVIDIA NV2 RAM region\n");
304 if (pdev->vendor == PCI_VENDOR_ID_IBM &&
305 IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
306 ret = vfio_pci_ibm_npu2_init(vdev);
307 if (ret && ret != -ENODEV) {
308 dev_warn(&vdev->pdev->dev,
309 "Failed to setup NVIDIA NV2 ATSD region\n");
314 vfio_pci_probe_mmaps(vdev);
319 vfio_pci_disable(vdev);
323 static void vfio_pci_disable(struct vfio_pci_device *vdev)
325 struct pci_dev *pdev = vdev->pdev;
326 struct vfio_pci_dummy_resource *dummy_res, *tmp;
327 struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
330 /* Stop the device from further DMA */
331 pci_clear_master(pdev);
333 vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
334 VFIO_IRQ_SET_ACTION_TRIGGER,
335 vdev->irq_type, 0, 0, NULL);
337 /* Device closed, don't need mutex here */
338 list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
339 &vdev->ioeventfds_list, next) {
340 vfio_virqfd_disable(&ioeventfd->virqfd);
341 list_del(&ioeventfd->next);
344 vdev->ioeventfds_nr = 0;
346 vdev->virq_disabled = false;
348 for (i = 0; i < vdev->num_regions; i++)
349 vdev->region[i].ops->release(vdev, &vdev->region[i]);
351 vdev->num_regions = 0;
353 vdev->region = NULL; /* don't krealloc a freed pointer */
355 vfio_config_free(vdev);
357 for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
358 if (!vdev->barmap[bar])
360 pci_iounmap(pdev, vdev->barmap[bar]);
361 pci_release_selected_regions(pdev, 1 << bar);
362 vdev->barmap[bar] = NULL;
365 list_for_each_entry_safe(dummy_res, tmp,
366 &vdev->dummy_resources_list, res_next) {
367 list_del(&dummy_res->res_next);
368 release_resource(&dummy_res->resource);
372 vdev->needs_reset = true;
375 * If we have saved state, restore it. If we can reset the device,
376 * even better. Resetting with current state seems better than
377 * nothing, but saving and restoring current state without reset
380 if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
381 pr_info("%s: Couldn't reload %s saved state\n",
382 __func__, dev_name(&pdev->dev));
384 if (!vdev->reset_works)
387 pci_save_state(pdev);
391 * Disable INTx and MSI, presumably to avoid spurious interrupts
392 * during reset. Stolen from pci_reset_function()
394 pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
397 * Try to reset the device. The success of this is dependent on
398 * being able to lock the device, which is not always possible.
400 if (vdev->reset_works && !pci_try_reset_function(pdev))
401 vdev->needs_reset = false;
403 pci_restore_state(pdev);
405 pci_disable_device(pdev);
407 vfio_pci_try_bus_reset(vdev);
409 if (!disable_idle_d3)
410 pci_set_power_state(pdev, PCI_D3hot);
413 static void vfio_pci_release(void *device_data)
415 struct vfio_pci_device *vdev = device_data;
417 mutex_lock(&vdev->reflck->lock);
419 if (!(--vdev->refcnt)) {
420 vfio_spapr_pci_eeh_release(vdev->pdev);
421 vfio_pci_disable(vdev);
424 mutex_unlock(&vdev->reflck->lock);
426 module_put(THIS_MODULE);
429 static int vfio_pci_open(void *device_data)
431 struct vfio_pci_device *vdev = device_data;
434 if (!try_module_get(THIS_MODULE))
437 mutex_lock(&vdev->reflck->lock);
440 ret = vfio_pci_enable(vdev);
444 vfio_spapr_pci_eeh_open(vdev->pdev);
448 mutex_unlock(&vdev->reflck->lock);
450 module_put(THIS_MODULE);
454 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
456 if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
459 if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
460 vdev->nointx || vdev->pdev->is_virtfn)
463 pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
466 } else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
470 pos = vdev->pdev->msi_cap;
472 pci_read_config_word(vdev->pdev,
473 pos + PCI_MSI_FLAGS, &flags);
474 return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
476 } else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
480 pos = vdev->pdev->msix_cap;
482 pci_read_config_word(vdev->pdev,
483 pos + PCI_MSIX_FLAGS, &flags);
485 return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
487 } else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
488 if (pci_is_pcie(vdev->pdev))
490 } else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
497 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
503 struct vfio_pci_fill_info {
506 struct vfio_pci_dependent_device *devices;
509 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
511 struct vfio_pci_fill_info *fill = data;
512 struct iommu_group *iommu_group;
514 if (fill->cur == fill->max)
515 return -EAGAIN; /* Something changed, try again */
517 iommu_group = iommu_group_get(&pdev->dev);
519 return -EPERM; /* Cannot reset non-isolated devices */
521 fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
522 fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
523 fill->devices[fill->cur].bus = pdev->bus->number;
524 fill->devices[fill->cur].devfn = pdev->devfn;
526 iommu_group_put(iommu_group);
530 struct vfio_pci_group_entry {
531 struct vfio_group *group;
535 struct vfio_pci_group_info {
537 struct vfio_pci_group_entry *groups;
540 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
542 struct vfio_pci_group_info *info = data;
543 struct iommu_group *group;
546 group = iommu_group_get(&pdev->dev);
550 id = iommu_group_id(group);
552 for (i = 0; i < info->count; i++)
553 if (info->groups[i].id == id)
556 iommu_group_put(group);
558 return (i == info->count) ? -EINVAL : 0;
561 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
563 for (; pdev; pdev = pdev->bus->self)
564 if (pdev->bus == slot->bus)
565 return (pdev->slot == slot);
569 struct vfio_pci_walk_info {
570 int (*fn)(struct pci_dev *, void *data);
572 struct pci_dev *pdev;
577 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
579 struct vfio_pci_walk_info *walk = data;
581 if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
582 walk->ret = walk->fn(pdev, walk->data);
587 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
588 int (*fn)(struct pci_dev *,
589 void *data), void *data,
592 struct vfio_pci_walk_info walk = {
593 .fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
596 pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
601 static int msix_mmappable_cap(struct vfio_pci_device *vdev,
602 struct vfio_info_cap *caps)
604 struct vfio_info_cap_header header = {
605 .id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
609 return vfio_info_add_capability(caps, &header, sizeof(header));
612 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
613 unsigned int type, unsigned int subtype,
614 const struct vfio_pci_regops *ops,
615 size_t size, u32 flags, void *data)
617 struct vfio_pci_region *region;
619 region = krealloc(vdev->region,
620 (vdev->num_regions + 1) * sizeof(*region),
625 vdev->region = region;
626 vdev->region[vdev->num_regions].type = type;
627 vdev->region[vdev->num_regions].subtype = subtype;
628 vdev->region[vdev->num_regions].ops = ops;
629 vdev->region[vdev->num_regions].size = size;
630 vdev->region[vdev->num_regions].flags = flags;
631 vdev->region[vdev->num_regions].data = data;
638 static long vfio_pci_ioctl(void *device_data,
639 unsigned int cmd, unsigned long arg)
641 struct vfio_pci_device *vdev = device_data;
644 if (cmd == VFIO_DEVICE_GET_INFO) {
645 struct vfio_device_info info;
647 minsz = offsetofend(struct vfio_device_info, num_irqs);
649 if (copy_from_user(&info, (void __user *)arg, minsz))
652 if (info.argsz < minsz)
655 info.flags = VFIO_DEVICE_FLAGS_PCI;
657 if (vdev->reset_works)
658 info.flags |= VFIO_DEVICE_FLAGS_RESET;
660 info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
661 info.num_irqs = VFIO_PCI_NUM_IRQS;
663 return copy_to_user((void __user *)arg, &info, minsz) ?
666 } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
667 struct pci_dev *pdev = vdev->pdev;
668 struct vfio_region_info info;
669 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
672 minsz = offsetofend(struct vfio_region_info, offset);
674 if (copy_from_user(&info, (void __user *)arg, minsz))
677 if (info.argsz < minsz)
680 switch (info.index) {
681 case VFIO_PCI_CONFIG_REGION_INDEX:
682 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
683 info.size = pdev->cfg_size;
684 info.flags = VFIO_REGION_INFO_FLAG_READ |
685 VFIO_REGION_INFO_FLAG_WRITE;
687 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
688 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
689 info.size = pci_resource_len(pdev, info.index);
695 info.flags = VFIO_REGION_INFO_FLAG_READ |
696 VFIO_REGION_INFO_FLAG_WRITE;
697 if (vdev->bar_mmap_supported[info.index]) {
698 info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
699 if (info.index == vdev->msix_bar) {
700 ret = msix_mmappable_cap(vdev, &caps);
707 case VFIO_PCI_ROM_REGION_INDEX:
712 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
715 /* Report the BAR size, not the ROM size */
716 info.size = pci_resource_len(pdev, info.index);
718 /* Shadow ROMs appear as PCI option ROMs */
719 if (pdev->resource[PCI_ROM_RESOURCE].flags &
720 IORESOURCE_ROM_SHADOW)
726 /* Is it really there? */
727 io = pci_map_rom(pdev, &size);
732 pci_unmap_rom(pdev, io);
734 info.flags = VFIO_REGION_INFO_FLAG_READ;
737 case VFIO_PCI_VGA_REGION_INDEX:
741 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
743 info.flags = VFIO_REGION_INFO_FLAG_READ |
744 VFIO_REGION_INFO_FLAG_WRITE;
749 struct vfio_region_info_cap_type cap_type = {
750 .header.id = VFIO_REGION_INFO_CAP_TYPE,
751 .header.version = 1 };
754 VFIO_PCI_NUM_REGIONS + vdev->num_regions)
756 info.index = array_index_nospec(info.index,
757 VFIO_PCI_NUM_REGIONS +
760 i = info.index - VFIO_PCI_NUM_REGIONS;
762 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
763 info.size = vdev->region[i].size;
764 info.flags = vdev->region[i].flags;
766 cap_type.type = vdev->region[i].type;
767 cap_type.subtype = vdev->region[i].subtype;
769 ret = vfio_info_add_capability(&caps, &cap_type.header,
774 if (vdev->region[i].ops->add_capability) {
775 ret = vdev->region[i].ops->add_capability(vdev,
776 &vdev->region[i], &caps);
784 info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
785 if (info.argsz < sizeof(info) + caps.size) {
786 info.argsz = sizeof(info) + caps.size;
789 vfio_info_cap_shift(&caps, sizeof(info));
790 if (copy_to_user((void __user *)arg +
791 sizeof(info), caps.buf,
796 info.cap_offset = sizeof(info);
802 return copy_to_user((void __user *)arg, &info, minsz) ?
805 } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
806 struct vfio_irq_info info;
808 minsz = offsetofend(struct vfio_irq_info, count);
810 if (copy_from_user(&info, (void __user *)arg, minsz))
813 if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
816 switch (info.index) {
817 case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
818 case VFIO_PCI_REQ_IRQ_INDEX:
820 case VFIO_PCI_ERR_IRQ_INDEX:
821 if (pci_is_pcie(vdev->pdev))
828 info.flags = VFIO_IRQ_INFO_EVENTFD;
830 info.count = vfio_pci_get_irq_count(vdev, info.index);
832 if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
833 info.flags |= (VFIO_IRQ_INFO_MASKABLE |
834 VFIO_IRQ_INFO_AUTOMASKED);
836 info.flags |= VFIO_IRQ_INFO_NORESIZE;
838 return copy_to_user((void __user *)arg, &info, minsz) ?
841 } else if (cmd == VFIO_DEVICE_SET_IRQS) {
842 struct vfio_irq_set hdr;
845 size_t data_size = 0;
847 minsz = offsetofend(struct vfio_irq_set, count);
849 if (copy_from_user(&hdr, (void __user *)arg, minsz))
852 max = vfio_pci_get_irq_count(vdev, hdr.index);
854 ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
855 VFIO_PCI_NUM_IRQS, &data_size);
860 data = memdup_user((void __user *)(arg + minsz),
863 return PTR_ERR(data);
866 mutex_lock(&vdev->igate);
868 ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
869 hdr.start, hdr.count, data);
871 mutex_unlock(&vdev->igate);
876 } else if (cmd == VFIO_DEVICE_RESET) {
877 return vdev->reset_works ?
878 pci_try_reset_function(vdev->pdev) : -EINVAL;
880 } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
881 struct vfio_pci_hot_reset_info hdr;
882 struct vfio_pci_fill_info fill = { 0 };
883 struct vfio_pci_dependent_device *devices = NULL;
887 minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
889 if (copy_from_user(&hdr, (void __user *)arg, minsz))
892 if (hdr.argsz < minsz)
897 /* Can we do a slot or bus reset or neither? */
898 if (!pci_probe_reset_slot(vdev->pdev->slot))
900 else if (pci_probe_reset_bus(vdev->pdev->bus))
903 /* How many devices are affected? */
904 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
910 WARN_ON(!fill.max); /* Should always be at least one */
913 * If there's enough space, fill it now, otherwise return
914 * -ENOSPC and the number of devices affected.
916 if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
918 hdr.count = fill.max;
919 goto reset_info_exit;
922 devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
926 fill.devices = devices;
928 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
933 * If a device was removed between counting and filling,
934 * we may come up short of fill.max. If a device was
935 * added, we'll have a return of -EAGAIN above.
938 hdr.count = fill.cur;
941 if (copy_to_user((void __user *)arg, &hdr, minsz))
945 if (copy_to_user((void __user *)(arg + minsz), devices,
946 hdr.count * sizeof(*devices)))
953 } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
954 struct vfio_pci_hot_reset hdr;
956 struct vfio_pci_group_entry *groups;
957 struct vfio_pci_group_info info;
959 int i, count = 0, ret = 0;
961 minsz = offsetofend(struct vfio_pci_hot_reset, count);
963 if (copy_from_user(&hdr, (void __user *)arg, minsz))
966 if (hdr.argsz < minsz || hdr.flags)
969 /* Can we do a slot or bus reset or neither? */
970 if (!pci_probe_reset_slot(vdev->pdev->slot))
972 else if (pci_probe_reset_bus(vdev->pdev->bus))
976 * We can't let userspace give us an arbitrarily large
977 * buffer to copy, so verify how many we think there
978 * could be. Note groups can have multiple devices so
979 * one group per device is the max.
981 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
987 /* Somewhere between 1 and count is OK */
988 if (!hdr.count || hdr.count > count)
991 group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
992 groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
993 if (!group_fds || !groups) {
999 if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1000 hdr.count * sizeof(*group_fds))) {
1007 * For each group_fd, get the group through the vfio external
1008 * user interface and store the group and iommu ID. This
1009 * ensures the group is held across the reset.
1011 for (i = 0; i < hdr.count; i++) {
1012 struct vfio_group *group;
1013 struct fd f = fdget(group_fds[i]);
1019 group = vfio_group_get_external_user(f.file);
1021 if (IS_ERR(group)) {
1022 ret = PTR_ERR(group);
1026 groups[i].group = group;
1027 groups[i].id = vfio_external_user_iommu_id(group);
1032 /* release reference to groups on error */
1034 goto hot_reset_release;
1036 info.count = hdr.count;
1037 info.groups = groups;
1040 * Test whether all the affected devices are contained
1041 * by the set of groups provided by the user.
1043 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1044 vfio_pci_validate_devs,
1047 /* User has access, do the reset */
1048 ret = pci_reset_bus(vdev->pdev);
1051 for (i--; i >= 0; i--)
1052 vfio_group_put_external_user(groups[i].group);
1056 } else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1057 struct vfio_device_ioeventfd ioeventfd;
1060 minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1062 if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1065 if (ioeventfd.argsz < minsz)
1068 if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1071 count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1073 if (hweight8(count) != 1 || ioeventfd.fd < -1)
1076 return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1077 ioeventfd.data, count, ioeventfd.fd);
1083 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1084 size_t count, loff_t *ppos, bool iswrite)
1086 unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1087 struct vfio_pci_device *vdev = device_data;
1089 if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1093 case VFIO_PCI_CONFIG_REGION_INDEX:
1094 return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1096 case VFIO_PCI_ROM_REGION_INDEX:
1099 return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1101 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1102 return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1104 case VFIO_PCI_VGA_REGION_INDEX:
1105 return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1107 index -= VFIO_PCI_NUM_REGIONS;
1108 return vdev->region[index].ops->rw(vdev, buf,
1109 count, ppos, iswrite);
1115 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
1116 size_t count, loff_t *ppos)
1121 return vfio_pci_rw(device_data, buf, count, ppos, false);
1124 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1125 size_t count, loff_t *ppos)
1130 return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1133 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1135 struct vfio_pci_device *vdev = device_data;
1136 struct pci_dev *pdev = vdev->pdev;
1138 u64 phys_len, req_len, pgoff, req_start;
1141 index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1143 if (vma->vm_end < vma->vm_start)
1145 if ((vma->vm_flags & VM_SHARED) == 0)
1147 if (index >= VFIO_PCI_NUM_REGIONS) {
1148 int regnum = index - VFIO_PCI_NUM_REGIONS;
1149 struct vfio_pci_region *region = vdev->region + regnum;
1151 if (region && region->ops && region->ops->mmap &&
1152 (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1153 return region->ops->mmap(vdev, region, vma);
1156 if (index >= VFIO_PCI_ROM_REGION_INDEX)
1158 if (!vdev->bar_mmap_supported[index])
1161 phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1162 req_len = vma->vm_end - vma->vm_start;
1163 pgoff = vma->vm_pgoff &
1164 ((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1165 req_start = pgoff << PAGE_SHIFT;
1167 if (req_start + req_len > phys_len)
1171 * Even though we don't make use of the barmap for the mmap,
1172 * we need to request the region and the barmap tracks that.
1174 if (!vdev->barmap[index]) {
1175 ret = pci_request_selected_regions(pdev,
1176 1 << index, "vfio-pci");
1180 vdev->barmap[index] = pci_iomap(pdev, index, 0);
1181 if (!vdev->barmap[index]) {
1182 pci_release_selected_regions(pdev, 1 << index);
1187 vma->vm_private_data = vdev;
1188 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1189 vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1191 return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1192 req_len, vma->vm_page_prot);
1195 static void vfio_pci_request(void *device_data, unsigned int count)
1197 struct vfio_pci_device *vdev = device_data;
1199 mutex_lock(&vdev->igate);
1201 if (vdev->req_trigger) {
1203 dev_notice_ratelimited(&vdev->pdev->dev,
1204 "Relaying device request to user (#%u)\n",
1206 eventfd_signal(vdev->req_trigger, 1);
1207 } else if (count == 0) {
1208 dev_warn(&vdev->pdev->dev,
1209 "No device request channel registered, blocked until released by user\n");
1212 mutex_unlock(&vdev->igate);
1215 static const struct vfio_device_ops vfio_pci_ops = {
1217 .open = vfio_pci_open,
1218 .release = vfio_pci_release,
1219 .ioctl = vfio_pci_ioctl,
1220 .read = vfio_pci_read,
1221 .write = vfio_pci_write,
1222 .mmap = vfio_pci_mmap,
1223 .request = vfio_pci_request,
1226 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev);
1227 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck);
1229 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1231 struct vfio_pci_device *vdev;
1232 struct iommu_group *group;
1235 if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1239 * Prevent binding to PFs with VFs enabled, this too easily allows
1240 * userspace instance with VFs and PFs from the same device, which
1241 * cannot work. Disabling SR-IOV here would initiate removing the
1242 * VFs, which would unbind the driver, which is prone to blocking
1243 * if that VF is also in use by vfio-pci. Just reject these PFs
1244 * and let the user sort it out.
1246 if (pci_num_vf(pdev)) {
1247 pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1251 group = vfio_iommu_group_get(&pdev->dev);
1255 vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1257 vfio_iommu_group_put(group, &pdev->dev);
1262 vdev->irq_type = VFIO_PCI_NUM_IRQS;
1263 mutex_init(&vdev->igate);
1264 spin_lock_init(&vdev->irqlock);
1265 mutex_init(&vdev->ioeventfds_lock);
1266 INIT_LIST_HEAD(&vdev->ioeventfds_list);
1268 ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1270 vfio_iommu_group_put(group, &pdev->dev);
1275 ret = vfio_pci_reflck_attach(vdev);
1277 vfio_del_group_dev(&pdev->dev);
1278 vfio_iommu_group_put(group, &pdev->dev);
1283 if (vfio_pci_is_vga(pdev)) {
1284 vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1285 vga_set_legacy_decoding(pdev,
1286 vfio_pci_set_vga_decode(vdev, false));
1289 if (!disable_idle_d3) {
1291 * pci-core sets the device power state to an unknown value at
1292 * bootup and after being removed from a driver. The only
1293 * transition it allows from this unknown state is to D0, which
1294 * typically happens when a driver calls pci_enable_device().
1295 * We're not ready to enable the device yet, but we do want to
1296 * be able to get to D3. Therefore first do a D0 transition
1297 * before going to D3.
1299 pci_set_power_state(pdev, PCI_D0);
1300 pci_set_power_state(pdev, PCI_D3hot);
1306 static void vfio_pci_remove(struct pci_dev *pdev)
1308 struct vfio_pci_device *vdev;
1310 vdev = vfio_del_group_dev(&pdev->dev);
1314 vfio_pci_reflck_put(vdev->reflck);
1316 vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1317 kfree(vdev->region);
1318 mutex_destroy(&vdev->ioeventfds_lock);
1321 if (vfio_pci_is_vga(pdev)) {
1322 vga_client_register(pdev, NULL, NULL, NULL);
1323 vga_set_legacy_decoding(pdev,
1324 VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1325 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1328 if (!disable_idle_d3)
1329 pci_set_power_state(pdev, PCI_D0);
1332 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1333 pci_channel_state_t state)
1335 struct vfio_pci_device *vdev;
1336 struct vfio_device *device;
1338 device = vfio_device_get_from_dev(&pdev->dev);
1340 return PCI_ERS_RESULT_DISCONNECT;
1342 vdev = vfio_device_data(device);
1344 vfio_device_put(device);
1345 return PCI_ERS_RESULT_DISCONNECT;
1348 mutex_lock(&vdev->igate);
1350 if (vdev->err_trigger)
1351 eventfd_signal(vdev->err_trigger, 1);
1353 mutex_unlock(&vdev->igate);
1355 vfio_device_put(device);
1357 return PCI_ERS_RESULT_CAN_RECOVER;
1360 static const struct pci_error_handlers vfio_err_handlers = {
1361 .error_detected = vfio_pci_aer_err_detected,
1364 static struct pci_driver vfio_pci_driver = {
1366 .id_table = NULL, /* only dynamic ids */
1367 .probe = vfio_pci_probe,
1368 .remove = vfio_pci_remove,
1369 .err_handler = &vfio_err_handlers,
1372 static DEFINE_MUTEX(reflck_lock);
1374 static struct vfio_pci_reflck *vfio_pci_reflck_alloc(void)
1376 struct vfio_pci_reflck *reflck;
1378 reflck = kzalloc(sizeof(*reflck), GFP_KERNEL);
1380 return ERR_PTR(-ENOMEM);
1382 kref_init(&reflck->kref);
1383 mutex_init(&reflck->lock);
1388 static void vfio_pci_reflck_get(struct vfio_pci_reflck *reflck)
1390 kref_get(&reflck->kref);
1393 static int vfio_pci_reflck_find(struct pci_dev *pdev, void *data)
1395 struct vfio_pci_reflck **preflck = data;
1396 struct vfio_device *device;
1397 struct vfio_pci_device *vdev;
1399 device = vfio_device_get_from_dev(&pdev->dev);
1403 if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1404 vfio_device_put(device);
1408 vdev = vfio_device_data(device);
1411 vfio_pci_reflck_get(vdev->reflck);
1412 *preflck = vdev->reflck;
1413 vfio_device_put(device);
1417 vfio_device_put(device);
1421 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev)
1423 bool slot = !pci_probe_reset_slot(vdev->pdev->slot);
1425 mutex_lock(&reflck_lock);
1427 if (pci_is_root_bus(vdev->pdev->bus) ||
1428 vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_reflck_find,
1429 &vdev->reflck, slot) <= 0)
1430 vdev->reflck = vfio_pci_reflck_alloc();
1432 mutex_unlock(&reflck_lock);
1434 return PTR_ERR_OR_ZERO(vdev->reflck);
1437 static void vfio_pci_reflck_release(struct kref *kref)
1439 struct vfio_pci_reflck *reflck = container_of(kref,
1440 struct vfio_pci_reflck,
1444 mutex_unlock(&reflck_lock);
1447 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck)
1449 kref_put_mutex(&reflck->kref, vfio_pci_reflck_release, &reflck_lock);
1452 struct vfio_devices {
1453 struct vfio_device **devices;
1458 static int vfio_pci_get_unused_devs(struct pci_dev *pdev, void *data)
1460 struct vfio_devices *devs = data;
1461 struct vfio_device *device;
1462 struct vfio_pci_device *vdev;
1464 if (devs->cur_index == devs->max_index)
1467 device = vfio_device_get_from_dev(&pdev->dev);
1471 if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1472 vfio_device_put(device);
1476 vdev = vfio_device_data(device);
1478 /* Fault if the device is not unused */
1480 vfio_device_put(device);
1484 devs->devices[devs->cur_index++] = device;
1489 * If a bus or slot reset is available for the provided device and:
1490 * - All of the devices affected by that bus or slot reset are unused
1492 * - At least one of the affected devices is marked dirty via
1493 * needs_reset (such as by lack of FLR support)
1494 * Then attempt to perform that bus or slot reset. Callers are required
1495 * to hold vdev->reflck->lock, protecting the bus/slot reset group from
1496 * concurrent opens. A vfio_device reference is acquired for each device
1497 * to prevent unbinds during the reset operation.
1499 * NB: vfio-core considers a group to be viable even if some devices are
1500 * bound to drivers like pci-stub or pcieport. Here we require all devices
1501 * to be bound to vfio_pci since that's the only way we can be sure they
1504 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1506 struct vfio_devices devs = { .cur_index = 0 };
1507 int i = 0, ret = -EINVAL;
1509 struct vfio_pci_device *tmp;
1511 if (!pci_probe_reset_slot(vdev->pdev->slot))
1513 else if (pci_probe_reset_bus(vdev->pdev->bus))
1516 if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1521 devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1525 if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1526 vfio_pci_get_unused_devs,
1530 /* Does at least one need a reset? */
1531 for (i = 0; i < devs.cur_index; i++) {
1532 tmp = vfio_device_data(devs.devices[i]);
1533 if (tmp->needs_reset) {
1534 ret = pci_reset_bus(vdev->pdev);
1540 for (i = 0; i < devs.cur_index; i++) {
1541 tmp = vfio_device_data(devs.devices[i]);
1544 * If reset was successful, affected devices no longer need
1545 * a reset and we should return all the collateral devices
1546 * to low power. If not successful, we either didn't reset
1547 * the bus or timed out waiting for it, so let's not touch
1551 tmp->needs_reset = false;
1553 if (tmp != vdev && !disable_idle_d3)
1554 pci_set_power_state(tmp->pdev, PCI_D3hot);
1557 vfio_device_put(devs.devices[i]);
1560 kfree(devs.devices);
1563 static void __exit vfio_pci_cleanup(void)
1565 pci_unregister_driver(&vfio_pci_driver);
1566 vfio_pci_uninit_perm_bits();
1569 static void __init vfio_pci_fill_ids(void)
1574 /* no ids passed actually */
1578 /* add ids specified in the module parameter */
1580 while ((id = strsep(&p, ","))) {
1581 unsigned int vendor, device, subvendor = PCI_ANY_ID,
1582 subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1588 fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1589 &vendor, &device, &subvendor, &subdevice,
1590 &class, &class_mask);
1593 pr_warn("invalid id string \"%s\"\n", id);
1597 rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1598 subvendor, subdevice, class, class_mask, 0);
1600 pr_warn("failed to add dynamic id [%04hx:%04hx[%04hx:%04hx]] class %#08x/%08x (%d)\n",
1601 vendor, device, subvendor, subdevice,
1602 class, class_mask, rc);
1604 pr_info("add [%04hx:%04hx[%04hx:%04hx]] class %#08x/%08x\n",
1605 vendor, device, subvendor, subdevice,
1610 static int __init vfio_pci_init(void)
1614 /* Allocate shared config space permision data used by all devices */
1615 ret = vfio_pci_init_perm_bits();
1619 /* Register and scan for devices */
1620 ret = pci_register_driver(&vfio_pci_driver);
1624 vfio_pci_fill_ids();
1629 vfio_pci_uninit_perm_bits();
1633 module_init(vfio_pci_init);
1634 module_exit(vfio_pci_cleanup);
1636 MODULE_VERSION(DRIVER_VERSION);
1637 MODULE_LICENSE("GPL v2");
1638 MODULE_AUTHOR(DRIVER_AUTHOR);
1639 MODULE_DESCRIPTION(DRIVER_DESC);