Linux Audio

Check our new training course

Loading...
v4.6
   1/*
   2 * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
   3 *     Author: Alex Williamson <alex.williamson@redhat.com>
   4 *
   5 * This program is free software; you can redistribute it and/or modify
   6 * it under the terms of the GNU General Public License version 2 as
   7 * published by the Free Software Foundation.
   8 *
   9 * Derived from original vfio:
  10 * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
  11 * Author: Tom Lyon, pugs@cisco.com
  12 */
  13
  14#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  15
  16#include <linux/device.h>
  17#include <linux/eventfd.h>
  18#include <linux/file.h>
  19#include <linux/interrupt.h>
  20#include <linux/iommu.h>
  21#include <linux/module.h>
  22#include <linux/mutex.h>
  23#include <linux/notifier.h>
  24#include <linux/pci.h>
  25#include <linux/pm_runtime.h>
  26#include <linux/slab.h>
  27#include <linux/types.h>
  28#include <linux/uaccess.h>
  29#include <linux/vfio.h>
  30#include <linux/vgaarb.h>
  31
  32#include "vfio_pci_private.h"
  33
  34#define DRIVER_VERSION  "0.2"
  35#define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
  36#define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
  37
  38static char ids[1024] __initdata;
  39module_param_string(ids, ids, sizeof(ids), 0);
  40MODULE_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
  42static bool nointxmask;
  43module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
  44MODULE_PARM_DESC(nointxmask,
  45		  "Disable support for PCI 2.3 style INTx masking.  If this resolves problems for specific devices, report lspci -vvvxxx to linux-pci@vger.kernel.org so the device can be fixed automatically via the broken_intx_masking flag.");
  46
  47#ifdef CONFIG_VFIO_PCI_VGA
  48static bool disable_vga;
  49module_param(disable_vga, bool, S_IRUGO);
  50MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
  51#endif
  52
  53static bool disable_idle_d3;
  54module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
  55MODULE_PARM_DESC(disable_idle_d3,
  56		 "Disable using the PCI D3 low power state for idle, unused devices");
  57
  58static DEFINE_MUTEX(driver_lock);
  59
  60static inline bool vfio_vga_disabled(void)
  61{
  62#ifdef CONFIG_VFIO_PCI_VGA
  63	return disable_vga;
  64#else
  65	return true;
  66#endif
  67}
  68
  69/*
  70 * Our VGA arbiter participation is limited since we don't know anything
  71 * about the device itself.  However, if the device is the only VGA device
  72 * downstream of a bridge and VFIO VGA support is disabled, then we can
  73 * safely return legacy VGA IO and memory as not decoded since the user
  74 * has no way to get to it and routing can be disabled externally at the
  75 * bridge.
  76 */
  77static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
  78{
  79	struct vfio_pci_device *vdev = opaque;
  80	struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
  81	unsigned char max_busnr;
  82	unsigned int decodes;
  83
  84	if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
  85		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
  86		       VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
  87
  88	max_busnr = pci_bus_max_busnr(pdev->bus);
  89	decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
  90
  91	while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
  92		if (tmp == pdev ||
  93		    pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
  94		    pci_is_root_bus(tmp->bus))
  95			continue;
  96
  97		if (tmp->bus->number >= pdev->bus->number &&
  98		    tmp->bus->number <= max_busnr) {
  99			pci_dev_put(tmp);
 100			decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
 101			break;
 102		}
 103	}
 104
 105	return decodes;
 106}
 107
 108static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
 109{
 110	return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
 111}
 112
 113static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
 114static void vfio_pci_disable(struct vfio_pci_device *vdev);
 115
 116static int vfio_pci_enable(struct vfio_pci_device *vdev)
 117{
 118	struct pci_dev *pdev = vdev->pdev;
 119	int ret;
 120	u16 cmd;
 121	u8 msix_pos;
 122
 123	pci_set_power_state(pdev, PCI_D0);
 124
 125	/* Don't allow our initial saved state to include busmaster */
 126	pci_clear_master(pdev);
 127
 128	ret = pci_enable_device(pdev);
 129	if (ret)
 130		return ret;
 131
 132	vdev->reset_works = (pci_reset_function(pdev) == 0);
 133	pci_save_state(pdev);
 134	vdev->pci_saved_state = pci_store_saved_state(pdev);
 135	if (!vdev->pci_saved_state)
 136		pr_debug("%s: Couldn't store %s saved state\n",
 137			 __func__, dev_name(&pdev->dev));
 138
 139	ret = vfio_config_init(vdev);
 140	if (ret) {
 141		kfree(vdev->pci_saved_state);
 142		vdev->pci_saved_state = NULL;
 143		pci_disable_device(pdev);
 144		return ret;
 145	}
 146
 147	if (likely(!nointxmask))
 148		vdev->pci_2_3 = pci_intx_mask_supported(pdev);
 149
 150	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
 151	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
 152		cmd &= ~PCI_COMMAND_INTX_DISABLE;
 153		pci_write_config_word(pdev, PCI_COMMAND, cmd);
 154	}
 155
 156	msix_pos = pdev->msix_cap;
 157	if (msix_pos) {
 158		u16 flags;
 159		u32 table;
 160
 161		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
 162		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
 163
 164		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
 165		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
 166		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
 167	} else
 168		vdev->msix_bar = 0xFF;
 169
 170	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
 
 171		vdev->has_vga = true;
 172
 173
 174	if (vfio_pci_is_vga(pdev) &&
 175	    pdev->vendor == PCI_VENDOR_ID_INTEL &&
 176	    IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
 177		ret = vfio_pci_igd_init(vdev);
 178		if (ret) {
 179			dev_warn(&vdev->pdev->dev,
 180				 "Failed to setup Intel IGD regions\n");
 181			vfio_pci_disable(vdev);
 182			return ret;
 183		}
 184	}
 185
 186	return 0;
 187}
 188
 189static void vfio_pci_disable(struct vfio_pci_device *vdev)
 190{
 191	struct pci_dev *pdev = vdev->pdev;
 192	int i, bar;
 193
 194	/* Stop the device from further DMA */
 195	pci_clear_master(pdev);
 196
 197	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
 198				VFIO_IRQ_SET_ACTION_TRIGGER,
 199				vdev->irq_type, 0, 0, NULL);
 200
 201	vdev->virq_disabled = false;
 202
 203	for (i = 0; i < vdev->num_regions; i++)
 204		vdev->region[i].ops->release(vdev, &vdev->region[i]);
 205
 206	vdev->num_regions = 0;
 207	kfree(vdev->region);
 208	vdev->region = NULL; /* don't krealloc a freed pointer */
 209
 210	vfio_config_free(vdev);
 211
 212	for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
 213		if (!vdev->barmap[bar])
 214			continue;
 215		pci_iounmap(pdev, vdev->barmap[bar]);
 216		pci_release_selected_regions(pdev, 1 << bar);
 217		vdev->barmap[bar] = NULL;
 218	}
 219
 220	vdev->needs_reset = true;
 221
 222	/*
 223	 * If we have saved state, restore it.  If we can reset the device,
 224	 * even better.  Resetting with current state seems better than
 225	 * nothing, but saving and restoring current state without reset
 226	 * is just busy work.
 227	 */
 228	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
 229		pr_info("%s: Couldn't reload %s saved state\n",
 230			__func__, dev_name(&pdev->dev));
 231
 232		if (!vdev->reset_works)
 233			goto out;
 234
 235		pci_save_state(pdev);
 236	}
 237
 238	/*
 239	 * Disable INTx and MSI, presumably to avoid spurious interrupts
 240	 * during reset.  Stolen from pci_reset_function()
 241	 */
 242	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
 243
 244	/*
 245	 * Try to reset the device.  The success of this is dependent on
 246	 * being able to lock the device, which is not always possible.
 247	 */
 248	if (vdev->reset_works && !pci_try_reset_function(pdev))
 249		vdev->needs_reset = false;
 
 
 
 
 250
 251	pci_restore_state(pdev);
 252out:
 253	pci_disable_device(pdev);
 254
 255	vfio_pci_try_bus_reset(vdev);
 256
 257	if (!disable_idle_d3)
 258		pci_set_power_state(pdev, PCI_D3hot);
 259}
 260
 261static void vfio_pci_release(void *device_data)
 262{
 263	struct vfio_pci_device *vdev = device_data;
 264
 265	mutex_lock(&driver_lock);
 266
 267	if (!(--vdev->refcnt)) {
 268		vfio_spapr_pci_eeh_release(vdev->pdev);
 269		vfio_pci_disable(vdev);
 270	}
 271
 272	mutex_unlock(&driver_lock);
 273
 274	module_put(THIS_MODULE);
 275}
 276
 277static int vfio_pci_open(void *device_data)
 278{
 279	struct vfio_pci_device *vdev = device_data;
 280	int ret = 0;
 281
 282	if (!try_module_get(THIS_MODULE))
 283		return -ENODEV;
 284
 285	mutex_lock(&driver_lock);
 286
 287	if (!vdev->refcnt) {
 288		ret = vfio_pci_enable(vdev);
 289		if (ret)
 290			goto error;
 291
 292		vfio_spapr_pci_eeh_open(vdev->pdev);
 293	}
 294	vdev->refcnt++;
 295error:
 296	mutex_unlock(&driver_lock);
 297	if (ret)
 298		module_put(THIS_MODULE);
 299	return ret;
 300}
 301
 302static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
 303{
 304	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
 305		u8 pin;
 306		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
 307		if (IS_ENABLED(CONFIG_VFIO_PCI_INTX) && pin)
 308			return 1;
 309
 310	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
 311		u8 pos;
 312		u16 flags;
 313
 314		pos = vdev->pdev->msi_cap;
 315		if (pos) {
 316			pci_read_config_word(vdev->pdev,
 317					     pos + PCI_MSI_FLAGS, &flags);
 318			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
 
 319		}
 320	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
 321		u8 pos;
 322		u16 flags;
 323
 324		pos = vdev->pdev->msix_cap;
 325		if (pos) {
 326			pci_read_config_word(vdev->pdev,
 327					     pos + PCI_MSIX_FLAGS, &flags);
 328
 329			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
 330		}
 331	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
 332		if (pci_is_pcie(vdev->pdev))
 333			return 1;
 334	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
 335		return 1;
 336	}
 337
 338	return 0;
 339}
 340
 341static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
 342{
 343	(*(int *)data)++;
 344	return 0;
 345}
 346
 347struct vfio_pci_fill_info {
 348	int max;
 349	int cur;
 350	struct vfio_pci_dependent_device *devices;
 351};
 352
 353static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
 354{
 355	struct vfio_pci_fill_info *fill = data;
 356	struct iommu_group *iommu_group;
 357
 358	if (fill->cur == fill->max)
 359		return -EAGAIN; /* Something changed, try again */
 360
 361	iommu_group = iommu_group_get(&pdev->dev);
 362	if (!iommu_group)
 363		return -EPERM; /* Cannot reset non-isolated devices */
 364
 365	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
 366	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
 367	fill->devices[fill->cur].bus = pdev->bus->number;
 368	fill->devices[fill->cur].devfn = pdev->devfn;
 369	fill->cur++;
 370	iommu_group_put(iommu_group);
 371	return 0;
 372}
 373
 374struct vfio_pci_group_entry {
 375	struct vfio_group *group;
 376	int id;
 377};
 378
 379struct vfio_pci_group_info {
 380	int count;
 381	struct vfio_pci_group_entry *groups;
 382};
 383
 384static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
 385{
 386	struct vfio_pci_group_info *info = data;
 387	struct iommu_group *group;
 388	int id, i;
 389
 390	group = iommu_group_get(&pdev->dev);
 391	if (!group)
 392		return -EPERM;
 393
 394	id = iommu_group_id(group);
 395
 396	for (i = 0; i < info->count; i++)
 397		if (info->groups[i].id == id)
 398			break;
 399
 400	iommu_group_put(group);
 401
 402	return (i == info->count) ? -EINVAL : 0;
 403}
 404
 405static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
 406{
 407	for (; pdev; pdev = pdev->bus->self)
 408		if (pdev->bus == slot->bus)
 409			return (pdev->slot == slot);
 410	return false;
 411}
 412
 413struct vfio_pci_walk_info {
 414	int (*fn)(struct pci_dev *, void *data);
 415	void *data;
 416	struct pci_dev *pdev;
 417	bool slot;
 418	int ret;
 419};
 420
 421static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
 422{
 423	struct vfio_pci_walk_info *walk = data;
 424
 425	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
 426		walk->ret = walk->fn(pdev, walk->data);
 427
 428	return walk->ret;
 429}
 430
 431static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
 432					 int (*fn)(struct pci_dev *,
 433						   void *data), void *data,
 434					 bool slot)
 435{
 436	struct vfio_pci_walk_info walk = {
 437		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
 438	};
 439
 440	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
 441
 442	return walk.ret;
 443}
 444
 445static int msix_sparse_mmap_cap(struct vfio_pci_device *vdev,
 446				struct vfio_info_cap *caps)
 447{
 448	struct vfio_info_cap_header *header;
 449	struct vfio_region_info_cap_sparse_mmap *sparse;
 450	size_t end, size;
 451	int nr_areas = 2, i = 0;
 452
 453	end = pci_resource_len(vdev->pdev, vdev->msix_bar);
 454
 455	/* If MSI-X table is aligned to the start or end, only one area */
 456	if (((vdev->msix_offset & PAGE_MASK) == 0) ||
 457	    (PAGE_ALIGN(vdev->msix_offset + vdev->msix_size) >= end))
 458		nr_areas = 1;
 459
 460	size = sizeof(*sparse) + (nr_areas * sizeof(*sparse->areas));
 461
 462	header = vfio_info_cap_add(caps, size,
 463				   VFIO_REGION_INFO_CAP_SPARSE_MMAP, 1);
 464	if (IS_ERR(header))
 465		return PTR_ERR(header);
 466
 467	sparse = container_of(header,
 468			      struct vfio_region_info_cap_sparse_mmap, header);
 469	sparse->nr_areas = nr_areas;
 470
 471	if (vdev->msix_offset & PAGE_MASK) {
 472		sparse->areas[i].offset = 0;
 473		sparse->areas[i].size = vdev->msix_offset & PAGE_MASK;
 474		i++;
 475	}
 476
 477	if (PAGE_ALIGN(vdev->msix_offset + vdev->msix_size) < end) {
 478		sparse->areas[i].offset = PAGE_ALIGN(vdev->msix_offset +
 479						     vdev->msix_size);
 480		sparse->areas[i].size = end - sparse->areas[i].offset;
 481		i++;
 482	}
 483
 484	return 0;
 485}
 486
 487static int region_type_cap(struct vfio_pci_device *vdev,
 488			   struct vfio_info_cap *caps,
 489			   unsigned int type, unsigned int subtype)
 490{
 491	struct vfio_info_cap_header *header;
 492	struct vfio_region_info_cap_type *cap;
 493
 494	header = vfio_info_cap_add(caps, sizeof(*cap),
 495				   VFIO_REGION_INFO_CAP_TYPE, 1);
 496	if (IS_ERR(header))
 497		return PTR_ERR(header);
 498
 499	cap = container_of(header, struct vfio_region_info_cap_type, header);
 500	cap->type = type;
 501	cap->subtype = subtype;
 502
 503	return 0;
 504}
 505
 506int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
 507				 unsigned int type, unsigned int subtype,
 508				 const struct vfio_pci_regops *ops,
 509				 size_t size, u32 flags, void *data)
 510{
 511	struct vfio_pci_region *region;
 512
 513	region = krealloc(vdev->region,
 514			  (vdev->num_regions + 1) * sizeof(*region),
 515			  GFP_KERNEL);
 516	if (!region)
 517		return -ENOMEM;
 518
 519	vdev->region = region;
 520	vdev->region[vdev->num_regions].type = type;
 521	vdev->region[vdev->num_regions].subtype = subtype;
 522	vdev->region[vdev->num_regions].ops = ops;
 523	vdev->region[vdev->num_regions].size = size;
 524	vdev->region[vdev->num_regions].flags = flags;
 525	vdev->region[vdev->num_regions].data = data;
 526
 527	vdev->num_regions++;
 528
 529	return 0;
 530}
 531
 532static long vfio_pci_ioctl(void *device_data,
 533			   unsigned int cmd, unsigned long arg)
 534{
 535	struct vfio_pci_device *vdev = device_data;
 536	unsigned long minsz;
 537
 538	if (cmd == VFIO_DEVICE_GET_INFO) {
 539		struct vfio_device_info info;
 540
 541		minsz = offsetofend(struct vfio_device_info, num_irqs);
 542
 543		if (copy_from_user(&info, (void __user *)arg, minsz))
 544			return -EFAULT;
 545
 546		if (info.argsz < minsz)
 547			return -EINVAL;
 548
 549		info.flags = VFIO_DEVICE_FLAGS_PCI;
 550
 551		if (vdev->reset_works)
 552			info.flags |= VFIO_DEVICE_FLAGS_RESET;
 553
 554		info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
 555		info.num_irqs = VFIO_PCI_NUM_IRQS;
 556
 557		return copy_to_user((void __user *)arg, &info, minsz) ?
 558			-EFAULT : 0;
 559
 560	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
 561		struct pci_dev *pdev = vdev->pdev;
 562		struct vfio_region_info info;
 563		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
 564		int i, ret;
 565
 566		minsz = offsetofend(struct vfio_region_info, offset);
 567
 568		if (copy_from_user(&info, (void __user *)arg, minsz))
 569			return -EFAULT;
 570
 571		if (info.argsz < minsz)
 572			return -EINVAL;
 573
 574		switch (info.index) {
 575		case VFIO_PCI_CONFIG_REGION_INDEX:
 576			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
 577			info.size = pdev->cfg_size;
 578			info.flags = VFIO_REGION_INFO_FLAG_READ |
 579				     VFIO_REGION_INFO_FLAG_WRITE;
 580			break;
 581		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
 582			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
 583			info.size = pci_resource_len(pdev, info.index);
 584			if (!info.size) {
 585				info.flags = 0;
 586				break;
 587			}
 588
 589			info.flags = VFIO_REGION_INFO_FLAG_READ |
 590				     VFIO_REGION_INFO_FLAG_WRITE;
 591			if (IS_ENABLED(CONFIG_VFIO_PCI_MMAP) &&
 592			    pci_resource_flags(pdev, info.index) &
 593			    IORESOURCE_MEM && info.size >= PAGE_SIZE) {
 594				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
 595				if (info.index == vdev->msix_bar) {
 596					ret = msix_sparse_mmap_cap(vdev, &caps);
 597					if (ret)
 598						return ret;
 599				}
 600			}
 601
 602			break;
 603		case VFIO_PCI_ROM_REGION_INDEX:
 604		{
 605			void __iomem *io;
 606			size_t size;
 607
 608			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
 609			info.flags = 0;
 610
 611			/* Report the BAR size, not the ROM size */
 612			info.size = pci_resource_len(pdev, info.index);
 613			if (!info.size) {
 614				/* Shadow ROMs appear as PCI option ROMs */
 615				if (pdev->resource[PCI_ROM_RESOURCE].flags &
 616							IORESOURCE_ROM_SHADOW)
 617					info.size = 0x20000;
 618				else
 619					break;
 620			}
 621
 622			/* Is it really there? */
 623			io = pci_map_rom(pdev, &size);
 624			if (!io || !size) {
 625				info.size = 0;
 626				break;
 627			}
 628			pci_unmap_rom(pdev, io);
 629
 630			info.flags = VFIO_REGION_INFO_FLAG_READ;
 631			break;
 632		}
 633		case VFIO_PCI_VGA_REGION_INDEX:
 634			if (!vdev->has_vga)
 635				return -EINVAL;
 636
 637			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
 638			info.size = 0xc0000;
 639			info.flags = VFIO_REGION_INFO_FLAG_READ |
 640				     VFIO_REGION_INFO_FLAG_WRITE;
 641
 642			break;
 643		default:
 644			if (info.index >=
 645			    VFIO_PCI_NUM_REGIONS + vdev->num_regions)
 646				return -EINVAL;
 647
 648			i = info.index - VFIO_PCI_NUM_REGIONS;
 649
 650			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
 651			info.size = vdev->region[i].size;
 652			info.flags = vdev->region[i].flags;
 653
 654			ret = region_type_cap(vdev, &caps,
 655					      vdev->region[i].type,
 656					      vdev->region[i].subtype);
 657			if (ret)
 658				return ret;
 659		}
 660
 661		if (caps.size) {
 662			info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
 663			if (info.argsz < sizeof(info) + caps.size) {
 664				info.argsz = sizeof(info) + caps.size;
 665				info.cap_offset = 0;
 666			} else {
 667				vfio_info_cap_shift(&caps, sizeof(info));
 668				if (copy_to_user((void __user *)arg +
 669						  sizeof(info), caps.buf,
 670						  caps.size)) {
 671					kfree(caps.buf);
 672					return -EFAULT;
 673				}
 674				info.cap_offset = sizeof(info);
 675			}
 676
 677			kfree(caps.buf);
 678		}
 679
 680		return copy_to_user((void __user *)arg, &info, minsz) ?
 681			-EFAULT : 0;
 682
 683	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
 684		struct vfio_irq_info info;
 685
 686		minsz = offsetofend(struct vfio_irq_info, count);
 687
 688		if (copy_from_user(&info, (void __user *)arg, minsz))
 689			return -EFAULT;
 690
 691		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
 692			return -EINVAL;
 693
 694		switch (info.index) {
 695		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
 696		case VFIO_PCI_REQ_IRQ_INDEX:
 697			break;
 698		case VFIO_PCI_ERR_IRQ_INDEX:
 699			if (pci_is_pcie(vdev->pdev))
 700				break;
 701		/* pass thru to return error */
 702		default:
 703			return -EINVAL;
 704		}
 705
 706		info.flags = VFIO_IRQ_INFO_EVENTFD;
 707
 708		info.count = vfio_pci_get_irq_count(vdev, info.index);
 709
 710		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
 711			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
 712				       VFIO_IRQ_INFO_AUTOMASKED);
 713		else
 714			info.flags |= VFIO_IRQ_INFO_NORESIZE;
 715
 716		return copy_to_user((void __user *)arg, &info, minsz) ?
 717			-EFAULT : 0;
 718
 719	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
 720		struct vfio_irq_set hdr;
 721		u8 *data = NULL;
 722		int ret = 0;
 723
 724		minsz = offsetofend(struct vfio_irq_set, count);
 725
 726		if (copy_from_user(&hdr, (void __user *)arg, minsz))
 727			return -EFAULT;
 728
 729		if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
 730		    hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
 731				  VFIO_IRQ_SET_ACTION_TYPE_MASK))
 732			return -EINVAL;
 733
 734		if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) {
 735			size_t size;
 736			int max = vfio_pci_get_irq_count(vdev, hdr.index);
 737
 738			if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL)
 739				size = sizeof(uint8_t);
 740			else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD)
 741				size = sizeof(int32_t);
 742			else
 743				return -EINVAL;
 744
 745			if (hdr.argsz - minsz < hdr.count * size ||
 746			    hdr.start >= max || hdr.start + hdr.count > max)
 747				return -EINVAL;
 748
 749			data = memdup_user((void __user *)(arg + minsz),
 750					   hdr.count * size);
 751			if (IS_ERR(data))
 752				return PTR_ERR(data);
 753		}
 754
 755		mutex_lock(&vdev->igate);
 756
 757		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
 758					      hdr.start, hdr.count, data);
 759
 760		mutex_unlock(&vdev->igate);
 761		kfree(data);
 762
 763		return ret;
 764
 765	} else if (cmd == VFIO_DEVICE_RESET) {
 766		return vdev->reset_works ?
 767			pci_try_reset_function(vdev->pdev) : -EINVAL;
 768
 769	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
 770		struct vfio_pci_hot_reset_info hdr;
 771		struct vfio_pci_fill_info fill = { 0 };
 772		struct vfio_pci_dependent_device *devices = NULL;
 773		bool slot = false;
 774		int ret = 0;
 775
 776		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
 777
 778		if (copy_from_user(&hdr, (void __user *)arg, minsz))
 779			return -EFAULT;
 780
 781		if (hdr.argsz < minsz)
 782			return -EINVAL;
 783
 784		hdr.flags = 0;
 785
 786		/* Can we do a slot or bus reset or neither? */
 787		if (!pci_probe_reset_slot(vdev->pdev->slot))
 788			slot = true;
 789		else if (pci_probe_reset_bus(vdev->pdev->bus))
 790			return -ENODEV;
 791
 792		/* How many devices are affected? */
 793		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
 794						    vfio_pci_count_devs,
 795						    &fill.max, slot);
 796		if (ret)
 797			return ret;
 798
 799		WARN_ON(!fill.max); /* Should always be at least one */
 800
 801		/*
 802		 * If there's enough space, fill it now, otherwise return
 803		 * -ENOSPC and the number of devices affected.
 804		 */
 805		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
 806			ret = -ENOSPC;
 807			hdr.count = fill.max;
 808			goto reset_info_exit;
 809		}
 810
 811		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
 812		if (!devices)
 813			return -ENOMEM;
 814
 815		fill.devices = devices;
 816
 817		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
 818						    vfio_pci_fill_devs,
 819						    &fill, slot);
 820
 821		/*
 822		 * If a device was removed between counting and filling,
 823		 * we may come up short of fill.max.  If a device was
 824		 * added, we'll have a return of -EAGAIN above.
 825		 */
 826		if (!ret)
 827			hdr.count = fill.cur;
 828
 829reset_info_exit:
 830		if (copy_to_user((void __user *)arg, &hdr, minsz))
 831			ret = -EFAULT;
 832
 833		if (!ret) {
 834			if (copy_to_user((void __user *)(arg + minsz), devices,
 835					 hdr.count * sizeof(*devices)))
 836				ret = -EFAULT;
 837		}
 838
 839		kfree(devices);
 840		return ret;
 841
 842	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
 843		struct vfio_pci_hot_reset hdr;
 844		int32_t *group_fds;
 845		struct vfio_pci_group_entry *groups;
 846		struct vfio_pci_group_info info;
 847		bool slot = false;
 848		int i, count = 0, ret = 0;
 849
 850		minsz = offsetofend(struct vfio_pci_hot_reset, count);
 851
 852		if (copy_from_user(&hdr, (void __user *)arg, minsz))
 853			return -EFAULT;
 854
 855		if (hdr.argsz < minsz || hdr.flags)
 856			return -EINVAL;
 857
 858		/* Can we do a slot or bus reset or neither? */
 859		if (!pci_probe_reset_slot(vdev->pdev->slot))
 860			slot = true;
 861		else if (pci_probe_reset_bus(vdev->pdev->bus))
 862			return -ENODEV;
 863
 864		/*
 865		 * We can't let userspace give us an arbitrarily large
 866		 * buffer to copy, so verify how many we think there
 867		 * could be.  Note groups can have multiple devices so
 868		 * one group per device is the max.
 869		 */
 870		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
 871						    vfio_pci_count_devs,
 872						    &count, slot);
 873		if (ret)
 874			return ret;
 875
 876		/* Somewhere between 1 and count is OK */
 877		if (!hdr.count || hdr.count > count)
 878			return -EINVAL;
 879
 880		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
 881		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
 882		if (!group_fds || !groups) {
 883			kfree(group_fds);
 884			kfree(groups);
 885			return -ENOMEM;
 886		}
 887
 888		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
 889				   hdr.count * sizeof(*group_fds))) {
 890			kfree(group_fds);
 891			kfree(groups);
 892			return -EFAULT;
 893		}
 894
 895		/*
 896		 * For each group_fd, get the group through the vfio external
 897		 * user interface and store the group and iommu ID.  This
 898		 * ensures the group is held across the reset.
 899		 */
 900		for (i = 0; i < hdr.count; i++) {
 901			struct vfio_group *group;
 902			struct fd f = fdget(group_fds[i]);
 903			if (!f.file) {
 904				ret = -EBADF;
 905				break;
 906			}
 907
 908			group = vfio_group_get_external_user(f.file);
 909			fdput(f);
 910			if (IS_ERR(group)) {
 911				ret = PTR_ERR(group);
 912				break;
 913			}
 914
 915			groups[i].group = group;
 916			groups[i].id = vfio_external_user_iommu_id(group);
 917		}
 918
 919		kfree(group_fds);
 920
 921		/* release reference to groups on error */
 922		if (ret)
 923			goto hot_reset_release;
 924
 925		info.count = hdr.count;
 926		info.groups = groups;
 927
 928		/*
 929		 * Test whether all the affected devices are contained
 930		 * by the set of groups provided by the user.
 931		 */
 932		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
 933						    vfio_pci_validate_devs,
 934						    &info, slot);
 935		if (!ret)
 936			/* User has access, do the reset */
 937			ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
 938				     pci_try_reset_bus(vdev->pdev->bus);
 939
 940hot_reset_release:
 941		for (i--; i >= 0; i--)
 942			vfio_group_put_external_user(groups[i].group);
 943
 944		kfree(groups);
 945		return ret;
 946	}
 947
 948	return -ENOTTY;
 949}
 950
 951static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
 952			   size_t count, loff_t *ppos, bool iswrite)
 953{
 954	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
 955	struct vfio_pci_device *vdev = device_data;
 956
 957	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
 958		return -EINVAL;
 959
 960	switch (index) {
 961	case VFIO_PCI_CONFIG_REGION_INDEX:
 962		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
 963
 964	case VFIO_PCI_ROM_REGION_INDEX:
 965		if (iswrite)
 966			return -EINVAL;
 967		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
 968
 969	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
 970		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
 971
 972	case VFIO_PCI_VGA_REGION_INDEX:
 973		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
 974	default:
 975		index -= VFIO_PCI_NUM_REGIONS;
 976		return vdev->region[index].ops->rw(vdev, buf,
 977						   count, ppos, iswrite);
 978	}
 979
 980	return -EINVAL;
 981}
 982
 983static ssize_t vfio_pci_read(void *device_data, char __user *buf,
 984			     size_t count, loff_t *ppos)
 985{
 986	if (!count)
 987		return 0;
 988
 989	return vfio_pci_rw(device_data, buf, count, ppos, false);
 990}
 991
 992static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
 993			      size_t count, loff_t *ppos)
 994{
 995	if (!count)
 996		return 0;
 997
 998	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
 999}
