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