1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
6 * Derived from original vfio:
7 * Copyright 2010 Cisco Systems, Inc. All rights reserved.
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/device.h>
14 #include <linux/eventfd.h>
15 #include <linux/file.h>
16 #include <linux/interrupt.h>
17 #include <linux/iommu.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/notifier.h>
21 #include <linux/pci.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/uaccess.h>
26 #include <linux/vfio.h>
27 #include <linux/vgaarb.h>
28 #include <linux/nospec.h>
29 #include <linux/sched/mm.h>
31 #include "vfio_pci_private.h"
33 #define DRIVER_VERSION "0.2"
35 #define DRIVER_DESC "VFIO PCI - User Level meta-driver"
37 static char ids[1024] __initdata;
38 module_param_string(ids, ids, sizeof(ids), 0);
39 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");
41 static bool nointxmask;
42 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
43 MODULE_PARM_DESC(nointxmask,
44 "Disable support for PCI 2.3 style INTx masking. If this resolves problems for specific devices, report lspci -vvvxxx to
[email protected] so the device can be fixed automatically via the broken_intx_masking flag.");
46 #ifdef CONFIG_VFIO_PCI_VGA
47 static bool disable_vga;
48 module_param(disable_vga, bool, S_IRUGO);
49 MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
52 static bool disable_idle_d3;
53 module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
54 MODULE_PARM_DESC(disable_idle_d3,
55 "Disable using the PCI D3 low power state for idle, unused devices");
57 static bool enable_sriov;
59 module_param(enable_sriov, bool, 0644);
60 MODULE_PARM_DESC(enable_sriov, "Enable support for SR-IOV configuration. Enabling SR-IOV on a PF typically requires support of the userspace PF driver, enabling VFs without such support may result in non-functional VFs or PF.");
63 static inline bool vfio_vga_disabled(void)
65 #ifdef CONFIG_VFIO_PCI_VGA
73 * Our VGA arbiter participation is limited since we don't know anything
74 * about the device itself. However, if the device is the only VGA device
75 * downstream of a bridge and VFIO VGA support is disabled, then we can
76 * safely return legacy VGA IO and memory as not decoded since the user
77 * has no way to get to it and routing can be disabled externally at the
80 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
82 struct vfio_pci_device *vdev = opaque;
83 struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
84 unsigned char max_busnr;
87 if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
88 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
89 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
91 max_busnr = pci_bus_max_busnr(pdev->bus);
92 decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
94 while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
96 pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
97 pci_is_root_bus(tmp->bus))
100 if (tmp->bus->number >= pdev->bus->number &&
101 tmp->bus->number <= max_busnr) {
103 decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
111 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
113 return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
116 static void vfio_pci_probe_mmaps(struct vfio_pci_device *vdev)
118 struct resource *res;
120 struct vfio_pci_dummy_resource *dummy_res;
122 INIT_LIST_HEAD(&vdev->dummy_resources_list);
124 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
125 int bar = i + PCI_STD_RESOURCES;
127 res = &vdev->pdev->resource[bar];
129 if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
132 if (!(res->flags & IORESOURCE_MEM))
136 * The PCI core shouldn't set up a resource with a
137 * type but zero size. But there may be bugs that
138 * cause us to do that.
140 if (!resource_size(res))
143 if (resource_size(res) >= PAGE_SIZE) {
144 vdev->bar_mmap_supported[bar] = true;
148 if (!(res->start & ~PAGE_MASK)) {
150 * Add a dummy resource to reserve the remainder
151 * of the exclusive page in case that hot-add
152 * device's bar is assigned into it.
154 dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
155 if (dummy_res == NULL)
158 dummy_res->resource.name = "vfio sub-page reserved";
159 dummy_res->resource.start = res->end + 1;
160 dummy_res->resource.end = res->start + PAGE_SIZE - 1;
161 dummy_res->resource.flags = res->flags;
162 if (request_resource(res->parent,
163 &dummy_res->resource)) {
167 dummy_res->index = bar;
168 list_add(&dummy_res->res_next,
169 &vdev->dummy_resources_list);
170 vdev->bar_mmap_supported[bar] = true;
174 * Here we don't handle the case when the BAR is not page
175 * aligned because we can't expect the BAR will be
176 * assigned into the same location in a page in guest
177 * when we passthrough the BAR. And it's hard to access
178 * this BAR in userspace because we have no way to get
179 * the BAR's location in a page.
182 vdev->bar_mmap_supported[bar] = false;
186 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
187 static void vfio_pci_disable(struct vfio_pci_device *vdev);
188 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data);
191 * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
192 * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
193 * If a device implements the former but not the latter we would typically
194 * expect broken_intx_masking be set and require an exclusive interrupt.
195 * However since we do have control of the device's ability to assert INTx,
196 * we can instead pretend that the device does not implement INTx, virtualizing
197 * the pin register to report zero and maintaining DisINTx set on the host.
199 static bool vfio_pci_nointx(struct pci_dev *pdev)
201 switch (pdev->vendor) {
202 case PCI_VENDOR_ID_INTEL:
203 switch (pdev->device) {
204 /* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
207 case 0x1580 ... 0x1581:
208 case 0x1583 ... 0x158b:
209 case 0x37d0 ... 0x37d2:
219 static void vfio_pci_probe_power_state(struct vfio_pci_device *vdev)
221 struct pci_dev *pdev = vdev->pdev;
227 pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
229 vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
233 * pci_set_power_state() wrapper handling devices which perform a soft reset on
234 * D3->D0 transition. Save state prior to D0/1/2->D3, stash it on the vdev,
235 * restore when returned to D0. Saved separately from pci_saved_state for use
236 * by PM capability emulation and separately from pci_dev internal saved state
237 * to avoid it being overwritten and consumed around other resets.
239 int vfio_pci_set_power_state(struct vfio_pci_device *vdev, pci_power_t state)
241 struct pci_dev *pdev = vdev->pdev;
242 bool needs_restore = false, needs_save = false;
245 if (vdev->needs_pm_restore) {
246 if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
247 pci_save_state(pdev);
251 if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
252 needs_restore = true;
255 ret = pci_set_power_state(pdev, state);
258 /* D3 might be unsupported via quirk, skip unless in D3 */
259 if (needs_save && pdev->current_state >= PCI_D3hot) {
260 vdev->pm_save = pci_store_saved_state(pdev);
261 } else if (needs_restore) {
262 pci_load_and_free_saved_state(pdev, &vdev->pm_save);
263 pci_restore_state(pdev);
270 static int vfio_pci_enable(struct vfio_pci_device *vdev)
272 struct pci_dev *pdev = vdev->pdev;
277 vfio_pci_set_power_state(vdev, PCI_D0);
279 /* Don't allow our initial saved state to include busmaster */
280 pci_clear_master(pdev);
282 ret = pci_enable_device(pdev);
286 /* If reset fails because of the device lock, fail this path entirely */
287 ret = pci_try_reset_function(pdev);
288 if (ret == -EAGAIN) {
289 pci_disable_device(pdev);
293 vdev->reset_works = !ret;
294 pci_save_state(pdev);
295 vdev->pci_saved_state = pci_store_saved_state(pdev);
296 if (!vdev->pci_saved_state)
297 pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
299 if (likely(!nointxmask)) {
300 if (vfio_pci_nointx(pdev)) {
301 pci_info(pdev, "Masking broken INTx support\n");
305 vdev->pci_2_3 = pci_intx_mask_supported(pdev);
308 pci_read_config_word(pdev, PCI_COMMAND, &cmd);
309 if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
310 cmd &= ~PCI_COMMAND_INTX_DISABLE;
311 pci_write_config_word(pdev, PCI_COMMAND, cmd);
314 ret = vfio_config_init(vdev);
316 kfree(vdev->pci_saved_state);
317 vdev->pci_saved_state = NULL;
318 pci_disable_device(pdev);
322 msix_pos = pdev->msix_cap;
327 pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
328 pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
330 vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
331 vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
332 vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
334 vdev->msix_bar = 0xFF;
336 if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
337 vdev->has_vga = true;
340 if (vfio_pci_is_vga(pdev) &&
341 pdev->vendor == PCI_VENDOR_ID_INTEL &&
342 IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
343 ret = vfio_pci_igd_init(vdev);
345 pci_warn(pdev, "Failed to setup Intel IGD regions\n");
350 if (pdev->vendor == PCI_VENDOR_ID_NVIDIA &&
351 IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
352 ret = vfio_pci_nvdia_v100_nvlink2_init(vdev);
353 if (ret && ret != -ENODEV) {
354 pci_warn(pdev, "Failed to setup NVIDIA NV2 RAM region\n");
359 if (pdev->vendor == PCI_VENDOR_ID_IBM &&
360 IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
361 ret = vfio_pci_ibm_npu2_init(vdev);
362 if (ret && ret != -ENODEV) {
363 pci_warn(pdev, "Failed to setup NVIDIA NV2 ATSD region\n");
368 vfio_pci_probe_mmaps(vdev);
373 vfio_pci_disable(vdev);
377 static void vfio_pci_disable(struct vfio_pci_device *vdev)
379 struct pci_dev *pdev = vdev->pdev;
380 struct vfio_pci_dummy_resource *dummy_res, *tmp;
381 struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
384 /* Stop the device from further DMA */
385 pci_clear_master(pdev);
387 vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
388 VFIO_IRQ_SET_ACTION_TRIGGER,
389 vdev->irq_type, 0, 0, NULL);
391 /* Device closed, don't need mutex here */
392 list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
393 &vdev->ioeventfds_list, next) {
394 vfio_virqfd_disable(&ioeventfd->virqfd);
395 list_del(&ioeventfd->next);
398 vdev->ioeventfds_nr = 0;
400 vdev->virq_disabled = false;
402 for (i = 0; i < vdev->num_regions; i++)
403 vdev->region[i].ops->release(vdev, &vdev->region[i]);
405 vdev->num_regions = 0;
407 vdev->region = NULL; /* don't krealloc a freed pointer */
409 vfio_config_free(vdev);
411 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
412 bar = i + PCI_STD_RESOURCES;
413 if (!vdev->barmap[bar])
415 pci_iounmap(pdev, vdev->barmap[bar]);
416 pci_release_selected_regions(pdev, 1 << bar);
417 vdev->barmap[bar] = NULL;
420 list_for_each_entry_safe(dummy_res, tmp,
421 &vdev->dummy_resources_list, res_next) {
422 list_del(&dummy_res->res_next);
423 release_resource(&dummy_res->resource);
427 vdev->needs_reset = true;
430 * If we have saved state, restore it. If we can reset the device,
431 * even better. Resetting with current state seems better than
432 * nothing, but saving and restoring current state without reset
435 if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
436 pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
438 if (!vdev->reset_works)
441 pci_save_state(pdev);
445 * Disable INTx and MSI, presumably to avoid spurious interrupts
446 * during reset. Stolen from pci_reset_function()
448 pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
451 * Try to get the locks ourselves to prevent a deadlock. The
452 * success of this is dependent on being able to lock the device,
453 * which is not always possible.
454 * We can not use the "try" reset interface here, which will
455 * overwrite the previously restored configuration information.
457 if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
458 if (device_trylock(&pdev->dev)) {
459 if (!__pci_reset_function_locked(pdev))
460 vdev->needs_reset = false;
461 device_unlock(&pdev->dev);
463 pci_cfg_access_unlock(pdev);
466 pci_restore_state(pdev);
468 pci_disable_device(pdev);
470 vfio_pci_try_bus_reset(vdev);
472 if (!disable_idle_d3)
473 vfio_pci_set_power_state(vdev, PCI_D3hot);
476 static struct pci_driver vfio_pci_driver;
478 static struct vfio_pci_device *get_pf_vdev(struct vfio_pci_device *vdev,
479 struct vfio_device **pf_dev)
481 struct pci_dev *physfn = pci_physfn(vdev->pdev);
483 if (!vdev->pdev->is_virtfn)
486 *pf_dev = vfio_device_get_from_dev(&physfn->dev);
490 if (pci_dev_driver(physfn) != &vfio_pci_driver) {
491 vfio_device_put(*pf_dev);
495 return vfio_device_data(*pf_dev);
498 static void vfio_pci_vf_token_user_add(struct vfio_pci_device *vdev, int val)
500 struct vfio_device *pf_dev;
501 struct vfio_pci_device *pf_vdev = get_pf_vdev(vdev, &pf_dev);
506 mutex_lock(&pf_vdev->vf_token->lock);
507 pf_vdev->vf_token->users += val;
508 WARN_ON(pf_vdev->vf_token->users < 0);
509 mutex_unlock(&pf_vdev->vf_token->lock);
511 vfio_device_put(pf_dev);
514 static void vfio_pci_release(void *device_data)
516 struct vfio_pci_device *vdev = device_data;
518 mutex_lock(&vdev->reflck->lock);
520 if (!(--vdev->refcnt)) {
521 vfio_pci_vf_token_user_add(vdev, -1);
522 vfio_spapr_pci_eeh_release(vdev->pdev);
523 vfio_pci_disable(vdev);
524 if (vdev->err_trigger) {
525 eventfd_ctx_put(vdev->err_trigger);
526 vdev->err_trigger = NULL;
528 if (vdev->req_trigger) {
529 eventfd_ctx_put(vdev->req_trigger);
530 vdev->req_trigger = NULL;
534 mutex_unlock(&vdev->reflck->lock);
536 module_put(THIS_MODULE);
539 static int vfio_pci_open(void *device_data)
541 struct vfio_pci_device *vdev = device_data;
544 if (!try_module_get(THIS_MODULE))
547 mutex_lock(&vdev->reflck->lock);
550 ret = vfio_pci_enable(vdev);
554 vfio_spapr_pci_eeh_open(vdev->pdev);
555 vfio_pci_vf_token_user_add(vdev, 1);
559 mutex_unlock(&vdev->reflck->lock);
561 module_put(THIS_MODULE);
565 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
567 if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
570 if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
571 vdev->nointx || vdev->pdev->is_virtfn)
574 pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
577 } else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
581 pos = vdev->pdev->msi_cap;
583 pci_read_config_word(vdev->pdev,
584 pos + PCI_MSI_FLAGS, &flags);
585 return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
587 } else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
591 pos = vdev->pdev->msix_cap;
593 pci_read_config_word(vdev->pdev,
594 pos + PCI_MSIX_FLAGS, &flags);
596 return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
598 } else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
599 if (pci_is_pcie(vdev->pdev))
601 } else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
608 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
614 struct vfio_pci_fill_info {
617 struct vfio_pci_dependent_device *devices;
620 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
622 struct vfio_pci_fill_info *fill = data;
623 struct iommu_group *iommu_group;
625 if (fill->cur == fill->max)
626 return -EAGAIN; /* Something changed, try again */
628 iommu_group = iommu_group_get(&pdev->dev);
630 return -EPERM; /* Cannot reset non-isolated devices */
632 fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
633 fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
634 fill->devices[fill->cur].bus = pdev->bus->number;
635 fill->devices[fill->cur].devfn = pdev->devfn;
637 iommu_group_put(iommu_group);
641 struct vfio_pci_group_entry {
642 struct vfio_group *group;
646 struct vfio_pci_group_info {
648 struct vfio_pci_group_entry *groups;
651 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
653 struct vfio_pci_group_info *info = data;
654 struct iommu_group *group;
657 group = iommu_group_get(&pdev->dev);
661 id = iommu_group_id(group);
663 for (i = 0; i < info->count; i++)
664 if (info->groups[i].id == id)
667 iommu_group_put(group);
669 return (i == info->count) ? -EINVAL : 0;
672 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
674 for (; pdev; pdev = pdev->bus->self)
675 if (pdev->bus == slot->bus)
676 return (pdev->slot == slot);
680 struct vfio_pci_walk_info {
681 int (*fn)(struct pci_dev *, void *data);
683 struct pci_dev *pdev;
688 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
690 struct vfio_pci_walk_info *walk = data;
692 if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
693 walk->ret = walk->fn(pdev, walk->data);
698 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
699 int (*fn)(struct pci_dev *,
700 void *data), void *data,
703 struct vfio_pci_walk_info walk = {
704 .fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
707 pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
712 static int msix_mmappable_cap(struct vfio_pci_device *vdev,
713 struct vfio_info_cap *caps)
715 struct vfio_info_cap_header header = {
716 .id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
720 return vfio_info_add_capability(caps, &header, sizeof(header));
723 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
724 unsigned int type, unsigned int subtype,
725 const struct vfio_pci_regops *ops,
726 size_t size, u32 flags, void *data)
728 struct vfio_pci_region *region;
730 region = krealloc(vdev->region,
731 (vdev->num_regions + 1) * sizeof(*region),
736 vdev->region = region;
737 vdev->region[vdev->num_regions].type = type;
738 vdev->region[vdev->num_regions].subtype = subtype;
739 vdev->region[vdev->num_regions].ops = ops;
740 vdev->region[vdev->num_regions].size = size;
741 vdev->region[vdev->num_regions].flags = flags;
742 vdev->region[vdev->num_regions].data = data;
749 struct vfio_devices {
750 struct vfio_device **devices;
755 static long vfio_pci_ioctl(void *device_data,
756 unsigned int cmd, unsigned long arg)
758 struct vfio_pci_device *vdev = device_data;
761 if (cmd == VFIO_DEVICE_GET_INFO) {
762 struct vfio_device_info info;
764 minsz = offsetofend(struct vfio_device_info, num_irqs);
766 if (copy_from_user(&info, (void __user *)arg, minsz))
769 if (info.argsz < minsz)
772 info.flags = VFIO_DEVICE_FLAGS_PCI;
774 if (vdev->reset_works)
775 info.flags |= VFIO_DEVICE_FLAGS_RESET;
777 info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
778 info.num_irqs = VFIO_PCI_NUM_IRQS;
780 return copy_to_user((void __user *)arg, &info, minsz) ?
783 } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
784 struct pci_dev *pdev = vdev->pdev;
785 struct vfio_region_info info;
786 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
789 minsz = offsetofend(struct vfio_region_info, offset);
791 if (copy_from_user(&info, (void __user *)arg, minsz))
794 if (info.argsz < minsz)
797 switch (info.index) {
798 case VFIO_PCI_CONFIG_REGION_INDEX:
799 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
800 info.size = pdev->cfg_size;
801 info.flags = VFIO_REGION_INFO_FLAG_READ |
802 VFIO_REGION_INFO_FLAG_WRITE;
804 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
805 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
806 info.size = pci_resource_len(pdev, info.index);
812 info.flags = VFIO_REGION_INFO_FLAG_READ |
813 VFIO_REGION_INFO_FLAG_WRITE;
814 if (vdev->bar_mmap_supported[info.index]) {
815 info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
816 if (info.index == vdev->msix_bar) {
817 ret = msix_mmappable_cap(vdev, &caps);
824 case VFIO_PCI_ROM_REGION_INDEX:
830 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
833 /* Report the BAR size, not the ROM size */
834 info.size = pci_resource_len(pdev, info.index);
836 /* Shadow ROMs appear as PCI option ROMs */
837 if (pdev->resource[PCI_ROM_RESOURCE].flags &
838 IORESOURCE_ROM_SHADOW)
845 * Is it really there? Enable memory decode for
846 * implicit access in pci_map_rom().
848 cmd = vfio_pci_memory_lock_and_enable(vdev);
849 io = pci_map_rom(pdev, &size);
851 info.flags = VFIO_REGION_INFO_FLAG_READ;
852 pci_unmap_rom(pdev, io);
856 vfio_pci_memory_unlock_and_restore(vdev, cmd);
860 case VFIO_PCI_VGA_REGION_INDEX:
864 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
866 info.flags = VFIO_REGION_INFO_FLAG_READ |
867 VFIO_REGION_INFO_FLAG_WRITE;
872 struct vfio_region_info_cap_type cap_type = {
873 .header.id = VFIO_REGION_INFO_CAP_TYPE,
874 .header.version = 1 };
877 VFIO_PCI_NUM_REGIONS + vdev->num_regions)
879 info.index = array_index_nospec(info.index,
880 VFIO_PCI_NUM_REGIONS +
883 i = info.index - VFIO_PCI_NUM_REGIONS;
885 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
886 info.size = vdev->region[i].size;
887 info.flags = vdev->region[i].flags;
889 cap_type.type = vdev->region[i].type;
890 cap_type.subtype = vdev->region[i].subtype;
892 ret = vfio_info_add_capability(&caps, &cap_type.header,
897 if (vdev->region[i].ops->add_capability) {
898 ret = vdev->region[i].ops->add_capability(vdev,
899 &vdev->region[i], &caps);
907 info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
908 if (info.argsz < sizeof(info) + caps.size) {
909 info.argsz = sizeof(info) + caps.size;
912 vfio_info_cap_shift(&caps, sizeof(info));
913 if (copy_to_user((void __user *)arg +
914 sizeof(info), caps.buf,
919 info.cap_offset = sizeof(info);
925 return copy_to_user((void __user *)arg, &info, minsz) ?
928 } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
929 struct vfio_irq_info info;
931 minsz = offsetofend(struct vfio_irq_info, count);
933 if (copy_from_user(&info, (void __user *)arg, minsz))
936 if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
939 switch (info.index) {
940 case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
941 case VFIO_PCI_REQ_IRQ_INDEX:
943 case VFIO_PCI_ERR_IRQ_INDEX:
944 if (pci_is_pcie(vdev->pdev))
951 info.flags = VFIO_IRQ_INFO_EVENTFD;
953 info.count = vfio_pci_get_irq_count(vdev, info.index);
955 if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
956 info.flags |= (VFIO_IRQ_INFO_MASKABLE |
957 VFIO_IRQ_INFO_AUTOMASKED);
959 info.flags |= VFIO_IRQ_INFO_NORESIZE;
961 return copy_to_user((void __user *)arg, &info, minsz) ?
964 } else if (cmd == VFIO_DEVICE_SET_IRQS) {
965 struct vfio_irq_set hdr;
968 size_t data_size = 0;
970 minsz = offsetofend(struct vfio_irq_set, count);
972 if (copy_from_user(&hdr, (void __user *)arg, minsz))
975 max = vfio_pci_get_irq_count(vdev, hdr.index);
977 ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
978 VFIO_PCI_NUM_IRQS, &data_size);
983 data = memdup_user((void __user *)(arg + minsz),
986 return PTR_ERR(data);
989 mutex_lock(&vdev->igate);
991 ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
992 hdr.start, hdr.count, data);
994 mutex_unlock(&vdev->igate);
999 } else if (cmd == VFIO_DEVICE_RESET) {
1002 if (!vdev->reset_works)
1005 vfio_pci_zap_and_down_write_memory_lock(vdev);
1006 ret = pci_try_reset_function(vdev->pdev);
1007 up_write(&vdev->memory_lock);
1011 } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
1012 struct vfio_pci_hot_reset_info hdr;
1013 struct vfio_pci_fill_info fill = { 0 };
1014 struct vfio_pci_dependent_device *devices = NULL;
1018 minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
1020 if (copy_from_user(&hdr, (void __user *)arg, minsz))
1023 if (hdr.argsz < minsz)
1028 /* Can we do a slot or bus reset or neither? */
1029 if (!pci_probe_reset_slot(vdev->pdev->slot))
1031 else if (pci_probe_reset_bus(vdev->pdev->bus))
1034 /* How many devices are affected? */
1035 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1036 vfio_pci_count_devs,
1041 WARN_ON(!fill.max); /* Should always be at least one */
1044 * If there's enough space, fill it now, otherwise return
1045 * -ENOSPC and the number of devices affected.
1047 if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
1049 hdr.count = fill.max;
1050 goto reset_info_exit;
1053 devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
1057 fill.devices = devices;
1059 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1064 * If a device was removed between counting and filling,
1065 * we may come up short of fill.max. If a device was
1066 * added, we'll have a return of -EAGAIN above.
1069 hdr.count = fill.cur;
1072 if (copy_to_user((void __user *)arg, &hdr, minsz))
1076 if (copy_to_user((void __user *)(arg + minsz), devices,
1077 hdr.count * sizeof(*devices)))
1084 } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1085 struct vfio_pci_hot_reset hdr;
1087 struct vfio_pci_group_entry *groups;
1088 struct vfio_pci_group_info info;
1089 struct vfio_devices devs = { .cur_index = 0 };
1091 int i, group_idx, mem_idx = 0, count = 0, ret = 0;
1093 minsz = offsetofend(struct vfio_pci_hot_reset, count);
1095 if (copy_from_user(&hdr, (void __user *)arg, minsz))
1098 if (hdr.argsz < minsz || hdr.flags)
1101 /* Can we do a slot or bus reset or neither? */
1102 if (!pci_probe_reset_slot(vdev->pdev->slot))
1104 else if (pci_probe_reset_bus(vdev->pdev->bus))
1108 * We can't let userspace give us an arbitrarily large
1109 * buffer to copy, so verify how many we think there
1110 * could be. Note groups can have multiple devices so
1111 * one group per device is the max.
1113 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1114 vfio_pci_count_devs,
1119 /* Somewhere between 1 and count is OK */
1120 if (!hdr.count || hdr.count > count)
1123 group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1124 groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1125 if (!group_fds || !groups) {
1131 if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1132 hdr.count * sizeof(*group_fds))) {
1139 * For each group_fd, get the group through the vfio external
1140 * user interface and store the group and iommu ID. This
1141 * ensures the group is held across the reset.
1143 for (group_idx = 0; group_idx < hdr.count; group_idx++) {
1144 struct vfio_group *group;
1145 struct fd f = fdget(group_fds[group_idx]);
1151 group = vfio_group_get_external_user(f.file);
1153 if (IS_ERR(group)) {
1154 ret = PTR_ERR(group);
1158 groups[group_idx].group = group;
1159 groups[group_idx].id =
1160 vfio_external_user_iommu_id(group);
1165 /* release reference to groups on error */
1167 goto hot_reset_release;
1169 info.count = hdr.count;
1170 info.groups = groups;
1173 * Test whether all the affected devices are contained
1174 * by the set of groups provided by the user.
1176 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1177 vfio_pci_validate_devs,
1180 goto hot_reset_release;
1182 devs.max_index = count;
1183 devs.devices = kcalloc(count, sizeof(struct vfio_device *),
1185 if (!devs.devices) {
1187 goto hot_reset_release;
1191 * We need to get memory_lock for each device, but devices
1192 * can share mmap_lock, therefore we need to zap and hold
1193 * the vma_lock for each device, and only then get each
1196 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1197 vfio_pci_try_zap_and_vma_lock_cb,
1200 goto hot_reset_release;
1202 for (; mem_idx < devs.cur_index; mem_idx++) {
1203 struct vfio_pci_device *tmp;
1205 tmp = vfio_device_data(devs.devices[mem_idx]);
1207 ret = down_write_trylock(&tmp->memory_lock);
1210 goto hot_reset_release;
1212 mutex_unlock(&tmp->vma_lock);
1215 /* User has access, do the reset */
1216 ret = pci_reset_bus(vdev->pdev);
1219 for (i = 0; i < devs.cur_index; i++) {
1220 struct vfio_device *device;
1221 struct vfio_pci_device *tmp;
1223 device = devs.devices[i];
1224 tmp = vfio_device_data(device);
1227 up_write(&tmp->memory_lock);
1229 mutex_unlock(&tmp->vma_lock);
1230 vfio_device_put(device);
1232 kfree(devs.devices);
1234 for (group_idx--; group_idx >= 0; group_idx--)
1235 vfio_group_put_external_user(groups[group_idx].group);
1239 } else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1240 struct vfio_device_ioeventfd ioeventfd;
1243 minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1245 if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1248 if (ioeventfd.argsz < minsz)
1251 if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1254 count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1256 if (hweight8(count) != 1 || ioeventfd.fd < -1)
1259 return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1260 ioeventfd.data, count, ioeventfd.fd);
1261 } else if (cmd == VFIO_DEVICE_FEATURE) {
1262 struct vfio_device_feature feature;
1265 minsz = offsetofend(struct vfio_device_feature, flags);
1267 if (copy_from_user(&feature, (void __user *)arg, minsz))
1270 if (feature.argsz < minsz)
1273 /* Check unknown flags */
1274 if (feature.flags & ~(VFIO_DEVICE_FEATURE_MASK |
1275 VFIO_DEVICE_FEATURE_SET |
1276 VFIO_DEVICE_FEATURE_GET |
1277 VFIO_DEVICE_FEATURE_PROBE))
1280 /* GET & SET are mutually exclusive except with PROBE */
1281 if (!(feature.flags & VFIO_DEVICE_FEATURE_PROBE) &&
1282 (feature.flags & VFIO_DEVICE_FEATURE_SET) &&
1283 (feature.flags & VFIO_DEVICE_FEATURE_GET))
1286 switch (feature.flags & VFIO_DEVICE_FEATURE_MASK) {
1287 case VFIO_DEVICE_FEATURE_PCI_VF_TOKEN:
1288 if (!vdev->vf_token)
1292 * We do not support GET of the VF Token UUID as this
1293 * could expose the token of the previous device user.
1295 if (feature.flags & VFIO_DEVICE_FEATURE_GET)
1298 if (feature.flags & VFIO_DEVICE_FEATURE_PROBE)
1301 /* Don't SET unless told to do so */
1302 if (!(feature.flags & VFIO_DEVICE_FEATURE_SET))
1305 if (feature.argsz < minsz + sizeof(uuid))
1308 if (copy_from_user(&uuid, (void __user *)(arg + minsz),
1312 mutex_lock(&vdev->vf_token->lock);
1313 uuid_copy(&vdev->vf_token->uuid, &uuid);
1314 mutex_unlock(&vdev->vf_token->lock);
1325 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1326 size_t count, loff_t *ppos, bool iswrite)
1328 unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1329 struct vfio_pci_device *vdev = device_data;
1331 if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1335 case VFIO_PCI_CONFIG_REGION_INDEX:
1336 return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1338 case VFIO_PCI_ROM_REGION_INDEX:
1341 return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1343 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1344 return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1346 case VFIO_PCI_VGA_REGION_INDEX:
1347 return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1349 index -= VFIO_PCI_NUM_REGIONS;
1350 return vdev->region[index].ops->rw(vdev, buf,
1351 count, ppos, iswrite);
1357 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
1358 size_t count, loff_t *ppos)
1363 return vfio_pci_rw(device_data, buf, count, ppos, false);
1366 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1367 size_t count, loff_t *ppos)
1372 return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1375 /* Return 1 on zap and vma_lock acquired, 0 on contention (only with @try) */
1376 static int vfio_pci_zap_and_vma_lock(struct vfio_pci_device *vdev, bool try)
1378 struct vfio_pci_mmap_vma *mmap_vma, *tmp;
1382 * vma_lock is nested under mmap_lock for vm_ops callback paths.
1383 * The memory_lock semaphore is used by both code paths calling
1384 * into this function to zap vmas and the vm_ops.fault callback
1385 * to protect the memory enable state of the device.
1387 * When zapping vmas we need to maintain the mmap_lock => vma_lock
1388 * ordering, which requires using vma_lock to walk vma_list to
1389 * acquire an mm, then dropping vma_lock to get the mmap_lock and
1390 * reacquiring vma_lock. This logic is derived from similar
1391 * requirements in uverbs_user_mmap_disassociate().
1393 * mmap_lock must always be the top-level lock when it is taken.
1394 * Therefore we can only hold the memory_lock write lock when
1395 * vma_list is empty, as we'd need to take mmap_lock to clear
1396 * entries. vma_list can only be guaranteed empty when holding
1397 * vma_lock, thus memory_lock is nested under vma_lock.
1399 * This enables the vm_ops.fault callback to acquire vma_lock,
1400 * followed by memory_lock read lock, while already holding
1401 * mmap_lock without risk of deadlock.
1404 struct mm_struct *mm = NULL;
1407 if (!mutex_trylock(&vdev->vma_lock))
1410 mutex_lock(&vdev->vma_lock);
1412 while (!list_empty(&vdev->vma_list)) {
1413 mmap_vma = list_first_entry(&vdev->vma_list,
1414 struct vfio_pci_mmap_vma,
1416 mm = mmap_vma->vma->vm_mm;
1417 if (mmget_not_zero(mm))
1420 list_del(&mmap_vma->vma_next);
1426 mutex_unlock(&vdev->vma_lock);
1429 if (!mmap_read_trylock(mm)) {
1436 if (mmget_still_valid(mm)) {
1438 if (!mutex_trylock(&vdev->vma_lock)) {
1439 mmap_read_unlock(mm);
1444 mutex_lock(&vdev->vma_lock);
1446 list_for_each_entry_safe(mmap_vma, tmp,
1447 &vdev->vma_list, vma_next) {
1448 struct vm_area_struct *vma = mmap_vma->vma;
1450 if (vma->vm_mm != mm)
1453 list_del(&mmap_vma->vma_next);
1456 zap_vma_ptes(vma, vma->vm_start,
1457 vma->vm_end - vma->vm_start);
1459 mutex_unlock(&vdev->vma_lock);
1461 mmap_read_unlock(mm);
1466 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_device *vdev)
1468 vfio_pci_zap_and_vma_lock(vdev, false);
1469 down_write(&vdev->memory_lock);
1470 mutex_unlock(&vdev->vma_lock);
1473 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_device *vdev)
1477 down_write(&vdev->memory_lock);
1478 pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1479 if (!(cmd & PCI_COMMAND_MEMORY))
1480 pci_write_config_word(vdev->pdev, PCI_COMMAND,
1481 cmd | PCI_COMMAND_MEMORY);
1486 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_device *vdev, u16 cmd)
1488 pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1489 up_write(&vdev->memory_lock);
1492 /* Caller holds vma_lock */
1493 static int __vfio_pci_add_vma(struct vfio_pci_device *vdev,
1494 struct vm_area_struct *vma)
1496 struct vfio_pci_mmap_vma *mmap_vma;
1498 mmap_vma = kmalloc(sizeof(*mmap_vma), GFP_KERNEL);
1502 mmap_vma->vma = vma;
1503 list_add(&mmap_vma->vma_next, &vdev->vma_list);
1509 * Zap mmaps on open so that we can fault them in on access and therefore
1510 * our vma_list only tracks mappings accessed since last zap.
1512 static void vfio_pci_mmap_open(struct vm_area_struct *vma)
1514 zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1517 static void vfio_pci_mmap_close(struct vm_area_struct *vma)
1519 struct vfio_pci_device *vdev = vma->vm_private_data;
1520 struct vfio_pci_mmap_vma *mmap_vma;
1522 mutex_lock(&vdev->vma_lock);
1523 list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1524 if (mmap_vma->vma == vma) {
1525 list_del(&mmap_vma->vma_next);
1530 mutex_unlock(&vdev->vma_lock);
1533 static vm_fault_t vfio_pci_mmap_fault(struct vm_fault *vmf)
1535 struct vm_area_struct *vma = vmf->vma;
1536 struct vfio_pci_device *vdev = vma->vm_private_data;
1537 vm_fault_t ret = VM_FAULT_NOPAGE;
1539 mutex_lock(&vdev->vma_lock);
1540 down_read(&vdev->memory_lock);
1542 if (!__vfio_pci_memory_enabled(vdev)) {
1543 ret = VM_FAULT_SIGBUS;
1544 mutex_unlock(&vdev->vma_lock);
1548 if (__vfio_pci_add_vma(vdev, vma)) {
1550 mutex_unlock(&vdev->vma_lock);
1554 mutex_unlock(&vdev->vma_lock);
1556 if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1557 vma->vm_end - vma->vm_start, vma->vm_page_prot))
1558 ret = VM_FAULT_SIGBUS;
1561 up_read(&vdev->memory_lock);
1565 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1566 .open = vfio_pci_mmap_open,
1567 .close = vfio_pci_mmap_close,
1568 .fault = vfio_pci_mmap_fault,
1571 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1573 struct vfio_pci_device *vdev = device_data;
1574 struct pci_dev *pdev = vdev->pdev;
1576 u64 phys_len, req_len, pgoff, req_start;
1579 index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1581 if (vma->vm_end < vma->vm_start)
1583 if ((vma->vm_flags & VM_SHARED) == 0)
1585 if (index >= VFIO_PCI_NUM_REGIONS) {
1586 int regnum = index - VFIO_PCI_NUM_REGIONS;
1587 struct vfio_pci_region *region = vdev->region + regnum;
1589 if (region && region->ops && region->ops->mmap &&
1590 (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1591 return region->ops->mmap(vdev, region, vma);
1594 if (index >= VFIO_PCI_ROM_REGION_INDEX)
1596 if (!vdev->bar_mmap_supported[index])
1599 phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1600 req_len = vma->vm_end - vma->vm_start;
1601 pgoff = vma->vm_pgoff &
1602 ((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1603 req_start = pgoff << PAGE_SHIFT;
1605 if (req_start + req_len > phys_len)
1609 * Even though we don't make use of the barmap for the mmap,
1610 * we need to request the region and the barmap tracks that.
1612 if (!vdev->barmap[index]) {
1613 ret = pci_request_selected_regions(pdev,
1614 1 << index, "vfio-pci");
1618 vdev->barmap[index] = pci_iomap(pdev, index, 0);
1619 if (!vdev->barmap[index]) {
1620 pci_release_selected_regions(pdev, 1 << index);
1625 vma->vm_private_data = vdev;
1626 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1627 vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1630 * See remap_pfn_range(), called from vfio_pci_fault() but we can't
1631 * change vm_flags within the fault handler. Set them now.
1633 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1634 vma->vm_ops = &vfio_pci_mmap_ops;
1639 static void vfio_pci_request(void *device_data, unsigned int count)
1641 struct vfio_pci_device *vdev = device_data;
1642 struct pci_dev *pdev = vdev->pdev;
1644 mutex_lock(&vdev->igate);
1646 if (vdev->req_trigger) {
1648 pci_notice_ratelimited(pdev,
1649 "Relaying device request to user (#%u)\n",
1651 eventfd_signal(vdev->req_trigger, 1);
1652 } else if (count == 0) {
1654 "No device request channel registered, blocked until released by user\n");
1657 mutex_unlock(&vdev->igate);
1660 static int vfio_pci_validate_vf_token(struct vfio_pci_device *vdev,
1661 bool vf_token, uuid_t *uuid)
1664 * There's always some degree of trust or collaboration between SR-IOV
1665 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1666 * can disrupt VFs with a reset, but often the PF has more explicit
1667 * access to deny service to the VF or access data passed through the
1668 * VF. We therefore require an opt-in via a shared VF token (UUID) to
1669 * represent this trust. This both prevents that a VF driver might
1670 * assume the PF driver is a trusted, in-kernel driver, and also that
1671 * a PF driver might be replaced with a rogue driver, unknown to in-use
1674 * Therefore when presented with a VF, if the PF is a vfio device and
1675 * it is bound to the vfio-pci driver, the user needs to provide a VF
1676 * token to access the device, in the form of appending a vf_token to
1677 * the device name, for example:
1679 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1681 * When presented with a PF which has VFs in use, the user must also
1682 * provide the current VF token to prove collaboration with existing
1683 * VF users. If VFs are not in use, the VF token provided for the PF
1684 * device will act to set the VF token.
1686 * If the VF token is provided but unused, an error is generated.
1688 if (!vdev->pdev->is_virtfn && !vdev->vf_token && !vf_token)
1689 return 0; /* No VF token provided or required */
1691 if (vdev->pdev->is_virtfn) {
1692 struct vfio_device *pf_dev;
1693 struct vfio_pci_device *pf_vdev = get_pf_vdev(vdev, &pf_dev);
1698 return 0; /* PF is not vfio-pci, no VF token */
1700 pci_info_ratelimited(vdev->pdev,
1701 "VF token incorrectly provided, PF not bound to vfio-pci\n");
1706 vfio_device_put(pf_dev);
1707 pci_info_ratelimited(vdev->pdev,
1708 "VF token required to access device\n");
1712 mutex_lock(&pf_vdev->vf_token->lock);
1713 match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1714 mutex_unlock(&pf_vdev->vf_token->lock);
1716 vfio_device_put(pf_dev);
1719 pci_info_ratelimited(vdev->pdev,
1720 "Incorrect VF token provided for device\n");
1723 } else if (vdev->vf_token) {
1724 mutex_lock(&vdev->vf_token->lock);
1725 if (vdev->vf_token->users) {
1727 mutex_unlock(&vdev->vf_token->lock);
1728 pci_info_ratelimited(vdev->pdev,
1729 "VF token required to access device\n");
1733 if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1734 mutex_unlock(&vdev->vf_token->lock);
1735 pci_info_ratelimited(vdev->pdev,
1736 "Incorrect VF token provided for device\n");
1739 } else if (vf_token) {
1740 uuid_copy(&vdev->vf_token->uuid, uuid);
1743 mutex_unlock(&vdev->vf_token->lock);
1744 } else if (vf_token) {
1745 pci_info_ratelimited(vdev->pdev,
1746 "VF token incorrectly provided, not a PF or VF\n");
1753 #define VF_TOKEN_ARG "vf_token="
1755 static int vfio_pci_match(void *device_data, char *buf)
1757 struct vfio_pci_device *vdev = device_data;
1758 bool vf_token = false;
1762 if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1763 return 0; /* No match */
1765 if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1766 buf += strlen(pci_name(vdev->pdev));
1769 return 0; /* No match: non-whitespace after name */
1777 if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1778 strlen(VF_TOKEN_ARG))) {
1779 buf += strlen(VF_TOKEN_ARG);
1781 if (strlen(buf) < UUID_STRING_LEN)
1784 ret = uuid_parse(buf, &uuid);
1789 buf += UUID_STRING_LEN;
1791 /* Unknown/duplicate option */
1797 ret = vfio_pci_validate_vf_token(vdev, vf_token, &uuid);
1801 return 1; /* Match */
1804 static const struct vfio_device_ops vfio_pci_ops = {
1806 .open = vfio_pci_open,
1807 .release = vfio_pci_release,
1808 .ioctl = vfio_pci_ioctl,
1809 .read = vfio_pci_read,
1810 .write = vfio_pci_write,
1811 .mmap = vfio_pci_mmap,
1812 .request = vfio_pci_request,
1813 .match = vfio_pci_match,
1816 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev);
1817 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck);
1818 static struct pci_driver vfio_pci_driver;
1820 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1821 unsigned long action, void *data)
1823 struct vfio_pci_device *vdev = container_of(nb,
1824 struct vfio_pci_device, nb);
1825 struct device *dev = data;
1826 struct pci_dev *pdev = to_pci_dev(dev);
1827 struct pci_dev *physfn = pci_physfn(pdev);
1829 if (action == BUS_NOTIFY_ADD_DEVICE &&
1830 pdev->is_virtfn && physfn == vdev->pdev) {
1831 pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1833 pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1835 } else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1836 pdev->is_virtfn && physfn == vdev->pdev) {
1837 struct pci_driver *drv = pci_dev_driver(pdev);
1839 if (drv && drv != &vfio_pci_driver)
1840 pci_warn(vdev->pdev,
1841 "VF %s bound to driver %s while PF bound to vfio-pci\n",
1842 pci_name(pdev), drv->name);
1848 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1850 struct vfio_pci_device *vdev;
1851 struct iommu_group *group;
1854 if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1858 * Prevent binding to PFs with VFs enabled, the VFs might be in use
1859 * by the host or other users. We cannot capture the VFs if they
1860 * already exist, nor can we track VF users. Disabling SR-IOV here
1861 * would initiate removing the VFs, which would unbind the driver,
1862 * which is prone to blocking if that VF is also in use by vfio-pci.
1863 * Just reject these PFs and let the user sort it out.
1865 if (pci_num_vf(pdev)) {
1866 pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1870 group = vfio_iommu_group_get(&pdev->dev);
1874 vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1881 vdev->irq_type = VFIO_PCI_NUM_IRQS;
1882 mutex_init(&vdev->igate);
1883 spin_lock_init(&vdev->irqlock);
1884 mutex_init(&vdev->ioeventfds_lock);
1885 INIT_LIST_HEAD(&vdev->ioeventfds_list);
1886 mutex_init(&vdev->vma_lock);
1887 INIT_LIST_HEAD(&vdev->vma_list);
1888 init_rwsem(&vdev->memory_lock);
1890 ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1894 ret = vfio_pci_reflck_attach(vdev);
1896 goto out_del_group_dev;
1898 if (pdev->is_physfn) {
1899 vdev->vf_token = kzalloc(sizeof(*vdev->vf_token), GFP_KERNEL);
1900 if (!vdev->vf_token) {
1905 mutex_init(&vdev->vf_token->lock);
1906 uuid_gen(&vdev->vf_token->uuid);
1908 vdev->nb.notifier_call = vfio_pci_bus_notifier;
1909 ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
1914 if (vfio_pci_is_vga(pdev)) {
1915 vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1916 vga_set_legacy_decoding(pdev,
1917 vfio_pci_set_vga_decode(vdev, false));
1920 vfio_pci_probe_power_state(vdev);
1922 if (!disable_idle_d3) {
1924 * pci-core sets the device power state to an unknown value at
1925 * bootup and after being removed from a driver. The only
1926 * transition it allows from this unknown state is to D0, which
1927 * typically happens when a driver calls pci_enable_device().
1928 * We're not ready to enable the device yet, but we do want to
1929 * be able to get to D3. Therefore first do a D0 transition
1930 * before going to D3.
1932 vfio_pci_set_power_state(vdev, PCI_D0);
1933 vfio_pci_set_power_state(vdev, PCI_D3hot);
1939 kfree(vdev->vf_token);
1941 vfio_pci_reflck_put(vdev->reflck);
1943 vfio_del_group_dev(&pdev->dev);
1947 vfio_iommu_group_put(group, &pdev->dev);
1951 static void vfio_pci_remove(struct pci_dev *pdev)
1953 struct vfio_pci_device *vdev;
1955 pci_disable_sriov(pdev);
1957 vdev = vfio_del_group_dev(&pdev->dev);
1961 if (vdev->vf_token) {
1962 WARN_ON(vdev->vf_token->users);
1963 mutex_destroy(&vdev->vf_token->lock);
1964 kfree(vdev->vf_token);
1967 if (vdev->nb.notifier_call)
1968 bus_unregister_notifier(&pci_bus_type, &vdev->nb);
1970 vfio_pci_reflck_put(vdev->reflck);
1972 vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1973 kfree(vdev->region);
1974 mutex_destroy(&vdev->ioeventfds_lock);
1976 if (!disable_idle_d3)
1977 vfio_pci_set_power_state(vdev, PCI_D0);
1979 kfree(vdev->pm_save);
1982 if (vfio_pci_is_vga(pdev)) {
1983 vga_client_register(pdev, NULL, NULL, NULL);
1984 vga_set_legacy_decoding(pdev,
1985 VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1986 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1990 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1991 pci_channel_state_t state)
1993 struct vfio_pci_device *vdev;
1994 struct vfio_device *device;
1996 device = vfio_device_get_from_dev(&pdev->dev);
1998 return PCI_ERS_RESULT_DISCONNECT;
2000 vdev = vfio_device_data(device);
2002 vfio_device_put(device);
2003 return PCI_ERS_RESULT_DISCONNECT;
2006 mutex_lock(&vdev->igate);
2008 if (vdev->err_trigger)
2009 eventfd_signal(vdev->err_trigger, 1);
2011 mutex_unlock(&vdev->igate);
2013 vfio_device_put(device);
2015 return PCI_ERS_RESULT_CAN_RECOVER;
2018 static int vfio_pci_sriov_configure(struct pci_dev *pdev, int nr_virtfn)
2020 struct vfio_pci_device *vdev;
2021 struct vfio_device *device;
2029 device = vfio_device_get_from_dev(&pdev->dev);
2033 vdev = vfio_device_data(device);
2035 vfio_device_put(device);
2040 pci_disable_sriov(pdev);
2042 ret = pci_enable_sriov(pdev, nr_virtfn);
2044 vfio_device_put(device);
2046 return ret < 0 ? ret : nr_virtfn;
2049 static const struct pci_error_handlers vfio_err_handlers = {
2050 .error_detected = vfio_pci_aer_err_detected,
2053 static struct pci_driver vfio_pci_driver = {
2055 .id_table = NULL, /* only dynamic ids */
2056 .probe = vfio_pci_probe,
2057 .remove = vfio_pci_remove,
2058 .sriov_configure = vfio_pci_sriov_configure,
2059 .err_handler = &vfio_err_handlers,
2062 static DEFINE_MUTEX(reflck_lock);
2064 static struct vfio_pci_reflck *vfio_pci_reflck_alloc(void)
2066 struct vfio_pci_reflck *reflck;
2068 reflck = kzalloc(sizeof(*reflck), GFP_KERNEL);
2070 return ERR_PTR(-ENOMEM);
2072 kref_init(&reflck->kref);
2073 mutex_init(&reflck->lock);
2078 static void vfio_pci_reflck_get(struct vfio_pci_reflck *reflck)
2080 kref_get(&reflck->kref);
2083 static int vfio_pci_reflck_find(struct pci_dev *pdev, void *data)
2085 struct vfio_pci_reflck **preflck = data;
2086 struct vfio_device *device;
2087 struct vfio_pci_device *vdev;
2089 device = vfio_device_get_from_dev(&pdev->dev);
2093 if (pci_dev_driver(pdev) != &vfio_pci_driver) {
2094 vfio_device_put(device);
2098 vdev = vfio_device_data(device);
2101 vfio_pci_reflck_get(vdev->reflck);
2102 *preflck = vdev->reflck;
2103 vfio_device_put(device);
2107 vfio_device_put(device);
2111 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev)
2113 bool slot = !pci_probe_reset_slot(vdev->pdev->slot);
2115 mutex_lock(&reflck_lock);
2117 if (pci_is_root_bus(vdev->pdev->bus) ||
2118 vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_reflck_find,
2119 &vdev->reflck, slot) <= 0)
2120 vdev->reflck = vfio_pci_reflck_alloc();
2122 mutex_unlock(&reflck_lock);
2124 return PTR_ERR_OR_ZERO(vdev->reflck);
2127 static void vfio_pci_reflck_release(struct kref *kref)
2129 struct vfio_pci_reflck *reflck = container_of(kref,
2130 struct vfio_pci_reflck,
2134 mutex_unlock(&reflck_lock);
2137 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck)
2139 kref_put_mutex(&reflck->kref, vfio_pci_reflck_release, &reflck_lock);
2142 static int vfio_pci_get_unused_devs(struct pci_dev *pdev, void *data)
2144 struct vfio_devices *devs = data;
2145 struct vfio_device *device;
2146 struct vfio_pci_device *vdev;
2148 if (devs->cur_index == devs->max_index)
2151 device = vfio_device_get_from_dev(&pdev->dev);
2155 if (pci_dev_driver(pdev) != &vfio_pci_driver) {
2156 vfio_device_put(device);
2160 vdev = vfio_device_data(device);
2162 /* Fault if the device is not unused */
2164 vfio_device_put(device);
2168 devs->devices[devs->cur_index++] = device;
2172 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data)
2174 struct vfio_devices *devs = data;
2175 struct vfio_device *device;
2176 struct vfio_pci_device *vdev;
2178 if (devs->cur_index == devs->max_index)
2181 device = vfio_device_get_from_dev(&pdev->dev);
2185 if (pci_dev_driver(pdev) != &vfio_pci_driver) {
2186 vfio_device_put(device);
2190 vdev = vfio_device_data(device);
2193 * Locking multiple devices is prone to deadlock, runaway and
2194 * unwind if we hit contention.
2196 if (!vfio_pci_zap_and_vma_lock(vdev, true)) {
2197 vfio_device_put(device);
2201 devs->devices[devs->cur_index++] = device;
2206 * If a bus or slot reset is available for the provided device and:
2207 * - All of the devices affected by that bus or slot reset are unused
2209 * - At least one of the affected devices is marked dirty via
2210 * needs_reset (such as by lack of FLR support)
2211 * Then attempt to perform that bus or slot reset. Callers are required
2212 * to hold vdev->reflck->lock, protecting the bus/slot reset group from
2213 * concurrent opens. A vfio_device reference is acquired for each device
2214 * to prevent unbinds during the reset operation.
2216 * NB: vfio-core considers a group to be viable even if some devices are
2217 * bound to drivers like pci-stub or pcieport. Here we require all devices
2218 * to be bound to vfio_pci since that's the only way we can be sure they
2221 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
2223 struct vfio_devices devs = { .cur_index = 0 };
2224 int i = 0, ret = -EINVAL;
2226 struct vfio_pci_device *tmp;
2228 if (!pci_probe_reset_slot(vdev->pdev->slot))
2230 else if (pci_probe_reset_bus(vdev->pdev->bus))
2233 if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
2238 devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
2242 if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
2243 vfio_pci_get_unused_devs,
2247 /* Does at least one need a reset? */
2248 for (i = 0; i < devs.cur_index; i++) {
2249 tmp = vfio_device_data(devs.devices[i]);
2250 if (tmp->needs_reset) {
2251 ret = pci_reset_bus(vdev->pdev);
2257 for (i = 0; i < devs.cur_index; i++) {
2258 tmp = vfio_device_data(devs.devices[i]);
2261 * If reset was successful, affected devices no longer need
2262 * a reset and we should return all the collateral devices
2263 * to low power. If not successful, we either didn't reset
2264 * the bus or timed out waiting for it, so let's not touch
2268 tmp->needs_reset = false;
2270 if (tmp != vdev && !disable_idle_d3)
2271 vfio_pci_set_power_state(tmp, PCI_D3hot);
2274 vfio_device_put(devs.devices[i]);
2277 kfree(devs.devices);
2280 static void __exit vfio_pci_cleanup(void)
2282 pci_unregister_driver(&vfio_pci_driver);
2283 vfio_pci_uninit_perm_bits();
2286 static void __init vfio_pci_fill_ids(void)
2291 /* no ids passed actually */
2295 /* add ids specified in the module parameter */
2297 while ((id = strsep(&p, ","))) {
2298 unsigned int vendor, device, subvendor = PCI_ANY_ID,
2299 subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
2305 fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
2306 &vendor, &device, &subvendor, &subdevice,
2307 &class, &class_mask);
2310 pr_warn("invalid id string \"%s\"\n", id);
2314 rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
2315 subvendor, subdevice, class, class_mask, 0);
2317 pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
2318 vendor, device, subvendor, subdevice,
2319 class, class_mask, rc);
2321 pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
2322 vendor, device, subvendor, subdevice,
2327 static int __init vfio_pci_init(void)
2331 /* Allocate shared config space permision data used by all devices */
2332 ret = vfio_pci_init_perm_bits();
2336 /* Register and scan for devices */
2337 ret = pci_register_driver(&vfio_pci_driver);
2341 vfio_pci_fill_ids();
2346 vfio_pci_uninit_perm_bits();
2350 module_init(vfio_pci_init);
2351 module_exit(vfio_pci_cleanup);
2353 MODULE_VERSION(DRIVER_VERSION);
2354 MODULE_LICENSE("GPL v2");
2355 MODULE_AUTHOR(DRIVER_AUTHOR);
2356 MODULE_DESCRIPTION(DRIVER_DESC);