1000
1001static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1002{
1003	struct vfio_pci_device *vdev = device_data;
1004	struct pci_dev *pdev = vdev->pdev;
1005	unsigned int index;
1006	u64 phys_len, req_len, pgoff, req_start;
1007	int ret;
1008
1009	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1010
1011	if (vma->vm_end < vma->vm_start)
1012		return -EINVAL;
1013	if ((vma->vm_flags & VM_SHARED) == 0)
1014		return -EINVAL;
1015	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1016		return -EINVAL;
1017	if (!(pci_resource_flags(pdev, index) & IORESOURCE_MEM))
1018		return -EINVAL;
1019
1020	phys_len = pci_resource_len(pdev, index);
1021	req_len = vma->vm_end - vma->vm_start;
1022	pgoff = vma->vm_pgoff &
1023		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1024	req_start = pgoff << PAGE_SHIFT;
1025
1026	if (phys_len < PAGE_SIZE || req_start + req_len > phys_len)
1027		return -EINVAL;
1028
1029	if (index == vdev->msix_bar) {
1030		/*
1031		 * Disallow mmaps overlapping the MSI-X table; users don't
1032		 * get to touch this directly.  We could find somewhere
1033		 * else to map the overlap, but page granularity is only
1034		 * a recommendation, not a requirement, so the user needs
1035		 * to know which bits are real.  Requiring them to mmap
1036		 * around the table makes that clear.
1037		 */
1038
1039		/* If neither entirely above nor below, then it overlaps */
1040		if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
1041		      req_start + req_len <= vdev->msix_offset))
1042			return -EINVAL;
1043	}
1044
1045	/*
1046	 * Even though we don't make use of the barmap for the mmap,
1047	 * we need to request the region and the barmap tracks that.
1048	 */
1049	if (!vdev->barmap[index]) {
1050		ret = pci_request_selected_regions(pdev,
1051						   1 << index, "vfio-pci");
1052		if (ret)
1053			return ret;
1054
1055		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1056	}
1057
1058	vma->vm_private_data = vdev;
1059	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1060	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1061
1062	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1063			       req_len, vma->vm_page_prot);
1064}
1065
1066static void vfio_pci_request(void *device_data, unsigned int count)
1067{
1068	struct vfio_pci_device *vdev = device_data;
1069
1070	mutex_lock(&vdev->igate);
1071
1072	if (vdev->req_trigger) {
1073		if (!(count % 10))
1074			dev_notice_ratelimited(&vdev->pdev->dev,
1075				"Relaying device request to user (#%u)\n",
1076				count);
1077		eventfd_signal(vdev->req_trigger, 1);
1078	} else if (count == 0) {
1079		dev_warn(&vdev->pdev->dev,
1080			"No device request channel registered, blocked until released by user\n");
1081	}
1082
1083	mutex_unlock(&vdev->igate);
1084}
1085
1086static const struct vfio_device_ops vfio_pci_ops = {
1087	.name		= "vfio-pci",
1088	.open		= vfio_pci_open,
1089	.release	= vfio_pci_release,
1090	.ioctl		= vfio_pci_ioctl,
1091	.read		= vfio_pci_read,
1092	.write		= vfio_pci_write,
1093	.mmap		= vfio_pci_mmap,
1094	.request	= vfio_pci_request,
1095};
1096
1097static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1098{
 
1099	struct vfio_pci_device *vdev;
1100	struct iommu_group *group;
1101	int ret;
1102
1103	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
 
1104		return -EINVAL;
1105
1106	group = vfio_iommu_group_get(&pdev->dev);
1107	if (!group)
1108		return -EINVAL;
1109
1110	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1111	if (!vdev) {
1112		vfio_iommu_group_put(group, &pdev->dev);
1113		return -ENOMEM;
1114	}
1115
1116	vdev->pdev = pdev;
1117	vdev->irq_type = VFIO_PCI_NUM_IRQS;
1118	mutex_init(&vdev->igate);
1119	spin_lock_init(&vdev->irqlock);
 
1120
1121	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1122	if (ret) {
1123		vfio_iommu_group_put(group, &pdev->dev);
1124		kfree(vdev);
1125		return ret;
1126	}
1127
1128	if (vfio_pci_is_vga(pdev)) {
1129		vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1130		vga_set_legacy_decoding(pdev,
1131					vfio_pci_set_vga_decode(vdev, false));
1132	}
1133
1134	if (!disable_idle_d3) {
1135		/*
1136		 * pci-core sets the device power state to an unknown value at
1137		 * bootup and after being removed from a driver.  The only
1138		 * transition it allows from this unknown state is to D0, which
1139		 * typically happens when a driver calls pci_enable_device().
1140		 * We're not ready to enable the device yet, but we do want to
1141		 * be able to get to D3.  Therefore first do a D0 transition
1142		 * before going to D3.
1143		 */
1144		pci_set_power_state(pdev, PCI_D0);
1145		pci_set_power_state(pdev, PCI_D3hot);
1146	}
1147
1148	return ret;
1149}
1150
1151static void vfio_pci_remove(struct pci_dev *pdev)
1152{
1153	struct vfio_pci_device *vdev;
1154
1155	vdev = vfio_del_group_dev(&pdev->dev);
1156	if (!vdev)
1157		return;
1158
1159	vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1160	kfree(vdev->region);
1161	kfree(vdev);
1162
1163	if (vfio_pci_is_vga(pdev)) {
1164		vga_client_register(pdev, NULL, NULL, NULL);
1165		vga_set_legacy_decoding(pdev,
1166				VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1167				VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1168	}
1169
1170	if (!disable_idle_d3)
1171		pci_set_power_state(pdev, PCI_D0);
1172}
1173
1174static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1175						  pci_channel_state_t state)
1176{
1177	struct vfio_pci_device *vdev;
1178	struct vfio_device *device;
1179
1180	device = vfio_device_get_from_dev(&pdev->dev);
1181	if (device == NULL)
1182		return PCI_ERS_RESULT_DISCONNECT;
1183
1184	vdev = vfio_device_data(device);
1185	if (vdev == NULL) {
1186		vfio_device_put(device);
1187		return PCI_ERS_RESULT_DISCONNECT;
1188	}
1189
1190	mutex_lock(&vdev->igate);
1191
1192	if (vdev->err_trigger)
1193		eventfd_signal(vdev->err_trigger, 1);
1194
1195	mutex_unlock(&vdev->igate);
1196
1197	vfio_device_put(device);
1198
1199	return PCI_ERS_RESULT_CAN_RECOVER;
1200}
1201
1202static const struct pci_error_handlers vfio_err_handlers = {
1203	.error_detected = vfio_pci_aer_err_detected,
1204};
1205
1206static struct pci_driver vfio_pci_driver = {
1207	.name		= "vfio-pci",
1208	.id_table	= NULL, /* only dynamic ids */
1209	.probe		= vfio_pci_probe,
1210	.remove		= vfio_pci_remove,
1211	.err_handler	= &vfio_err_handlers,
1212};
1213
1214struct vfio_devices {
1215	struct vfio_device **devices;
1216	int cur_index;
1217	int max_index;
1218};
1219
1220static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
1221{
1222	struct vfio_devices *devs = data;
1223	struct vfio_device *device;
1224
1225	if (devs->cur_index == devs->max_index)
1226		return -ENOSPC;
1227
1228	device = vfio_device_get_from_dev(&pdev->dev);
1229	if (!device)
1230		return -EINVAL;
1231
1232	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1233		vfio_device_put(device);
1234		return -EBUSY;
1235	}
1236
1237	devs->devices[devs->cur_index++] = device;
1238	return 0;
1239}
1240
1241/*
1242 * Attempt to do a bus/slot reset if there are devices affected by a reset for
1243 * this device that are needs_reset and all of the affected devices are unused
1244 * (!refcnt).  Callers are required to hold driver_lock when calling this to
1245 * prevent device opens and concurrent bus reset attempts.  We prevent device
1246 * unbinds by acquiring and holding a reference to the vfio_device.
1247 *
1248 * NB: vfio-core considers a group to be viable even if some devices are
1249 * bound to drivers like pci-stub or pcieport.  Here we require all devices
1250 * to be bound to vfio_pci since that's the only way we can be sure they
1251 * stay put.
1252 */
1253static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1254{
1255	struct vfio_devices devs = { .cur_index = 0 };
1256	int i = 0, ret = -EINVAL;
1257	bool needs_reset = false, slot = false;
1258	struct vfio_pci_device *tmp;
1259
1260	if (!pci_probe_reset_slot(vdev->pdev->slot))
1261		slot = true;
1262	else if (pci_probe_reset_bus(vdev->pdev->bus))
1263		return;
1264
1265	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1266					  &i, slot) || !i)
1267		return;
1268
1269	devs.max_index = i;
1270	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1271	if (!devs.devices)
1272		return;
1273
1274	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1275					  vfio_pci_get_devs, &devs, slot))
1276		goto put_devs;
1277
1278	for (i = 0; i < devs.cur_index; i++) {
1279		tmp = vfio_device_data(devs.devices[i]);
1280		if (tmp->needs_reset)
1281			needs_reset = true;
1282		if (tmp->refcnt)
1283			goto put_devs;
1284	}
1285
1286	if (needs_reset)
1287		ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1288			     pci_try_reset_bus(vdev->pdev->bus);
1289
1290put_devs:
1291	for (i = 0; i < devs.cur_index; i++) {
1292		tmp = vfio_device_data(devs.devices[i]);
1293		if (!ret)
1294			tmp->needs_reset = false;
1295
1296		if (!tmp->refcnt && !disable_idle_d3)
1297			pci_set_power_state(tmp->pdev, PCI_D3hot);
1298
1299		vfio_device_put(devs.devices[i]);
1300	}
1301
1302	kfree(devs.devices);
1303}
1304
1305static void __exit vfio_pci_cleanup(void)
1306{
1307	pci_unregister_driver(&vfio_pci_driver);
 
1308	vfio_pci_uninit_perm_bits();
1309}
1310
1311static void __init vfio_pci_fill_ids(void)
1312{
1313	char *p, *id;
1314	int rc;
1315
1316	/* no ids passed actually */
1317	if (ids[0] == '\0')
1318		return;
1319
1320	/* add ids specified in the module parameter */
1321	p = ids;
1322	while ((id = strsep(&p, ","))) {
1323		unsigned int vendor, device, subvendor = PCI_ANY_ID,
1324			subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1325		int fields;
1326
1327		if (!strlen(id))
1328			continue;
1329
1330		fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1331				&vendor, &device, &subvendor, &subdevice,
1332				&class, &class_mask);
1333
1334		if (fields < 2) {
1335			pr_warn("invalid id string \"%s\"\n", id);
1336			continue;
1337		}
1338
1339		rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1340				   subvendor, subdevice, class, class_mask, 0);
1341		if (rc)
1342			pr_warn("failed to add dynamic id [%04hx:%04hx[%04hx:%04hx]] class %#08x/%08x (%d)\n",
1343				vendor, device, subvendor, subdevice,
1344				class, class_mask, rc);
1345		else
1346			pr_info("add [%04hx:%04hx[%04hx:%04hx]] class %#08x/%08x\n",
1347				vendor, device, subvendor, subdevice,
1348				class, class_mask);
1349	}
1350}
1351
1352static int __init vfio_pci_init(void)
1353{
1354	int ret;
1355
1356	/* Allocate shared config space permision data used by all devices */
1357	ret = vfio_pci_init_perm_bits();
1358	if (ret)
1359		return ret;
1360
 
 
 
 
 
1361	/* Register and scan for devices */
1362	ret = pci_register_driver(&vfio_pci_driver);
1363	if (ret)
1364		goto out_driver;
1365
1366	vfio_pci_fill_ids();
1367
1368	return 0;
1369
1370out_driver:
 
 
1371	vfio_pci_uninit_perm_bits();
1372	return ret;
1373}
1374
1375module_init(vfio_pci_init);
1376module_exit(vfio_pci_cleanup);
1377
1378MODULE_VERSION(DRIVER_VERSION);
1379MODULE_LICENSE("GPL v2");
1380MODULE_AUTHOR(DRIVER_AUTHOR);
1381MODULE_DESCRIPTION(DRIVER_DESC);
v3.15
  1/*
  2 * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
  3 *     Author: Alex Williamson <alex.williamson@redhat.com>
  4 *
  5 * This program is free software; you can redistribute it and/or modify
  6 * it under the terms of the GNU General Public License version 2 as
  7 * published by the Free Software Foundation.
  8 *
  9 * Derived from original vfio:
 10 * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
 11 * Author: Tom Lyon, pugs@cisco.com
 12 */
 13
 
 
 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/vfio.h>
 
 28
 29#include "vfio_pci_private.h"
 30
 31#define DRIVER_VERSION  "0.2"
 32#define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
 33#define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
 34
 
 
 
 
 35static bool nointxmask;
 36module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
 37MODULE_PARM_DESC(nointxmask,
 38		  "Disable support for PCI 2.3 style INTx masking.  If this resolves problems for specific devices, report lspci -vvvxxx to linux-pci@vger.kernel.org so the device can be fixed automatically via the broken_intx_masking flag.");
 39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 40static int vfio_pci_enable(struct vfio_pci_device *vdev)
 41{
 42	struct pci_dev *pdev = vdev->pdev;
 43	int ret;
 44	u16 cmd;
 45	u8 msix_pos;
 46
 
 
 
 
 
 47	ret = pci_enable_device(pdev);
 48	if (ret)
 49		return ret;
 50
 51	vdev->reset_works = (pci_reset_function(pdev) == 0);
 52	pci_save_state(pdev);
 53	vdev->pci_saved_state = pci_store_saved_state(pdev);
 54	if (!vdev->pci_saved_state)
 55		pr_debug("%s: Couldn't store %s saved state\n",
 56			 __func__, dev_name(&pdev->dev));
 57
 58	ret = vfio_config_init(vdev);
 59	if (ret) {
 60		pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state);
 
 61		pci_disable_device(pdev);
 62		return ret;
 63	}
 64
 65	if (likely(!nointxmask))
 66		vdev->pci_2_3 = pci_intx_mask_supported(pdev);
 67
 68	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
 69	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
 70		cmd &= ~PCI_COMMAND_INTX_DISABLE;
 71		pci_write_config_word(pdev, PCI_COMMAND, cmd);
 72	}
 73
 74	msix_pos = pdev->msix_cap;
 75	if (msix_pos) {
 76		u16 flags;
 77		u32 table;
 78
 79		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
 80		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
 81
 82		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
 83		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
 84		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
 85	} else
 86		vdev->msix_bar = 0xFF;
 87
 88#ifdef CONFIG_VFIO_PCI_VGA
 89	if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
 90		vdev->has_vga = true;
 91#endif
 
 
 
 
 
 
 
 
 
 
 
 
 92
 93	return 0;
 94}
 95
 96static void vfio_pci_disable(struct vfio_pci_device *vdev)
 97{
 98	struct pci_dev *pdev = vdev->pdev;
 99	int bar;
100
101	pci_disable_device(pdev);
 
102
103	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
104				VFIO_IRQ_SET_ACTION_TRIGGER,
105				vdev->irq_type, 0, 0, NULL);
106
107	vdev->virq_disabled = false;
108
 
 
 
 
 
 
 
