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/aperture.h>
14 #include <linux/device.h>
15 #include <linux/eventfd.h>
16 #include <linux/file.h>
17 #include <linux/interrupt.h>
18 #include <linux/iommu.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/notifier.h>
22 #include <linux/pci.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/slab.h>
25 #include <linux/types.h>
26 #include <linux/uaccess.h>
27 #include <linux/vgaarb.h>
28 #include <linux/nospec.h>
29 #include <linux/sched/mm.h>
31 #include <linux/vfio_pci_core.h>
34 #define DRIVER_DESC "core driver for VFIO based PCI devices"
36 static bool nointxmask;
37 static bool disable_vga;
38 static bool disable_idle_d3;
40 /* List of PF's that vfio_pci_core_sriov_configure() has been called on */
41 static DEFINE_MUTEX(vfio_pci_sriov_pfs_mutex);
42 static LIST_HEAD(vfio_pci_sriov_pfs);
44 static inline bool vfio_vga_disabled(void)
46 #ifdef CONFIG_VFIO_PCI_VGA
54 * Our VGA arbiter participation is limited since we don't know anything
55 * about the device itself. However, if the device is the only VGA device
56 * downstream of a bridge and VFIO VGA support is disabled, then we can
57 * safely return legacy VGA IO and memory as not decoded since the user
58 * has no way to get to it and routing can be disabled externally at the
61 static unsigned int vfio_pci_set_decode(struct pci_dev *pdev, bool single_vga)
63 struct pci_dev *tmp = NULL;
64 unsigned char max_busnr;
67 if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
68 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
69 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
71 max_busnr = pci_bus_max_busnr(pdev->bus);
72 decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
74 while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
76 pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
77 pci_is_root_bus(tmp->bus))
80 if (tmp->bus->number >= pdev->bus->number &&
81 tmp->bus->number <= max_busnr) {
83 decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
91 static void vfio_pci_probe_mmaps(struct vfio_pci_core_device *vdev)
95 struct vfio_pci_dummy_resource *dummy_res;
97 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
98 int bar = i + PCI_STD_RESOURCES;
100 res = &vdev->pdev->resource[bar];
102 if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
105 if (!(res->flags & IORESOURCE_MEM))
109 * The PCI core shouldn't set up a resource with a
110 * type but zero size. But there may be bugs that
111 * cause us to do that.
113 if (!resource_size(res))
116 if (resource_size(res) >= PAGE_SIZE) {
117 vdev->bar_mmap_supported[bar] = true;
121 if (!(res->start & ~PAGE_MASK)) {
123 * Add a dummy resource to reserve the remainder
124 * of the exclusive page in case that hot-add
125 * device's bar is assigned into it.
127 dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
128 if (dummy_res == NULL)
131 dummy_res->resource.name = "vfio sub-page reserved";
132 dummy_res->resource.start = res->end + 1;
133 dummy_res->resource.end = res->start + PAGE_SIZE - 1;
134 dummy_res->resource.flags = res->flags;
135 if (request_resource(res->parent,
136 &dummy_res->resource)) {
140 dummy_res->index = bar;
141 list_add(&dummy_res->res_next,
142 &vdev->dummy_resources_list);
143 vdev->bar_mmap_supported[bar] = true;
147 * Here we don't handle the case when the BAR is not page
148 * aligned because we can't expect the BAR will be
149 * assigned into the same location in a page in guest
150 * when we passthrough the BAR. And it's hard to access
151 * this BAR in userspace because we have no way to get
152 * the BAR's location in a page.
155 vdev->bar_mmap_supported[bar] = false;
159 struct vfio_pci_group_info;
160 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set);
161 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
162 struct vfio_pci_group_info *groups);
165 * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
166 * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
167 * If a device implements the former but not the latter we would typically
168 * expect broken_intx_masking be set and require an exclusive interrupt.
169 * However since we do have control of the device's ability to assert INTx,
170 * we can instead pretend that the device does not implement INTx, virtualizing
171 * the pin register to report zero and maintaining DisINTx set on the host.
173 static bool vfio_pci_nointx(struct pci_dev *pdev)
175 switch (pdev->vendor) {
176 case PCI_VENDOR_ID_INTEL:
177 switch (pdev->device) {
178 /* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
181 case 0x1580 ... 0x1581:
182 case 0x1583 ... 0x158b:
183 case 0x37d0 ... 0x37d2:
195 static void vfio_pci_probe_power_state(struct vfio_pci_core_device *vdev)
197 struct pci_dev *pdev = vdev->pdev;
203 pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
205 vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
209 * pci_set_power_state() wrapper handling devices which perform a soft reset on
210 * D3->D0 transition. Save state prior to D0/1/2->D3, stash it on the vdev,
211 * restore when returned to D0. Saved separately from pci_saved_state for use
212 * by PM capability emulation and separately from pci_dev internal saved state
213 * to avoid it being overwritten and consumed around other resets.
215 int vfio_pci_set_power_state(struct vfio_pci_core_device *vdev, pci_power_t state)
217 struct pci_dev *pdev = vdev->pdev;
218 bool needs_restore = false, needs_save = false;
221 /* Prevent changing power state for PFs with VFs enabled */
222 if (pci_num_vf(pdev) && state > PCI_D0)
225 if (vdev->needs_pm_restore) {
226 if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
227 pci_save_state(pdev);
231 if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
232 needs_restore = true;
235 ret = pci_set_power_state(pdev, state);
238 /* D3 might be unsupported via quirk, skip unless in D3 */
239 if (needs_save && pdev->current_state >= PCI_D3hot) {
241 * The current PCI state will be saved locally in
242 * 'pm_save' during the D3hot transition. When the
243 * device state is changed to D0 again with the current
244 * function, then pci_store_saved_state() will restore
245 * the state and will free the memory pointed by
246 * 'pm_save'. There are few cases where the PCI power
247 * state can be changed to D0 without the involvement
248 * of the driver. For these cases, free the earlier
249 * allocated memory first before overwriting 'pm_save'
250 * to prevent the memory leak.
252 kfree(vdev->pm_save);
253 vdev->pm_save = pci_store_saved_state(pdev);
254 } else if (needs_restore) {
255 pci_load_and_free_saved_state(pdev, &vdev->pm_save);
256 pci_restore_state(pdev);
264 * The dev_pm_ops needs to be provided to make pci-driver runtime PM working,
265 * so use structure without any callbacks.
267 * The pci-driver core runtime PM routines always save the device state
268 * before going into suspended state. If the device is going into low power
269 * state with only with runtime PM ops, then no explicit handling is needed
270 * for the devices which have NoSoftRst-.
272 static const struct dev_pm_ops vfio_pci_core_pm_ops = { };
274 int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)
276 struct pci_dev *pdev = vdev->pdev;
281 if (!disable_idle_d3) {
282 ret = pm_runtime_resume_and_get(&pdev->dev);
287 /* Don't allow our initial saved state to include busmaster */
288 pci_clear_master(pdev);
290 ret = pci_enable_device(pdev);
294 /* If reset fails because of the device lock, fail this path entirely */
295 ret = pci_try_reset_function(pdev);
297 goto out_disable_device;
299 vdev->reset_works = !ret;
300 pci_save_state(pdev);
301 vdev->pci_saved_state = pci_store_saved_state(pdev);
302 if (!vdev->pci_saved_state)
303 pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
305 if (likely(!nointxmask)) {
306 if (vfio_pci_nointx(pdev)) {
307 pci_info(pdev, "Masking broken INTx support\n");
311 vdev->pci_2_3 = pci_intx_mask_supported(pdev);
314 pci_read_config_word(pdev, PCI_COMMAND, &cmd);
315 if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
316 cmd &= ~PCI_COMMAND_INTX_DISABLE;
317 pci_write_config_word(pdev, PCI_COMMAND, cmd);
320 ret = vfio_pci_zdev_open_device(vdev);
324 ret = vfio_config_init(vdev);
328 msix_pos = pdev->msix_cap;
333 pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
334 pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
336 vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
337 vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
338 vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
340 vdev->msix_bar = 0xFF;
342 if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
343 vdev->has_vga = true;
349 vfio_pci_zdev_close_device(vdev);
351 kfree(vdev->pci_saved_state);
352 vdev->pci_saved_state = NULL;
354 pci_disable_device(pdev);
356 if (!disable_idle_d3)
357 pm_runtime_put(&pdev->dev);
360 EXPORT_SYMBOL_GPL(vfio_pci_core_enable);
362 void vfio_pci_core_disable(struct vfio_pci_core_device *vdev)
364 struct pci_dev *pdev = vdev->pdev;
365 struct vfio_pci_dummy_resource *dummy_res, *tmp;
366 struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
369 /* For needs_reset */
370 lockdep_assert_held(&vdev->vdev.dev_set->lock);
373 * This function can be invoked while the power state is non-D0.
374 * This function calls __pci_reset_function_locked() which internally
375 * can use pci_pm_reset() for the function reset. pci_pm_reset() will
376 * fail if the power state is non-D0. Also, for the devices which
377 * have NoSoftRst-, the reset function can cause the PCI config space
378 * reset without restoring the original state (saved locally in
381 vfio_pci_set_power_state(vdev, PCI_D0);
383 /* Stop the device from further DMA */
384 pci_clear_master(pdev);
386 vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
387 VFIO_IRQ_SET_ACTION_TRIGGER,
388 vdev->irq_type, 0, 0, NULL);
390 /* Device closed, don't need mutex here */
391 list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
392 &vdev->ioeventfds_list, next) {
393 vfio_virqfd_disable(&ioeventfd->virqfd);
394 list_del(&ioeventfd->next);
397 vdev->ioeventfds_nr = 0;
399 vdev->virq_disabled = false;
401 for (i = 0; i < vdev->num_regions; i++)
402 vdev->region[i].ops->release(vdev, &vdev->region[i]);
404 vdev->num_regions = 0;
406 vdev->region = NULL; /* don't krealloc a freed pointer */
408 vfio_config_free(vdev);
410 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
411 bar = i + PCI_STD_RESOURCES;
412 if (!vdev->barmap[bar])
414 pci_iounmap(pdev, vdev->barmap[bar]);
415 pci_release_selected_regions(pdev, 1 << bar);
416 vdev->barmap[bar] = NULL;
419 list_for_each_entry_safe(dummy_res, tmp,
420 &vdev->dummy_resources_list, res_next) {
421 list_del(&dummy_res->res_next);
422 release_resource(&dummy_res->resource);
426 vdev->needs_reset = true;
428 vfio_pci_zdev_close_device(vdev);
431 * If we have saved state, restore it. If we can reset the device,
432 * even better. Resetting with current state seems better than
433 * nothing, but saving and restoring current state without reset
436 if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
437 pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
439 if (!vdev->reset_works)
442 pci_save_state(pdev);
446 * Disable INTx and MSI, presumably to avoid spurious interrupts
447 * during reset. Stolen from pci_reset_function()
449 pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
452 * Try to get the locks ourselves to prevent a deadlock. The
453 * success of this is dependent on being able to lock the device,
454 * which is not always possible.
455 * We can not use the "try" reset interface here, which will
456 * overwrite the previously restored configuration information.
458 if (vdev->reset_works && pci_dev_trylock(pdev)) {
459 if (!__pci_reset_function_locked(pdev))
460 vdev->needs_reset = false;
461 pci_dev_unlock(pdev);
464 pci_restore_state(pdev);
466 pci_disable_device(pdev);
468 vfio_pci_dev_set_try_reset(vdev->vdev.dev_set);
470 /* Put the pm-runtime usage counter acquired during enable */
471 if (!disable_idle_d3)
472 pm_runtime_put(&pdev->dev);
474 EXPORT_SYMBOL_GPL(vfio_pci_core_disable);
476 void vfio_pci_core_close_device(struct vfio_device *core_vdev)
478 struct vfio_pci_core_device *vdev =
479 container_of(core_vdev, struct vfio_pci_core_device, vdev);
481 if (vdev->sriov_pf_core_dev) {
482 mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
483 WARN_ON(!vdev->sriov_pf_core_dev->vf_token->users);
484 vdev->sriov_pf_core_dev->vf_token->users--;
485 mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
487 vfio_spapr_pci_eeh_release(vdev->pdev);
488 vfio_pci_core_disable(vdev);
490 mutex_lock(&vdev->igate);
491 if (vdev->err_trigger) {
492 eventfd_ctx_put(vdev->err_trigger);
493 vdev->err_trigger = NULL;
495 if (vdev->req_trigger) {
496 eventfd_ctx_put(vdev->req_trigger);
497 vdev->req_trigger = NULL;
499 mutex_unlock(&vdev->igate);
501 EXPORT_SYMBOL_GPL(vfio_pci_core_close_device);
503 void vfio_pci_core_finish_enable(struct vfio_pci_core_device *vdev)
505 vfio_pci_probe_mmaps(vdev);
506 vfio_spapr_pci_eeh_open(vdev->pdev);
508 if (vdev->sriov_pf_core_dev) {
509 mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
510 vdev->sriov_pf_core_dev->vf_token->users++;
511 mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
514 EXPORT_SYMBOL_GPL(vfio_pci_core_finish_enable);
516 static int vfio_pci_get_irq_count(struct vfio_pci_core_device *vdev, int irq_type)
518 if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
521 if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
522 vdev->nointx || vdev->pdev->is_virtfn)
525 pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
528 } else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
532 pos = vdev->pdev->msi_cap;
534 pci_read_config_word(vdev->pdev,
535 pos + PCI_MSI_FLAGS, &flags);
536 return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
538 } else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
542 pos = vdev->pdev->msix_cap;
544 pci_read_config_word(vdev->pdev,
545 pos + PCI_MSIX_FLAGS, &flags);
547 return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
549 } else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
550 if (pci_is_pcie(vdev->pdev))
552 } else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
559 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
565 struct vfio_pci_fill_info {
568 struct vfio_pci_dependent_device *devices;
571 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
573 struct vfio_pci_fill_info *fill = data;
574 struct iommu_group *iommu_group;
576 if (fill->cur == fill->max)
577 return -EAGAIN; /* Something changed, try again */
579 iommu_group = iommu_group_get(&pdev->dev);
581 return -EPERM; /* Cannot reset non-isolated devices */
583 fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
584 fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
585 fill->devices[fill->cur].bus = pdev->bus->number;
586 fill->devices[fill->cur].devfn = pdev->devfn;
588 iommu_group_put(iommu_group);
592 struct vfio_pci_group_info {
597 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
599 for (; pdev; pdev = pdev->bus->self)
600 if (pdev->bus == slot->bus)
601 return (pdev->slot == slot);
605 struct vfio_pci_walk_info {
606 int (*fn)(struct pci_dev *pdev, void *data);
608 struct pci_dev *pdev;
613 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
615 struct vfio_pci_walk_info *walk = data;
617 if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
618 walk->ret = walk->fn(pdev, walk->data);
623 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
624 int (*fn)(struct pci_dev *,
625 void *data), void *data,
628 struct vfio_pci_walk_info walk = {
629 .fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
632 pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
637 static int msix_mmappable_cap(struct vfio_pci_core_device *vdev,
638 struct vfio_info_cap *caps)
640 struct vfio_info_cap_header header = {
641 .id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
645 return vfio_info_add_capability(caps, &header, sizeof(header));
648 int vfio_pci_register_dev_region(struct vfio_pci_core_device *vdev,
649 unsigned int type, unsigned int subtype,
650 const struct vfio_pci_regops *ops,
651 size_t size, u32 flags, void *data)
653 struct vfio_pci_region *region;
655 region = krealloc(vdev->region,
656 (vdev->num_regions + 1) * sizeof(*region),
661 vdev->region = region;
662 vdev->region[vdev->num_regions].type = type;
663 vdev->region[vdev->num_regions].subtype = subtype;
664 vdev->region[vdev->num_regions].ops = ops;
665 vdev->region[vdev->num_regions].size = size;
666 vdev->region[vdev->num_regions].flags = flags;
667 vdev->region[vdev->num_regions].data = data;
673 EXPORT_SYMBOL_GPL(vfio_pci_register_dev_region);
675 long vfio_pci_core_ioctl(struct vfio_device *core_vdev, unsigned int cmd,
678 struct vfio_pci_core_device *vdev =
679 container_of(core_vdev, struct vfio_pci_core_device, vdev);
682 if (cmd == VFIO_DEVICE_GET_INFO) {
683 struct vfio_device_info info;
684 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
688 minsz = offsetofend(struct vfio_device_info, num_irqs);
690 /* For backward compatibility, cannot require this */
691 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
693 if (copy_from_user(&info, (void __user *)arg, minsz))
696 if (info.argsz < minsz)
699 if (info.argsz >= capsz) {
704 info.flags = VFIO_DEVICE_FLAGS_PCI;
706 if (vdev->reset_works)
707 info.flags |= VFIO_DEVICE_FLAGS_RESET;
709 info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
710 info.num_irqs = VFIO_PCI_NUM_IRQS;
712 ret = vfio_pci_info_zdev_add_caps(vdev, &caps);
713 if (ret && ret != -ENODEV) {
714 pci_warn(vdev->pdev, "Failed to setup zPCI info capabilities\n");
719 info.flags |= VFIO_DEVICE_FLAGS_CAPS;
720 if (info.argsz < sizeof(info) + caps.size) {
721 info.argsz = sizeof(info) + caps.size;
723 vfio_info_cap_shift(&caps, sizeof(info));
724 if (copy_to_user((void __user *)arg +
725 sizeof(info), caps.buf,
730 info.cap_offset = sizeof(info);
736 return copy_to_user((void __user *)arg, &info, minsz) ?
739 } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
740 struct pci_dev *pdev = vdev->pdev;
741 struct vfio_region_info info;
742 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
745 minsz = offsetofend(struct vfio_region_info, offset);
747 if (copy_from_user(&info, (void __user *)arg, minsz))
750 if (info.argsz < minsz)
753 switch (info.index) {
754 case VFIO_PCI_CONFIG_REGION_INDEX:
755 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
756 info.size = pdev->cfg_size;
757 info.flags = VFIO_REGION_INFO_FLAG_READ |
758 VFIO_REGION_INFO_FLAG_WRITE;
760 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
761 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
762 info.size = pci_resource_len(pdev, info.index);
768 info.flags = VFIO_REGION_INFO_FLAG_READ |
769 VFIO_REGION_INFO_FLAG_WRITE;
770 if (vdev->bar_mmap_supported[info.index]) {
771 info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
772 if (info.index == vdev->msix_bar) {
773 ret = msix_mmappable_cap(vdev, &caps);
780 case VFIO_PCI_ROM_REGION_INDEX:
786 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
789 /* Report the BAR size, not the ROM size */
790 info.size = pci_resource_len(pdev, info.index);
792 /* Shadow ROMs appear as PCI option ROMs */
793 if (pdev->resource[PCI_ROM_RESOURCE].flags &
794 IORESOURCE_ROM_SHADOW)
801 * Is it really there? Enable memory decode for
802 * implicit access in pci_map_rom().
804 cmd = vfio_pci_memory_lock_and_enable(vdev);
805 io = pci_map_rom(pdev, &size);
807 info.flags = VFIO_REGION_INFO_FLAG_READ;
808 pci_unmap_rom(pdev, io);
812 vfio_pci_memory_unlock_and_restore(vdev, cmd);
816 case VFIO_PCI_VGA_REGION_INDEX:
820 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
822 info.flags = VFIO_REGION_INFO_FLAG_READ |
823 VFIO_REGION_INFO_FLAG_WRITE;
828 struct vfio_region_info_cap_type cap_type = {
829 .header.id = VFIO_REGION_INFO_CAP_TYPE,
830 .header.version = 1 };
833 VFIO_PCI_NUM_REGIONS + vdev->num_regions)
835 info.index = array_index_nospec(info.index,
836 VFIO_PCI_NUM_REGIONS +
839 i = info.index - VFIO_PCI_NUM_REGIONS;
841 info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
842 info.size = vdev->region[i].size;
843 info.flags = vdev->region[i].flags;
845 cap_type.type = vdev->region[i].type;
846 cap_type.subtype = vdev->region[i].subtype;
848 ret = vfio_info_add_capability(&caps, &cap_type.header,
853 if (vdev->region[i].ops->add_capability) {
854 ret = vdev->region[i].ops->add_capability(vdev,
855 &vdev->region[i], &caps);
863 info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
864 if (info.argsz < sizeof(info) + caps.size) {
865 info.argsz = sizeof(info) + caps.size;
868 vfio_info_cap_shift(&caps, sizeof(info));
869 if (copy_to_user((void __user *)arg +
870 sizeof(info), caps.buf,
875 info.cap_offset = sizeof(info);
881 return copy_to_user((void __user *)arg, &info, minsz) ?
884 } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
885 struct vfio_irq_info info;
887 minsz = offsetofend(struct vfio_irq_info, count);
889 if (copy_from_user(&info, (void __user *)arg, minsz))
892 if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
895 switch (info.index) {
896 case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
897 case VFIO_PCI_REQ_IRQ_INDEX:
899 case VFIO_PCI_ERR_IRQ_INDEX:
900 if (pci_is_pcie(vdev->pdev))
907 info.flags = VFIO_IRQ_INFO_EVENTFD;
909 info.count = vfio_pci_get_irq_count(vdev, info.index);
911 if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
912 info.flags |= (VFIO_IRQ_INFO_MASKABLE |
913 VFIO_IRQ_INFO_AUTOMASKED);
915 info.flags |= VFIO_IRQ_INFO_NORESIZE;
917 return copy_to_user((void __user *)arg, &info, minsz) ?
920 } else if (cmd == VFIO_DEVICE_SET_IRQS) {
921 struct vfio_irq_set hdr;
924 size_t data_size = 0;
926 minsz = offsetofend(struct vfio_irq_set, count);
928 if (copy_from_user(&hdr, (void __user *)arg, minsz))
931 max = vfio_pci_get_irq_count(vdev, hdr.index);
933 ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
934 VFIO_PCI_NUM_IRQS, &data_size);
939 data = memdup_user((void __user *)(arg + minsz),
942 return PTR_ERR(data);
945 mutex_lock(&vdev->igate);
947 ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
948 hdr.start, hdr.count, data);
950 mutex_unlock(&vdev->igate);
955 } else if (cmd == VFIO_DEVICE_RESET) {
958 if (!vdev->reset_works)
961 vfio_pci_zap_and_down_write_memory_lock(vdev);
964 * This function can be invoked while the power state is non-D0.
965 * If pci_try_reset_function() has been called while the power
966 * state is non-D0, then pci_try_reset_function() will
967 * internally set the power state to D0 without vfio driver
968 * involvement. For the devices which have NoSoftRst-, the
969 * reset function can cause the PCI config space reset without
970 * restoring the original state (saved locally in
973 vfio_pci_set_power_state(vdev, PCI_D0);
975 ret = pci_try_reset_function(vdev->pdev);
976 up_write(&vdev->memory_lock);
980 } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
981 struct vfio_pci_hot_reset_info hdr;
982 struct vfio_pci_fill_info fill = { 0 };
983 struct vfio_pci_dependent_device *devices = NULL;
987 minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
989 if (copy_from_user(&hdr, (void __user *)arg, minsz))
992 if (hdr.argsz < minsz)
997 /* Can we do a slot or bus reset or neither? */
998 if (!pci_probe_reset_slot(vdev->pdev->slot))
1000 else if (pci_probe_reset_bus(vdev->pdev->bus))
1003 /* How many devices are affected? */
1004 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1005 vfio_pci_count_devs,
1010 WARN_ON(!fill.max); /* Should always be at least one */
1013 * If there's enough space, fill it now, otherwise return
1014 * -ENOSPC and the number of devices affected.
1016 if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
1018 hdr.count = fill.max;
1019 goto reset_info_exit;
1022 devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
1026 fill.devices = devices;
1028 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1033 * If a device was removed between counting and filling,
1034 * we may come up short of fill.max. If a device was
1035 * added, we'll have a return of -EAGAIN above.
1038 hdr.count = fill.cur;
1041 if (copy_to_user((void __user *)arg, &hdr, minsz))
1045 if (copy_to_user((void __user *)(arg + minsz), devices,
1046 hdr.count * sizeof(*devices)))
1053 } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1054 struct vfio_pci_hot_reset hdr;
1056 struct file **files;
1057 struct vfio_pci_group_info info;
1059 int file_idx, count = 0, ret = 0;
1061 minsz = offsetofend(struct vfio_pci_hot_reset, count);
1063 if (copy_from_user(&hdr, (void __user *)arg, minsz))
1066 if (hdr.argsz < minsz || hdr.flags)
1069 /* Can we do a slot or bus reset or neither? */
1070 if (!pci_probe_reset_slot(vdev->pdev->slot))
1072 else if (pci_probe_reset_bus(vdev->pdev->bus))
1076 * We can't let userspace give us an arbitrarily large
1077 * buffer to copy, so verify how many we think there
1078 * could be. Note groups can have multiple devices so
1079 * one group per device is the max.
1081 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1082 vfio_pci_count_devs,
1087 /* Somewhere between 1 and count is OK */
1088 if (!hdr.count || hdr.count > count)
1091 group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1092 files = kcalloc(hdr.count, sizeof(*files), GFP_KERNEL);
1093 if (!group_fds || !files) {
1099 if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1100 hdr.count * sizeof(*group_fds))) {
1107 * For each group_fd, get the group through the vfio external
1108 * user interface and store the group and iommu ID. This
1109 * ensures the group is held across the reset.
1111 for (file_idx = 0; file_idx < hdr.count; file_idx++) {
1112 struct file *file = fget(group_fds[file_idx]);
1119 /* Ensure the FD is a vfio group FD.*/
1120 if (!vfio_file_iommu_group(file)) {
1126 files[file_idx] = file;
1131 /* release reference to groups on error */
1133 goto hot_reset_release;
1135 info.count = hdr.count;
1138 ret = vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, &info);
1141 for (file_idx--; file_idx >= 0; file_idx--)
1142 fput(files[file_idx]);
1146 } else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1147 struct vfio_device_ioeventfd ioeventfd;
1150 minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1152 if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1155 if (ioeventfd.argsz < minsz)
1158 if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1161 count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1163 if (hweight8(count) != 1 || ioeventfd.fd < -1)
1166 return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1167 ioeventfd.data, count, ioeventfd.fd);
1171 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl);
1173 static int vfio_pci_core_feature_token(struct vfio_device *device, u32 flags,
1174 void __user *arg, size_t argsz)
1176 struct vfio_pci_core_device *vdev =
1177 container_of(device, struct vfio_pci_core_device, vdev);
1181 if (!vdev->vf_token)
1184 * We do not support GET of the VF Token UUID as this could
1185 * expose the token of the previous device user.
1187 ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
1192 if (copy_from_user(&uuid, arg, sizeof(uuid)))
1195 mutex_lock(&vdev->vf_token->lock);
1196 uuid_copy(&vdev->vf_token->uuid, &uuid);
1197 mutex_unlock(&vdev->vf_token->lock);
1201 int vfio_pci_core_ioctl_feature(struct vfio_device *device, u32 flags,
1202 void __user *arg, size_t argsz)
1204 switch (flags & VFIO_DEVICE_FEATURE_MASK) {
1205 case VFIO_DEVICE_FEATURE_PCI_VF_TOKEN:
1206 return vfio_pci_core_feature_token(device, flags, arg, argsz);
1211 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl_feature);
1213 static ssize_t vfio_pci_rw(struct vfio_pci_core_device *vdev, char __user *buf,
1214 size_t count, loff_t *ppos, bool iswrite)
1216 unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1218 if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1222 case VFIO_PCI_CONFIG_REGION_INDEX:
1223 return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1225 case VFIO_PCI_ROM_REGION_INDEX:
1228 return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1230 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1231 return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1233 case VFIO_PCI_VGA_REGION_INDEX:
1234 return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1236 index -= VFIO_PCI_NUM_REGIONS;
1237 return vdev->region[index].ops->rw(vdev, buf,
1238 count, ppos, iswrite);
1244 ssize_t vfio_pci_core_read(struct vfio_device *core_vdev, char __user *buf,
1245 size_t count, loff_t *ppos)
1247 struct vfio_pci_core_device *vdev =
1248 container_of(core_vdev, struct vfio_pci_core_device, vdev);
1253 return vfio_pci_rw(vdev, buf, count, ppos, false);
1255 EXPORT_SYMBOL_GPL(vfio_pci_core_read);
1257 ssize_t vfio_pci_core_write(struct vfio_device *core_vdev, const char __user *buf,
1258 size_t count, loff_t *ppos)
1260 struct vfio_pci_core_device *vdev =
1261 container_of(core_vdev, struct vfio_pci_core_device, vdev);
1266 return vfio_pci_rw(vdev, (char __user *)buf, count, ppos, true);
1268 EXPORT_SYMBOL_GPL(vfio_pci_core_write);
1270 /* Return 1 on zap and vma_lock acquired, 0 on contention (only with @try) */
1271 static int vfio_pci_zap_and_vma_lock(struct vfio_pci_core_device *vdev, bool try)
1273 struct vfio_pci_mmap_vma *mmap_vma, *tmp;
1277 * vma_lock is nested under mmap_lock for vm_ops callback paths.
1278 * The memory_lock semaphore is used by both code paths calling
1279 * into this function to zap vmas and the vm_ops.fault callback
1280 * to protect the memory enable state of the device.
1282 * When zapping vmas we need to maintain the mmap_lock => vma_lock
1283 * ordering, which requires using vma_lock to walk vma_list to
1284 * acquire an mm, then dropping vma_lock to get the mmap_lock and
1285 * reacquiring vma_lock. This logic is derived from similar
1286 * requirements in uverbs_user_mmap_disassociate().
1288 * mmap_lock must always be the top-level lock when it is taken.
1289 * Therefore we can only hold the memory_lock write lock when
1290 * vma_list is empty, as we'd need to take mmap_lock to clear
1291 * entries. vma_list can only be guaranteed empty when holding
1292 * vma_lock, thus memory_lock is nested under vma_lock.
1294 * This enables the vm_ops.fault callback to acquire vma_lock,
1295 * followed by memory_lock read lock, while already holding
1296 * mmap_lock without risk of deadlock.
1299 struct mm_struct *mm = NULL;
1302 if (!mutex_trylock(&vdev->vma_lock))
1305 mutex_lock(&vdev->vma_lock);
1307 while (!list_empty(&vdev->vma_list)) {
1308 mmap_vma = list_first_entry(&vdev->vma_list,
1309 struct vfio_pci_mmap_vma,
1311 mm = mmap_vma->vma->vm_mm;
1312 if (mmget_not_zero(mm))
1315 list_del(&mmap_vma->vma_next);
1321 mutex_unlock(&vdev->vma_lock);
1324 if (!mmap_read_trylock(mm)) {
1332 if (!mutex_trylock(&vdev->vma_lock)) {
1333 mmap_read_unlock(mm);
1338 mutex_lock(&vdev->vma_lock);
1340 list_for_each_entry_safe(mmap_vma, tmp,
1341 &vdev->vma_list, vma_next) {
1342 struct vm_area_struct *vma = mmap_vma->vma;
1344 if (vma->vm_mm != mm)
1347 list_del(&mmap_vma->vma_next);
1350 zap_vma_ptes(vma, vma->vm_start,
1351 vma->vm_end - vma->vm_start);
1353 mutex_unlock(&vdev->vma_lock);
1354 mmap_read_unlock(mm);
1359 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device *vdev)
1361 vfio_pci_zap_and_vma_lock(vdev, false);
1362 down_write(&vdev->memory_lock);
1363 mutex_unlock(&vdev->vma_lock);
1366 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_core_device *vdev)
1370 down_write(&vdev->memory_lock);
1371 pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1372 if (!(cmd & PCI_COMMAND_MEMORY))
1373 pci_write_config_word(vdev->pdev, PCI_COMMAND,
1374 cmd | PCI_COMMAND_MEMORY);
1379 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_core_device *vdev, u16 cmd)
1381 pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1382 up_write(&vdev->memory_lock);
1385 /* Caller holds vma_lock */
1386 static int __vfio_pci_add_vma(struct vfio_pci_core_device *vdev,
1387 struct vm_area_struct *vma)
1389 struct vfio_pci_mmap_vma *mmap_vma;
1391 mmap_vma = kmalloc(sizeof(*mmap_vma), GFP_KERNEL);
1395 mmap_vma->vma = vma;
1396 list_add(&mmap_vma->vma_next, &vdev->vma_list);
1402 * Zap mmaps on open so that we can fault them in on access and therefore
1403 * our vma_list only tracks mappings accessed since last zap.
1405 static void vfio_pci_mmap_open(struct vm_area_struct *vma)
1407 zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1410 static void vfio_pci_mmap_close(struct vm_area_struct *vma)
1412 struct vfio_pci_core_device *vdev = vma->vm_private_data;
1413 struct vfio_pci_mmap_vma *mmap_vma;
1415 mutex_lock(&vdev->vma_lock);
1416 list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1417 if (mmap_vma->vma == vma) {
1418 list_del(&mmap_vma->vma_next);
1423 mutex_unlock(&vdev->vma_lock);
1426 static vm_fault_t vfio_pci_mmap_fault(struct vm_fault *vmf)
1428 struct vm_area_struct *vma = vmf->vma;
1429 struct vfio_pci_core_device *vdev = vma->vm_private_data;
1430 struct vfio_pci_mmap_vma *mmap_vma;
1431 vm_fault_t ret = VM_FAULT_NOPAGE;
1433 mutex_lock(&vdev->vma_lock);
1434 down_read(&vdev->memory_lock);
1436 if (!__vfio_pci_memory_enabled(vdev)) {
1437 ret = VM_FAULT_SIGBUS;
1442 * We populate the whole vma on fault, so we need to test whether
1443 * the vma has already been mapped, such as for concurrent faults
1444 * to the same vma. io_remap_pfn_range() will trigger a BUG_ON if
1445 * we ask it to fill the same range again.
1447 list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1448 if (mmap_vma->vma == vma)
1452 if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1453 vma->vm_end - vma->vm_start,
1454 vma->vm_page_prot)) {
1455 ret = VM_FAULT_SIGBUS;
1456 zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1460 if (__vfio_pci_add_vma(vdev, vma)) {
1462 zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1466 up_read(&vdev->memory_lock);
1467 mutex_unlock(&vdev->vma_lock);
1471 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1472 .open = vfio_pci_mmap_open,
1473 .close = vfio_pci_mmap_close,
1474 .fault = vfio_pci_mmap_fault,
1477 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma)
1479 struct vfio_pci_core_device *vdev =
1480 container_of(core_vdev, struct vfio_pci_core_device, vdev);
1481 struct pci_dev *pdev = vdev->pdev;
1483 u64 phys_len, req_len, pgoff, req_start;
1486 index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1488 if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1490 if (vma->vm_end < vma->vm_start)
1492 if ((vma->vm_flags & VM_SHARED) == 0)
1494 if (index >= VFIO_PCI_NUM_REGIONS) {
1495 int regnum = index - VFIO_PCI_NUM_REGIONS;
1496 struct vfio_pci_region *region = vdev->region + regnum;
1498 if (region->ops && region->ops->mmap &&
1499 (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1500 return region->ops->mmap(vdev, region, vma);
1503 if (index >= VFIO_PCI_ROM_REGION_INDEX)
1505 if (!vdev->bar_mmap_supported[index])
1508 phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1509 req_len = vma->vm_end - vma->vm_start;
1510 pgoff = vma->vm_pgoff &
1511 ((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1512 req_start = pgoff << PAGE_SHIFT;
1514 if (req_start + req_len > phys_len)
1518 * Even though we don't make use of the barmap for the mmap,
1519 * we need to request the region and the barmap tracks that.
1521 if (!vdev->barmap[index]) {
1522 ret = pci_request_selected_regions(pdev,
1523 1 << index, "vfio-pci");
1527 vdev->barmap[index] = pci_iomap(pdev, index, 0);
1528 if (!vdev->barmap[index]) {
1529 pci_release_selected_regions(pdev, 1 << index);
1534 vma->vm_private_data = vdev;
1535 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1536 vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1539 * See remap_pfn_range(), called from vfio_pci_fault() but we can't
1540 * change vm_flags within the fault handler. Set them now.
1542 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1543 vma->vm_ops = &vfio_pci_mmap_ops;
1547 EXPORT_SYMBOL_GPL(vfio_pci_core_mmap);
1549 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count)
1551 struct vfio_pci_core_device *vdev =
1552 container_of(core_vdev, struct vfio_pci_core_device, vdev);
1553 struct pci_dev *pdev = vdev->pdev;
1555 mutex_lock(&vdev->igate);
1557 if (vdev->req_trigger) {
1559 pci_notice_ratelimited(pdev,
1560 "Relaying device request to user (#%u)\n",
1562 eventfd_signal(vdev->req_trigger, 1);
1563 } else if (count == 0) {
1565 "No device request channel registered, blocked until released by user\n");
1568 mutex_unlock(&vdev->igate);
1570 EXPORT_SYMBOL_GPL(vfio_pci_core_request);
1572 static int vfio_pci_validate_vf_token(struct vfio_pci_core_device *vdev,
1573 bool vf_token, uuid_t *uuid)
1576 * There's always some degree of trust or collaboration between SR-IOV
1577 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1578 * can disrupt VFs with a reset, but often the PF has more explicit
1579 * access to deny service to the VF or access data passed through the
1580 * VF. We therefore require an opt-in via a shared VF token (UUID) to
1581 * represent this trust. This both prevents that a VF driver might
1582 * assume the PF driver is a trusted, in-kernel driver, and also that
1583 * a PF driver might be replaced with a rogue driver, unknown to in-use
1586 * Therefore when presented with a VF, if the PF is a vfio device and
1587 * it is bound to the vfio-pci driver, the user needs to provide a VF
1588 * token to access the device, in the form of appending a vf_token to
1589 * the device name, for example:
1591 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1593 * When presented with a PF which has VFs in use, the user must also
1594 * provide the current VF token to prove collaboration with existing
1595 * VF users. If VFs are not in use, the VF token provided for the PF
1596 * device will act to set the VF token.
1598 * If the VF token is provided but unused, an error is generated.
1600 if (vdev->pdev->is_virtfn) {
1601 struct vfio_pci_core_device *pf_vdev = vdev->sriov_pf_core_dev;
1606 return 0; /* PF is not vfio-pci, no VF token */
1608 pci_info_ratelimited(vdev->pdev,
1609 "VF token incorrectly provided, PF not bound to vfio-pci\n");
1614 pci_info_ratelimited(vdev->pdev,
1615 "VF token required to access device\n");
1619 mutex_lock(&pf_vdev->vf_token->lock);
1620 match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1621 mutex_unlock(&pf_vdev->vf_token->lock);
1624 pci_info_ratelimited(vdev->pdev,
1625 "Incorrect VF token provided for device\n");
1628 } else if (vdev->vf_token) {
1629 mutex_lock(&vdev->vf_token->lock);
1630 if (vdev->vf_token->users) {
1632 mutex_unlock(&vdev->vf_token->lock);
1633 pci_info_ratelimited(vdev->pdev,
1634 "VF token required to access device\n");
1638 if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1639 mutex_unlock(&vdev->vf_token->lock);
1640 pci_info_ratelimited(vdev->pdev,
1641 "Incorrect VF token provided for device\n");
1644 } else if (vf_token) {
1645 uuid_copy(&vdev->vf_token->uuid, uuid);
1648 mutex_unlock(&vdev->vf_token->lock);
1649 } else if (vf_token) {
1650 pci_info_ratelimited(vdev->pdev,
1651 "VF token incorrectly provided, not a PF or VF\n");
1658 #define VF_TOKEN_ARG "vf_token="
1660 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf)
1662 struct vfio_pci_core_device *vdev =
1663 container_of(core_vdev, struct vfio_pci_core_device, vdev);
1664 bool vf_token = false;
1668 if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1669 return 0; /* No match */
1671 if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1672 buf += strlen(pci_name(vdev->pdev));
1675 return 0; /* No match: non-whitespace after name */
1683 if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1684 strlen(VF_TOKEN_ARG))) {
1685 buf += strlen(VF_TOKEN_ARG);
1687 if (strlen(buf) < UUID_STRING_LEN)
1690 ret = uuid_parse(buf, &uuid);
1695 buf += UUID_STRING_LEN;
1697 /* Unknown/duplicate option */
1703 ret = vfio_pci_validate_vf_token(vdev, vf_token, &uuid);
1707 return 1; /* Match */
1709 EXPORT_SYMBOL_GPL(vfio_pci_core_match);
1711 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1712 unsigned long action, void *data)
1714 struct vfio_pci_core_device *vdev = container_of(nb,
1715 struct vfio_pci_core_device, nb);
1716 struct device *dev = data;
1717 struct pci_dev *pdev = to_pci_dev(dev);
1718 struct pci_dev *physfn = pci_physfn(pdev);
1720 if (action == BUS_NOTIFY_ADD_DEVICE &&
1721 pdev->is_virtfn && physfn == vdev->pdev) {
1722 pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1724 pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1725 vdev->vdev.ops->name);
1726 } else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1727 pdev->is_virtfn && physfn == vdev->pdev) {
1728 struct pci_driver *drv = pci_dev_driver(pdev);
1730 if (drv && drv != pci_dev_driver(vdev->pdev))
1731 pci_warn(vdev->pdev,
1732 "VF %s bound to driver %s while PF bound to driver %s\n",
1733 pci_name(pdev), drv->name,
1734 pci_dev_driver(vdev->pdev)->name);
1740 static int vfio_pci_vf_init(struct vfio_pci_core_device *vdev)
1742 struct pci_dev *pdev = vdev->pdev;
1743 struct vfio_pci_core_device *cur;
1744 struct pci_dev *physfn;
1747 if (pdev->is_virtfn) {
1749 * If this VF was created by our vfio_pci_core_sriov_configure()
1750 * then we can find the PF vfio_pci_core_device now, and due to
1751 * the locking in pci_disable_sriov() it cannot change until
1752 * this VF device driver is removed.
1754 physfn = pci_physfn(vdev->pdev);
1755 mutex_lock(&vfio_pci_sriov_pfs_mutex);
1756 list_for_each_entry(cur, &vfio_pci_sriov_pfs, sriov_pfs_item) {
1757 if (cur->pdev == physfn) {
1758 vdev->sriov_pf_core_dev = cur;
1762 mutex_unlock(&vfio_pci_sriov_pfs_mutex);
1766 /* Not a SRIOV PF */
1767 if (!pdev->is_physfn)
1770 vdev->vf_token = kzalloc(sizeof(*vdev->vf_token), GFP_KERNEL);
1771 if (!vdev->vf_token)
1774 mutex_init(&vdev->vf_token->lock);
1775 uuid_gen(&vdev->vf_token->uuid);
1777 vdev->nb.notifier_call = vfio_pci_bus_notifier;
1778 ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
1780 kfree(vdev->vf_token);
1786 static void vfio_pci_vf_uninit(struct vfio_pci_core_device *vdev)
1788 if (!vdev->vf_token)
1791 bus_unregister_notifier(&pci_bus_type, &vdev->nb);
1792 WARN_ON(vdev->vf_token->users);
1793 mutex_destroy(&vdev->vf_token->lock);
1794 kfree(vdev->vf_token);
1797 static int vfio_pci_vga_init(struct vfio_pci_core_device *vdev)
1799 struct pci_dev *pdev = vdev->pdev;
1802 if (!vfio_pci_is_vga(pdev))
1805 ret = aperture_remove_conflicting_pci_devices(pdev, vdev->vdev.ops->name);
1809 ret = vga_client_register(pdev, vfio_pci_set_decode);
1812 vga_set_legacy_decoding(pdev, vfio_pci_set_decode(pdev, false));
1816 static void vfio_pci_vga_uninit(struct vfio_pci_core_device *vdev)
1818 struct pci_dev *pdev = vdev->pdev;
1820 if (!vfio_pci_is_vga(pdev))
1822 vga_client_unregister(pdev);
1823 vga_set_legacy_decoding(pdev, VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1824 VGA_RSRC_LEGACY_IO |
1825 VGA_RSRC_LEGACY_MEM);
1828 void vfio_pci_core_init_device(struct vfio_pci_core_device *vdev,
1829 struct pci_dev *pdev,
1830 const struct vfio_device_ops *vfio_pci_ops)
1832 vfio_init_group_dev(&vdev->vdev, &pdev->dev, vfio_pci_ops);
1834 vdev->irq_type = VFIO_PCI_NUM_IRQS;
1835 mutex_init(&vdev->igate);
1836 spin_lock_init(&vdev->irqlock);
1837 mutex_init(&vdev->ioeventfds_lock);
1838 INIT_LIST_HEAD(&vdev->dummy_resources_list);
1839 INIT_LIST_HEAD(&vdev->ioeventfds_list);
1840 mutex_init(&vdev->vma_lock);
1841 INIT_LIST_HEAD(&vdev->vma_list);
1842 INIT_LIST_HEAD(&vdev->sriov_pfs_item);
1843 init_rwsem(&vdev->memory_lock);
1845 EXPORT_SYMBOL_GPL(vfio_pci_core_init_device);
1847 void vfio_pci_core_uninit_device(struct vfio_pci_core_device *vdev)
1849 mutex_destroy(&vdev->igate);
1850 mutex_destroy(&vdev->ioeventfds_lock);
1851 mutex_destroy(&vdev->vma_lock);
1852 vfio_uninit_group_dev(&vdev->vdev);
1853 kfree(vdev->region);
1854 kfree(vdev->pm_save);
1856 EXPORT_SYMBOL_GPL(vfio_pci_core_uninit_device);
1858 int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)
1860 struct pci_dev *pdev = vdev->pdev;
1861 struct device *dev = &pdev->dev;
1864 /* Drivers must set the vfio_pci_core_device to their drvdata */
1865 if (WARN_ON(vdev != dev_get_drvdata(dev)))
1868 if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1871 if (vdev->vdev.mig_ops) {
1872 if (!(vdev->vdev.mig_ops->migration_get_state &&
1873 vdev->vdev.mig_ops->migration_set_state) ||
1874 !(vdev->vdev.migration_flags & VFIO_MIGRATION_STOP_COPY))
1879 * Prevent binding to PFs with VFs enabled, the VFs might be in use
1880 * by the host or other users. We cannot capture the VFs if they
1881 * already exist, nor can we track VF users. Disabling SR-IOV here
1882 * would initiate removing the VFs, which would unbind the driver,
1883 * which is prone to blocking if that VF is also in use by vfio-pci.
1884 * Just reject these PFs and let the user sort it out.
1886 if (pci_num_vf(pdev)) {
1887 pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1891 if (pci_is_root_bus(pdev->bus)) {
1892 ret = vfio_assign_device_set(&vdev->vdev, vdev);
1893 } else if (!pci_probe_reset_slot(pdev->slot)) {
1894 ret = vfio_assign_device_set(&vdev->vdev, pdev->slot);
1897 * If there is no slot reset support for this device, the whole
1898 * bus needs to be grouped together to support bus-wide resets.
1900 ret = vfio_assign_device_set(&vdev->vdev, pdev->bus);
1905 ret = vfio_pci_vf_init(vdev);
1908 ret = vfio_pci_vga_init(vdev);
1912 vfio_pci_probe_power_state(vdev);
1915 * pci-core sets the device power state to an unknown value at
1916 * bootup and after being removed from a driver. The only
1917 * transition it allows from this unknown state is to D0, which
1918 * typically happens when a driver calls pci_enable_device().
1919 * We're not ready to enable the device yet, but we do want to
1920 * be able to get to D3. Therefore first do a D0 transition
1921 * before enabling runtime PM.
1923 vfio_pci_set_power_state(vdev, PCI_D0);
1925 dev->driver->pm = &vfio_pci_core_pm_ops;
1926 pm_runtime_allow(dev);
1927 if (!disable_idle_d3)
1928 pm_runtime_put(dev);
1930 ret = vfio_register_group_dev(&vdev->vdev);
1936 if (!disable_idle_d3)
1937 pm_runtime_get_noresume(dev);
1939 pm_runtime_forbid(dev);
1941 vfio_pci_vf_uninit(vdev);
1944 EXPORT_SYMBOL_GPL(vfio_pci_core_register_device);
1946 void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)
1948 vfio_pci_core_sriov_configure(vdev, 0);
1950 vfio_unregister_group_dev(&vdev->vdev);
1952 vfio_pci_vf_uninit(vdev);
1953 vfio_pci_vga_uninit(vdev);
1955 if (!disable_idle_d3)
1956 pm_runtime_get_noresume(&vdev->pdev->dev);
1958 pm_runtime_forbid(&vdev->pdev->dev);
1960 EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device);
1962 pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev,
1963 pci_channel_state_t state)
1965 struct vfio_pci_core_device *vdev = dev_get_drvdata(&pdev->dev);
1967 mutex_lock(&vdev->igate);
1969 if (vdev->err_trigger)
1970 eventfd_signal(vdev->err_trigger, 1);
1972 mutex_unlock(&vdev->igate);
1974 return PCI_ERS_RESULT_CAN_RECOVER;
1976 EXPORT_SYMBOL_GPL(vfio_pci_core_aer_err_detected);
1978 int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev,
1981 struct pci_dev *pdev = vdev->pdev;
1984 device_lock_assert(&pdev->dev);
1987 mutex_lock(&vfio_pci_sriov_pfs_mutex);
1989 * The thread that adds the vdev to the list is the only thread
1990 * that gets to call pci_enable_sriov() and we will only allow
1991 * it to be called once without going through
1992 * pci_disable_sriov()
1994 if (!list_empty(&vdev->sriov_pfs_item)) {
1998 list_add_tail(&vdev->sriov_pfs_item, &vfio_pci_sriov_pfs);
1999 mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2002 * The PF power state should always be higher than the VF power
2003 * state. The PF can be in low power state either with runtime
2004 * power management (when there is no user) or PCI_PM_CTRL
2005 * register write by the user. If PF is in the low power state,
2006 * then change the power state to D0 first before enabling
2007 * SR-IOV. Also, this function can be called at any time, and
2008 * userspace PCI_PM_CTRL write can race against this code path,
2009 * so protect the same with 'memory_lock'.
2011 ret = pm_runtime_resume_and_get(&pdev->dev);
2015 down_write(&vdev->memory_lock);
2016 vfio_pci_set_power_state(vdev, PCI_D0);
2017 ret = pci_enable_sriov(pdev, nr_virtfn);
2018 up_write(&vdev->memory_lock);
2020 pm_runtime_put(&pdev->dev);
2026 if (pci_num_vf(pdev)) {
2027 pci_disable_sriov(pdev);
2028 pm_runtime_put(&pdev->dev);
2032 mutex_lock(&vfio_pci_sriov_pfs_mutex);
2033 list_del_init(&vdev->sriov_pfs_item);
2035 mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2038 EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure);
2040 const struct pci_error_handlers vfio_pci_core_err_handlers = {
2041 .error_detected = vfio_pci_core_aer_err_detected,
2043 EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers);
2045 static bool vfio_dev_in_groups(struct vfio_pci_core_device *vdev,
2046 struct vfio_pci_group_info *groups)
2050 for (i = 0; i < groups->count; i++)
2051 if (vfio_file_has_dev(groups->files[i], &vdev->vdev))
2056 static int vfio_pci_is_device_in_set(struct pci_dev *pdev, void *data)
2058 struct vfio_device_set *dev_set = data;
2059 struct vfio_device *cur;
2061 list_for_each_entry(cur, &dev_set->device_list, dev_set_list)
2062 if (cur->dev == &pdev->dev)
2068 * vfio-core considers a group to be viable and will create a vfio_device even
2069 * if some devices are bound to drivers like pci-stub or pcieport. Here we
2070 * require all PCI devices to be inside our dev_set since that ensures they stay
2071 * put and that every driver controlling the device can co-ordinate with the
2074 * Returns the pci_dev to pass to pci_reset_bus() if every PCI device to be
2075 * reset is inside the dev_set, and pci_reset_bus() can succeed. NULL otherwise.
2077 static struct pci_dev *
2078 vfio_pci_dev_set_resettable(struct vfio_device_set *dev_set)
2080 struct pci_dev *pdev;
2082 lockdep_assert_held(&dev_set->lock);
2085 * By definition all PCI devices in the dev_set share the same PCI
2086 * reset, so any pci_dev will have the same outcomes for
2087 * pci_probe_reset_*() and pci_reset_bus().
2089 pdev = list_first_entry(&dev_set->device_list,
2090 struct vfio_pci_core_device,
2091 vdev.dev_set_list)->pdev;
2093 /* pci_reset_bus() is supported */
2094 if (pci_probe_reset_slot(pdev->slot) && pci_probe_reset_bus(pdev->bus))
2097 if (vfio_pci_for_each_slot_or_bus(pdev, vfio_pci_is_device_in_set,
2099 !pci_probe_reset_slot(pdev->slot)))
2104 static int vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set *dev_set)
2106 struct vfio_pci_core_device *cur;
2109 list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2110 ret = pm_runtime_resume_and_get(&cur->pdev->dev);
2118 list_for_each_entry_continue_reverse(cur, &dev_set->device_list,
2120 pm_runtime_put(&cur->pdev->dev);
2126 * We need to get memory_lock for each device, but devices can share mmap_lock,
2127 * therefore we need to zap and hold the vma_lock for each device, and only then
2128 * get each memory_lock.
2130 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
2131 struct vfio_pci_group_info *groups)
2133 struct vfio_pci_core_device *cur_mem;
2134 struct vfio_pci_core_device *cur_vma;
2135 struct vfio_pci_core_device *cur;
2136 struct pci_dev *pdev;
2140 mutex_lock(&dev_set->lock);
2141 cur_mem = list_first_entry(&dev_set->device_list,
2142 struct vfio_pci_core_device,
2145 pdev = vfio_pci_dev_set_resettable(dev_set);
2151 list_for_each_entry(cur_vma, &dev_set->device_list, vdev.dev_set_list) {
2153 * Test whether all the affected devices are contained by the
2154 * set of groups provided by the user.
2156 if (!vfio_dev_in_groups(cur_vma, groups)) {
2162 * Locking multiple devices is prone to deadlock, runaway and
2163 * unwind if we hit contention.
2165 if (!vfio_pci_zap_and_vma_lock(cur_vma, true)) {
2172 list_for_each_entry(cur_mem, &dev_set->device_list, vdev.dev_set_list) {
2173 if (!down_write_trylock(&cur_mem->memory_lock)) {
2177 mutex_unlock(&cur_mem->vma_lock);
2182 * The pci_reset_bus() will reset all the devices in the bus.
2183 * The power state can be non-D0 for some of the devices in the bus.
2184 * For these devices, the pci_reset_bus() will internally set
2185 * the power state to D0 without vfio driver involvement.
2186 * For the devices which have NoSoftRst-, the reset function can
2187 * cause the PCI config space reset without restoring the original
2188 * state (saved locally in 'vdev->pm_save').
2190 list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2191 vfio_pci_set_power_state(cur, PCI_D0);
2193 ret = pci_reset_bus(pdev);
2196 list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2202 up_write(&cur->memory_lock);
2204 mutex_unlock(&cur->vma_lock);
2207 mutex_unlock(&dev_set->lock);
2211 static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)
2213 struct vfio_pci_core_device *cur;
2214 bool needs_reset = false;
2216 list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2217 /* No VFIO device in the set can have an open device FD */
2218 if (cur->vdev.open_count)
2220 needs_reset |= cur->needs_reset;
2226 * If a bus or slot reset is available for the provided dev_set and:
2227 * - All of the devices affected by that bus or slot reset are unused
2228 * - At least one of the affected devices is marked dirty via
2229 * needs_reset (such as by lack of FLR support)
2230 * Then attempt to perform that bus or slot reset.
2232 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set)
2234 struct vfio_pci_core_device *cur;
2235 struct pci_dev *pdev;
2236 bool reset_done = false;
2238 if (!vfio_pci_dev_set_needs_reset(dev_set))
2241 pdev = vfio_pci_dev_set_resettable(dev_set);
2246 * Some of the devices in the bus can be in the runtime suspended
2247 * state. Increment the usage count for all the devices in the dev_set
2248 * before reset and decrement the same after reset.
2250 if (!disable_idle_d3 && vfio_pci_dev_set_pm_runtime_get(dev_set))
2253 if (!pci_reset_bus(pdev))
2256 list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2258 cur->needs_reset = false;
2260 if (!disable_idle_d3)
2261 pm_runtime_put(&cur->pdev->dev);
2265 void vfio_pci_core_set_params(bool is_nointxmask, bool is_disable_vga,
2266 bool is_disable_idle_d3)
2268 nointxmask = is_nointxmask;
2269 disable_vga = is_disable_vga;
2270 disable_idle_d3 = is_disable_idle_d3;
2272 EXPORT_SYMBOL_GPL(vfio_pci_core_set_params);
2274 static void vfio_pci_core_cleanup(void)
2276 vfio_pci_uninit_perm_bits();
2279 static int __init vfio_pci_core_init(void)
2281 /* Allocate shared config space permission data used by all devices */
2282 return vfio_pci_init_perm_bits();
2285 module_init(vfio_pci_core_init);
2286 module_exit(vfio_pci_core_cleanup);
2288 MODULE_LICENSE("GPL v2");
2289 MODULE_AUTHOR(DRIVER_AUTHOR);
2290 MODULE_DESCRIPTION(DRIVER_DESC);