qemu/hw/vfio/pci.c
<<
>>
Prefs
   1/*
   2 * vfio based device assignment support
   3 *
   4 * Copyright Red Hat, Inc. 2012
   5 *
   6 * Authors:
   7 *  Alex Williamson <alex.williamson@redhat.com>
   8 *
   9 * This work is licensed under the terms of the GNU GPL, version 2.  See
  10 * the COPYING file in the top-level directory.
  11 *
  12 * Based on qemu-kvm device-assignment:
  13 *  Adapted for KVM by Qumranet.
  14 *  Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
  15 *  Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
  16 *  Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
  17 *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
  18 *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
  19 */
  20
  21#include "qemu/osdep.h"
  22#include <linux/vfio.h>
  23#include <sys/ioctl.h>
  24
  25#include "hw/hw.h"
  26#include "hw/pci/msi.h"
  27#include "hw/pci/msix.h"
  28#include "hw/pci/pci_bridge.h"
  29#include "hw/qdev-properties.h"
  30#include "hw/qdev-properties-system.h"
  31#include "migration/vmstate.h"
  32#include "qemu/error-report.h"
  33#include "qemu/main-loop.h"
  34#include "qemu/module.h"
  35#include "qemu/option.h"
  36#include "qemu/range.h"
  37#include "qemu/units.h"
  38#include "sysemu/kvm.h"
  39#include "sysemu/runstate.h"
  40#include "sysemu/sysemu.h"
  41#include "pci.h"
  42#include "trace.h"
  43#include "qapi/error.h"
  44#include "migration/blocker.h"
  45#include "migration/qemu-file.h"
  46
  47#define TYPE_VFIO_PCI_NOHOTPLUG "vfio-pci-nohotplug"
  48
  49static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
  50static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
  51
  52/*
  53 * Disabling BAR mmaping can be slow, but toggling it around INTx can
  54 * also be a huge overhead.  We try to get the best of both worlds by
  55 * waiting until an interrupt to disable mmaps (subsequent transitions
  56 * to the same state are effectively no overhead).  If the interrupt has
  57 * been serviced and the time gap is long enough, we re-enable mmaps for
  58 * performance.  This works well for things like graphics cards, which
  59 * may not use their interrupt at all and are penalized to an unusable
  60 * level by read/write BAR traps.  Other devices, like NICs, have more
  61 * regular interrupts and see much better latency by staying in non-mmap
  62 * mode.  We therefore set the default mmap_timeout such that a ping
  63 * is just enough to keep the mmap disabled.  Users can experiment with
  64 * other options with the x-intx-mmap-timeout-ms parameter (a value of
  65 * zero disables the timer).
  66 */
  67static void vfio_intx_mmap_enable(void *opaque)
  68{
  69    VFIOPCIDevice *vdev = opaque;
  70
  71    if (vdev->intx.pending) {
  72        timer_mod(vdev->intx.mmap_timer,
  73                       qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
  74        return;
  75    }
  76
  77    vfio_mmap_set_enabled(vdev, true);
  78}
  79
  80static void vfio_intx_interrupt(void *opaque)
  81{
  82    VFIOPCIDevice *vdev = opaque;
  83
  84    if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
  85        return;
  86    }
  87
  88    trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
  89
  90    vdev->intx.pending = true;
  91    pci_irq_assert(&vdev->pdev);
  92    vfio_mmap_set_enabled(vdev, false);
  93    if (vdev->intx.mmap_timeout) {
  94        timer_mod(vdev->intx.mmap_timer,
  95                       qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
  96    }
  97}
  98
  99static void vfio_intx_eoi(VFIODevice *vbasedev)
 100{
 101    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
 102
 103    if (!vdev->intx.pending) {
 104        return;
 105    }
 106
 107    trace_vfio_intx_eoi(vbasedev->name);
 108
 109    vdev->intx.pending = false;
 110    pci_irq_deassert(&vdev->pdev);
 111    vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 112}
 113
 114static void vfio_intx_enable_kvm(VFIOPCIDevice *vdev, Error **errp)
 115{
 116#ifdef CONFIG_KVM
 117    int irq_fd = event_notifier_get_fd(&vdev->intx.interrupt);
 118
 119    if (vdev->no_kvm_intx || !kvm_irqfds_enabled() ||
 120        vdev->intx.route.mode != PCI_INTX_ENABLED ||
 121        !kvm_resamplefds_enabled()) {
 122        return;
 123    }
 124
 125    /* Get to a known interrupt state */
 126    qemu_set_fd_handler(irq_fd, NULL, NULL, vdev);
 127    vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 128    vdev->intx.pending = false;
 129    pci_irq_deassert(&vdev->pdev);
 130
 131    /* Get an eventfd for resample/unmask */
 132    if (event_notifier_init(&vdev->intx.unmask, 0)) {
 133        error_setg(errp, "event_notifier_init failed eoi");
 134        goto fail;
 135    }
 136
 137    if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state,
 138                                           &vdev->intx.interrupt,
 139                                           &vdev->intx.unmask,
 140                                           vdev->intx.route.irq)) {
 141        error_setg_errno(errp, errno, "failed to setup resample irqfd");
 142        goto fail_irqfd;
 143    }
 144
 145    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
 146                               VFIO_IRQ_SET_ACTION_UNMASK,
 147                               event_notifier_get_fd(&vdev->intx.unmask),
 148                               errp)) {
 149        goto fail_vfio;
 150    }
 151
 152    /* Let'em rip */
 153    vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 154
 155    vdev->intx.kvm_accel = true;
 156
 157    trace_vfio_intx_enable_kvm(vdev->vbasedev.name);
 158
 159    return;
 160
 161fail_vfio:
 162    kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
 163                                          vdev->intx.route.irq);
 164fail_irqfd:
 165    event_notifier_cleanup(&vdev->intx.unmask);
 166fail:
 167    qemu_set_fd_handler(irq_fd, vfio_intx_interrupt, NULL, vdev);
 168    vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 169#endif
 170}
 171
 172static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev)
 173{
 174#ifdef CONFIG_KVM
 175    if (!vdev->intx.kvm_accel) {
 176        return;
 177    }
 178
 179    /*
 180     * Get to a known state, hardware masked, QEMU ready to accept new
 181     * interrupts, QEMU IRQ de-asserted.
 182     */
 183    vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 184    vdev->intx.pending = false;
 185    pci_irq_deassert(&vdev->pdev);
 186
 187    /* Tell KVM to stop listening for an INTx irqfd */
 188    if (kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
 189                                              vdev->intx.route.irq)) {
 190        error_report("vfio: Error: Failed to disable INTx irqfd: %m");
 191    }
 192
 193    /* We only need to close the eventfd for VFIO to cleanup the kernel side */
 194    event_notifier_cleanup(&vdev->intx.unmask);
 195
 196    /* QEMU starts listening for interrupt events. */
 197    qemu_set_fd_handler(event_notifier_get_fd(&vdev->intx.interrupt),
 198                        vfio_intx_interrupt, NULL, vdev);
 199
 200    vdev->intx.kvm_accel = false;
 201
 202    /* If we've missed an event, let it re-fire through QEMU */
 203    vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 204
 205    trace_vfio_intx_disable_kvm(vdev->vbasedev.name);
 206#endif
 207}
 208
 209static void vfio_intx_update(VFIOPCIDevice *vdev, PCIINTxRoute *route)
 210{
 211    Error *err = NULL;
 212
 213    trace_vfio_intx_update(vdev->vbasedev.name,
 214                           vdev->intx.route.irq, route->irq);
 215
 216    vfio_intx_disable_kvm(vdev);
 217
 218    vdev->intx.route = *route;
 219
 220    if (route->mode != PCI_INTX_ENABLED) {
 221        return;
 222    }
 223
 224    vfio_intx_enable_kvm(vdev, &err);
 225    if (err) {
 226        warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
 227    }
 228
 229    /* Re-enable the interrupt in cased we missed an EOI */
 230    vfio_intx_eoi(&vdev->vbasedev);
 231}
 232
 233static void vfio_intx_routing_notifier(PCIDevice *pdev)
 234{
 235    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
 236    PCIINTxRoute route;
 237
 238    if (vdev->interrupt != VFIO_INT_INTx) {
 239        return;
 240    }
 241
 242    route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
 243
 244    if (pci_intx_route_changed(&vdev->intx.route, &route)) {
 245        vfio_intx_update(vdev, &route);
 246    }
 247}
 248
 249static void vfio_irqchip_change(Notifier *notify, void *data)
 250{
 251    VFIOPCIDevice *vdev = container_of(notify, VFIOPCIDevice,
 252                                       irqchip_change_notifier);
 253
 254    vfio_intx_update(vdev, &vdev->intx.route);
 255}
 256
 257static int vfio_intx_enable(VFIOPCIDevice *vdev, Error **errp)
 258{
 259    uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
 260    Error *err = NULL;
 261    int32_t fd;
 262    int ret;
 263
 264
 265    if (!pin) {
 266        return 0;
 267    }
 268
 269    vfio_disable_interrupts(vdev);
 270
 271    vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
 272    pci_config_set_interrupt_pin(vdev->pdev.config, pin);
 273
 274#ifdef CONFIG_KVM
 275    /*
 276     * Only conditional to avoid generating error messages on platforms
 277     * where we won't actually use the result anyway.
 278     */
 279    if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
 280        vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
 281                                                        vdev->intx.pin);
 282    }
 283#endif
 284
 285    ret = event_notifier_init(&vdev->intx.interrupt, 0);
 286    if (ret) {
 287        error_setg_errno(errp, -ret, "event_notifier_init failed");
 288        return ret;
 289    }
 290    fd = event_notifier_get_fd(&vdev->intx.interrupt);
 291    qemu_set_fd_handler(fd, vfio_intx_interrupt, NULL, vdev);
 292
 293    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
 294                               VFIO_IRQ_SET_ACTION_TRIGGER, fd, errp)) {
 295        qemu_set_fd_handler(fd, NULL, NULL, vdev);
 296        event_notifier_cleanup(&vdev->intx.interrupt);
 297        return -errno;
 298    }
 299
 300    vfio_intx_enable_kvm(vdev, &err);
 301    if (err) {
 302        warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
 303    }
 304
 305    vdev->interrupt = VFIO_INT_INTx;
 306
 307    trace_vfio_intx_enable(vdev->vbasedev.name);
 308    return 0;
 309}
 310
 311static void vfio_intx_disable(VFIOPCIDevice *vdev)
 312{
 313    int fd;
 314
 315    timer_del(vdev->intx.mmap_timer);
 316    vfio_intx_disable_kvm(vdev);
 317    vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
 318    vdev->intx.pending = false;
 319    pci_irq_deassert(&vdev->pdev);
 320    vfio_mmap_set_enabled(vdev, true);
 321
 322    fd = event_notifier_get_fd(&vdev->intx.interrupt);
 323    qemu_set_fd_handler(fd, NULL, NULL, vdev);
 324    event_notifier_cleanup(&vdev->intx.interrupt);
 325
 326    vdev->interrupt = VFIO_INT_NONE;
 327
 328    trace_vfio_intx_disable(vdev->vbasedev.name);
 329}
 330
 331/*
 332 * MSI/X
 333 */
 334static void vfio_msi_interrupt(void *opaque)
 335{
 336    VFIOMSIVector *vector = opaque;
 337    VFIOPCIDevice *vdev = vector->vdev;
 338    MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector);
 339    void (*notify)(PCIDevice *dev, unsigned vector);
 340    MSIMessage msg;
 341    int nr = vector - vdev->msi_vectors;
 342
 343    if (!event_notifier_test_and_clear(&vector->interrupt)) {
 344        return;
 345    }
 346
 347    if (vdev->interrupt == VFIO_INT_MSIX) {
 348        get_msg = msix_get_message;
 349        notify = msix_notify;
 350
 351        /* A masked vector firing needs to use the PBA, enable it */
 352        if (msix_is_masked(&vdev->pdev, nr)) {
 353            set_bit(nr, vdev->msix->pending);
 354            memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, true);
 355            trace_vfio_msix_pba_enable(vdev->vbasedev.name);
 356        }
 357    } else if (vdev->interrupt == VFIO_INT_MSI) {
 358        get_msg = msi_get_message;
 359        notify = msi_notify;
 360    } else {
 361        abort();
 362    }
 363
 364    msg = get_msg(&vdev->pdev, nr);
 365    trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
 366    notify(&vdev->pdev, nr);
 367}
 368
 369static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
 370{
 371    struct vfio_irq_set *irq_set;
 372    int ret = 0, i, argsz;
 373    int32_t *fds;
 374
 375    argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
 376
 377    irq_set = g_malloc0(argsz);
 378    irq_set->argsz = argsz;
 379    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
 380    irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
 381    irq_set->start = 0;
 382    irq_set->count = vdev->nr_vectors;
 383    fds = (int32_t *)&irq_set->data;
 384
 385    for (i = 0; i < vdev->nr_vectors; i++) {
 386        int fd = -1;
 387
 388        /*
 389         * MSI vs MSI-X - The guest has direct access to MSI mask and pending
 390         * bits, therefore we always use the KVM signaling path when setup.
 391         * MSI-X mask and pending bits are emulated, so we want to use the
 392         * KVM signaling path only when configured and unmasked.
 393         */
 394        if (vdev->msi_vectors[i].use) {
 395            if (vdev->msi_vectors[i].virq < 0 ||
 396                (msix && msix_is_masked(&vdev->pdev, i))) {
 397                fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
 398            } else {
 399                fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
 400            }
 401        }
 402
 403        fds[i] = fd;
 404    }
 405
 406    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
 407
 408    g_free(irq_set);
 409
 410    return ret;
 411}
 412
 413static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector,
 414                                  int vector_n, bool msix)
 415{
 416    int virq;
 417
 418    if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi)) {
 419        return;
 420    }
 421
 422    if (event_notifier_init(&vector->kvm_interrupt, 0)) {
 423        return;
 424    }
 425
 426    virq = kvm_irqchip_add_msi_route(kvm_state, vector_n, &vdev->pdev);
 427    if (virq < 0) {
 428        event_notifier_cleanup(&vector->kvm_interrupt);
 429        return;
 430    }
 431
 432    if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
 433                                       NULL, virq) < 0) {
 434        kvm_irqchip_release_virq(kvm_state, virq);
 435        event_notifier_cleanup(&vector->kvm_interrupt);
 436        return;
 437    }
 438
 439    vector->virq = virq;
 440}
 441
 442static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
 443{
 444    kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
 445                                          vector->virq);
 446    kvm_irqchip_release_virq(kvm_state, vector->virq);
 447    vector->virq = -1;
 448    event_notifier_cleanup(&vector->kvm_interrupt);
 449}
 450
 451static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg,
 452                                     PCIDevice *pdev)
 453{
 454    kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg, pdev);
 455    kvm_irqchip_commit_routes(kvm_state);
 456}
 457
 458static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
 459                                   MSIMessage *msg, IOHandler *handler)
 460{
 461    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
 462    VFIOMSIVector *vector;
 463    int ret;
 464
 465    trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
 466
 467    vector = &vdev->msi_vectors[nr];
 468
 469    if (!vector->use) {
 470        vector->vdev = vdev;
 471        vector->virq = -1;
 472        if (event_notifier_init(&vector->interrupt, 0)) {
 473            error_report("vfio: Error: event_notifier_init failed");
 474        }
 475        vector->use = true;
 476        msix_vector_use(pdev, nr);
 477    }
 478
 479    qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
 480                        handler, NULL, vector);
 481
 482    /*
 483     * Attempt to enable route through KVM irqchip,
 484     * default to userspace handling if unavailable.
 485     */
 486    if (vector->virq >= 0) {
 487        if (!msg) {
 488            vfio_remove_kvm_msi_virq(vector);
 489        } else {
 490            vfio_update_kvm_msi_virq(vector, *msg, pdev);
 491        }
 492    } else {
 493        if (msg) {
 494            vfio_add_kvm_msi_virq(vdev, vector, nr, true);
 495        }
 496    }
 497
 498    /*
 499     * We don't want to have the host allocate all possible MSI vectors
 500     * for a device if they're not in use, so we shutdown and incrementally
 501     * increase them as needed.
 502     */
 503    if (vdev->nr_vectors < nr + 1) {
 504        vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
 505        vdev->nr_vectors = nr + 1;
 506        ret = vfio_enable_vectors(vdev, true);
 507        if (ret) {
 508            error_report("vfio: failed to enable vectors, %d", ret);
 509        }
 510    } else {
 511        Error *err = NULL;
 512        int32_t fd;
 513
 514        if (vector->virq >= 0) {
 515            fd = event_notifier_get_fd(&vector->kvm_interrupt);
 516        } else {
 517            fd = event_notifier_get_fd(&vector->interrupt);
 518        }
 519
 520        if (vfio_set_irq_signaling(&vdev->vbasedev,
 521                                     VFIO_PCI_MSIX_IRQ_INDEX, nr,
 522                                     VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
 523            error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
 524        }
 525    }
 526
 527    /* Disable PBA emulation when nothing more is pending. */
 528    clear_bit(nr, vdev->msix->pending);
 529    if (find_first_bit(vdev->msix->pending,
 530                       vdev->nr_vectors) == vdev->nr_vectors) {
 531        memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
 532        trace_vfio_msix_pba_disable(vdev->vbasedev.name);
 533    }
 534
 535    return 0;
 536}
 537
 538static int vfio_msix_vector_use(PCIDevice *pdev,
 539                                unsigned int nr, MSIMessage msg)
 540{
 541    return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
 542}
 543
 544static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
 545{
 546    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
 547    VFIOMSIVector *vector = &vdev->msi_vectors[nr];
 548
 549    trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
 550
 551    /*
 552     * There are still old guests that mask and unmask vectors on every
 553     * interrupt.  If we're using QEMU bypass with a KVM irqfd, leave all of
 554     * the KVM setup in place, simply switch VFIO to use the non-bypass
 555     * eventfd.  We'll then fire the interrupt through QEMU and the MSI-X
 556     * core will mask the interrupt and set pending bits, allowing it to
 557     * be re-asserted on unmask.  Nothing to do if already using QEMU mode.
 558     */
 559    if (vector->virq >= 0) {
 560        int32_t fd = event_notifier_get_fd(&vector->interrupt);
 561        Error *err = NULL;
 562
 563        if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX, nr,
 564                                   VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
 565            error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
 566        }
 567    }
 568}
 569
 570static void vfio_msix_enable(VFIOPCIDevice *vdev)
 571{
 572    PCIDevice *pdev = &vdev->pdev;
 573    unsigned int nr, max_vec = 0;
 574
 575    vfio_disable_interrupts(vdev);
 576
 577    vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->msix->entries);
 578
 579    vdev->interrupt = VFIO_INT_MSIX;
 580
 581    /*
 582     * Some communication channels between VF & PF or PF & fw rely on the
 583     * physical state of the device and expect that enabling MSI-X from the
 584     * guest enables the same on the host.  When our guest is Linux, the
 585     * guest driver call to pci_enable_msix() sets the enabling bit in the
 586     * MSI-X capability, but leaves the vector table masked.  We therefore
 587     * can't rely on a vector_use callback (from request_irq() in the guest)
 588     * to switch the physical device into MSI-X mode because that may come a
 589     * long time after pci_enable_msix().  This code enables vector 0 with
 590     * triggering to userspace, then immediately release the vector, leaving
 591     * the physical device with no vectors enabled, but MSI-X enabled, just
 592     * like the guest view.
 593     * If there are already unmasked vectors (in migration resume phase and
 594     * some guest startups) which will be enabled soon, we can allocate all
 595     * of them here to avoid inefficiently disabling and enabling vectors
 596     * repeatedly later.
 597     */
 598    if (!pdev->msix_function_masked) {
 599        for (nr = 0; nr < msix_nr_vectors_allocated(pdev); nr++) {
 600            if (!msix_is_masked(pdev, nr)) {
 601                max_vec = nr;
 602            }
 603        }
 604    }
 605    vfio_msix_vector_do_use(pdev, max_vec, NULL, NULL);
 606    vfio_msix_vector_release(pdev, max_vec);
 607
 608    if (msix_set_vector_notifiers(pdev, vfio_msix_vector_use,
 609                                  vfio_msix_vector_release, NULL)) {
 610        error_report("vfio: msix_set_vector_notifiers failed");
 611    }
 612
 613    trace_vfio_msix_enable(vdev->vbasedev.name);
 614}
 615
 616static void vfio_msi_enable(VFIOPCIDevice *vdev)
 617{
 618    int ret, i;
 619
 620    vfio_disable_interrupts(vdev);
 621
 622    vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
 623retry:
 624    vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->nr_vectors);
 625
 626    for (i = 0; i < vdev->nr_vectors; i++) {
 627        VFIOMSIVector *vector = &vdev->msi_vectors[i];
 628
 629        vector->vdev = vdev;
 630        vector->virq = -1;
 631        vector->use = true;
 632
 633        if (event_notifier_init(&vector->interrupt, 0)) {
 634            error_report("vfio: Error: event_notifier_init failed");
 635        }
 636
 637        qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
 638                            vfio_msi_interrupt, NULL, vector);
 639
 640        /*
 641         * Attempt to enable route through KVM irqchip,
 642         * default to userspace handling if unavailable.
 643         */
 644        vfio_add_kvm_msi_virq(vdev, vector, i, false);
 645    }
 646
 647    /* Set interrupt type prior to possible interrupts */
 648    vdev->interrupt = VFIO_INT_MSI;
 649
 650    ret = vfio_enable_vectors(vdev, false);
 651    if (ret) {
 652        if (ret < 0) {
 653            error_report("vfio: Error: Failed to setup MSI fds: %m");
 654        } else if (ret != vdev->nr_vectors) {
 655            error_report("vfio: Error: Failed to enable %d "
 656                         "MSI vectors, retry with %d", vdev->nr_vectors, ret);
 657        }
 658
 659        for (i = 0; i < vdev->nr_vectors; i++) {
 660            VFIOMSIVector *vector = &vdev->msi_vectors[i];
 661            if (vector->virq >= 0) {
 662                vfio_remove_kvm_msi_virq(vector);
 663            }
 664            qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
 665                                NULL, NULL, NULL);
 666            event_notifier_cleanup(&vector->interrupt);
 667        }
 668
 669        g_free(vdev->msi_vectors);
 670        vdev->msi_vectors = NULL;
 671
 672        if (ret > 0 && ret != vdev->nr_vectors) {
 673            vdev->nr_vectors = ret;
 674            goto retry;
 675        }
 676        vdev->nr_vectors = 0;
 677
 678        /*
 679         * Failing to setup MSI doesn't really fall within any specification.
 680         * Let's try leaving interrupts disabled and hope the guest figures
 681         * out to fall back to INTx for this device.
 682         */
 683        error_report("vfio: Error: Failed to enable MSI");
 684        vdev->interrupt = VFIO_INT_NONE;
 685
 686        return;
 687    }
 688
 689    trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);
 690}
 691
 692static void vfio_msi_disable_common(VFIOPCIDevice *vdev)
 693{
 694    Error *err = NULL;
 695    int i;
 696
 697    for (i = 0; i < vdev->nr_vectors; i++) {
 698        VFIOMSIVector *vector = &vdev->msi_vectors[i];
 699        if (vdev->msi_vectors[i].use) {
 700            if (vector->virq >= 0) {
 701                vfio_remove_kvm_msi_virq(vector);
 702            }
 703            qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
 704                                NULL, NULL, NULL);
 705            event_notifier_cleanup(&vector->interrupt);
 706        }
 707    }
 708
 709    g_free(vdev->msi_vectors);
 710    vdev->msi_vectors = NULL;
 711    vdev->nr_vectors = 0;
 712    vdev->interrupt = VFIO_INT_NONE;
 713
 714    vfio_intx_enable(vdev, &err);
 715    if (err) {
 716        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
 717    }
 718}
 719
 720static void vfio_msix_disable(VFIOPCIDevice *vdev)
 721{
 722    int i;
 723
 724    msix_unset_vector_notifiers(&vdev->pdev);
 725
 726    /*
 727     * MSI-X will only release vectors if MSI-X is still enabled on the
 728     * device, check through the rest and release it ourselves if necessary.
 729     */
 730    for (i = 0; i < vdev->nr_vectors; i++) {
 731        if (vdev->msi_vectors[i].use) {
 732            vfio_msix_vector_release(&vdev->pdev, i);
 733            msix_vector_unuse(&vdev->pdev, i);
 734        }
 735    }
 736
 737    if (vdev->nr_vectors) {
 738        vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
 739    }
 740
 741    vfio_msi_disable_common(vdev);
 742
 743    memset(vdev->msix->pending, 0,
 744           BITS_TO_LONGS(vdev->msix->entries) * sizeof(unsigned long));
 745
 746    trace_vfio_msix_disable(vdev->vbasedev.name);
 747}
 748
 749static void vfio_msi_disable(VFIOPCIDevice *vdev)
 750{
 751    vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
 752    vfio_msi_disable_common(vdev);
 753
 754    trace_vfio_msi_disable(vdev->vbasedev.name);
 755}
 756
 757static void vfio_update_msi(VFIOPCIDevice *vdev)
 758{
 759    int i;
 760
 761    for (i = 0; i < vdev->nr_vectors; i++) {
 762        VFIOMSIVector *vector = &vdev->msi_vectors[i];
 763        MSIMessage msg;
 764
 765        if (!vector->use || vector->virq < 0) {
 766            continue;
 767        }
 768
 769        msg = msi_get_message(&vdev->pdev, i);
 770        vfio_update_kvm_msi_virq(vector, msg, &vdev->pdev);
 771    }
 772}
 773
 774static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
 775{
 776    struct vfio_region_info *reg_info;
 777    uint64_t size;
 778    off_t off = 0;
 779    ssize_t bytes;
 780
 781    if (vfio_get_region_info(&vdev->vbasedev,
 782                             VFIO_PCI_ROM_REGION_INDEX, &reg_info)) {
 783        error_report("vfio: Error getting ROM info: %m");
 784        return;
 785    }
 786
 787    trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info->size,
 788                            (unsigned long)reg_info->offset,
 789                            (unsigned long)reg_info->flags);
 790
 791    vdev->rom_size = size = reg_info->size;
 792    vdev->rom_offset = reg_info->offset;
 793
 794    g_free(reg_info);
 795
 796    if (!vdev->rom_size) {
 797        vdev->rom_read_failed = true;
 798        error_report("vfio-pci: Cannot read device rom at "
 799                    "%s", vdev->vbasedev.name);
 800        error_printf("Device option ROM contents are probably invalid "
 801                    "(check dmesg).\nSkip option ROM probe with rombar=0, "
 802                    "or load from file with romfile=\n");
 803        return;
 804    }
 805
 806    vdev->rom = g_malloc(size);
 807    memset(vdev->rom, 0xff, size);
 808
 809    while (size) {
 810        bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
 811                      size, vdev->rom_offset + off);
 812        if (bytes == 0) {
 813            break;
 814        } else if (bytes > 0) {
 815            off += bytes;
 816            size -= bytes;
 817        } else {
 818            if (errno == EINTR || errno == EAGAIN) {
 819                continue;
 820            }
 821            error_report("vfio: Error reading device ROM: %m");
 822            break;
 823        }
 824    }
 825
 826    /*
 827     * Test the ROM signature against our device, if the vendor is correct
 828     * but the device ID doesn't match, store the correct device ID and
 829     * recompute the checksum.  Intel IGD devices need this and are known
 830     * to have bogus checksums so we can't simply adjust the checksum.
 831     */
 832    if (pci_get_word(vdev->rom) == 0xaa55 &&
 833        pci_get_word(vdev->rom + 0x18) + 8 < vdev->rom_size &&
 834        !memcmp(vdev->rom + pci_get_word(vdev->rom + 0x18), "PCIR", 4)) {
 835        uint16_t vid, did;
 836
 837        vid = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 4);
 838        did = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6);
 839
 840        if (vid == vdev->vendor_id && did != vdev->device_id) {
 841            int i;
 842            uint8_t csum, *data = vdev->rom;
 843
 844            pci_set_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6,
 845                         vdev->device_id);
 846            data[6] = 0;
 847
 848            for (csum = 0, i = 0; i < vdev->rom_size; i++) {
 849                csum += data[i];
 850            }
 851
 852            data[6] = -csum;
 853        }
 854    }
 855}
 856
 857static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
 858{
 859    VFIOPCIDevice *vdev = opaque;
 860    union {
 861        uint8_t byte;
 862        uint16_t word;
 863        uint32_t dword;
 864        uint64_t qword;
 865    } val;
 866    uint64_t data = 0;
 867
 868    /* Load the ROM lazily when the guest tries to read it */
 869    if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
 870        vfio_pci_load_rom(vdev);
 871    }
 872
 873    memcpy(&val, vdev->rom + addr,
 874           (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
 875
 876    switch (size) {
 877    case 1:
 878        data = val.byte;
 879        break;
 880    case 2:
 881        data = le16_to_cpu(val.word);
 882        break;
 883    case 4:
 884        data = le32_to_cpu(val.dword);
 885        break;
 886    default:
 887        hw_error("vfio: unsupported read size, %d bytes\n", size);
 888        break;
 889    }
 890
 891    trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
 892
 893    return data;
 894}
 895
 896static void vfio_rom_write(void *opaque, hwaddr addr,
 897                           uint64_t data, unsigned size)
 898{
 899}
 900
 901static const MemoryRegionOps vfio_rom_ops = {
 902    .read = vfio_rom_read,
 903    .write = vfio_rom_write,
 904    .endianness = DEVICE_LITTLE_ENDIAN,
 905};
 906
 907static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
 908{
 909    uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
 910    off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
 911    DeviceState *dev = DEVICE(vdev);
 912    char *name;
 913    int fd = vdev->vbasedev.fd;
 914
 915    if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
 916        /* Since pci handles romfile, just print a message and return */
 917        if (vfio_opt_rom_in_denylist(vdev) && vdev->pdev.romfile) {
 918            warn_report("Device at %s is known to cause system instability"
 919                        " issues during option rom execution",
 920                        vdev->vbasedev.name);
 921            error_printf("Proceeding anyway since user specified romfile\n");
 922        }
 923        return;
 924    }
 925
 926    /*
 927     * Use the same size ROM BAR as the physical device.  The contents
 928     * will get filled in later when the guest tries to read it.
 929     */
 930    if (pread(fd, &orig, 4, offset) != 4 ||
 931        pwrite(fd, &size, 4, offset) != 4 ||
 932        pread(fd, &size, 4, offset) != 4 ||
 933        pwrite(fd, &orig, 4, offset) != 4) {
 934        error_report("%s(%s) failed: %m", __func__, vdev->vbasedev.name);
 935        return;
 936    }
 937
 938    size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
 939
 940    if (!size) {
 941        return;
 942    }
 943
 944    if (vfio_opt_rom_in_denylist(vdev)) {
 945        if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {
 946            warn_report("Device at %s is known to cause system instability"
 947                        " issues during option rom execution",
 948                        vdev->vbasedev.name);
 949            error_printf("Proceeding anyway since user specified"
 950                         " non zero value for rombar\n");
 951        } else {
 952            warn_report("Rom loading for device at %s has been disabled"
 953                        " due to system instability issues",
 954                        vdev->vbasedev.name);
 955            error_printf("Specify rombar=1 or romfile to force\n");
 956            return;
 957        }
 958    }
 959
 960    trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
 961
 962    name = g_strdup_printf("vfio[%s].rom", vdev->vbasedev.name);
 963
 964    memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
 965                          &vfio_rom_ops, vdev, name, size);
 966    g_free(name);
 967
 968    pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
 969                     PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
 970
 971    vdev->rom_read_failed = false;
 972}
 973
 974void vfio_vga_write(void *opaque, hwaddr addr,
 975                           uint64_t data, unsigned size)
 976{
 977    VFIOVGARegion *region = opaque;
 978    VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
 979    union {
 980        uint8_t byte;
 981        uint16_t word;
 982        uint32_t dword;
 983        uint64_t qword;
 984    } buf;
 985    off_t offset = vga->fd_offset + region->offset + addr;
 986
 987    switch (size) {
 988    case 1:
 989        buf.byte = data;
 990        break;
 991    case 2:
 992        buf.word = cpu_to_le16(data);
 993        break;
 994    case 4:
 995        buf.dword = cpu_to_le32(data);
 996        break;
 997    default:
 998        hw_error("vfio: unsupported write size, %d bytes", size);
 999        break;
1000    }
1001
1002    if (pwrite(vga->fd, &buf, size, offset) != size) {
1003        error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
1004                     __func__, region->offset + addr, data, size);
1005    }
1006
1007    trace_vfio_vga_write(region->offset + addr, data, size);
1008}
1009
1010uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
1011{
1012    VFIOVGARegion *region = opaque;
1013    VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1014    union {
1015        uint8_t byte;
1016        uint16_t word;
1017        uint32_t dword;
1018        uint64_t qword;
1019    } buf;
1020    uint64_t data = 0;
1021    off_t offset = vga->fd_offset + region->offset + addr;
1022
1023    if (pread(vga->fd, &buf, size, offset) != size) {
1024        error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1025                     __func__, region->offset + addr, size);
1026        return (uint64_t)-1;
1027    }
1028
1029    switch (size) {
1030    case 1:
1031        data = buf.byte;
1032        break;
1033    case 2:
1034        data = le16_to_cpu(buf.word);
1035        break;
1036    case 4:
1037        data = le32_to_cpu(buf.dword);
1038        break;
1039    default:
1040        hw_error("vfio: unsupported read size, %d bytes", size);
1041        break;
1042    }
1043
1044    trace_vfio_vga_read(region->offset + addr, size, data);
1045
1046    return data;
1047}
1048
1049static const MemoryRegionOps vfio_vga_ops = {
1050    .read = vfio_vga_read,
1051    .write = vfio_vga_write,
1052    .endianness = DEVICE_LITTLE_ENDIAN,
1053};
1054
1055/*
1056 * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page
1057 * size if the BAR is in an exclusive page in host so that we could map
1058 * this BAR to guest. But this sub-page BAR may not occupy an exclusive
1059 * page in guest. So we should set the priority of the expanded memory
1060 * region to zero in case of overlap with BARs which share the same page
1061 * with the sub-page BAR in guest. Besides, we should also recover the
1062 * size of this sub-page BAR when its base address is changed in guest
1063 * and not page aligned any more.
1064 */
1065static void vfio_sub_page_bar_update_mapping(PCIDevice *pdev, int bar)
1066{
1067    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1068    VFIORegion *region = &vdev->bars[bar].region;
1069    MemoryRegion *mmap_mr, *region_mr, *base_mr;
1070    PCIIORegion *r;
1071    pcibus_t bar_addr;
1072    uint64_t size = region->size;
1073
1074    /* Make sure that the whole region is allowed to be mmapped */
1075    if (region->nr_mmaps != 1 || !region->mmaps[0].mmap ||
1076        region->mmaps[0].size != region->size) {
1077        return;
1078    }
1079
1080    r = &pdev->io_regions[bar];
1081    bar_addr = r->addr;
1082    base_mr = vdev->bars[bar].mr;
1083    region_mr = region->mem;
1084    mmap_mr = &region->mmaps[0].mem;
1085
1086    /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */
1087    if (bar_addr != PCI_BAR_UNMAPPED &&
1088        !(bar_addr & ~qemu_real_host_page_mask)) {
1089        size = qemu_real_host_page_size;
1090    }
1091
1092    memory_region_transaction_begin();
1093
1094    if (vdev->bars[bar].size < size) {
1095        memory_region_set_size(base_mr, size);
1096    }
1097    memory_region_set_size(region_mr, size);
1098    memory_region_set_size(mmap_mr, size);
1099    if (size != vdev->bars[bar].size && memory_region_is_mapped(base_mr)) {
1100        memory_region_del_subregion(r->address_space, base_mr);
1101        memory_region_add_subregion_overlap(r->address_space,
1102                                            bar_addr, base_mr, 0);
1103    }
1104
1105    memory_region_transaction_commit();
1106}
1107
1108/*
1109 * PCI config space
1110 */
1111uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
1112{
1113    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1114    uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
1115
1116    memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
1117    emu_bits = le32_to_cpu(emu_bits);
1118
1119    if (emu_bits) {
1120        emu_val = pci_default_read_config(pdev, addr, len);
1121    }
1122
1123    if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
1124        ssize_t ret;
1125
1126        ret = pread(vdev->vbasedev.fd, &phys_val, len,
1127                    vdev->config_offset + addr);
1128        if (ret != len) {
1129            error_report("%s(%s, 0x%x, 0x%x) failed: %m",
1130                         __func__, vdev->vbasedev.name, addr, len);
1131            return -errno;
1132        }
1133        phys_val = le32_to_cpu(phys_val);
1134    }
1135
1136    val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
1137
1138    trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
1139
1140    return val;
1141}
1142
1143void vfio_pci_write_config(PCIDevice *pdev,
1144                           uint32_t addr, uint32_t val, int len)
1145{
1146    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1147    uint32_t val_le = cpu_to_le32(val);
1148
1149    trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
1150
1151    /* Write everything to VFIO, let it filter out what we can't write */
1152    if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
1153                != len) {
1154        error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %m",
1155                     __func__, vdev->vbasedev.name, addr, val, len);
1156    }
1157
1158    /* MSI/MSI-X Enabling/Disabling */
1159    if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
1160        ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
1161        int is_enabled, was_enabled = msi_enabled(pdev);
1162
1163        pci_default_write_config(pdev, addr, val, len);
1164
1165        is_enabled = msi_enabled(pdev);
1166
1167        if (!was_enabled) {
1168            if (is_enabled) {
1169                vfio_msi_enable(vdev);
1170            }
1171        } else {
1172            if (!is_enabled) {
1173                vfio_msi_disable(vdev);
1174            } else {
1175                vfio_update_msi(vdev);
1176            }
1177        }
1178    } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
1179        ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
1180        int is_enabled, was_enabled = msix_enabled(pdev);
1181
1182        pci_default_write_config(pdev, addr, val, len);
1183
1184        is_enabled = msix_enabled(pdev);
1185
1186        if (!was_enabled && is_enabled) {
1187            vfio_msix_enable(vdev);
1188        } else if (was_enabled && !is_enabled) {
1189            vfio_msix_disable(vdev);
1190        }
1191    } else if (ranges_overlap(addr, len, PCI_BASE_ADDRESS_0, 24) ||
1192        range_covers_byte(addr, len, PCI_COMMAND)) {
1193        pcibus_t old_addr[PCI_NUM_REGIONS - 1];
1194        int bar;
1195
1196        for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1197            old_addr[bar] = pdev->io_regions[bar].addr;
1198        }
1199
1200        pci_default_write_config(pdev, addr, val, len);
1201
1202        for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1203            if (old_addr[bar] != pdev->io_regions[bar].addr &&
1204                vdev->bars[bar].region.size > 0 &&
1205                vdev->bars[bar].region.size < qemu_real_host_page_size) {
1206                vfio_sub_page_bar_update_mapping(pdev, bar);
1207            }
1208        }
1209    } else {
1210        /* Write everything to QEMU to keep emulated bits correct */
1211        pci_default_write_config(pdev, addr, val, len);
1212    }
1213}
1214
1215/*
1216 * Interrupt setup
1217 */
1218static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
1219{
1220    /*
1221     * More complicated than it looks.  Disabling MSI/X transitions the
1222     * device to INTx mode (if supported).  Therefore we need to first
1223     * disable MSI/X and then cleanup by disabling INTx.
1224     */
1225    if (vdev->interrupt == VFIO_INT_MSIX) {
1226        vfio_msix_disable(vdev);
1227    } else if (vdev->interrupt == VFIO_INT_MSI) {
1228        vfio_msi_disable(vdev);
1229    }
1230
1231    if (vdev->interrupt == VFIO_INT_INTx) {
1232        vfio_intx_disable(vdev);
1233    }
1234}
1235
1236static int vfio_msi_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
1237{
1238    uint16_t ctrl;
1239    bool msi_64bit, msi_maskbit;
1240    int ret, entries;
1241    Error *err = NULL;
1242
1243    if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
1244              vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
1245        error_setg_errno(errp, errno, "failed reading MSI PCI_CAP_FLAGS");
1246        return -errno;
1247    }
1248    ctrl = le16_to_cpu(ctrl);
1249
1250    msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
1251    msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
1252    entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
1253
1254    trace_vfio_msi_setup(vdev->vbasedev.name, pos);
1255
1256    ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit, &err);
1257    if (ret < 0) {
1258        if (ret == -ENOTSUP) {
1259            return 0;
1260        }
1261        error_propagate_prepend(errp, err, "msi_init failed: ");
1262        return ret;
1263    }
1264    vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
1265
1266    return 0;
1267}
1268
1269static void vfio_pci_fixup_msix_region(VFIOPCIDevice *vdev)
1270{
1271    off_t start, end;
1272    VFIORegion *region = &vdev->bars[vdev->msix->table_bar].region;
1273
1274    /*
1275     * If the host driver allows mapping of a MSIX data, we are going to
1276     * do map the entire BAR and emulate MSIX table on top of that.
1277     */
1278    if (vfio_has_region_cap(&vdev->vbasedev, region->nr,
1279                            VFIO_REGION_INFO_CAP_MSIX_MAPPABLE)) {
1280        return;
1281    }
1282
1283    /*
1284     * We expect to find a single mmap covering the whole BAR, anything else
1285     * means it's either unsupported or already setup.
1286     */
1287    if (region->nr_mmaps != 1 || region->mmaps[0].offset ||
1288        region->size != region->mmaps[0].size) {
1289        return;
1290    }
1291
1292    /* MSI-X table start and end aligned to host page size */
1293    start = vdev->msix->table_offset & qemu_real_host_page_mask;
1294    end = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
1295                               (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
1296
1297    /*
1298     * Does the MSI-X table cover the beginning of the BAR?  The whole BAR?
1299     * NB - Host page size is necessarily a power of two and so is the PCI
1300     * BAR (not counting EA yet), therefore if we have host page aligned
1301     * @start and @end, then any remainder of the BAR before or after those
1302     * must be at least host page sized and therefore mmap'able.
1303     */
1304    if (!start) {
1305        if (end >= region->size) {
1306            region->nr_mmaps = 0;
1307            g_free(region->mmaps);
1308            region->mmaps = NULL;
1309            trace_vfio_msix_fixup(vdev->vbasedev.name,
1310                                  vdev->msix->table_bar, 0, 0);
1311        } else {
1312            region->mmaps[0].offset = end;
1313            region->mmaps[0].size = region->size - end;
1314            trace_vfio_msix_fixup(vdev->vbasedev.name,
1315                              vdev->msix->table_bar, region->mmaps[0].offset,
1316                              region->mmaps[0].offset + region->mmaps[0].size);
1317        }
1318
1319    /* Maybe it's aligned at the end of the BAR */
1320    } else if (end >= region->size) {
1321        region->mmaps[0].size = start;
1322        trace_vfio_msix_fixup(vdev->vbasedev.name,
1323                              vdev->msix->table_bar, region->mmaps[0].offset,
1324                              region->mmaps[0].offset + region->mmaps[0].size);
1325
1326    /* Otherwise it must split the BAR */
1327    } else {
1328        region->nr_mmaps = 2;
1329        region->mmaps = g_renew(VFIOMmap, region->mmaps, 2);
1330
1331        memcpy(&region->mmaps[1], &region->mmaps[0], sizeof(VFIOMmap));
1332
1333        region->mmaps[0].size = start;
1334        trace_vfio_msix_fixup(vdev->vbasedev.name,
1335                              vdev->msix->table_bar, region->mmaps[0].offset,
1336                              region->mmaps[0].offset + region->mmaps[0].size);
1337
1338        region->mmaps[1].offset = end;
1339        region->mmaps[1].size = region->size - end;
1340        trace_vfio_msix_fixup(vdev->vbasedev.name,
1341                              vdev->msix->table_bar, region->mmaps[1].offset,
1342                              region->mmaps[1].offset + region->mmaps[1].size);
1343    }
1344}
1345
1346static void vfio_pci_relocate_msix(VFIOPCIDevice *vdev, Error **errp)
1347{
1348    int target_bar = -1;
1349    size_t msix_sz;
1350
1351    if (!vdev->msix || vdev->msix_relo == OFF_AUTOPCIBAR_OFF) {
1352        return;
1353    }
1354
1355    /* The actual minimum size of MSI-X structures */
1356    msix_sz = (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE) +
1357              (QEMU_ALIGN_UP(vdev->msix->entries, 64) / 8);
1358    /* Round up to host pages, we don't want to share a page */
1359    msix_sz = REAL_HOST_PAGE_ALIGN(msix_sz);
1360    /* PCI BARs must be a power of 2 */
1361    msix_sz = pow2ceil(msix_sz);
1362
1363    if (vdev->msix_relo == OFF_AUTOPCIBAR_AUTO) {
1364        /*
1365         * TODO: Lookup table for known devices.
1366         *
1367         * Logically we might use an algorithm here to select the BAR adding
1368         * the least additional MMIO space, but we cannot programatically
1369         * predict the driver dependency on BAR ordering or sizing, therefore
1370         * 'auto' becomes a lookup for combinations reported to work.
1371         */
1372        if (target_bar < 0) {
1373            error_setg(errp, "No automatic MSI-X relocation available for "
1374                       "device %04x:%04x", vdev->vendor_id, vdev->device_id);
1375            return;
1376        }
1377    } else {
1378        target_bar = (int)(vdev->msix_relo - OFF_AUTOPCIBAR_BAR0);
1379    }
1380
1381    /* I/O port BARs cannot host MSI-X structures */
1382    if (vdev->bars[target_bar].ioport) {
1383        error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1384                   "I/O port BAR", target_bar);
1385        return;
1386    }
1387
1388    /* Cannot use a BAR in the "shadow" of a 64-bit BAR */
1389    if (!vdev->bars[target_bar].size &&
1390         target_bar > 0 && vdev->bars[target_bar - 1].mem64) {
1391        error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1392                   "consumed by 64-bit BAR %d", target_bar, target_bar - 1);
1393        return;
1394    }
1395
1396    /* 2GB max size for 32-bit BARs, cannot double if already > 1G */
1397    if (vdev->bars[target_bar].size > 1 * GiB &&
1398        !vdev->bars[target_bar].mem64) {
1399        error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1400                   "no space to extend 32-bit BAR", target_bar);
1401        return;
1402    }
1403
1404    /*
1405     * If adding a new BAR, test if we can make it 64bit.  We make it
1406     * prefetchable since QEMU MSI-X emulation has no read side effects
1407     * and doing so makes mapping more flexible.
1408     */
1409    if (!vdev->bars[target_bar].size) {
1410        if (target_bar < (PCI_ROM_SLOT - 1) &&
1411            !vdev->bars[target_bar + 1].size) {
1412            vdev->bars[target_bar].mem64 = true;
1413            vdev->bars[target_bar].type = PCI_BASE_ADDRESS_MEM_TYPE_64;
1414        }
1415        vdev->bars[target_bar].type |= PCI_BASE_ADDRESS_MEM_PREFETCH;
1416        vdev->bars[target_bar].size = msix_sz;
1417        vdev->msix->table_offset = 0;
1418    } else {
1419        vdev->bars[target_bar].size = MAX(vdev->bars[target_bar].size * 2,
1420                                          msix_sz * 2);
1421        /*
1422         * Due to above size calc, MSI-X always starts halfway into the BAR,
1423         * which will always be a separate host page.
1424         */
1425        vdev->msix->table_offset = vdev->bars[target_bar].size / 2;
1426    }
1427
1428    vdev->msix->table_bar = target_bar;
1429    vdev->msix->pba_bar = target_bar;
1430    /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */
1431    vdev->msix->pba_offset = vdev->msix->table_offset +
1432                                  (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE);
1433
1434    trace_vfio_msix_relo(vdev->vbasedev.name,
1435                         vdev->msix->table_bar, vdev->msix->table_offset);
1436}
1437
1438/*
1439 * We don't have any control over how pci_add_capability() inserts
1440 * capabilities into the chain.  In order to setup MSI-X we need a
1441 * MemoryRegion for the BAR.  In order to setup the BAR and not
1442 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1443 * need to first look for where the MSI-X table lives.  So we
1444 * unfortunately split MSI-X setup across two functions.
1445 */
1446static void vfio_msix_early_setup(VFIOPCIDevice *vdev, Error **errp)
1447{
1448    uint8_t pos;
1449    uint16_t ctrl;
1450    uint32_t table, pba;
1451    int fd = vdev->vbasedev.fd;
1452    VFIOMSIXInfo *msix;
1453
1454    pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
1455    if (!pos) {
1456        return;
1457    }
1458
1459    if (pread(fd, &ctrl, sizeof(ctrl),
1460              vdev->config_offset + pos + PCI_MSIX_FLAGS) != sizeof(ctrl)) {
1461        error_setg_errno(errp, errno, "failed to read PCI MSIX FLAGS");
1462        return;
1463    }
1464
1465    if (pread(fd, &table, sizeof(table),
1466              vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
1467        error_setg_errno(errp, errno, "failed to read PCI MSIX TABLE");
1468        return;
1469    }
1470
1471    if (pread(fd, &pba, sizeof(pba),
1472              vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
1473        error_setg_errno(errp, errno, "failed to read PCI MSIX PBA");
1474        return;
1475    }
1476
1477    ctrl = le16_to_cpu(ctrl);
1478    table = le32_to_cpu(table);
1479    pba = le32_to_cpu(pba);
1480
1481    msix = g_malloc0(sizeof(*msix));
1482    msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
1483    msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
1484    msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
1485    msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
1486    msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
1487
1488    /*
1489     * Test the size of the pba_offset variable and catch if it extends outside
1490     * of the specified BAR. If it is the case, we need to apply a hardware
1491     * specific quirk if the device is known or we have a broken configuration.
1492     */
1493    if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) {
1494        /*
1495         * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
1496         * adapters. The T5 hardware returns an incorrect value of 0x8000 for
1497         * the VF PBA offset while the BAR itself is only 8k. The correct value
1498         * is 0x1000, so we hard code that here.
1499         */
1500        if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO &&
1501            (vdev->device_id & 0xff00) == 0x5800) {
1502            msix->pba_offset = 0x1000;
1503        } else if (vdev->msix_relo == OFF_AUTOPCIBAR_OFF) {
1504            error_setg(errp, "hardware reports invalid configuration, "
1505                       "MSIX PBA outside of specified BAR");
1506            g_free(msix);
1507            return;
1508        }
1509    }
1510
1511    trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar,
1512                                msix->table_offset, msix->entries);
1513    vdev->msix = msix;
1514
1515    vfio_pci_fixup_msix_region(vdev);
1516
1517    vfio_pci_relocate_msix(vdev, errp);
1518}
1519
1520static int vfio_msix_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
1521{
1522    int ret;
1523    Error *err = NULL;
1524
1525    vdev->msix->pending = g_malloc0(BITS_TO_LONGS(vdev->msix->entries) *
1526                                    sizeof(unsigned long));
1527    ret = msix_init(&vdev->pdev, vdev->msix->entries,
1528                    vdev->bars[vdev->msix->table_bar].mr,
1529                    vdev->msix->table_bar, vdev->msix->table_offset,
1530                    vdev->bars[vdev->msix->pba_bar].mr,
1531                    vdev->msix->pba_bar, vdev->msix->pba_offset, pos,
1532                    &err);
1533    if (ret < 0) {
1534        if (ret == -ENOTSUP) {
1535            warn_report_err(err);
1536            return 0;
1537        }
1538
1539        error_propagate(errp, err);
1540        return ret;
1541    }
1542
1543    /*
1544     * The PCI spec suggests that devices provide additional alignment for
1545     * MSI-X structures and avoid overlapping non-MSI-X related registers.
1546     * For an assigned device, this hopefully means that emulation of MSI-X
1547     * structures does not affect the performance of the device.  If devices
1548     * fail to provide that alignment, a significant performance penalty may
1549     * result, for instance Mellanox MT27500 VFs:
1550     * http://www.spinics.net/lists/kvm/msg125881.html
1551     *
1552     * The PBA is simply not that important for such a serious regression and
1553     * most drivers do not appear to look at it.  The solution for this is to
1554     * disable the PBA MemoryRegion unless it's being used.  We disable it
1555     * here and only enable it if a masked vector fires through QEMU.  As the
1556     * vector-use notifier is called, which occurs on unmask, we test whether
1557     * PBA emulation is needed and again disable if not.
1558     */
1559    memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
1560
1561    /*
1562     * The emulated machine may provide a paravirt interface for MSIX setup
1563     * so it is not strictly necessary to emulate MSIX here. This becomes
1564     * helpful when frequently accessed MMIO registers are located in
1565     * subpages adjacent to the MSIX table but the MSIX data containing page
1566     * cannot be mapped because of a host page size bigger than the MSIX table
1567     * alignment.
1568     */
1569    if (object_property_get_bool(OBJECT(qdev_get_machine()),
1570                                 "vfio-no-msix-emulation", NULL)) {
1571        memory_region_set_enabled(&vdev->pdev.msix_table_mmio, false);
1572    }
1573
1574    return 0;
1575}
1576
1577static void vfio_teardown_msi(VFIOPCIDevice *vdev)
1578{
1579    msi_uninit(&vdev->pdev);
1580
1581    if (vdev->msix) {
1582        msix_uninit(&vdev->pdev,
1583                    vdev->bars[vdev->msix->table_bar].mr,
1584                    vdev->bars[vdev->msix->pba_bar].mr);
1585        g_free(vdev->msix->pending);
1586    }
1587}
1588
1589/*
1590 * Resource setup
1591 */
1592static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
1593{
1594    int i;
1595
1596    for (i = 0; i < PCI_ROM_SLOT; i++) {
1597        vfio_region_mmaps_set_enabled(&vdev->bars[i].region, enabled);
1598    }
1599}
1600
1601static void vfio_bar_prepare(VFIOPCIDevice *vdev, int nr)
1602{
1603    VFIOBAR *bar = &vdev->bars[nr];
1604
1605    uint32_t pci_bar;
1606    int ret;
1607
1608    /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
1609    if (!bar->region.size) {
1610        return;
1611    }
1612
1613    /* Determine what type of BAR this is for registration */
1614    ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
1615                vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
1616    if (ret != sizeof(pci_bar)) {
1617        error_report("vfio: Failed to read BAR %d (%m)", nr);
1618        return;
1619    }
1620
1621    pci_bar = le32_to_cpu(pci_bar);
1622    bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
1623    bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
1624    bar->type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
1625                                         ~PCI_BASE_ADDRESS_MEM_MASK);
1626    bar->size = bar->region.size;
1627}
1628
1629static void vfio_bars_prepare(VFIOPCIDevice *vdev)
1630{
1631    int i;
1632
1633    for (i = 0; i < PCI_ROM_SLOT; i++) {
1634        vfio_bar_prepare(vdev, i);
1635    }
1636}
1637
1638static void vfio_bar_register(VFIOPCIDevice *vdev, int nr)
1639{
1640    VFIOBAR *bar = &vdev->bars[nr];
1641    char *name;
1642
1643    if (!bar->size) {
1644        return;
1645    }
1646
1647    bar->mr = g_new0(MemoryRegion, 1);
1648    name = g_strdup_printf("%s base BAR %d", vdev->vbasedev.name, nr);
1649    memory_region_init_io(bar->mr, OBJECT(vdev), NULL, NULL, name, bar->size);
1650    g_free(name);
1651
1652    if (bar->region.size) {
1653        memory_region_add_subregion(bar->mr, 0, bar->region.mem);
1654
1655        if (vfio_region_mmap(&bar->region)) {
1656            error_report("Failed to mmap %s BAR %d. Performance may be slow",
1657                         vdev->vbasedev.name, nr);
1658        }
1659    }
1660
1661    pci_register_bar(&vdev->pdev, nr, bar->type, bar->mr);
1662}
1663
1664static void vfio_bars_register(VFIOPCIDevice *vdev)
1665{
1666    int i;
1667
1668    for (i = 0; i < PCI_ROM_SLOT; i++) {
1669        vfio_bar_register(vdev, i);
1670    }
1671}
1672
1673static void vfio_bars_exit(VFIOPCIDevice *vdev)
1674{
1675    int i;
1676
1677    for (i = 0; i < PCI_ROM_SLOT; i++) {
1678        VFIOBAR *bar = &vdev->bars[i];
1679
1680        vfio_bar_quirk_exit(vdev, i);
1681        vfio_region_exit(&bar->region);
1682        if (bar->region.size) {
1683            memory_region_del_subregion(bar->mr, bar->region.mem);
1684        }
1685    }
1686
1687    if (vdev->vga) {
1688        pci_unregister_vga(&vdev->pdev);
1689        vfio_vga_quirk_exit(vdev);
1690    }
1691}
1692
1693static void vfio_bars_finalize(VFIOPCIDevice *vdev)
1694{
1695    int i;
1696
1697    for (i = 0; i < PCI_ROM_SLOT; i++) {
1698        VFIOBAR *bar = &vdev->bars[i];
1699
1700        vfio_bar_quirk_finalize(vdev, i);
1701        vfio_region_finalize(&bar->region);
1702        if (bar->size) {
1703            object_unparent(OBJECT(bar->mr));
1704            g_free(bar->mr);
1705        }
1706    }
1707
1708    if (vdev->vga) {
1709        vfio_vga_quirk_finalize(vdev);
1710        for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
1711            object_unparent(OBJECT(&vdev->vga->region[i].mem));
1712        }
1713        g_free(vdev->vga);
1714    }
1715}
1716
1717/*
1718 * General setup
1719 */
1720static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
1721{
1722    uint8_t tmp;
1723    uint16_t next = PCI_CONFIG_SPACE_SIZE;
1724
1725    for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
1726         tmp = pdev->config[tmp + PCI_CAP_LIST_NEXT]) {
1727        if (tmp > pos && tmp < next) {
1728            next = tmp;
1729        }
1730    }
1731
1732    return next - pos;
1733}
1734
1735
1736static uint16_t vfio_ext_cap_max_size(const uint8_t *config, uint16_t pos)
1737{
1738    uint16_t tmp, next = PCIE_CONFIG_SPACE_SIZE;
1739
1740    for (tmp = PCI_CONFIG_SPACE_SIZE; tmp;
1741        tmp = PCI_EXT_CAP_NEXT(pci_get_long(config + tmp))) {
1742        if (tmp > pos && tmp < next) {
1743            next = tmp;
1744        }
1745    }
1746
1747    return next - pos;
1748}
1749
1750static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
1751{
1752    pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
1753}
1754
1755static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
1756                                   uint16_t val, uint16_t mask)
1757{
1758    vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
1759    vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
1760    vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
1761}
1762
1763static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
1764{
1765    pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
1766}
1767
1768static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
1769                                   uint32_t val, uint32_t mask)
1770{
1771    vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
1772    vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
1773    vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
1774}
1775
1776static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,
1777                               Error **errp)
1778{
1779    uint16_t flags;
1780    uint8_t type;
1781
1782    flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
1783    type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
1784
1785    if (type != PCI_EXP_TYPE_ENDPOINT &&
1786        type != PCI_EXP_TYPE_LEG_END &&
1787        type != PCI_EXP_TYPE_RC_END) {
1788
1789        error_setg(errp, "assignment of PCIe type 0x%x "
1790                   "devices is not currently supported", type);
1791        return -EINVAL;
1792    }
1793
1794    if (!pci_bus_is_express(pci_get_bus(&vdev->pdev))) {
1795        PCIBus *bus = pci_get_bus(&vdev->pdev);
1796        PCIDevice *bridge;
1797
1798        /*
1799         * Traditionally PCI device assignment exposes the PCIe capability
1800         * as-is on non-express buses.  The reason being that some drivers
1801         * simply assume that it's there, for example tg3.  However when
1802         * we're running on a native PCIe machine type, like Q35, we need
1803         * to hide the PCIe capability.  The reason for this is twofold;
1804         * first Windows guests get a Code 10 error when the PCIe capability
1805         * is exposed in this configuration.  Therefore express devices won't
1806         * work at all unless they're attached to express buses in the VM.
1807         * Second, a native PCIe machine introduces the possibility of fine
1808         * granularity IOMMUs supporting both translation and isolation.
1809         * Guest code to discover the IOMMU visibility of a device, such as
1810         * IOMMU grouping code on Linux, is very aware of device types and
1811         * valid transitions between bus types.  An express device on a non-
1812         * express bus is not a valid combination on bare metal systems.
1813         *
1814         * Drivers that require a PCIe capability to make the device
1815         * functional are simply going to need to have their devices placed
1816         * on a PCIe bus in the VM.
1817         */
1818        while (!pci_bus_is_root(bus)) {
1819            bridge = pci_bridge_get_device(bus);
1820            bus = pci_get_bus(bridge);
1821        }
1822
1823        if (pci_bus_is_express(bus)) {
1824            return 0;
1825        }
1826
1827    } else if (pci_bus_is_root(pci_get_bus(&vdev->pdev))) {
1828        /*
1829         * On a Root Complex bus Endpoints become Root Complex Integrated
1830         * Endpoints, which changes the type and clears the LNK & LNK2 fields.
1831         */
1832        if (type == PCI_EXP_TYPE_ENDPOINT) {
1833            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1834                                   PCI_EXP_TYPE_RC_END << 4,
1835                                   PCI_EXP_FLAGS_TYPE);
1836
1837            /* Link Capabilities, Status, and Control goes away */
1838            if (size > PCI_EXP_LNKCTL) {
1839                vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
1840                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1841                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
1842
1843#ifndef PCI_EXP_LNKCAP2
1844#define PCI_EXP_LNKCAP2 44
1845#endif
1846#ifndef PCI_EXP_LNKSTA2
1847#define PCI_EXP_LNKSTA2 50
1848#endif
1849                /* Link 2 Capabilities, Status, and Control goes away */
1850                if (size > PCI_EXP_LNKCAP2) {
1851                    vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
1852                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
1853                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
1854                }
1855            }
1856
1857        } else if (type == PCI_EXP_TYPE_LEG_END) {
1858            /*
1859             * Legacy endpoints don't belong on the root complex.  Windows
1860             * seems to be happier with devices if we skip the capability.
1861             */
1862            return 0;
1863        }
1864
1865    } else {
1866        /*
1867         * Convert Root Complex Integrated Endpoints to regular endpoints.
1868         * These devices don't support LNK/LNK2 capabilities, so make them up.
1869         */
1870        if (type == PCI_EXP_TYPE_RC_END) {
1871            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1872                                   PCI_EXP_TYPE_ENDPOINT << 4,
1873                                   PCI_EXP_FLAGS_TYPE);
1874            vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
1875                           QEMU_PCI_EXP_LNKCAP_MLW(QEMU_PCI_EXP_LNK_X1) |
1876                           QEMU_PCI_EXP_LNKCAP_MLS(QEMU_PCI_EXP_LNK_2_5GT), ~0);
1877            vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1878        }
1879    }
1880
1881    /*
1882     * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0
1883     * (Niantic errate #35) causing Windows to error with a Code 10 for the
1884     * device on Q35.  Fixup any such devices to report version 1.  If we
1885     * were to remove the capability entirely the guest would lose extended
1886     * config space.
1887     */
1888    if ((flags & PCI_EXP_FLAGS_VERS) == 0) {
1889        vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1890                               1, PCI_EXP_FLAGS_VERS);
1891    }
1892
1893    pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,
1894                             errp);
1895    if (pos < 0) {
1896        return pos;
1897    }
1898
1899    vdev->pdev.exp.exp_cap = pos;
1900
1901    return pos;
1902}
1903
1904static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
1905{
1906    uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
1907
1908    if (cap & PCI_EXP_DEVCAP_FLR) {
1909        trace_vfio_check_pcie_flr(vdev->vbasedev.name);
1910        vdev->has_flr = true;
1911    }
1912}
1913
1914static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
1915{
1916    uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
1917
1918    if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
1919        trace_vfio_check_pm_reset(vdev->vbasedev.name);
1920        vdev->has_pm_reset = true;
1921    }
1922}
1923
1924static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
1925{
1926    uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
1927
1928    if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
1929        trace_vfio_check_af_flr(vdev->vbasedev.name);
1930        vdev->has_flr = true;
1931    }
1932}
1933
1934static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos, Error **errp)
1935{
1936    PCIDevice *pdev = &vdev->pdev;
1937    uint8_t cap_id, next, size;
1938    int ret;
1939
1940    cap_id = pdev->config[pos];
1941    next = pdev->config[pos + PCI_CAP_LIST_NEXT];
1942
1943    /*
1944     * If it becomes important to configure capabilities to their actual
1945     * size, use this as the default when it's something we don't recognize.
1946     * Since QEMU doesn't actually handle many of the config accesses,
1947     * exact size doesn't seem worthwhile.
1948     */
1949    size = vfio_std_cap_max_size(pdev, pos);
1950
1951    /*
1952     * pci_add_capability always inserts the new capability at the head
1953     * of the chain.  Therefore to end up with a chain that matches the
1954     * physical device, we insert from the end by making this recursive.
1955     * This is also why we pre-calculate size above as cached config space
1956     * will be changed as we unwind the stack.
1957     */
1958    if (next) {
1959        ret = vfio_add_std_cap(vdev, next, errp);
1960        if (ret) {
1961            return ret;
1962        }
1963    } else {
1964        /* Begin the rebuild, use QEMU emulated list bits */
1965        pdev->config[PCI_CAPABILITY_LIST] = 0;
1966        vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
1967        vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1968
1969        ret = vfio_add_virt_caps(vdev, errp);
1970        if (ret) {
1971            return ret;
1972        }
1973    }
1974
1975    /* Scale down size, esp in case virt caps were added above */
1976    size = MIN(size, vfio_std_cap_max_size(pdev, pos));
1977
1978    /* Use emulated next pointer to allow dropping caps */
1979    pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff);
1980
1981    switch (cap_id) {
1982    case PCI_CAP_ID_MSI:
1983        ret = vfio_msi_setup(vdev, pos, errp);
1984        break;
1985    case PCI_CAP_ID_EXP:
1986        vfio_check_pcie_flr(vdev, pos);
1987        ret = vfio_setup_pcie_cap(vdev, pos, size, errp);
1988        break;
1989    case PCI_CAP_ID_MSIX:
1990        ret = vfio_msix_setup(vdev, pos, errp);
1991        break;
1992    case PCI_CAP_ID_PM:
1993        vfio_check_pm_reset(vdev, pos);
1994        vdev->pm_cap = pos;
1995        ret = pci_add_capability(pdev, cap_id, pos, size, errp);
1996        break;
1997    case PCI_CAP_ID_AF:
1998        vfio_check_af_flr(vdev, pos);
1999        ret = pci_add_capability(pdev, cap_id, pos, size, errp);
2000        break;
2001    default:
2002        ret = pci_add_capability(pdev, cap_id, pos, size, errp);
2003        break;
2004    }
2005
2006    if (ret < 0) {
2007        error_prepend(errp,
2008                      "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
2009                      cap_id, size, pos);
2010        return ret;
2011    }
2012
2013    return 0;
2014}
2015
2016static void vfio_add_ext_cap(VFIOPCIDevice *vdev)
2017{
2018    PCIDevice *pdev = &vdev->pdev;
2019    uint32_t header;
2020    uint16_t cap_id, next, size;
2021    uint8_t cap_ver;
2022    uint8_t *config;
2023
2024    /* Only add extended caps if we have them and the guest can see them */
2025    if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) ||
2026        !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) {
2027        return;
2028    }
2029
2030    /*
2031     * pcie_add_capability always inserts the new capability at the tail
2032     * of the chain.  Therefore to end up with a chain that matches the
2033     * physical device, we cache the config space to avoid overwriting
2034     * the original config space when we parse the extended capabilities.
2035     */
2036    config = g_memdup(pdev->config, vdev->config_size);
2037
2038    /*
2039     * Extended capabilities are chained with each pointing to the next, so we
2040     * can drop anything other than the head of the chain simply by modifying
2041     * the previous next pointer.  Seed the head of the chain here such that
2042     * we can simply skip any capabilities we want to drop below, regardless
2043     * of their position in the chain.  If this stub capability still exists
2044     * after we add the capabilities we want to expose, update the capability
2045     * ID to zero.  Note that we cannot seed with the capability header being
2046     * zero as this conflicts with definition of an absent capability chain
2047     * and prevents capabilities beyond the head of the list from being added.
2048     * By replacing the dummy capability ID with zero after walking the device
2049     * chain, we also transparently mark extended capabilities as absent if
2050     * no capabilities were added.  Note that the PCIe spec defines an absence
2051     * of extended capabilities to be determined by a value of zero for the
2052     * capability ID, version, AND next pointer.  A non-zero next pointer
2053     * should be sufficient to indicate additional capabilities are present,
2054     * which will occur if we call pcie_add_capability() below.  The entire
2055     * first dword is emulated to support this.
2056     *
2057     * NB. The kernel side does similar masking, so be prepared that our
2058     * view of the device may also contain a capability ID zero in the head
2059     * of the chain.  Skip it for the same reason that we cannot seed the
2060     * chain with a zero capability.
2061     */
2062    pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE,
2063                 PCI_EXT_CAP(0xFFFF, 0, 0));
2064    pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0);
2065    pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0);
2066
2067    for (next = PCI_CONFIG_SPACE_SIZE; next;
2068         next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) {
2069        header = pci_get_long(config + next);
2070        cap_id = PCI_EXT_CAP_ID(header);
2071        cap_ver = PCI_EXT_CAP_VER(header);
2072
2073        /*
2074         * If it becomes important to configure extended capabilities to their
2075         * actual size, use this as the default when it's something we don't
2076         * recognize. Since QEMU doesn't actually handle many of the config
2077         * accesses, exact size doesn't seem worthwhile.
2078         */
2079        size = vfio_ext_cap_max_size(config, next);
2080
2081        /* Use emulated next pointer to allow dropping extended caps */
2082        pci_long_test_and_set_mask(vdev->emulated_config_bits + next,
2083                                   PCI_EXT_CAP_NEXT_MASK);
2084
2085        switch (cap_id) {
2086        case 0: /* kernel masked capability */
2087        case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */
2088        case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */
2089        case PCI_EXT_CAP_ID_REBAR: /* Can't expose read-only */
2090            trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next);
2091            break;
2092        default:
2093            pcie_add_capability(pdev, cap_id, cap_ver, next, size);
2094        }
2095
2096    }
2097
2098    /* Cleanup chain head ID if necessary */
2099    if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) {
2100        pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0);
2101    }
2102
2103    g_free(config);
2104    return;
2105}
2106
2107static int vfio_add_capabilities(VFIOPCIDevice *vdev, Error **errp)
2108{
2109    PCIDevice *pdev = &vdev->pdev;
2110    int ret;
2111
2112    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2113        !pdev->config[PCI_CAPABILITY_LIST]) {
2114        return 0; /* Nothing to add */
2115    }
2116
2117    ret = vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp);
2118    if (ret) {
2119        return ret;
2120    }
2121
2122    vfio_add_ext_cap(vdev);
2123    return 0;
2124}
2125
2126static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
2127{
2128    PCIDevice *pdev = &vdev->pdev;
2129    uint16_t cmd;
2130
2131    vfio_disable_interrupts(vdev);
2132
2133    /* Make sure the device is in D0 */
2134    if (vdev->pm_cap) {
2135        uint16_t pmcsr;
2136        uint8_t state;
2137
2138        pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2139        state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2140        if (state) {
2141            pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2142            vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2143            /* vfio handles the necessary delay here */
2144            pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2145            state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2146            if (state) {
2147                error_report("vfio: Unable to power on device, stuck in D%d",
2148                             state);
2149            }
2150        }
2151    }
2152
2153    /*
2154     * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
2155     * Also put INTx Disable in known state.
2156     */
2157    cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2158    cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2159             PCI_COMMAND_INTX_DISABLE);
2160    vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2161}
2162
2163static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
2164{
2165    Error *err = NULL;
2166    int nr;
2167
2168    vfio_intx_enable(vdev, &err);
2169    if (err) {
2170        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2171    }
2172
2173    for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) {
2174        off_t addr = vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr);
2175        uint32_t val = 0;
2176        uint32_t len = sizeof(val);
2177
2178        if (pwrite(vdev->vbasedev.fd, &val, len, addr) != len) {
2179            error_report("%s(%s) reset bar %d failed: %m", __func__,
2180                         vdev->vbasedev.name, nr);
2181        }
2182    }
2183
2184    vfio_quirk_reset(vdev);
2185}
2186
2187static bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
2188{
2189    char tmp[13];
2190
2191    sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
2192            addr->bus, addr->slot, addr->function);
2193
2194    return (strcmp(tmp, name) == 0);
2195}
2196
2197static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
2198{
2199    VFIOGroup *group;
2200    struct vfio_pci_hot_reset_info *info;
2201    struct vfio_pci_dependent_device *devices;
2202    struct vfio_pci_hot_reset *reset;
2203    int32_t *fds;
2204    int ret, i, count;
2205    bool multi = false;
2206
2207    trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
2208
2209    if (!single) {
2210        vfio_pci_pre_reset(vdev);
2211    }
2212    vdev->vbasedev.needs_reset = false;
2213
2214    info = g_malloc0(sizeof(*info));
2215    info->argsz = sizeof(*info);
2216
2217    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2218    if (ret && errno != ENOSPC) {
2219        ret = -errno;
2220        if (!vdev->has_pm_reset) {
2221            error_report("vfio: Cannot reset device %s, "
2222                         "no available reset mechanism.", vdev->vbasedev.name);
2223        }
2224        goto out_single;
2225    }
2226
2227    count = info->count;
2228    info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2229    info->argsz = sizeof(*info) + (count * sizeof(*devices));
2230    devices = &info->devices[0];
2231
2232    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2233    if (ret) {
2234        ret = -errno;
2235        error_report("vfio: hot reset info failed: %m");
2236        goto out_single;
2237    }
2238
2239    trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
2240
2241    /* Verify that we have all the groups required */
2242    for (i = 0; i < info->count; i++) {
2243        PCIHostDeviceAddress host;
2244        VFIOPCIDevice *tmp;
2245        VFIODevice *vbasedev_iter;
2246
2247        host.domain = devices[i].segment;
2248        host.bus = devices[i].bus;
2249        host.slot = PCI_SLOT(devices[i].devfn);
2250        host.function = PCI_FUNC(devices[i].devfn);
2251
2252        trace_vfio_pci_hot_reset_dep_devices(host.domain,
2253                host.bus, host.slot, host.function, devices[i].group_id);
2254
2255        if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
2256            continue;
2257        }
2258
2259        QLIST_FOREACH(group, &vfio_group_list, next) {
2260            if (group->groupid == devices[i].group_id) {
2261                break;
2262            }
2263        }
2264
2265        if (!group) {
2266            if (!vdev->has_pm_reset) {
2267                error_report("vfio: Cannot reset device %s, "
2268                             "depends on group %d which is not owned.",
2269                             vdev->vbasedev.name, devices[i].group_id);
2270            }
2271            ret = -EPERM;
2272            goto out;
2273        }
2274
2275        /* Prep dependent devices for reset and clear our marker. */
2276        QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2277            if (!vbasedev_iter->dev->realized ||
2278                vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2279                continue;
2280            }
2281            tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2282            if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
2283                if (single) {
2284                    ret = -EINVAL;
2285                    goto out_single;
2286                }
2287                vfio_pci_pre_reset(tmp);
2288                tmp->vbasedev.needs_reset = false;
2289                multi = true;
2290                break;
2291            }
2292        }
2293    }
2294
2295    if (!single && !multi) {
2296        ret = -EINVAL;
2297        goto out_single;
2298    }
2299
2300    /* Determine how many group fds need to be passed */
2301    count = 0;
2302    QLIST_FOREACH(group, &vfio_group_list, next) {
2303        for (i = 0; i < info->count; i++) {
2304            if (group->groupid == devices[i].group_id) {
2305                count++;
2306                break;
2307            }
2308        }
2309    }
2310
2311    reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2312    reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2313    fds = &reset->group_fds[0];
2314
2315    /* Fill in group fds */
2316    QLIST_FOREACH(group, &vfio_group_list, next) {
2317        for (i = 0; i < info->count; i++) {
2318            if (group->groupid == devices[i].group_id) {
2319                fds[reset->count++] = group->fd;
2320                break;
2321            }
2322        }
2323    }
2324
2325    /* Bus reset! */
2326    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
2327    g_free(reset);
2328
2329    trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
2330                                    ret ? "%m" : "Success");
2331
2332out:
2333    /* Re-enable INTx on affected devices */
2334    for (i = 0; i < info->count; i++) {
2335        PCIHostDeviceAddress host;
2336        VFIOPCIDevice *tmp;
2337        VFIODevice *vbasedev_iter;
2338
2339        host.domain = devices[i].segment;
2340        host.bus = devices[i].bus;
2341        host.slot = PCI_SLOT(devices[i].devfn);
2342        host.function = PCI_FUNC(devices[i].devfn);
2343
2344        if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
2345            continue;
2346        }
2347
2348        QLIST_FOREACH(group, &vfio_group_list, next) {
2349            if (group->groupid == devices[i].group_id) {
2350                break;
2351            }
2352        }
2353
2354        if (!group) {
2355            break;
2356        }
2357
2358        QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2359            if (!vbasedev_iter->dev->realized ||
2360                vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2361                continue;
2362            }
2363            tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2364            if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
2365                vfio_pci_post_reset(tmp);
2366                break;
2367            }
2368        }
2369    }
2370out_single:
2371    if (!single) {
2372        vfio_pci_post_reset(vdev);
2373    }
2374    g_free(info);
2375
2376    return ret;
2377}
2378
2379/*
2380 * We want to differentiate hot reset of mulitple in-use devices vs hot reset
2381 * of a single in-use device.  VFIO_DEVICE_RESET will already handle the case
2382 * of doing hot resets when there is only a single device per bus.  The in-use
2383 * here refers to how many VFIODevices are affected.  A hot reset that affects
2384 * multiple devices, but only a single in-use device, means that we can call
2385 * it from our bus ->reset() callback since the extent is effectively a single
2386 * device.  This allows us to make use of it in the hotplug path.  When there
2387 * are multiple in-use devices, we can only trigger the hot reset during a
2388 * system reset and thus from our reset handler.  We separate _one vs _multi
2389 * here so that we don't overlap and do a double reset on the system reset
2390 * path where both our reset handler and ->reset() callback are used.  Calling
2391 * _one() will only do a hot reset for the one in-use devices case, calling
2392 * _multi() will do nothing if a _one() would have been sufficient.
2393 */
2394static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
2395{
2396    return vfio_pci_hot_reset(vdev, true);
2397}
2398
2399static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
2400{
2401    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2402    return vfio_pci_hot_reset(vdev, false);
2403}
2404
2405static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
2406{
2407    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2408    if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
2409        vbasedev->needs_reset = true;
2410    }
2411}
2412
2413static Object *vfio_pci_get_object(VFIODevice *vbasedev)
2414{
2415    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2416
2417    return OBJECT(vdev);
2418}
2419
2420static bool vfio_msix_present(void *opaque, int version_id)
2421{
2422    PCIDevice *pdev = opaque;
2423
2424    return msix_present(pdev);
2425}
2426
2427const VMStateDescription vmstate_vfio_pci_config = {
2428    .name = "VFIOPCIDevice",
2429    .version_id = 1,
2430    .minimum_version_id = 1,
2431    .fields = (VMStateField[]) {
2432        VMSTATE_PCI_DEVICE(pdev, VFIOPCIDevice),
2433        VMSTATE_MSIX_TEST(pdev, VFIOPCIDevice, vfio_msix_present),
2434        VMSTATE_END_OF_LIST()
2435    }
2436};
2437
2438static void vfio_pci_save_config(VFIODevice *vbasedev, QEMUFile *f)
2439{
2440    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2441
2442    vmstate_save_state(f, &vmstate_vfio_pci_config, vdev, NULL);
2443}
2444
2445static int vfio_pci_load_config(VFIODevice *vbasedev, QEMUFile *f)
2446{
2447    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2448    PCIDevice *pdev = &vdev->pdev;
2449    int ret;
2450
2451    ret = vmstate_load_state(f, &vmstate_vfio_pci_config, vdev, 1);
2452    if (ret) {
2453        return ret;
2454    }
2455
2456    vfio_pci_write_config(pdev, PCI_COMMAND,
2457                          pci_get_word(pdev->config + PCI_COMMAND), 2);
2458
2459    if (msi_enabled(pdev)) {
2460        vfio_msi_enable(vdev);
2461    } else if (msix_enabled(pdev)) {
2462        vfio_msix_enable(vdev);
2463    }
2464
2465    return ret;
2466}
2467
2468static VFIODeviceOps vfio_pci_ops = {
2469    .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
2470    .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
2471    .vfio_eoi = vfio_intx_eoi,
2472    .vfio_get_object = vfio_pci_get_object,
2473    .vfio_save_config = vfio_pci_save_config,
2474    .vfio_load_config = vfio_pci_load_config,
2475};
2476
2477int vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp)
2478{
2479    VFIODevice *vbasedev = &vdev->vbasedev;
2480    struct vfio_region_info *reg_info;
2481    int ret;
2482
2483    ret = vfio_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, &reg_info);
2484    if (ret) {
2485        error_setg_errno(errp, -ret,
2486                         "failed getting region info for VGA region index %d",
2487                         VFIO_PCI_VGA_REGION_INDEX);
2488        return ret;
2489    }
2490
2491    if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) ||
2492        !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) ||
2493        reg_info->size < 0xbffff + 1) {
2494        error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx",
2495                   (unsigned long)reg_info->flags,
2496                   (unsigned long)reg_info->size);
2497        g_free(reg_info);
2498        return -EINVAL;
2499    }
2500
2501    vdev->vga = g_new0(VFIOVGA, 1);
2502
2503    vdev->vga->fd_offset = reg_info->offset;
2504    vdev->vga->fd = vdev->vbasedev.fd;
2505
2506    g_free(reg_info);
2507
2508    vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
2509    vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
2510    QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks);
2511
2512    memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2513                          OBJECT(vdev), &vfio_vga_ops,
2514                          &vdev->vga->region[QEMU_PCI_VGA_MEM],
2515                          "vfio-vga-mmio@0xa0000",
2516                          QEMU_PCI_VGA_MEM_SIZE);
2517
2518    vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
2519    vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
2520    QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks);
2521
2522    memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2523                          OBJECT(vdev), &vfio_vga_ops,
2524                          &vdev->vga->region[QEMU_PCI_VGA_IO_LO],
2525                          "vfio-vga-io@0x3b0",
2526                          QEMU_PCI_VGA_IO_LO_SIZE);
2527
2528    vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
2529    vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
2530    QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks);
2531
2532    memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
2533                          OBJECT(vdev), &vfio_vga_ops,
2534                          &vdev->vga->region[QEMU_PCI_VGA_IO_HI],
2535                          "vfio-vga-io@0x3c0",
2536                          QEMU_PCI_VGA_IO_HI_SIZE);
2537
2538    pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2539                     &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2540                     &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem);
2541
2542    return 0;
2543}
2544
2545static void vfio_populate_device(VFIOPCIDevice *vdev, Error **errp)
2546{
2547    VFIODevice *vbasedev = &vdev->vbasedev;
2548    struct vfio_region_info *reg_info;
2549    struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
2550    int i, ret = -1;
2551
2552    /* Sanity check device */
2553    if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
2554        error_setg(errp, "this isn't a PCI device");
2555        return;
2556    }
2557
2558    if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
2559        error_setg(errp, "unexpected number of io regions %u",
2560                   vbasedev->num_regions);
2561        return;
2562    }
2563
2564    if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
2565        error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs);
2566        return;
2567    }
2568
2569    for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
2570        char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i);
2571
2572        ret = vfio_region_setup(OBJECT(vdev), vbasedev,
2573                                &vdev->bars[i].region, i, name);
2574        g_free(name);
2575
2576        if (ret) {
2577            error_setg_errno(errp, -ret, "failed to get region %d info", i);
2578            return;
2579        }
2580
2581        QLIST_INIT(&vdev->bars[i].quirks);
2582    }
2583
2584    ret = vfio_get_region_info(vbasedev,
2585                               VFIO_PCI_CONFIG_REGION_INDEX, &reg_info);
2586    if (ret) {
2587        error_setg_errno(errp, -ret, "failed to get config info");
2588        return;
2589    }
2590
2591    trace_vfio_populate_device_config(vdev->vbasedev.name,
2592                                      (unsigned long)reg_info->size,
2593                                      (unsigned long)reg_info->offset,
2594                                      (unsigned long)reg_info->flags);
2595
2596    vdev->config_size = reg_info->size;
2597    if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
2598        vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
2599    }
2600    vdev->config_offset = reg_info->offset;
2601
2602    g_free(reg_info);
2603
2604    if (vdev->features & VFIO_FEATURE_ENABLE_VGA) {
2605        ret = vfio_populate_vga(vdev, errp);
2606        if (ret) {
2607            error_append_hint(errp, "device does not support "
2608                              "requested feature x-vga\n");
2609            return;
2610        }
2611    }
2612
2613    irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
2614
2615    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
2616    if (ret) {
2617        /* This can fail for an old kernel or legacy PCI dev */
2618        trace_vfio_populate_device_get_irq_info_failure(strerror(errno));
2619    } else if (irq_info.count == 1) {
2620        vdev->pci_aer = true;
2621    } else {
2622        warn_report(VFIO_MSG_PREFIX
2623                    "Could not enable error recovery for the device",
2624                    vbasedev->name);
2625    }
2626}
2627
2628static void vfio_put_device(VFIOPCIDevice *vdev)
2629{
2630    g_free(vdev->vbasedev.name);
2631    g_free(vdev->msix);
2632
2633    vfio_put_base_device(&vdev->vbasedev);
2634}
2635
2636static void vfio_err_notifier_handler(void *opaque)
2637{
2638    VFIOPCIDevice *vdev = opaque;
2639
2640    if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
2641        return;
2642    }
2643
2644    /*
2645     * TBD. Retrieve the error details and decide what action
2646     * needs to be taken. One of the actions could be to pass
2647     * the error to the guest and have the guest driver recover
2648     * from the error. This requires that PCIe capabilities be
2649     * exposed to the guest. For now, we just terminate the
2650     * guest to contain the error.
2651     */
2652
2653    error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name);
2654
2655    vm_stop(RUN_STATE_INTERNAL_ERROR);
2656}
2657
2658/*
2659 * Registers error notifier for devices supporting error recovery.
2660 * If we encounter a failure in this function, we report an error
2661 * and continue after disabling error recovery support for the
2662 * device.
2663 */
2664static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
2665{
2666    Error *err = NULL;
2667    int32_t fd;
2668
2669    if (!vdev->pci_aer) {
2670        return;
2671    }
2672
2673    if (event_notifier_init(&vdev->err_notifier, 0)) {
2674        error_report("vfio: Unable to init event notifier for error detection");
2675        vdev->pci_aer = false;
2676        return;
2677    }
2678
2679    fd = event_notifier_get_fd(&vdev->err_notifier);
2680    qemu_set_fd_handler(fd, vfio_err_notifier_handler, NULL, vdev);
2681
2682    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
2683                               VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
2684        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2685        qemu_set_fd_handler(fd, NULL, NULL, vdev);
2686        event_notifier_cleanup(&vdev->err_notifier);
2687        vdev->pci_aer = false;
2688    }
2689}
2690
2691static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
2692{
2693    Error *err = NULL;
2694
2695    if (!vdev->pci_aer) {
2696        return;
2697    }
2698
2699    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
2700                               VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
2701        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2702    }
2703    qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
2704                        NULL, NULL, vdev);
2705    event_notifier_cleanup(&vdev->err_notifier);
2706}
2707
2708static void vfio_req_notifier_handler(void *opaque)
2709{
2710    VFIOPCIDevice *vdev = opaque;
2711    Error *err = NULL;
2712
2713    if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
2714        return;
2715    }
2716
2717    qdev_unplug(DEVICE(vdev), &err);
2718    if (err) {
2719        warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2720    }
2721}
2722
2723static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
2724{
2725    struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
2726                                      .index = VFIO_PCI_REQ_IRQ_INDEX };
2727    Error *err = NULL;
2728    int32_t fd;
2729
2730    if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
2731        return;
2732    }
2733
2734    if (ioctl(vdev->vbasedev.fd,
2735              VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
2736        return;
2737    }
2738
2739    if (event_notifier_init(&vdev->req_notifier, 0)) {
2740        error_report("vfio: Unable to init event notifier for device request");
2741        return;
2742    }
2743
2744    fd = event_notifier_get_fd(&vdev->req_notifier);
2745    qemu_set_fd_handler(fd, vfio_req_notifier_handler, NULL, vdev);
2746
2747    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
2748                           VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
2749        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2750        qemu_set_fd_handler(fd, NULL, NULL, vdev);
2751        event_notifier_cleanup(&vdev->req_notifier);
2752    } else {
2753        vdev->req_enabled = true;
2754    }
2755}
2756
2757static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
2758{
2759    Error *err = NULL;
2760
2761    if (!vdev->req_enabled) {
2762        return;
2763    }
2764
2765    if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
2766                               VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
2767        error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2768    }
2769    qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
2770                        NULL, NULL, vdev);
2771    event_notifier_cleanup(&vdev->req_notifier);
2772
2773    vdev->req_enabled = false;
2774}
2775
2776static void vfio_realize(PCIDevice *pdev, Error **errp)
2777{
2778    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
2779    VFIODevice *vbasedev_iter;
2780    VFIOGroup *group;
2781    char *tmp, *subsys, group_path[PATH_MAX], *group_name;
2782    Error *err = NULL;
2783    ssize_t len;
2784    struct stat st;
2785    int groupid;
2786    int i, ret;
2787    bool is_mdev;
2788
2789    if (!vdev->vbasedev.sysfsdev) {
2790        if (!(~vdev->host.domain || ~vdev->host.bus ||
2791              ~vdev->host.slot || ~vdev->host.function)) {
2792            error_setg(errp, "No provided host device");
2793            error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
2794                              "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
2795            return;
2796        }
2797        vdev->vbasedev.sysfsdev =
2798            g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
2799                            vdev->host.domain, vdev->host.bus,
2800                            vdev->host.slot, vdev->host.function);
2801    }
2802
2803    if (stat(vdev->vbasedev.sysfsdev, &st) < 0) {
2804        error_setg_errno(errp, errno, "no such host device");
2805        error_prepend(errp, VFIO_MSG_PREFIX, vdev->vbasedev.sysfsdev);
2806        return;
2807    }
2808
2809    vdev->vbasedev.name = g_path_get_basename(vdev->vbasedev.sysfsdev);
2810    vdev->vbasedev.ops = &vfio_pci_ops;
2811    vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
2812    vdev->vbasedev.dev = DEVICE(vdev);
2813
2814    tmp = g_strdup_printf("%s/iommu_group", vdev->vbasedev.sysfsdev);
2815    len = readlink(tmp, group_path, sizeof(group_path));
2816    g_free(tmp);
2817
2818    if (len <= 0 || len >= sizeof(group_path)) {
2819        error_setg_errno(errp, len < 0 ? errno : ENAMETOOLONG,
2820                         "no iommu_group found");
2821        goto error;
2822    }
2823
2824    group_path[len] = 0;
2825
2826    group_name = basename(group_path);
2827    if (sscanf(group_name, "%d", &groupid) != 1) {
2828        error_setg_errno(errp, errno, "failed to read %s", group_path);
2829        goto error;
2830    }
2831
2832    trace_vfio_realize(vdev->vbasedev.name, groupid);
2833
2834    group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev), errp);
2835    if (!group) {
2836        goto error;
2837    }
2838
2839    QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2840        if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
2841            error_setg(errp, "device is already attached");
2842            vfio_put_group(group);
2843            goto error;
2844        }
2845    }
2846
2847    /*
2848     * Mediated devices *might* operate compatibly with discarding of RAM, but
2849     * we cannot know for certain, it depends on whether the mdev vendor driver
2850     * stays in sync with the active working set of the guest driver.  Prevent
2851     * the x-balloon-allowed option unless this is minimally an mdev device.
2852     */
2853    tmp = g_strdup_printf("%s/subsystem", vdev->vbasedev.sysfsdev);
2854    subsys = realpath(tmp, NULL);
2855    g_free(tmp);
2856    is_mdev = subsys && (strcmp(subsys, "/sys/bus/mdev") == 0);
2857    free(subsys);
2858
2859    trace_vfio_mdev(vdev->vbasedev.name, is_mdev);
2860
2861    if (vdev->vbasedev.ram_block_discard_allowed && !is_mdev) {
2862        error_setg(errp, "x-balloon-allowed only potentially compatible "
2863                   "with mdev devices");
2864        vfio_put_group(group);
2865        goto error;
2866    }
2867
2868    ret = vfio_get_device(group, vdev->vbasedev.name, &vdev->vbasedev, errp);
2869    if (ret) {
2870        vfio_put_group(group);
2871        goto error;
2872    }
2873
2874    vfio_populate_device(vdev, &err);
2875    if (err) {
2876        error_propagate(errp, err);
2877        goto error;
2878    }
2879
2880    /* Get a copy of config space */
2881    ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
2882                MIN(pci_config_size(&vdev->pdev), vdev->config_size),
2883                vdev->config_offset);
2884    if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
2885        ret = ret < 0 ? -errno : -EFAULT;
2886        error_setg_errno(errp, -ret, "failed to read device config space");
2887        goto error;
2888    }
2889
2890    /* vfio emulates a lot for us, but some bits need extra love */
2891    vdev->emulated_config_bits = g_malloc0(vdev->config_size);
2892
2893    /* QEMU can choose to expose the ROM or not */
2894    memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
2895    /* QEMU can also add or extend BARs */
2896    memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4);
2897
2898    /*
2899     * The PCI spec reserves vendor ID 0xffff as an invalid value.  The
2900     * device ID is managed by the vendor and need only be a 16-bit value.
2901     * Allow any 16-bit value for subsystem so they can be hidden or changed.
2902     */
2903    if (vdev->vendor_id != PCI_ANY_ID) {
2904        if (vdev->vendor_id >= 0xffff) {
2905            error_setg(errp, "invalid PCI vendor ID provided");
2906            goto error;
2907        }
2908        vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
2909        trace_vfio_pci_emulated_vendor_id(vdev->vbasedev.name, vdev->vendor_id);
2910    } else {
2911        vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2912    }
2913
2914    if (vdev->device_id != PCI_ANY_ID) {
2915        if (vdev->device_id > 0xffff) {
2916            error_setg(errp, "invalid PCI device ID provided");
2917            goto error;
2918        }
2919        vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
2920        trace_vfio_pci_emulated_device_id(vdev->vbasedev.name, vdev->device_id);
2921    } else {
2922        vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2923    }
2924
2925    if (vdev->sub_vendor_id != PCI_ANY_ID) {
2926        if (vdev->sub_vendor_id > 0xffff) {
2927            error_setg(errp, "invalid PCI subsystem vendor ID provided");
2928            goto error;
2929        }
2930        vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
2931                               vdev->sub_vendor_id, ~0);
2932        trace_vfio_pci_emulated_sub_vendor_id(vdev->vbasedev.name,
2933                                              vdev->sub_vendor_id);
2934    }
2935
2936    if (vdev->sub_device_id != PCI_ANY_ID) {
2937        if (vdev->sub_device_id > 0xffff) {
2938            error_setg(errp, "invalid PCI subsystem device ID provided");
2939            goto error;
2940        }
2941        vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
2942        trace_vfio_pci_emulated_sub_device_id(vdev->vbasedev.name,
2943                                              vdev->sub_device_id);
2944    }
2945
2946    /* QEMU can change multi-function devices to single function, or reverse */
2947    vdev->emulated_config_bits[PCI_HEADER_TYPE] =
2948                                              PCI_HEADER_TYPE_MULTI_FUNCTION;
2949
2950    /* Restore or clear multifunction, this is always controlled by QEMU */
2951    if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
2952        vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
2953    } else {
2954        vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
2955    }
2956
2957    /*
2958     * Clear host resource mapping info.  If we choose not to register a
2959     * BAR, such as might be the case with the option ROM, we can get
2960     * confusing, unwritable, residual addresses from the host here.
2961     */
2962    memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
2963    memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
2964
2965    vfio_pci_size_rom(vdev);
2966
2967    vfio_bars_prepare(vdev);
2968
2969    vfio_msix_early_setup(vdev, &err);
2970    if (err) {
2971        error_propagate(errp, err);
2972        goto error;
2973    }
2974
2975    vfio_bars_register(vdev);
2976
2977    ret = vfio_add_capabilities(vdev, errp);
2978    if (ret) {
2979        goto out_teardown;
2980    }
2981
2982    if (vdev->vga) {
2983        vfio_vga_quirk_setup(vdev);
2984    }
2985
2986    for (i = 0; i < PCI_ROM_SLOT; i++) {
2987        vfio_bar_quirk_setup(vdev, i);
2988    }
2989
2990    if (!vdev->igd_opregion &&
2991        vdev->features & VFIO_FEATURE_ENABLE_IGD_OPREGION) {
2992        struct vfio_region_info *opregion;
2993
2994        if (vdev->pdev.qdev.hotplugged) {
2995            error_setg(errp,
2996                       "cannot support IGD OpRegion feature on hotplugged "
2997                       "device");
2998            goto out_teardown;
2999        }
3000
3001        ret = vfio_get_dev_region_info(&vdev->vbasedev,
3002                        VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
3003                        VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
3004        if (ret) {
3005            error_setg_errno(errp, -ret,
3006                             "does not support requested IGD OpRegion feature");
3007            goto out_teardown;
3008        }
3009
3010        ret = vfio_pci_igd_opregion_init(vdev, opregion, errp);
3011        g_free(opregion);
3012        if (ret) {
3013            goto out_teardown;
3014        }
3015    }
3016
3017    /* QEMU emulates all of MSI & MSIX */
3018    if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3019        memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3020               MSIX_CAP_LENGTH);
3021    }
3022
3023    if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3024        memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3025               vdev->msi_cap_size);
3026    }
3027
3028    if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
3029        vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
3030                                                  vfio_intx_mmap_enable, vdev);
3031        pci_device_set_intx_routing_notifier(&vdev->pdev,
3032                                             vfio_intx_routing_notifier);
3033        vdev->irqchip_change_notifier.notify = vfio_irqchip_change;
3034        kvm_irqchip_add_change_notifier(&vdev->irqchip_change_notifier);
3035        ret = vfio_intx_enable(vdev, errp);
3036        if (ret) {
3037            goto out_deregister;
3038        }
3039    }
3040
3041    if (vdev->display != ON_OFF_AUTO_OFF) {
3042        ret = vfio_display_probe(vdev, errp);
3043        if (ret) {
3044            goto out_deregister;
3045        }
3046    }
3047    if (vdev->enable_ramfb && vdev->dpy == NULL) {
3048        error_setg(errp, "ramfb=on requires display=on");
3049        goto out_deregister;
3050    }
3051    if (vdev->display_xres || vdev->display_yres) {
3052        if (vdev->dpy == NULL) {
3053            error_setg(errp, "xres and yres properties require display=on");
3054            goto out_deregister;
3055        }
3056        if (vdev->dpy->edid_regs == NULL) {
3057            error_setg(errp, "xres and yres properties need edid support");
3058            goto out_deregister;
3059        }
3060    }
3061
3062    if (vdev->vendor_id == PCI_VENDOR_ID_NVIDIA) {
3063        ret = vfio_pci_nvidia_v100_ram_init(vdev, errp);
3064        if (ret && ret != -ENODEV) {
3065            error_report("Failed to setup NVIDIA V100 GPU RAM");
3066        }
3067    }
3068
3069    if (vdev->vendor_id == PCI_VENDOR_ID_IBM) {
3070        ret = vfio_pci_nvlink2_init(vdev, errp);
3071        if (ret && ret != -ENODEV) {
3072            error_report("Failed to setup NVlink2 bridge");
3073        }
3074    }
3075
3076    if (!pdev->failover_pair_id) {
3077        ret = vfio_migration_probe(&vdev->vbasedev, errp);
3078        if (ret) {
3079            error_report("%s: Migration disabled", vdev->vbasedev.name);
3080        }
3081    }
3082
3083    vfio_register_err_notifier(vdev);
3084    vfio_register_req_notifier(vdev);
3085    vfio_setup_resetfn_quirk(vdev);
3086
3087    return;
3088
3089out_deregister:
3090    pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3091    kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
3092out_teardown:
3093    vfio_teardown_msi(vdev);
3094    vfio_bars_exit(vdev);
3095error:
3096    error_prepend(errp, VFIO_MSG_PREFIX, vdev->vbasedev.name);
3097}
3098
3099static void vfio_instance_finalize(Object *obj)
3100{
3101    VFIOPCIDevice *vdev = VFIO_PCI(obj);
3102    VFIOGroup *group = vdev->vbasedev.group;
3103
3104    vfio_display_finalize(vdev);
3105    vfio_bars_finalize(vdev);
3106    g_free(vdev->emulated_config_bits);
3107    g_free(vdev->rom);
3108    /*
3109     * XXX Leaking igd_opregion is not an oversight, we can't remove the
3110     * fw_cfg entry therefore leaking this allocation seems like the safest
3111     * option.
3112     *
3113     * g_free(vdev->igd_opregion);
3114     */
3115    vfio_put_device(vdev);
3116    vfio_put_group(group);
3117}
3118
3119static void vfio_exitfn(PCIDevice *pdev)
3120{
3121    VFIOPCIDevice *vdev = VFIO_PCI(pdev);
3122
3123    vfio_unregister_req_notifier(vdev);
3124    vfio_unregister_err_notifier(vdev);
3125    pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3126    if (vdev->irqchip_change_notifier.notify) {
3127        kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
3128    }
3129    vfio_disable_interrupts(vdev);
3130    if (vdev->intx.mmap_timer) {
3131        timer_free(vdev->intx.mmap_timer);
3132    }
3133    vfio_teardown_msi(vdev);
3134    vfio_bars_exit(vdev);
3135    vfio_migration_finalize(&vdev->vbasedev);
3136}
3137
3138static void vfio_pci_reset(DeviceState *dev)
3139{
3140    VFIOPCIDevice *vdev = VFIO_PCI(dev);
3141
3142    trace_vfio_pci_reset(vdev->vbasedev.name);
3143
3144    vfio_pci_pre_reset(vdev);
3145
3146    if (vdev->display != ON_OFF_AUTO_OFF) {
3147        vfio_display_reset(vdev);
3148    }
3149
3150    if (vdev->resetfn && !vdev->resetfn(vdev)) {
3151        goto post_reset;
3152    }
3153
3154    if (vdev->vbasedev.reset_works &&
3155        (vdev->has_flr || !vdev->has_pm_reset) &&
3156        !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3157        trace_vfio_pci_reset_flr(vdev->vbasedev.name);
3158        goto post_reset;
3159    }
3160
3161    /* See if we can do our own bus reset */
3162    if (!vfio_pci_hot_reset_one(vdev)) {
3163        goto post_reset;
3164    }
3165
3166    /* If nothing else works and the device supports PM reset, use it */
3167    if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
3168        !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3169        trace_vfio_pci_reset_pm(vdev->vbasedev.name);
3170        goto post_reset;
3171    }
3172
3173post_reset:
3174    vfio_pci_post_reset(vdev);
3175}
3176
3177static void vfio_instance_init(Object *obj)
3178{
3179    PCIDevice *pci_dev = PCI_DEVICE(obj);
3180    VFIOPCIDevice *vdev = VFIO_PCI(obj);
3181
3182    device_add_bootindex_property(obj, &vdev->bootindex,
3183                                  "bootindex", NULL,
3184                                  &pci_dev->qdev);
3185    vdev->host.domain = ~0U;
3186    vdev->host.bus = ~0U;
3187    vdev->host.slot = ~0U;
3188    vdev->host.function = ~0U;
3189
3190    vdev->nv_gpudirect_clique = 0xFF;
3191
3192    /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
3193     * line, therefore, no need to wait to realize like other devices */
3194    pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
3195}
3196
3197static Property vfio_pci_dev_properties[] = {
3198    DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
3199    DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev),
3200    DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice,
3201                            vbasedev.pre_copy_dirty_page_tracking,
3202                            ON_OFF_AUTO_ON),
3203    DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice,
3204                            display, ON_OFF_AUTO_OFF),
3205    DEFINE_PROP_UINT32("xres", VFIOPCIDevice, display_xres, 0),
3206    DEFINE_PROP_UINT32("yres", VFIOPCIDevice, display_yres, 0),
3207    DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
3208                       intx.mmap_timeout, 1100),
3209    DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
3210                    VFIO_FEATURE_ENABLE_VGA_BIT, false),
3211    DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
3212                    VFIO_FEATURE_ENABLE_REQ_BIT, true),
3213    DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features,
3214                    VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, false),
3215    DEFINE_PROP_BOOL("x-enable-migration", VFIOPCIDevice,
3216                     vbasedev.enable_migration, false),
3217    DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
3218    DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice,
3219                     vbasedev.ram_block_discard_allowed, false),
3220    DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
3221    DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
3222    DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
3223    DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice,
3224                     no_geforce_quirks, false),
3225    DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice, no_kvm_ioeventfd,
3226                     false),
3227    DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice, no_vfio_ioeventfd,
3228                     false),
3229    DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID),
3230    DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID),
3231    DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice,
3232                       sub_vendor_id, PCI_ANY_ID),
3233    DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice,
3234                       sub_device_id, PCI_ANY_ID),
3235    DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0),
3236    DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice,
3237                                   nv_gpudirect_clique,
3238                                   qdev_prop_nv_gpudirect_clique, uint8_t),
3239    DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
3240                                OFF_AUTOPCIBAR_OFF),
3241    /*
3242     * TODO - support passed fds... is this necessary?
3243     * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3244     * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
3245     */
3246    DEFINE_PROP_END_OF_LIST(),
3247};
3248
3249static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3250{
3251    DeviceClass *dc = DEVICE_CLASS(klass);
3252    PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3253
3254    dc->reset = vfio_pci_reset;
3255    device_class_set_props(dc, vfio_pci_dev_properties);
3256    dc->desc = "VFIO-based PCI device assignment";
3257    set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3258    pdc->realize = vfio_realize;
3259    pdc->exit = vfio_exitfn;
3260    pdc->config_read = vfio_pci_read_config;
3261    pdc->config_write = vfio_pci_write_config;
3262}
3263
3264static const TypeInfo vfio_pci_dev_info = {
3265    .name = TYPE_VFIO_PCI,
3266    .parent = TYPE_PCI_DEVICE,
3267    .instance_size = sizeof(VFIOPCIDevice),
3268    .class_init = vfio_pci_dev_class_init,
3269    .instance_init = vfio_instance_init,
3270    .instance_finalize = vfio_instance_finalize,
3271    .interfaces = (InterfaceInfo[]) {
3272        { INTERFACE_PCIE_DEVICE },
3273        { INTERFACE_CONVENTIONAL_PCI_DEVICE },
3274        { }
3275    },
3276};
3277
3278static Property vfio_pci_dev_nohotplug_properties[] = {
3279    DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice, enable_ramfb, false),
3280    DEFINE_PROP_END_OF_LIST(),
3281};
3282
3283static void vfio_pci_nohotplug_dev_class_init(ObjectClass *klass, void *data)
3284{
3285    DeviceClass *dc = DEVICE_CLASS(klass);
3286
3287    device_class_set_props(dc, vfio_pci_dev_nohotplug_properties);
3288    dc->hotpluggable = false;
3289}
3290
3291static const TypeInfo vfio_pci_nohotplug_dev_info = {
3292    .name = TYPE_VFIO_PCI_NOHOTPLUG,
3293    .parent = TYPE_VFIO_PCI,
3294    .instance_size = sizeof(VFIOPCIDevice),
3295    .class_init = vfio_pci_nohotplug_dev_class_init,
3296};
3297
3298static void register_vfio_pci_dev_type(void)
3299{
3300    type_register_static(&vfio_pci_dev_info);
3301    type_register_static(&vfio_pci_nohotplug_dev_info);
3302}
3303
3304type_init(register_vfio_pci_dev_type)
3305