109	vfio_config_free(vdev);
110
111	for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
112		if (!vdev->barmap[bar])
113			continue;
114		pci_iounmap(pdev, vdev->barmap[bar]);
115		pci_release_selected_regions(pdev, 1 << bar);
116		vdev->barmap[bar] = NULL;
117	}
118
 
 
119	/*
120	 * If we have saved state, restore it.  If we can reset the device,
121	 * even better.  Resetting with current state seems better than
122	 * nothing, but saving and restoring current state without reset
123	 * is just busy work.
124	 */
125	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
126		pr_info("%s: Couldn't reload %s saved state\n",
127			__func__, dev_name(&pdev->dev));
128
129		if (!vdev->reset_works)
130			return;
131
132		pci_save_state(pdev);
133	}
134
135	/*
136	 * Disable INTx and MSI, presumably to avoid spurious interrupts
137	 * during reset.  Stolen from pci_reset_function()
138	 */
139	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
140
141	/*
142	 * Try to reset the device.  The success of this is dependent on
143	 * being able to lock the device, which is not always possible.
144	 */
145	if (vdev->reset_works) {
146		int ret = pci_try_reset_function(pdev);
147		if (ret)
148			pr_warn("%s: Failed to reset device %s (%d)\n",
149				__func__, dev_name(&pdev->dev), ret);
150	}
151
152	pci_restore_state(pdev);
 
 
 
 
 
 
 
153}
154
155static void vfio_pci_release(void *device_data)
156{
157	struct vfio_pci_device *vdev = device_data;
158
159	if (atomic_dec_and_test(&vdev->refcnt))
 
 
 
160		vfio_pci_disable(vdev);
 
 
 
161
162	module_put(THIS_MODULE);
163}
164
165static int vfio_pci_open(void *device_data)
166{
167	struct vfio_pci_device *vdev = device_data;
 
168
169	if (!try_module_get(THIS_MODULE))
170		return -ENODEV;
171
172	if (atomic_inc_return(&vdev->refcnt) == 1) {
173		int ret = vfio_pci_enable(vdev);
174		if (ret) {
175			module_put(THIS_MODULE);
176			return ret;
177		}
 
 
178	}
179
180	return 0;
 
 
 
 
181}
182
183static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
184{
185	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
186		u8 pin;
187		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
188		if (pin)
189			return 1;
190
191	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
192		u8 pos;
193		u16 flags;
194
195		pos = vdev->pdev->msi_cap;
196		if (pos) {
197			pci_read_config_word(vdev->pdev,
198					     pos + PCI_MSI_FLAGS, &flags);
199
200			return 1 << (flags & PCI_MSI_FLAGS_QMASK);
201		}
202	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
203		u8 pos;
204		u16 flags;
205
206		pos = vdev->pdev->msix_cap;
207		if (pos) {
208			pci_read_config_word(vdev->pdev,
209					     pos + PCI_MSIX_FLAGS, &flags);
210
211			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
212		}
213	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX)
214		if (pci_is_pcie(vdev->pdev))
215			return 1;
 
 
 
216
217	return 0;
218}
219
220static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
221{
222	(*(int *)data)++;
223	return 0;
224}
225
226struct vfio_pci_fill_info {
227	int max;
228	int cur;
229	struct vfio_pci_dependent_device *devices;
230};
231
232static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
233{
234	struct vfio_pci_fill_info *fill = data;
235	struct iommu_group *iommu_group;
236
237	if (fill->cur == fill->max)
238		return -EAGAIN; /* Something changed, try again */
239
240	iommu_group = iommu_group_get(&pdev->dev);
241	if (!iommu_group)
242		return -EPERM; /* Cannot reset non-isolated devices */
243
244	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
245	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
246	fill->devices[fill->cur].bus = pdev->bus->number;
247	fill->devices[fill->cur].devfn = pdev->devfn;
248	fill->cur++;
249	iommu_group_put(iommu_group);
250	return 0;
251}
252
253struct vfio_pci_group_entry {
254	struct vfio_group *group;
255	int id;
256};
257
258struct vfio_pci_group_info {
259	int count;
260	struct vfio_pci_group_entry *groups;
261};
262
263static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
264{
265	struct vfio_pci_group_info *info = data;
266	struct iommu_group *group;
267	int id, i;
268
269	group = iommu_group_get(&pdev->dev);
270	if (!group)
271		return -EPERM;
272
273	id = iommu_group_id(group);
274
275	for (i = 0; i < info->count; i++)
276		if (info->groups[i].id == id)
277			break;
278
279	iommu_group_put(group);
280
281	return (i == info->count) ? -EINVAL : 0;
282}
283
284static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
285{
286	for (; pdev; pdev = pdev->bus->self)
287		if (pdev->bus == slot->bus)
288			return (pdev->slot == slot);
289	return false;
290}
291
292struct vfio_pci_walk_info {
293	int (*fn)(struct pci_dev *, void *data);
294	void *data;
295	struct pci_dev *pdev;
296	bool slot;
297	int ret;
298};
299
300static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
301{
302	struct vfio_pci_walk_info *walk = data;
303
304	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
305		walk->ret = walk->fn(pdev, walk->data);
306
307	return walk->ret;
308}
309
310static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
311					 int (*fn)(struct pci_dev *,
312						   void *data), void *data,
313					 bool slot)
314{
315	struct vfio_pci_walk_info walk = {
316		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
317	};
318
319	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
320
321	return walk.ret;
322}
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324static long vfio_pci_ioctl(void *device_data,
325			   unsigned int cmd, unsigned long arg)
326{
327	struct vfio_pci_device *vdev = device_data;
328	unsigned long minsz;
329
330	if (cmd == VFIO_DEVICE_GET_INFO) {
331		struct vfio_device_info info;
332
333		minsz = offsetofend(struct vfio_device_info, num_irqs);
334
335		if (copy_from_user(&info, (void __user *)arg, minsz))
336			return -EFAULT;
337
338		if (info.argsz < minsz)
339			return -EINVAL;
340
341		info.flags = VFIO_DEVICE_FLAGS_PCI;
342
343		if (vdev->reset_works)
344			info.flags |= VFIO_DEVICE_FLAGS_RESET;
345
346		info.num_regions = VFIO_PCI_NUM_REGIONS;
347		info.num_irqs = VFIO_PCI_NUM_IRQS;
348
349		return copy_to_user((void __user *)arg, &info, minsz);
 
350
351	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
352		struct pci_dev *pdev = vdev->pdev;
353		struct vfio_region_info info;
 
 
354
355		minsz = offsetofend(struct vfio_region_info, offset);
356
357		if (copy_from_user(&info, (void __user *)arg, minsz))
358			return -EFAULT;
359
360		if (info.argsz < minsz)
361			return -EINVAL;
362
363		switch (info.index) {
364		case VFIO_PCI_CONFIG_REGION_INDEX:
365			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
366			info.size = pdev->cfg_size;
367			info.flags = VFIO_REGION_INFO_FLAG_READ |
368				     VFIO_REGION_INFO_FLAG_WRITE;
369			break;
370		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
371			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
372			info.size = pci_resource_len(pdev, info.index);
373			if (!info.size) {
374				info.flags = 0;
375				break;
376			}
377
378			info.flags = VFIO_REGION_INFO_FLAG_READ |
379				     VFIO_REGION_INFO_FLAG_WRITE;
380			if (pci_resource_flags(pdev, info.index) &
381			    IORESOURCE_MEM && info.size >= PAGE_SIZE)
 
382				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
 
 
 
 
 
 
 
383			break;
384		case VFIO_PCI_ROM_REGION_INDEX:
385		{
386			void __iomem *io;
387			size_t size;
388
389			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
390			info.flags = 0;
391
392			/* Report the BAR size, not the ROM size */
393			info.size = pci_resource_len(pdev, info.index);
394			if (!info.size)
395				break;
 
 
 
 
 
 
396
397			/* Is it really there? */
398			io = pci_map_rom(pdev, &size);
399			if (!io || !size) {
400				info.size = 0;
401				break;
402			}
403			pci_unmap_rom(pdev, io);
404
405			info.flags = VFIO_REGION_INFO_FLAG_READ;
406			break;
407		}
408		case VFIO_PCI_VGA_REGION_INDEX:
409			if (!vdev->has_vga)
410				return -EINVAL;
411
412			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
413			info.size = 0xc0000;
414			info.flags = VFIO_REGION_INFO_FLAG_READ |
415				     VFIO_REGION_INFO_FLAG_WRITE;
416
417			break;
418		default:
419			return -EINVAL;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420		}
421
422		return copy_to_user((void __user *)arg, &info, minsz);
 
423
424	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
425		struct vfio_irq_info info;
426
427		minsz = offsetofend(struct vfio_irq_info, count);
428
429		if (copy_from_user(&info, (void __user *)arg, minsz))
430			return -EFAULT;
431
432		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
433			return -EINVAL;
434
435		switch (info.index) {
436		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
 
437			break;
438		case VFIO_PCI_ERR_IRQ_INDEX:
439			if (pci_is_pcie(vdev->pdev))
440				break;
441		/* pass thru to return error */
442		default:
443			return -EINVAL;
444		}
445
446		info.flags = VFIO_IRQ_INFO_EVENTFD;
447
448		info.count = vfio_pci_get_irq_count(vdev, info.index);
449
450		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
451			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
452				       VFIO_IRQ_INFO_AUTOMASKED);
453		else
454			info.flags |= VFIO_IRQ_INFO_NORESIZE;
455
456		return copy_to_user((void __user *)arg, &info, minsz);
 
457
458	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
459		struct vfio_irq_set hdr;
460		u8 *data = NULL;
461		int ret = 0;
462
463		minsz = offsetofend(struct vfio_irq_set, count);
464
465		if (copy_from_user(&hdr, (void __user *)arg, minsz))
466			return -EFAULT;
467
468		if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
469		    hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
470				  VFIO_IRQ_SET_ACTION_TYPE_MASK))
471			return -EINVAL;
472
473		if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) {
474			size_t size;
475			int max = vfio_pci_get_irq_count(vdev, hdr.index);
476
477			if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL)
478				size = sizeof(uint8_t);
479			else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD)
480				size = sizeof(int32_t);
481			else
482				return -EINVAL;
483
484			if (hdr.argsz - minsz < hdr.count * size ||
485			    hdr.start >= max || hdr.start + hdr.count > max)
486				return -EINVAL;
487
488			data = memdup_user((void __user *)(arg + minsz),
489					   hdr.count * size);
490			if (IS_ERR(data))
491				return PTR_ERR(data);
492		}
493
494		mutex_lock(&vdev->igate);
495
496		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
497					      hdr.start, hdr.count, data);
498
499		mutex_unlock(&vdev->igate);
500		kfree(data);
501
502		return ret;
503
504	} else if (cmd == VFIO_DEVICE_RESET) {
505		return vdev->reset_works ?
506			pci_try_reset_function(vdev->pdev) : -EINVAL;
507
508	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
509		struct vfio_pci_hot_reset_info hdr;
510		struct vfio_pci_fill_info fill = { 0 };
511		struct vfio_pci_dependent_device *devices = NULL;
512		bool slot = false;
513		int ret = 0;
514
515		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
516
517		if (copy_from_user(&hdr, (void __user *)arg, minsz))
518			return -EFAULT;
519
520		if (hdr.argsz < minsz)
521			return -EINVAL;
522
523		hdr.flags = 0;
524
525		/* Can we do a slot or bus reset or neither? */
526		if (!pci_probe_reset_slot(vdev->pdev->slot))
527			slot = true;
528		else if (pci_probe_reset_bus(vdev->pdev->bus))
529			return -ENODEV;
530
531		/* How many devices are affected? */
532		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
533						    vfio_pci_count_devs,
534						    &fill.max, slot);
535		if (ret)
536			return ret;
537
538		WARN_ON(!fill.max); /* Should always be at least one */
539
540		/*
541		 * If there's enough space, fill it now, otherwise return
542		 * -ENOSPC and the number of devices affected.
543		 */
544		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
545			ret = -ENOSPC;
546			hdr.count = fill.max;
547			goto reset_info_exit;
548		}
549
550		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
551		if (!devices)
552			return -ENOMEM;
553
554		fill.devices = devices;
555
556		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
557						    vfio_pci_fill_devs,
558						    &fill, slot);
559
560		/*
561		 * If a device was removed between counting and filling,
562		 * we may come up short of fill.max.  If a device was
563		 * added, we'll have a return of -EAGAIN above.
564		 */
565		if (!ret)
566			hdr.count = fill.cur;
567
568reset_info_exit:
569		if (copy_to_user((void __user *)arg, &hdr, minsz))
570			ret = -EFAULT;
571
572		if (!ret) {
573			if (copy_to_user((void __user *)(arg + minsz), devices,
574					 hdr.count * sizeof(*devices)))
575				ret = -EFAULT;
576		}
577
578		kfree(devices);
579		return ret;
580
581	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
582		struct vfio_pci_hot_reset hdr;
583		int32_t *group_fds;
584		struct vfio_pci_group_entry *groups;
585		struct vfio_pci_group_info info;
586		bool slot = false;
587		int i, count = 0, ret = 0;
588
589		minsz = offsetofend(struct vfio_pci_hot_reset, count);
590
591		if (copy_from_user(&hdr, (void __user *)arg, minsz))
592			return -EFAULT;
593
594		if (hdr.argsz < minsz || hdr.flags)
595			return -EINVAL;
596
597		/* Can we do a slot or bus reset or neither? */
598		if (!pci_probe_reset_slot(vdev->pdev->slot))
599			slot = true;
600		else if (pci_probe_reset_bus(vdev->pdev->bus))
601			return -ENODEV;
602
603		/*
604		 * We can't let userspace give us an arbitrarily large
605		 * buffer to copy, so verify how many we think there
606		 * could be.  Note groups can have multiple devices so
607		 * one group per device is the max.
608		 */
609		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
610						    vfio_pci_count_devs,
611						    &count, slot);
612		if (ret)
613			return ret;
614
615		/* Somewhere between 1 and count is OK */
616		if (!hdr.count || hdr.count > count)
617			return -EINVAL;
618
619		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
620		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
621		if (!group_fds || !groups) {
622			kfree(group_fds);
623			kfree(groups);
624			return -ENOMEM;
625		}
626
627		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
628				   hdr.count * sizeof(*group_fds))) {
629			kfree(group_fds);
630			kfree(groups);
631			return -EFAULT;
632		}
633
634		/*
635		 * For each group_fd, get the group through the vfio external
636		 * user interface and store the group and iommu ID.  This
637		 * ensures the group is held across the reset.
638		 */
639		for (i = 0; i < hdr.count; i++) {
640			struct vfio_group *group;
641			struct fd f = fdget(group_fds[i]);
642			if (!f.file) {
643				ret = -EBADF;
644				break;
645			}
646
647			group = vfio_group_get_external_user(f.file);
648			fdput(f);
649			if (IS_ERR(group)) {
650				ret = PTR_ERR(group);
651				break;
652			}
653
654			groups[i].group = group;
655			groups[i].id = vfio_external_user_iommu_id(group);
656		}
657
658		kfree(group_fds);
659
660		/* release reference to groups on error */
661		if (ret)
662			goto hot_reset_release;
663
664		info.count = hdr.count;
665		info.groups = groups;
666
667		/*
668		 * Test whether all the affected devices are contained
669		 * by the set of groups provided by the user.
670		 */
671		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
672						    vfio_pci_validate_devs,
673						    &info, slot);
674		if (!ret)
675			/* User has access, do the reset */
676			ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
677				     pci_try_reset_bus(vdev->pdev->bus);
678
679hot_reset_release:
680		for (i--; i >= 0; i--)
681			vfio_group_put_external_user(groups[i].group);
682
683		kfree(groups);
684		return ret;
685	}
686
687	return -ENOTTY;
688}
689
690static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
691			   size_t count, loff_t *ppos, bool iswrite)
692{
693	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
694	struct vfio_pci_device *vdev = device_data;
695
696	if (index >= VFIO_PCI_NUM_REGIONS)
697		return -EINVAL;
698
699	switch (index) {
700	case VFIO_PCI_CONFIG_REGION_INDEX:
701		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
702
703	case VFIO_PCI_ROM_REGION_INDEX:
704		if (iswrite)
705			return -EINVAL;
706		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
707
708	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
709		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
710
711	case VFIO_PCI_VGA_REGION_INDEX:
712		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
 
 
 
 
713	}
714
715	return -EINVAL;
716}
717
718static ssize_t vfio_pci_read(void *device_data, char __user *buf,
719			     size_t count, loff_t *ppos)
720{
721	if (!count)
722		return 0;
723
724	return vfio_pci_rw(device_data, buf, count, ppos, false);
725}
726
727static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
728			      size_t count, loff_t *ppos)
729{
730	if (!count)
731		return 0;
732
733	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
734}
735
736static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
737{
738	struct vfio_pci_device *vdev = device_data;
739	struct pci_dev *pdev = vdev->pdev;
740	unsigned int index;
741	u64 phys_len, req_len, pgoff, req_start;
742	int ret;
743
744	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
745
746	if (vma->vm_end < vma->vm_start)
747		return -EINVAL;
748	if ((vma->vm_flags & VM_SHARED) == 0)
749		return -EINVAL;
750	if (index >= VFIO_PCI_ROM_REGION_INDEX)
751		return -EINVAL;
752	if (!(pci_resource_flags(pdev, index) & IORESOURCE_MEM))
753		return -EINVAL;
754
755	phys_len = pci_resource_len(pdev, index);
756	req_len = vma->vm_end - vma->vm_start;
757	pgoff = vma->vm_pgoff &
758		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
759	req_start = pgoff << PAGE_SHIFT;
760
761	if (phys_len < PAGE_SIZE || req_start + req_len > phys_len)
762		return -EINVAL;
763
764	if (index == vdev->msix_bar) {
765		/*
766		 * Disallow mmaps overlapping the MSI-X table; users don't
767		 * get to touch this directly.  We could find somewhere
768		 * else to map the overlap, but page granularity is only
769		 * a recommendation, not a requirement, so the user needs
770		 * to know which bits are real.  Requiring them to mmap
771		 * around the table makes that clear.
772		 */
773
774		/* If neither entirely above nor below, then it overlaps */
775		if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
776		      req_start + req_len <= vdev->msix_offset))
777			return -EINVAL;
778	}
779
780	/*
781	 * Even though we don't make use of the barmap for the mmap,
782	 * we need to request the region and the barmap tracks that.
783	 */
784	if (!vdev->barmap[index]) {
785		ret = pci_request_selected_regions(pdev,
786						   1 << index, "vfio-pci");
787		if (ret)
788			return ret;
789
790		vdev->barmap[index] = pci_iomap(pdev, index, 0);
791	}
792
793	vma->vm_private_data = vdev;
794	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
795	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
796
797	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
798			       req_len, vma->vm_page_prot);
799}
800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801static const struct vfio_device_ops vfio_pci_ops = {
802	.name		= "vfio-pci",
803	.open		= vfio_pci_open,
804	.release	= vfio_pci_release,
805	.ioctl		= vfio_pci_ioctl,
806	.read		= vfio_pci_read,
807	.write		= vfio_pci_write,
808	.mmap		= vfio_pci_mmap,
 
809};
810
811static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
812{
813	u8 type;
814	struct vfio_pci_device *vdev;
815	struct iommu_group *group;
816	int ret;
817
818	pci_read_config_byte(pdev, PCI_HEADER_TYPE, &type);
819	if ((type & PCI_HEADER_TYPE) != PCI_HEADER_TYPE_NORMAL)
820		return -EINVAL;
821
822	group = iommu_group_get(&pdev->dev);
823	if (!group)
824		return -EINVAL;
825
826	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
827	if (!vdev) {
828		iommu_group_put(group);
829		return -ENOMEM;
830	}
831
832	vdev->pdev = pdev;
833	vdev->irq_type = VFIO_PCI_NUM_IRQS;
834	mutex_init(&vdev->igate);
835	spin_lock_init(&vdev->irqlock);
836	atomic_set(&vdev->refcnt, 0);
837
838	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
839	if (ret) {
840		iommu_group_put(group);
841		kfree(vdev);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
842	}
843
844	return ret;
845}
846
847static void vfio_pci_remove(struct pci_dev *pdev)
848{
849	struct vfio_pci_device *vdev;
850
851	vdev = vfio_del_group_dev(&pdev->dev);
852	if (!vdev)
853		return;
854
855	iommu_group_put(pdev->dev.iommu_group);
 
856	kfree(vdev);
 
 
 
 
 
 
 
 
 
 
857}
858
859static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
860						  pci_channel_state_t state)
861{
862	struct vfio_pci_device *vdev;
863	struct vfio_device *device;
864
865	device = vfio_device_get_from_dev(&pdev->dev);
866	if (device == NULL)
867		return PCI_ERS_RESULT_DISCONNECT;
868
869	vdev = vfio_device_data(device);
870	if (vdev == NULL) {
871		vfio_device_put(device);
872		return PCI_ERS_RESULT_DISCONNECT;
873	}
874
875	mutex_lock(&vdev->igate);
876
877	if (vdev->err_trigger)
878		eventfd_signal(vdev->err_trigger, 1);
879
880	mutex_unlock(&vdev->igate);
881
882	vfio_device_put(device);
883
884	return PCI_ERS_RESULT_CAN_RECOVER;
885}
886
887static struct pci_error_handlers vfio_err_handlers = {
888	.error_detected = vfio_pci_aer_err_detected,
889};
890
891static struct pci_driver vfio_pci_driver = {
892	.name		= "vfio-pci",
893	.id_table	= NULL, /* only dynamic ids */
894	.probe		= vfio_pci_probe,
895	.remove		= vfio_pci_remove,
896	.err_handler	= &vfio_err_handlers,
897};
898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899static void __exit vfio_pci_cleanup(void)
900{
901	pci_unregister_driver(&vfio_pci_driver);
902	vfio_pci_virqfd_exit();
903	vfio_pci_uninit_perm_bits();
904}
905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906static int __init vfio_pci_init(void)
907{
908	int ret;
909
910	/* Allocate shared config space permision data used by all devices */
911	ret = vfio_pci_init_perm_bits();
912	if (ret)
913		return ret;
914
915	/* Start the virqfd cleanup handler */
916	ret = vfio_pci_virqfd_init();
917	if (ret)
918		goto out_virqfd;
919
920	/* Register and scan for devices */
921	ret = pci_register_driver(&vfio_pci_driver);
922	if (ret)
923		goto out_driver;
924
 
 
925	return 0;
926
927out_driver:
928	vfio_pci_virqfd_exit();
929out_virqfd:
930	vfio_pci_uninit_perm_bits();
931	return ret;
932}
933
934module_init(vfio_pci_init);
935module_exit(vfio_pci_cleanup);
936
937MODULE_VERSION(DRIVER_VERSION);
938MODULE_LICENSE("GPL v2");
939MODULE_AUTHOR(DRIVER_AUTHOR);
940MODULE_DESCRIPTION(DRIVER_DESC);