qemu/hw/pci/pci.c
<<
>>
Prefs
   1/*
   2 * QEMU PCI bus manager
   3 *
   4 * Copyright (c) 2004 Fabrice Bellard
   5 *
   6 * Permission is hereby granted, free of charge, to any person obtaining a copy
   7 * of this software and associated documentation files (the "Software"), to deal
   8 * in the Software without restriction, including without limitation the rights
   9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10 * copies of the Software, and to permit persons to whom the Software is
  11 * furnished to do so, subject to the following conditions:
  12 *
  13 * The above copyright notice and this permission notice shall be included in
  14 * all copies or substantial portions of the Software.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22 * THE SOFTWARE.
  23 */
  24
  25#include "qemu/osdep.h"
  26#include "qemu/datadir.h"
  27#include "qemu/units.h"
  28#include "hw/irq.h"
  29#include "hw/pci/pci.h"
  30#include "hw/pci/pci_bridge.h"
  31#include "hw/pci/pci_bus.h"
  32#include "hw/pci/pci_host.h"
  33#include "hw/qdev-properties.h"
  34#include "hw/qdev-properties-system.h"
  35#include "migration/qemu-file-types.h"
  36#include "migration/vmstate.h"
  37#include "net/net.h"
  38#include "sysemu/numa.h"
  39#include "sysemu/sysemu.h"
  40#include "hw/loader.h"
  41#include "qemu/error-report.h"
  42#include "qemu/range.h"
  43#include "trace.h"
  44#include "hw/pci/msi.h"
  45#include "hw/pci/msix.h"
  46#include "hw/hotplug.h"
  47#include "hw/boards.h"
  48#include "qapi/error.h"
  49#include "qemu/cutils.h"
  50#include "pci-internal.h"
  51
  52#include "hw/xen/xen.h"
  53#include "hw/i386/kvm/xen_evtchn.h"
  54
  55//#define DEBUG_PCI
  56#ifdef DEBUG_PCI
  57# define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
  58#else
  59# define PCI_DPRINTF(format, ...)       do { } while (0)
  60#endif
  61
  62bool pci_available = true;
  63
  64static char *pcibus_get_dev_path(DeviceState *dev);
  65static char *pcibus_get_fw_dev_path(DeviceState *dev);
  66static void pcibus_reset(BusState *qbus);
  67
  68static Property pci_props[] = {
  69    DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
  70    DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
  71    DEFINE_PROP_UINT32("romsize", PCIDevice, romsize, -1),
  72    DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
  73    DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
  74                    QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
  75    DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
  76                    QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
  77    DEFINE_PROP_BIT("x-pcie-extcap-init", PCIDevice, cap_present,
  78                    QEMU_PCIE_EXTCAP_INIT_BITNR, true),
  79    DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
  80                       failover_pair_id),
  81    DEFINE_PROP_UINT32("acpi-index",  PCIDevice, acpi_index, 0),
  82    DEFINE_PROP_BIT("x-pcie-err-unc-mask", PCIDevice, cap_present,
  83                    QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
  84    DEFINE_PROP_END_OF_LIST()
  85};
  86
  87static const VMStateDescription vmstate_pcibus = {
  88    .name = "PCIBUS",
  89    .version_id = 1,
  90    .minimum_version_id = 1,
  91    .fields = (VMStateField[]) {
  92        VMSTATE_INT32_EQUAL(nirq, PCIBus, NULL),
  93        VMSTATE_VARRAY_INT32(irq_count, PCIBus,
  94                             nirq, 0, vmstate_info_int32,
  95                             int32_t),
  96        VMSTATE_END_OF_LIST()
  97    }
  98};
  99
 100static gint g_cmp_uint32(gconstpointer a, gconstpointer b, gpointer user_data)
 101{
 102    return a - b;
 103}
 104
 105static GSequence *pci_acpi_index_list(void)
 106{
 107    static GSequence *used_acpi_index_list;
 108
 109    if (!used_acpi_index_list) {
 110        used_acpi_index_list = g_sequence_new(NULL);
 111    }
 112    return used_acpi_index_list;
 113}
 114
 115static void pci_init_bus_master(PCIDevice *pci_dev)
 116{
 117    AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
 118
 119    memory_region_init_alias(&pci_dev->bus_master_enable_region,
 120                             OBJECT(pci_dev), "bus master",
 121                             dma_as->root, 0, memory_region_size(dma_as->root));
 122    memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
 123    memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
 124                                &pci_dev->bus_master_enable_region);
 125}
 126
 127static void pcibus_machine_done(Notifier *notifier, void *data)
 128{
 129    PCIBus *bus = container_of(notifier, PCIBus, machine_done);
 130    int i;
 131
 132    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
 133        if (bus->devices[i]) {
 134            pci_init_bus_master(bus->devices[i]);
 135        }
 136    }
 137}
 138
 139static void pci_bus_realize(BusState *qbus, Error **errp)
 140{
 141    PCIBus *bus = PCI_BUS(qbus);
 142
 143    bus->machine_done.notify = pcibus_machine_done;
 144    qemu_add_machine_init_done_notifier(&bus->machine_done);
 145
 146    vmstate_register(NULL, VMSTATE_INSTANCE_ID_ANY, &vmstate_pcibus, bus);
 147}
 148
 149static void pcie_bus_realize(BusState *qbus, Error **errp)
 150{
 151    PCIBus *bus = PCI_BUS(qbus);
 152    Error *local_err = NULL;
 153
 154    pci_bus_realize(qbus, &local_err);
 155    if (local_err) {
 156        error_propagate(errp, local_err);
 157        return;
 158    }
 159
 160    /*
 161     * A PCI-E bus can support extended config space if it's the root
 162     * bus, or if the bus/bridge above it does as well
 163     */
 164    if (pci_bus_is_root(bus)) {
 165        bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
 166    } else {
 167        PCIBus *parent_bus = pci_get_bus(bus->parent_dev);
 168
 169        if (pci_bus_allows_extended_config_space(parent_bus)) {
 170            bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
 171        }
 172    }
 173}
 174
 175static void pci_bus_unrealize(BusState *qbus)
 176{
 177    PCIBus *bus = PCI_BUS(qbus);
 178
 179    qemu_remove_machine_init_done_notifier(&bus->machine_done);
 180
 181    vmstate_unregister(NULL, &vmstate_pcibus, bus);
 182}
 183
 184static int pcibus_num(PCIBus *bus)
 185{
 186    if (pci_bus_is_root(bus)) {
 187        return 0; /* pci host bridge */
 188    }
 189    return bus->parent_dev->config[PCI_SECONDARY_BUS];
 190}
 191
 192static uint16_t pcibus_numa_node(PCIBus *bus)
 193{
 194    return NUMA_NODE_UNASSIGNED;
 195}
 196
 197static void pci_bus_class_init(ObjectClass *klass, void *data)
 198{
 199    BusClass *k = BUS_CLASS(klass);
 200    PCIBusClass *pbc = PCI_BUS_CLASS(klass);
 201
 202    k->print_dev = pcibus_dev_print;
 203    k->get_dev_path = pcibus_get_dev_path;
 204    k->get_fw_dev_path = pcibus_get_fw_dev_path;
 205    k->realize = pci_bus_realize;
 206    k->unrealize = pci_bus_unrealize;
 207    k->reset = pcibus_reset;
 208
 209    pbc->bus_num = pcibus_num;
 210    pbc->numa_node = pcibus_numa_node;
 211}
 212
 213static const TypeInfo pci_bus_info = {
 214    .name = TYPE_PCI_BUS,
 215    .parent = TYPE_BUS,
 216    .instance_size = sizeof(PCIBus),
 217    .class_size = sizeof(PCIBusClass),
 218    .class_init = pci_bus_class_init,
 219};
 220
 221static const TypeInfo cxl_interface_info = {
 222    .name          = INTERFACE_CXL_DEVICE,
 223    .parent        = TYPE_INTERFACE,
 224};
 225
 226static const TypeInfo pcie_interface_info = {
 227    .name          = INTERFACE_PCIE_DEVICE,
 228    .parent        = TYPE_INTERFACE,
 229};
 230
 231static const TypeInfo conventional_pci_interface_info = {
 232    .name          = INTERFACE_CONVENTIONAL_PCI_DEVICE,
 233    .parent        = TYPE_INTERFACE,
 234};
 235
 236static void pcie_bus_class_init(ObjectClass *klass, void *data)
 237{
 238    BusClass *k = BUS_CLASS(klass);
 239
 240    k->realize = pcie_bus_realize;
 241}
 242
 243static const TypeInfo pcie_bus_info = {
 244    .name = TYPE_PCIE_BUS,
 245    .parent = TYPE_PCI_BUS,
 246    .class_init = pcie_bus_class_init,
 247};
 248
 249static const TypeInfo cxl_bus_info = {
 250    .name       = TYPE_CXL_BUS,
 251    .parent     = TYPE_PCIE_BUS,
 252    .class_init = pcie_bus_class_init,
 253};
 254
 255static void pci_update_mappings(PCIDevice *d);
 256static void pci_irq_handler(void *opaque, int irq_num, int level);
 257static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
 258static void pci_del_option_rom(PCIDevice *pdev);
 259
 260static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
 261static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
 262
 263PCIHostStateList pci_host_bridges;
 264
 265int pci_bar(PCIDevice *d, int reg)
 266{
 267    uint8_t type;
 268
 269    /* PCIe virtual functions do not have their own BARs */
 270    assert(!pci_is_vf(d));
 271
 272    if (reg != PCI_ROM_SLOT)
 273        return PCI_BASE_ADDRESS_0 + reg * 4;
 274
 275    type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
 276    return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
 277}
 278
 279static inline int pci_irq_state(PCIDevice *d, int irq_num)
 280{
 281        return (d->irq_state >> irq_num) & 0x1;
 282}
 283
 284static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
 285{
 286        d->irq_state &= ~(0x1 << irq_num);
 287        d->irq_state |= level << irq_num;
 288}
 289
 290static void pci_bus_change_irq_level(PCIBus *bus, int irq_num, int change)
 291{
 292    assert(irq_num >= 0);
 293    assert(irq_num < bus->nirq);
 294    bus->irq_count[irq_num] += change;
 295    bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
 296}
 297
 298static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
 299{
 300    PCIBus *bus;
 301    for (;;) {
 302        int dev_irq = irq_num;
 303        bus = pci_get_bus(pci_dev);
 304        assert(bus->map_irq);
 305        irq_num = bus->map_irq(pci_dev, irq_num);
 306        trace_pci_route_irq(dev_irq, DEVICE(pci_dev)->canonical_path, irq_num,
 307                            pci_bus_is_root(bus) ? "root-complex"
 308                                    : DEVICE(bus->parent_dev)->canonical_path);
 309        if (bus->set_irq)
 310            break;
 311        pci_dev = bus->parent_dev;
 312    }
 313    pci_bus_change_irq_level(bus, irq_num, change);
 314}
 315
 316int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
 317{
 318    assert(irq_num >= 0);
 319    assert(irq_num < bus->nirq);
 320    return !!bus->irq_count[irq_num];
 321}
 322
 323/* Update interrupt status bit in config space on interrupt
 324 * state change. */
 325static void pci_update_irq_status(PCIDevice *dev)
 326{
 327    if (dev->irq_state) {
 328        dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
 329    } else {
 330        dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
 331    }
 332}
 333
 334void pci_device_deassert_intx(PCIDevice *dev)
 335{
 336    int i;
 337    for (i = 0; i < PCI_NUM_PINS; ++i) {
 338        pci_irq_handler(dev, i, 0);
 339    }
 340}
 341
 342static void pci_msi_trigger(PCIDevice *dev, MSIMessage msg)
 343{
 344    MemTxAttrs attrs = {};
 345
 346    /*
 347     * Xen uses the high bits of the address to contain some of the bits
 348     * of the PIRQ#. Therefore we can't just send the write cycle and
 349     * trust that it's caught by the APIC at 0xfee00000 because the
 350     * target of the write might be e.g. 0x0x1000fee46000 for PIRQ#4166.
 351     * So we intercept the delivery here instead of in kvm_send_msi().
 352     */
 353    if (xen_mode == XEN_EMULATE &&
 354        xen_evtchn_deliver_pirq_msi(msg.address, msg.data)) {
 355        return;
 356    }
 357    attrs.requester_id = pci_requester_id(dev);
 358    address_space_stl_le(&dev->bus_master_as, msg.address, msg.data,
 359                         attrs, NULL);
 360}
 361
 362static void pci_reset_regions(PCIDevice *dev)
 363{
 364    int r;
 365    if (pci_is_vf(dev)) {
 366        return;
 367    }
 368
 369    for (r = 0; r < PCI_NUM_REGIONS; ++r) {
 370        PCIIORegion *region = &dev->io_regions[r];
 371        if (!region->size) {
 372            continue;
 373        }
 374
 375        if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
 376            region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
 377            pci_set_quad(dev->config + pci_bar(dev, r), region->type);
 378        } else {
 379            pci_set_long(dev->config + pci_bar(dev, r), region->type);
 380        }
 381    }
 382}
 383
 384static void pci_do_device_reset(PCIDevice *dev)
 385{
 386    pci_device_deassert_intx(dev);
 387    assert(dev->irq_state == 0);
 388
 389    /* Clear all writable bits */
 390    pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
 391                                 pci_get_word(dev->wmask + PCI_COMMAND) |
 392                                 pci_get_word(dev->w1cmask + PCI_COMMAND));
 393    pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
 394                                 pci_get_word(dev->wmask + PCI_STATUS) |
 395                                 pci_get_word(dev->w1cmask + PCI_STATUS));
 396    /* Some devices make bits of PCI_INTERRUPT_LINE read only */
 397    pci_byte_test_and_clear_mask(dev->config + PCI_INTERRUPT_LINE,
 398                              pci_get_word(dev->wmask + PCI_INTERRUPT_LINE) |
 399                              pci_get_word(dev->w1cmask + PCI_INTERRUPT_LINE));
 400    dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
 401    pci_reset_regions(dev);
 402    pci_update_mappings(dev);
 403
 404    msi_reset(dev);
 405    msix_reset(dev);
 406}
 407
 408/*
 409 * This function is called on #RST and FLR.
 410 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
 411 */
 412void pci_device_reset(PCIDevice *dev)
 413{
 414    device_cold_reset(&dev->qdev);
 415    pci_do_device_reset(dev);
 416}
 417
 418/*
 419 * Trigger pci bus reset under a given bus.
 420 * Called via bus_cold_reset on RST# assert, after the devices
 421 * have been reset device_cold_reset-ed already.
 422 */
 423static void pcibus_reset(BusState *qbus)
 424{
 425    PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
 426    int i;
 427
 428    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
 429        if (bus->devices[i]) {
 430            pci_do_device_reset(bus->devices[i]);
 431        }
 432    }
 433
 434    for (i = 0; i < bus->nirq; i++) {
 435        assert(bus->irq_count[i] == 0);
 436    }
 437}
 438
 439static void pci_host_bus_register(DeviceState *host)
 440{
 441    PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
 442
 443    QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
 444}
 445
 446static void pci_host_bus_unregister(DeviceState *host)
 447{
 448    PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
 449
 450    QLIST_REMOVE(host_bridge, next);
 451}
 452
 453PCIBus *pci_device_root_bus(const PCIDevice *d)
 454{
 455    PCIBus *bus = pci_get_bus(d);
 456
 457    while (!pci_bus_is_root(bus)) {
 458        d = bus->parent_dev;
 459        assert(d != NULL);
 460
 461        bus = pci_get_bus(d);
 462    }
 463
 464    return bus;
 465}
 466
 467const char *pci_root_bus_path(PCIDevice *dev)
 468{
 469    PCIBus *rootbus = pci_device_root_bus(dev);
 470    PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
 471    PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
 472
 473    assert(host_bridge->bus == rootbus);
 474
 475    if (hc->root_bus_path) {
 476        return (*hc->root_bus_path)(host_bridge, rootbus);
 477    }
 478
 479    return rootbus->qbus.name;
 480}
 481
 482bool pci_bus_bypass_iommu(PCIBus *bus)
 483{
 484    PCIBus *rootbus = bus;
 485    PCIHostState *host_bridge;
 486
 487    if (!pci_bus_is_root(bus)) {
 488        rootbus = pci_device_root_bus(bus->parent_dev);
 489    }
 490
 491    host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
 492
 493    assert(host_bridge->bus == rootbus);
 494
 495    return host_bridge->bypass_iommu;
 496}
 497
 498static void pci_root_bus_internal_init(PCIBus *bus, DeviceState *parent,
 499                                       MemoryRegion *address_space_mem,
 500                                       MemoryRegion *address_space_io,
 501                                       uint8_t devfn_min)
 502{
 503    assert(PCI_FUNC(devfn_min) == 0);
 504    bus->devfn_min = devfn_min;
 505    bus->slot_reserved_mask = 0x0;
 506    bus->address_space_mem = address_space_mem;
 507    bus->address_space_io = address_space_io;
 508    bus->flags |= PCI_BUS_IS_ROOT;
 509
 510    /* host bridge */
 511    QLIST_INIT(&bus->child);
 512
 513    pci_host_bus_register(parent);
 514}
 515
 516static void pci_bus_uninit(PCIBus *bus)
 517{
 518    pci_host_bus_unregister(BUS(bus)->parent);
 519}
 520
 521bool pci_bus_is_express(const PCIBus *bus)
 522{
 523    return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
 524}
 525
 526void pci_root_bus_init(PCIBus *bus, size_t bus_size, DeviceState *parent,
 527                       const char *name,
 528                       MemoryRegion *address_space_mem,
 529                       MemoryRegion *address_space_io,
 530                       uint8_t devfn_min, const char *typename)
 531{
 532    qbus_init(bus, bus_size, typename, parent, name);
 533    pci_root_bus_internal_init(bus, parent, address_space_mem,
 534                               address_space_io, devfn_min);
 535}
 536
 537PCIBus *pci_root_bus_new(DeviceState *parent, const char *name,
 538                         MemoryRegion *address_space_mem,
 539                         MemoryRegion *address_space_io,
 540                         uint8_t devfn_min, const char *typename)
 541{
 542    PCIBus *bus;
 543
 544    bus = PCI_BUS(qbus_new(typename, parent, name));
 545    pci_root_bus_internal_init(bus, parent, address_space_mem,
 546                               address_space_io, devfn_min);
 547    return bus;
 548}
 549
 550void pci_root_bus_cleanup(PCIBus *bus)
 551{
 552    pci_bus_uninit(bus);
 553    /* the caller of the unplug hotplug handler will delete this device */
 554    qbus_unrealize(BUS(bus));
 555}
 556
 557void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq,
 558                  void *irq_opaque, int nirq)
 559{
 560    bus->set_irq = set_irq;
 561    bus->irq_opaque = irq_opaque;
 562    bus->nirq = nirq;
 563    bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
 564}
 565
 566void pci_bus_map_irqs(PCIBus *bus, pci_map_irq_fn map_irq)
 567{
 568    bus->map_irq = map_irq;
 569}
 570
 571void pci_bus_irqs_cleanup(PCIBus *bus)
 572{
 573    bus->set_irq = NULL;
 574    bus->map_irq = NULL;
 575    bus->irq_opaque = NULL;
 576    bus->nirq = 0;
 577    g_free(bus->irq_count);
 578}
 579
 580PCIBus *pci_register_root_bus(DeviceState *parent, const char *name,
 581                              pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
 582                              void *irq_opaque,
 583                              MemoryRegion *address_space_mem,
 584                              MemoryRegion *address_space_io,
 585                              uint8_t devfn_min, int nirq,
 586                              const char *typename)
 587{
 588    PCIBus *bus;
 589
 590    bus = pci_root_bus_new(parent, name, address_space_mem,
 591                           address_space_io, devfn_min, typename);
 592    pci_bus_irqs(bus, set_irq, irq_opaque, nirq);
 593    pci_bus_map_irqs(bus, map_irq);
 594    return bus;
 595}
 596
 597void pci_unregister_root_bus(PCIBus *bus)
 598{
 599    pci_bus_irqs_cleanup(bus);
 600    pci_root_bus_cleanup(bus);
 601}
 602
 603int pci_bus_num(PCIBus *s)
 604{
 605    return PCI_BUS_GET_CLASS(s)->bus_num(s);
 606}
 607
 608/* Returns the min and max bus numbers of a PCI bus hierarchy */
 609void pci_bus_range(PCIBus *bus, int *min_bus, int *max_bus)
 610{
 611    int i;
 612    *min_bus = *max_bus = pci_bus_num(bus);
 613
 614    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
 615        PCIDevice *dev = bus->devices[i];
 616
 617        if (dev && IS_PCI_BRIDGE(dev)) {
 618            *min_bus = MIN(*min_bus, dev->config[PCI_SECONDARY_BUS]);
 619            *max_bus = MAX(*max_bus, dev->config[PCI_SUBORDINATE_BUS]);
 620        }
 621    }
 622}
 623
 624int pci_bus_numa_node(PCIBus *bus)
 625{
 626    return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
 627}
 628
 629static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
 630                                 const VMStateField *field)
 631{
 632    PCIDevice *s = container_of(pv, PCIDevice, config);
 633    uint8_t *config;
 634    int i;
 635
 636    assert(size == pci_config_size(s));
 637    config = g_malloc(size);
 638
 639    qemu_get_buffer(f, config, size);
 640    for (i = 0; i < size; ++i) {
 641        if ((config[i] ^ s->config[i]) &
 642            s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
 643            error_report("%s: Bad config data: i=0x%x read: %x device: %x "
 644                         "cmask: %x wmask: %x w1cmask:%x", __func__,
 645                         i, config[i], s->config[i],
 646                         s->cmask[i], s->wmask[i], s->w1cmask[i]);
 647            g_free(config);
 648            return -EINVAL;
 649        }
 650    }
 651    memcpy(s->config, config, size);
 652
 653    pci_update_mappings(s);
 654    if (IS_PCI_BRIDGE(s)) {
 655        pci_bridge_update_mappings(PCI_BRIDGE(s));
 656    }
 657
 658    memory_region_set_enabled(&s->bus_master_enable_region,
 659                              pci_get_word(s->config + PCI_COMMAND)
 660                              & PCI_COMMAND_MASTER);
 661
 662    g_free(config);
 663    return 0;
 664}
 665
 666/* just put buffer */
 667static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
 668                                 const VMStateField *field, JSONWriter *vmdesc)
 669{
 670    const uint8_t **v = pv;
 671    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
 672    qemu_put_buffer(f, *v, size);
 673
 674    return 0;
 675}
 676
 677static VMStateInfo vmstate_info_pci_config = {
 678    .name = "pci config",
 679    .get  = get_pci_config_device,
 680    .put  = put_pci_config_device,
 681};
 682
 683static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
 684                             const VMStateField *field)
 685{
 686    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
 687    uint32_t irq_state[PCI_NUM_PINS];
 688    int i;
 689    for (i = 0; i < PCI_NUM_PINS; ++i) {
 690        irq_state[i] = qemu_get_be32(f);
 691        if (irq_state[i] != 0x1 && irq_state[i] != 0) {
 692            fprintf(stderr, "irq state %d: must be 0 or 1.\n",
 693                    irq_state[i]);
 694            return -EINVAL;
 695        }
 696    }
 697
 698    for (i = 0; i < PCI_NUM_PINS; ++i) {
 699        pci_set_irq_state(s, i, irq_state[i]);
 700    }
 701
 702    return 0;
 703}
 704
 705static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
 706                             const VMStateField *field, JSONWriter *vmdesc)
 707{
 708    int i;
 709    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
 710
 711    for (i = 0; i < PCI_NUM_PINS; ++i) {
 712        qemu_put_be32(f, pci_irq_state(s, i));
 713    }
 714
 715    return 0;
 716}
 717
 718static VMStateInfo vmstate_info_pci_irq_state = {
 719    .name = "pci irq state",
 720    .get  = get_pci_irq_state,
 721    .put  = put_pci_irq_state,
 722};
 723
 724static bool migrate_is_pcie(void *opaque, int version_id)
 725{
 726    return pci_is_express((PCIDevice *)opaque);
 727}
 728
 729static bool migrate_is_not_pcie(void *opaque, int version_id)
 730{
 731    return !pci_is_express((PCIDevice *)opaque);
 732}
 733
 734const VMStateDescription vmstate_pci_device = {
 735    .name = "PCIDevice",
 736    .version_id = 2,
 737    .minimum_version_id = 1,
 738    .fields = (VMStateField[]) {
 739        VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
 740        VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
 741                                   migrate_is_not_pcie,
 742                                   0, vmstate_info_pci_config,
 743                                   PCI_CONFIG_SPACE_SIZE),
 744        VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
 745                                   migrate_is_pcie,
 746                                   0, vmstate_info_pci_config,
 747                                   PCIE_CONFIG_SPACE_SIZE),
 748        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
 749                                   vmstate_info_pci_irq_state,
 750                                   PCI_NUM_PINS * sizeof(int32_t)),
 751        VMSTATE_END_OF_LIST()
 752    }
 753};
 754
 755
 756void pci_device_save(PCIDevice *s, QEMUFile *f)
 757{
 758    /* Clear interrupt status bit: it is implicit
 759     * in irq_state which we are saving.
 760     * This makes us compatible with old devices
 761     * which never set or clear this bit. */
 762    s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
 763    vmstate_save_state(f, &vmstate_pci_device, s, NULL);
 764    /* Restore the interrupt status bit. */
 765    pci_update_irq_status(s);
 766}
 767
 768int pci_device_load(PCIDevice *s, QEMUFile *f)
 769{
 770    int ret;
 771    ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id);
 772    /* Restore the interrupt status bit. */
 773    pci_update_irq_status(s);
 774    return ret;
 775}
 776
 777static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
 778{
 779    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
 780                 pci_default_sub_vendor_id);
 781    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
 782                 pci_default_sub_device_id);
 783}
 784
 785/*
 786 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
 787 *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
 788 */
 789static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
 790                             unsigned int *slotp, unsigned int *funcp)
 791{
 792    const char *p;
 793    char *e;
 794    unsigned long val;
 795    unsigned long dom = 0, bus = 0;
 796    unsigned int slot = 0;
 797    unsigned int func = 0;
 798
 799    p = addr;
 800    val = strtoul(p, &e, 16);
 801    if (e == p)
 802        return -1;
 803    if (*e == ':') {
 804        bus = val;
 805        p = e + 1;
 806        val = strtoul(p, &e, 16);
 807        if (e == p)
 808            return -1;
 809        if (*e == ':') {
 810            dom = bus;
 811            bus = val;
 812            p = e + 1;
 813            val = strtoul(p, &e, 16);
 814            if (e == p)
 815                return -1;
 816        }
 817    }
 818
 819    slot = val;
 820
 821    if (funcp != NULL) {
 822        if (*e != '.')
 823            return -1;
 824
 825        p = e + 1;
 826        val = strtoul(p, &e, 16);
 827        if (e == p)
 828            return -1;
 829
 830        func = val;
 831    }
 832
 833    /* if funcp == NULL func is 0 */
 834    if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
 835        return -1;
 836
 837    if (*e)
 838        return -1;
 839
 840    *domp = dom;
 841    *busp = bus;
 842    *slotp = slot;
 843    if (funcp != NULL)
 844        *funcp = func;
 845    return 0;
 846}
 847
 848static void pci_init_cmask(PCIDevice *dev)
 849{
 850    pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
 851    pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
 852    dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
 853    dev->cmask[PCI_REVISION_ID] = 0xff;
 854    dev->cmask[PCI_CLASS_PROG] = 0xff;
 855    pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
 856    dev->cmask[PCI_HEADER_TYPE] = 0xff;
 857    dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
 858}
 859
 860static void pci_init_wmask(PCIDevice *dev)
 861{
 862    int config_size = pci_config_size(dev);
 863
 864    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
 865    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
 866    pci_set_word(dev->wmask + PCI_COMMAND,
 867                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
 868                 PCI_COMMAND_INTX_DISABLE);
 869    pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
 870
 871    memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
 872           config_size - PCI_CONFIG_HEADER_SIZE);
 873}
 874
 875static void pci_init_w1cmask(PCIDevice *dev)
 876{
 877    /*
 878     * Note: It's okay to set w1cmask even for readonly bits as
 879     * long as their value is hardwired to 0.
 880     */
 881    pci_set_word(dev->w1cmask + PCI_STATUS,
 882                 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
 883                 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
 884                 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
 885}
 886
 887static void pci_init_mask_bridge(PCIDevice *d)
 888{
 889    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
 890       PCI_SEC_LETENCY_TIMER */
 891    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
 892
 893    /* base and limit */
 894    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
 895    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
 896    pci_set_word(d->wmask + PCI_MEMORY_BASE,
 897                 PCI_MEMORY_RANGE_MASK & 0xffff);
 898    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
 899                 PCI_MEMORY_RANGE_MASK & 0xffff);
 900    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
 901                 PCI_PREF_RANGE_MASK & 0xffff);
 902    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
 903                 PCI_PREF_RANGE_MASK & 0xffff);
 904
 905    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
 906    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
 907
 908    /* Supported memory and i/o types */
 909    d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
 910    d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
 911    pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
 912                               PCI_PREF_RANGE_TYPE_64);
 913    pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
 914                               PCI_PREF_RANGE_TYPE_64);
 915
 916    /*
 917     * TODO: Bridges default to 10-bit VGA decoding but we currently only
 918     * implement 16-bit decoding (no alias support).
 919     */
 920    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
 921                 PCI_BRIDGE_CTL_PARITY |
 922                 PCI_BRIDGE_CTL_SERR |
 923                 PCI_BRIDGE_CTL_ISA |
 924                 PCI_BRIDGE_CTL_VGA |
 925                 PCI_BRIDGE_CTL_VGA_16BIT |
 926                 PCI_BRIDGE_CTL_MASTER_ABORT |
 927                 PCI_BRIDGE_CTL_BUS_RESET |
 928                 PCI_BRIDGE_CTL_FAST_BACK |
 929                 PCI_BRIDGE_CTL_DISCARD |
 930                 PCI_BRIDGE_CTL_SEC_DISCARD |
 931                 PCI_BRIDGE_CTL_DISCARD_SERR);
 932    /* Below does not do anything as we never set this bit, put here for
 933     * completeness. */
 934    pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
 935                 PCI_BRIDGE_CTL_DISCARD_STATUS);
 936    d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
 937    d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
 938    pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
 939                               PCI_PREF_RANGE_TYPE_MASK);
 940    pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
 941                               PCI_PREF_RANGE_TYPE_MASK);
 942}
 943
 944static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
 945{
 946    uint8_t slot = PCI_SLOT(dev->devfn);
 947    uint8_t func;
 948
 949    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
 950        dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
 951    }
 952
 953    /*
 954     * With SR/IOV and ARI, a device at function 0 need not be a multifunction
 955     * device, as it may just be a VF that ended up with function 0 in
 956     * the legacy PCI interpretation. Avoid failing in such cases:
 957     */
 958    if (pci_is_vf(dev) &&
 959        dev->exp.sriov_vf.pf->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
 960        return;
 961    }
 962
 963    /*
 964     * multifunction bit is interpreted in two ways as follows.
 965     *   - all functions must set the bit to 1.
 966     *     Example: Intel X53
 967     *   - function 0 must set the bit, but the rest function (> 0)
 968     *     is allowed to leave the bit to 0.
 969     *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
 970     *
 971     * So OS (at least Linux) checks the bit of only function 0,
 972     * and doesn't see the bit of function > 0.
 973     *
 974     * The below check allows both interpretation.
 975     */
 976    if (PCI_FUNC(dev->devfn)) {
 977        PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
 978        if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
 979            /* function 0 should set multifunction bit */
 980            error_setg(errp, "PCI: single function device can't be populated "
 981                       "in function %x.%x", slot, PCI_FUNC(dev->devfn));
 982            return;
 983        }
 984        return;
 985    }
 986
 987    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
 988        return;
 989    }
 990    /* function 0 indicates single function, so function > 0 must be NULL */
 991    for (func = 1; func < PCI_FUNC_MAX; ++func) {
 992        if (bus->devices[PCI_DEVFN(slot, func)]) {
 993            error_setg(errp, "PCI: %x.0 indicates single function, "
 994                       "but %x.%x is already populated.",
 995                       slot, slot, func);
 996            return;
 997        }
 998    }
 999}
1000
1001static void pci_config_alloc(PCIDevice *pci_dev)
1002{
1003    int config_size = pci_config_size(pci_dev);
1004
1005    pci_dev->config = g_malloc0(config_size);
1006    pci_dev->cmask = g_malloc0(config_size);
1007    pci_dev->wmask = g_malloc0(config_size);
1008    pci_dev->w1cmask = g_malloc0(config_size);
1009    pci_dev->used = g_malloc0(config_size);
1010}
1011
1012static void pci_config_free(PCIDevice *pci_dev)
1013{
1014    g_free(pci_dev->config);
1015    g_free(pci_dev->cmask);
1016    g_free(pci_dev->wmask);
1017    g_free(pci_dev->w1cmask);
1018    g_free(pci_dev->used);
1019}
1020
1021static void do_pci_unregister_device(PCIDevice *pci_dev)
1022{
1023    pci_get_bus(pci_dev)->devices[pci_dev->devfn] = NULL;
1024    pci_config_free(pci_dev);
1025
1026    if (xen_mode == XEN_EMULATE) {
1027        xen_evtchn_remove_pci_device(pci_dev);
1028    }
1029    if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
1030        memory_region_del_subregion(&pci_dev->bus_master_container_region,
1031                                    &pci_dev->bus_master_enable_region);
1032    }
1033    address_space_destroy(&pci_dev->bus_master_as);
1034}
1035
1036/* Extract PCIReqIDCache into BDF format */
1037static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
1038{
1039    uint8_t bus_n;
1040    uint16_t result;
1041
1042    switch (cache->type) {
1043    case PCI_REQ_ID_BDF:
1044        result = pci_get_bdf(cache->dev);
1045        break;
1046    case PCI_REQ_ID_SECONDARY_BUS:
1047        bus_n = pci_dev_bus_num(cache->dev);
1048        result = PCI_BUILD_BDF(bus_n, 0);
1049        break;
1050    default:
1051        error_report("Invalid PCI requester ID cache type: %d",
1052                     cache->type);
1053        exit(1);
1054        break;
1055    }
1056
1057    return result;
1058}
1059
1060/* Parse bridges up to the root complex and return requester ID
1061 * cache for specific device.  For full PCIe topology, the cache
1062 * result would be exactly the same as getting BDF of the device.
1063 * However, several tricks are required when system mixed up with
1064 * legacy PCI devices and PCIe-to-PCI bridges.
1065 *
1066 * Here we cache the proxy device (and type) not requester ID since
1067 * bus number might change from time to time.
1068 */
1069static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
1070{
1071    PCIDevice *parent;
1072    PCIReqIDCache cache = {
1073        .dev = dev,
1074        .type = PCI_REQ_ID_BDF,
1075    };
1076
1077    while (!pci_bus_is_root(pci_get_bus(dev))) {
1078        /* We are under PCI/PCIe bridges */
1079        parent = pci_get_bus(dev)->parent_dev;
1080        if (pci_is_express(parent)) {
1081            if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
1082                /* When we pass through PCIe-to-PCI/PCIX bridges, we
1083                 * override the requester ID using secondary bus
1084                 * number of parent bridge with zeroed devfn
1085                 * (pcie-to-pci bridge spec chap 2.3). */
1086                cache.type = PCI_REQ_ID_SECONDARY_BUS;
1087                cache.dev = dev;
1088            }
1089        } else {
1090            /* Legacy PCI, override requester ID with the bridge's
1091             * BDF upstream.  When the root complex connects to
1092             * legacy PCI devices (including buses), it can only
1093             * obtain requester ID info from directly attached
1094             * devices.  If devices are attached under bridges, only
1095             * the requester ID of the bridge that is directly
1096             * attached to the root complex can be recognized. */
1097            cache.type = PCI_REQ_ID_BDF;
1098            cache.dev = parent;
1099        }
1100        dev = parent;
1101    }
1102
1103    return cache;
1104}
1105
1106uint16_t pci_requester_id(PCIDevice *dev)
1107{
1108    return pci_req_id_cache_extract(&dev->requester_id_cache);
1109}
1110
1111static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
1112{
1113    return !(bus->devices[devfn]);
1114}
1115
1116static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
1117{
1118    return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
1119}
1120
1121/* -1 for devfn means auto assign */
1122static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
1123                                         const char *name, int devfn,
1124                                         Error **errp)
1125{
1126    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1127    PCIConfigReadFunc *config_read = pc->config_read;
1128    PCIConfigWriteFunc *config_write = pc->config_write;
1129    Error *local_err = NULL;
1130    DeviceState *dev = DEVICE(pci_dev);
1131    PCIBus *bus = pci_get_bus(pci_dev);
1132    bool is_bridge = IS_PCI_BRIDGE(pci_dev);
1133
1134    /* Only pci bridges can be attached to extra PCI root buses */
1135    if (pci_bus_is_root(bus) && bus->parent_dev && !is_bridge) {
1136        error_setg(errp,
1137                   "PCI: Only PCI/PCIe bridges can be plugged into %s",
1138                    bus->parent_dev->name);
1139        return NULL;
1140    }
1141
1142    if (devfn < 0) {
1143        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
1144            devfn += PCI_FUNC_MAX) {
1145            if (pci_bus_devfn_available(bus, devfn) &&
1146                   !pci_bus_devfn_reserved(bus, devfn)) {
1147                goto found;
1148            }
1149        }
1150        error_setg(errp, "PCI: no slot/function available for %s, all in use "
1151                   "or reserved", name);
1152        return NULL;
1153    found: ;
1154    } else if (pci_bus_devfn_reserved(bus, devfn)) {
1155        error_setg(errp, "PCI: slot %d function %d not available for %s,"
1156                   " reserved",
1157                   PCI_SLOT(devfn), PCI_FUNC(devfn), name);
1158        return NULL;
1159    } else if (!pci_bus_devfn_available(bus, devfn)) {
1160        error_setg(errp, "PCI: slot %d function %d not available for %s,"
1161                   " in use by %s,id=%s",
1162                   PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1163                   bus->devices[devfn]->name, bus->devices[devfn]->qdev.id);
1164        return NULL;
1165    } else if (dev->hotplugged &&
1166               !pci_is_vf(pci_dev) &&
1167               pci_get_function_0(pci_dev)) {
1168        error_setg(errp, "PCI: slot %d function 0 already occupied by %s,"
1169                   " new func %s cannot be exposed to guest.",
1170                   PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1171                   pci_get_function_0(pci_dev)->name,
1172                   name);
1173
1174       return NULL;
1175    }
1176
1177    pci_dev->devfn = devfn;
1178    pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1179    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1180
1181    memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
1182                       "bus master container", UINT64_MAX);
1183    address_space_init(&pci_dev->bus_master_as,
1184                       &pci_dev->bus_master_container_region, pci_dev->name);
1185
1186    if (phase_check(PHASE_MACHINE_READY)) {
1187        pci_init_bus_master(pci_dev);
1188    }
1189    pci_dev->irq_state = 0;
1190    pci_config_alloc(pci_dev);
1191
1192    pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1193    pci_config_set_device_id(pci_dev->config, pc->device_id);
1194    pci_config_set_revision(pci_dev->config, pc->revision);
1195    pci_config_set_class(pci_dev->config, pc->class_id);
1196
1197    if (!is_bridge) {
1198        if (pc->subsystem_vendor_id || pc->subsystem_id) {
1199            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1200                         pc->subsystem_vendor_id);
1201            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1202                         pc->subsystem_id);
1203        } else {
1204            pci_set_default_subsystem_id(pci_dev);
1205        }
1206    } else {
1207        /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1208        assert(!pc->subsystem_vendor_id);
1209        assert(!pc->subsystem_id);
1210    }
1211    pci_init_cmask(pci_dev);
1212    pci_init_wmask(pci_dev);
1213    pci_init_w1cmask(pci_dev);
1214    if (is_bridge) {
1215        pci_init_mask_bridge(pci_dev);
1216    }
1217    pci_init_multifunction(bus, pci_dev, &local_err);
1218    if (local_err) {
1219        error_propagate(errp, local_err);
1220        do_pci_unregister_device(pci_dev);
1221        return NULL;
1222    }
1223
1224    if (!config_read)
1225        config_read = pci_default_read_config;
1226    if (!config_write)
1227        config_write = pci_default_write_config;
1228    pci_dev->config_read = config_read;
1229    pci_dev->config_write = config_write;
1230    bus->devices[devfn] = pci_dev;
1231    pci_dev->version_id = 2; /* Current pci device vmstate version */
1232    return pci_dev;
1233}
1234
1235static void pci_unregister_io_regions(PCIDevice *pci_dev)
1236{
1237    PCIIORegion *r;
1238    int i;
1239
1240    for(i = 0; i < PCI_NUM_REGIONS; i++) {
1241        r = &pci_dev->io_regions[i];
1242        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1243            continue;
1244        memory_region_del_subregion(r->address_space, r->memory);
1245    }
1246
1247    pci_unregister_vga(pci_dev);
1248}
1249
1250static void pci_qdev_unrealize(DeviceState *dev)
1251{
1252    PCIDevice *pci_dev = PCI_DEVICE(dev);
1253    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1254
1255    pci_unregister_io_regions(pci_dev);
1256    pci_del_option_rom(pci_dev);
1257
1258    if (pc->exit) {
1259        pc->exit(pci_dev);
1260    }
1261
1262    pci_device_deassert_intx(pci_dev);
1263    do_pci_unregister_device(pci_dev);
1264
1265    pci_dev->msi_trigger = NULL;
1266
1267    /*
1268     * clean up acpi-index so it could reused by another device
1269     */
1270    if (pci_dev->acpi_index) {
1271        GSequence *used_indexes = pci_acpi_index_list();
1272
1273        g_sequence_remove(g_sequence_lookup(used_indexes,
1274                          GINT_TO_POINTER(pci_dev->acpi_index),
1275                          g_cmp_uint32, NULL));
1276    }
1277}
1278
1279void pci_register_bar(PCIDevice *pci_dev, int region_num,
1280                      uint8_t type, MemoryRegion *memory)
1281{
1282    PCIIORegion *r;
1283    uint32_t addr; /* offset in pci config space */
1284    uint64_t wmask;
1285    pcibus_t size = memory_region_size(memory);
1286    uint8_t hdr_type;
1287
1288    assert(!pci_is_vf(pci_dev)); /* VFs must use pcie_sriov_vf_register_bar */
1289    assert(region_num >= 0);
1290    assert(region_num < PCI_NUM_REGIONS);
1291    assert(is_power_of_2(size));
1292
1293    /* A PCI bridge device (with Type 1 header) may only have at most 2 BARs */
1294    hdr_type =
1295        pci_dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1296    assert(hdr_type != PCI_HEADER_TYPE_BRIDGE || region_num < 2);
1297
1298    r = &pci_dev->io_regions[region_num];
1299    r->addr = PCI_BAR_UNMAPPED;
1300    r->size = size;
1301    r->type = type;
1302    r->memory = memory;
1303    r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1304                        ? pci_get_bus(pci_dev)->address_space_io
1305                        : pci_get_bus(pci_dev)->address_space_mem;
1306
1307    wmask = ~(size - 1);
1308    if (region_num == PCI_ROM_SLOT) {
1309        /* ROM enable bit is writable */
1310        wmask |= PCI_ROM_ADDRESS_ENABLE;
1311    }
1312
1313    addr = pci_bar(pci_dev, region_num);
1314    pci_set_long(pci_dev->config + addr, type);
1315
1316    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1317        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1318        pci_set_quad(pci_dev->wmask + addr, wmask);
1319        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1320    } else {
1321        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1322        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1323    }
1324}
1325
1326static void pci_update_vga(PCIDevice *pci_dev)
1327{
1328    uint16_t cmd;
1329
1330    if (!pci_dev->has_vga) {
1331        return;
1332    }
1333
1334    cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1335
1336    memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1337                              cmd & PCI_COMMAND_MEMORY);
1338    memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1339                              cmd & PCI_COMMAND_IO);
1340    memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1341                              cmd & PCI_COMMAND_IO);
1342}
1343
1344void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1345                      MemoryRegion *io_lo, MemoryRegion *io_hi)
1346{
1347    PCIBus *bus = pci_get_bus(pci_dev);
1348
1349    assert(!pci_dev->has_vga);
1350
1351    assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1352    pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1353    memory_region_add_subregion_overlap(bus->address_space_mem,
1354                                        QEMU_PCI_VGA_MEM_BASE, mem, 1);
1355
1356    assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1357    pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1358    memory_region_add_subregion_overlap(bus->address_space_io,
1359                                        QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1360
1361    assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1362    pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1363    memory_region_add_subregion_overlap(bus->address_space_io,
1364                                        QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1365    pci_dev->has_vga = true;
1366
1367    pci_update_vga(pci_dev);
1368}
1369
1370void pci_unregister_vga(PCIDevice *pci_dev)
1371{
1372    PCIBus *bus = pci_get_bus(pci_dev);
1373
1374    if (!pci_dev->has_vga) {
1375        return;
1376    }
1377
1378    memory_region_del_subregion(bus->address_space_mem,
1379                                pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1380    memory_region_del_subregion(bus->address_space_io,
1381                                pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1382    memory_region_del_subregion(bus->address_space_io,
1383                                pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1384    pci_dev->has_vga = false;
1385}
1386
1387pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1388{
1389    return pci_dev->io_regions[region_num].addr;
1390}
1391
1392static pcibus_t pci_config_get_bar_addr(PCIDevice *d, int reg,
1393                                        uint8_t type, pcibus_t size)
1394{
1395    pcibus_t new_addr;
1396    if (!pci_is_vf(d)) {
1397        int bar = pci_bar(d, reg);
1398        if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1399            new_addr = pci_get_quad(d->config + bar);
1400        } else {
1401            new_addr = pci_get_long(d->config + bar);
1402        }
1403    } else {
1404        PCIDevice *pf = d->exp.sriov_vf.pf;
1405        uint16_t sriov_cap = pf->exp.sriov_cap;
1406        int bar = sriov_cap + PCI_SRIOV_BAR + reg * 4;
1407        uint16_t vf_offset =
1408            pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_OFFSET);
1409        uint16_t vf_stride =
1410            pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_STRIDE);
1411        uint32_t vf_num = (d->devfn - (pf->devfn + vf_offset)) / vf_stride;
1412
1413        if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1414            new_addr = pci_get_quad(pf->config + bar);
1415        } else {
1416            new_addr = pci_get_long(pf->config + bar);
1417        }
1418        new_addr += vf_num * size;
1419    }
1420    /* The ROM slot has a specific enable bit, keep it intact */
1421    if (reg != PCI_ROM_SLOT) {
1422        new_addr &= ~(size - 1);
1423    }
1424    return new_addr;
1425}
1426
1427pcibus_t pci_bar_address(PCIDevice *d,
1428                         int reg, uint8_t type, pcibus_t size)
1429{
1430    pcibus_t new_addr, last_addr;
1431    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1432    Object *machine = qdev_get_machine();
1433    ObjectClass *oc = object_get_class(machine);
1434    MachineClass *mc = MACHINE_CLASS(oc);
1435    bool allow_0_address = mc->pci_allow_0_address;
1436
1437    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1438        if (!(cmd & PCI_COMMAND_IO)) {
1439            return PCI_BAR_UNMAPPED;
1440        }
1441        new_addr = pci_config_get_bar_addr(d, reg, type, size);
1442        last_addr = new_addr + size - 1;
1443        /* Check if 32 bit BAR wraps around explicitly.
1444         * TODO: make priorities correct and remove this work around.
1445         */
1446        if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1447            (!allow_0_address && new_addr == 0)) {
1448            return PCI_BAR_UNMAPPED;
1449        }
1450        return new_addr;
1451    }
1452
1453    if (!(cmd & PCI_COMMAND_MEMORY)) {
1454        return PCI_BAR_UNMAPPED;
1455    }
1456    new_addr = pci_config_get_bar_addr(d, reg, type, size);
1457    /* the ROM slot has a specific enable bit */
1458    if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1459        return PCI_BAR_UNMAPPED;
1460    }
1461    new_addr &= ~(size - 1);
1462    last_addr = new_addr + size - 1;
1463    /* NOTE: we do not support wrapping */
1464    /* XXX: as we cannot support really dynamic
1465       mappings, we handle specific values as invalid
1466       mappings. */
1467    if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1468        (!allow_0_address && new_addr == 0)) {
1469        return PCI_BAR_UNMAPPED;
1470    }
1471
1472    /* Now pcibus_t is 64bit.
1473     * Check if 32 bit BAR wraps around explicitly.
1474     * Without this, PC ide doesn't work well.
1475     * TODO: remove this work around.
1476     */
1477    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1478        return PCI_BAR_UNMAPPED;
1479    }
1480
1481    /*
1482     * OS is allowed to set BAR beyond its addressable
1483     * bits. For example, 32 bit OS can set 64bit bar
1484     * to >4G. Check it. TODO: we might need to support
1485     * it in the future for e.g. PAE.
1486     */
1487    if (last_addr >= HWADDR_MAX) {
1488        return PCI_BAR_UNMAPPED;
1489    }
1490
1491    return new_addr;
1492}
1493
1494static void pci_update_mappings(PCIDevice *d)
1495{
1496    PCIIORegion *r;
1497    int i;
1498    pcibus_t new_addr;
1499
1500    for(i = 0; i < PCI_NUM_REGIONS; i++) {
1501        r = &d->io_regions[i];
1502
1503        /* this region isn't registered */
1504        if (!r->size)
1505            continue;
1506
1507        new_addr = pci_bar_address(d, i, r->type, r->size);
1508        if (!d->has_power) {
1509            new_addr = PCI_BAR_UNMAPPED;
1510        }
1511
1512        /* This bar isn't changed */
1513        if (new_addr == r->addr)
1514            continue;
1515
1516        /* now do the real mapping */
1517        if (r->addr != PCI_BAR_UNMAPPED) {
1518            trace_pci_update_mappings_del(d->name, pci_dev_bus_num(d),
1519                                          PCI_SLOT(d->devfn),
1520                                          PCI_FUNC(d->devfn),
1521                                          i, r->addr, r->size);
1522            memory_region_del_subregion(r->address_space, r->memory);
1523        }
1524        r->addr = new_addr;
1525        if (r->addr != PCI_BAR_UNMAPPED) {
1526            trace_pci_update_mappings_add(d->name, pci_dev_bus_num(d),
1527                                          PCI_SLOT(d->devfn),
1528                                          PCI_FUNC(d->devfn),
1529                                          i, r->addr, r->size);
1530            memory_region_add_subregion_overlap(r->address_space,
1531                                                r->addr, r->memory, 1);
1532        }
1533    }
1534
1535    pci_update_vga(d);
1536}
1537
1538static inline int pci_irq_disabled(PCIDevice *d)
1539{
1540    return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1541}
1542
1543/* Called after interrupt disabled field update in config space,
1544 * assert/deassert interrupts if necessary.
1545 * Gets original interrupt disable bit value (before update). */
1546static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1547{
1548    int i, disabled = pci_irq_disabled(d);
1549    if (disabled == was_irq_disabled)
1550        return;
1551    for (i = 0; i < PCI_NUM_PINS; ++i) {
1552        int state = pci_irq_state(d, i);
1553        pci_change_irq_level(d, i, disabled ? -state : state);
1554    }
1555}
1556
1557uint32_t pci_default_read_config(PCIDevice *d,
1558                                 uint32_t address, int len)
1559{
1560    uint32_t val = 0;
1561
1562    assert(address + len <= pci_config_size(d));
1563
1564    if (pci_is_express_downstream_port(d) &&
1565        ranges_overlap(address, len, d->exp.exp_cap + PCI_EXP_LNKSTA, 2)) {
1566        pcie_sync_bridge_lnk(d);
1567    }
1568    memcpy(&val, d->config + address, len);
1569    return le32_to_cpu(val);
1570}
1571
1572void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1573{
1574    int i, was_irq_disabled = pci_irq_disabled(d);
1575    uint32_t val = val_in;
1576
1577    assert(addr + l <= pci_config_size(d));
1578
1579    for (i = 0; i < l; val >>= 8, ++i) {
1580        uint8_t wmask = d->wmask[addr + i];
1581        uint8_t w1cmask = d->w1cmask[addr + i];
1582        assert(!(wmask & w1cmask));
1583        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1584        d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1585    }
1586    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1587        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1588        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1589        range_covers_byte(addr, l, PCI_COMMAND))
1590        pci_update_mappings(d);
1591
1592    if (range_covers_byte(addr, l, PCI_COMMAND)) {
1593        pci_update_irq_disabled(d, was_irq_disabled);
1594        memory_region_set_enabled(&d->bus_master_enable_region,
1595                                  (pci_get_word(d->config + PCI_COMMAND)
1596                                   & PCI_COMMAND_MASTER) && d->has_power);
1597    }
1598
1599    msi_write_config(d, addr, val_in, l);
1600    msix_write_config(d, addr, val_in, l);
1601    pcie_sriov_config_write(d, addr, val_in, l);
1602}
1603
1604/***********************************************************/
1605/* generic PCI irq support */
1606
1607/* 0 <= irq_num <= 3. level must be 0 or 1 */
1608static void pci_irq_handler(void *opaque, int irq_num, int level)
1609{
1610    PCIDevice *pci_dev = opaque;
1611    int change;
1612
1613    assert(0 <= irq_num && irq_num < PCI_NUM_PINS);
1614    assert(level == 0 || level == 1);
1615    change = level - pci_irq_state(pci_dev, irq_num);
1616    if (!change)
1617        return;
1618
1619    pci_set_irq_state(pci_dev, irq_num, level);
1620    pci_update_irq_status(pci_dev);
1621    if (pci_irq_disabled(pci_dev))
1622        return;
1623    pci_change_irq_level(pci_dev, irq_num, change);
1624}
1625
1626qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1627{
1628    int intx = pci_intx(pci_dev);
1629    assert(0 <= intx && intx < PCI_NUM_PINS);
1630
1631    return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1632}
1633
1634void pci_set_irq(PCIDevice *pci_dev, int level)
1635{
1636    int intx = pci_intx(pci_dev);
1637    pci_irq_handler(pci_dev, intx, level);
1638}
1639
1640/* Special hooks used by device assignment */
1641void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1642{
1643    assert(pci_bus_is_root(bus));
1644    bus->route_intx_to_irq = route_intx_to_irq;
1645}
1646
1647PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1648{
1649    PCIBus *bus;
1650
1651    do {
1652        int dev_irq = pin;
1653        bus = pci_get_bus(dev);
1654        pin = bus->map_irq(dev, pin);
1655        trace_pci_route_irq(dev_irq, DEVICE(dev)->canonical_path, pin,
1656                            pci_bus_is_root(bus) ? "root-complex"
1657                                    : DEVICE(bus->parent_dev)->canonical_path);
1658        dev = bus->parent_dev;
1659    } while (dev);
1660
1661    if (!bus->route_intx_to_irq) {
1662        error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1663                     object_get_typename(OBJECT(bus->qbus.parent)));
1664        return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1665    }
1666
1667    return bus->route_intx_to_irq(bus->irq_opaque, pin);
1668}
1669
1670bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1671{
1672    return old->mode != new->mode || old->irq != new->irq;
1673}
1674
1675void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1676{
1677    PCIDevice *dev;
1678    PCIBus *sec;
1679    int i;
1680
1681    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1682        dev = bus->devices[i];
1683        if (dev && dev->intx_routing_notifier) {
1684            dev->intx_routing_notifier(dev);
1685        }
1686    }
1687
1688    QLIST_FOREACH(sec, &bus->child, sibling) {
1689        pci_bus_fire_intx_routing_notifier(sec);
1690    }
1691}
1692
1693void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1694                                          PCIINTxRoutingNotifier notifier)
1695{
1696    dev->intx_routing_notifier = notifier;
1697}
1698
1699/*
1700 * PCI-to-PCI bridge specification
1701 * 9.1: Interrupt routing. Table 9-1
1702 *
1703 * the PCI Express Base Specification, Revision 2.1
1704 * 2.2.8.1: INTx interrupt signaling - Rules
1705 *          the Implementation Note
1706 *          Table 2-20
1707 */
1708/*
1709 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1710 * 0-origin unlike PCI interrupt pin register.
1711 */
1712int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1713{
1714    return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1715}
1716
1717/***********************************************************/
1718/* monitor info on PCI */
1719
1720static const pci_class_desc pci_class_descriptions[] =
1721{
1722    { 0x0001, "VGA controller", "display"},
1723    { 0x0100, "SCSI controller", "scsi"},
1724    { 0x0101, "IDE controller", "ide"},
1725    { 0x0102, "Floppy controller", "fdc"},
1726    { 0x0103, "IPI controller", "ipi"},
1727    { 0x0104, "RAID controller", "raid"},
1728    { 0x0106, "SATA controller"},
1729    { 0x0107, "SAS controller"},
1730    { 0x0180, "Storage controller"},
1731    { 0x0200, "Ethernet controller", "ethernet"},
1732    { 0x0201, "Token Ring controller", "token-ring"},
1733    { 0x0202, "FDDI controller", "fddi"},
1734    { 0x0203, "ATM controller", "atm"},
1735    { 0x0280, "Network controller"},
1736    { 0x0300, "VGA controller", "display", 0x00ff},
1737    { 0x0301, "XGA controller"},
1738    { 0x0302, "3D controller"},
1739    { 0x0380, "Display controller"},
1740    { 0x0400, "Video controller", "video"},
1741    { 0x0401, "Audio controller", "sound"},
1742    { 0x0402, "Phone"},
1743    { 0x0403, "Audio controller", "sound"},
1744    { 0x0480, "Multimedia controller"},
1745    { 0x0500, "RAM controller", "memory"},
1746    { 0x0501, "Flash controller", "flash"},
1747    { 0x0580, "Memory controller"},
1748    { 0x0600, "Host bridge", "host"},
1749    { 0x0601, "ISA bridge", "isa"},
1750    { 0x0602, "EISA bridge", "eisa"},
1751    { 0x0603, "MC bridge", "mca"},
1752    { 0x0604, "PCI bridge", "pci-bridge"},
1753    { 0x0605, "PCMCIA bridge", "pcmcia"},
1754    { 0x0606, "NUBUS bridge", "nubus"},
1755    { 0x0607, "CARDBUS bridge", "cardbus"},
1756    { 0x0608, "RACEWAY bridge"},
1757    { 0x0680, "Bridge"},
1758    { 0x0700, "Serial port", "serial"},
1759    { 0x0701, "Parallel port", "parallel"},
1760    { 0x0800, "Interrupt controller", "interrupt-controller"},
1761    { 0x0801, "DMA controller", "dma-controller"},
1762    { 0x0802, "Timer", "timer"},
1763    { 0x0803, "RTC", "rtc"},
1764    { 0x0900, "Keyboard", "keyboard"},
1765    { 0x0901, "Pen", "pen"},
1766    { 0x0902, "Mouse", "mouse"},
1767    { 0x0A00, "Dock station", "dock", 0x00ff},
1768    { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1769    { 0x0c00, "Firewire controller", "firewire"},
1770    { 0x0c01, "Access bus controller", "access-bus"},
1771    { 0x0c02, "SSA controller", "ssa"},
1772    { 0x0c03, "USB controller", "usb"},
1773    { 0x0c04, "Fibre channel controller", "fibre-channel"},
1774    { 0x0c05, "SMBus"},
1775    { 0, NULL}
1776};
1777
1778void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1779                                           pci_bus_dev_fn fn,
1780                                           void *opaque)
1781{
1782    PCIDevice *d;
1783    int devfn;
1784
1785    for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1786        d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1787        if (d) {
1788            fn(bus, d, opaque);
1789        }
1790    }
1791}
1792
1793void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1794                                 pci_bus_dev_fn fn, void *opaque)
1795{
1796    bus = pci_find_bus_nr(bus, bus_num);
1797
1798    if (bus) {
1799        pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1800    }
1801}
1802
1803void pci_for_each_device_under_bus(PCIBus *bus,
1804                                   pci_bus_dev_fn fn, void *opaque)
1805{
1806    PCIDevice *d;
1807    int devfn;
1808
1809    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1810        d = bus->devices[devfn];
1811        if (d) {
1812            fn(bus, d, opaque);
1813        }
1814    }
1815}
1816
1817void pci_for_each_device(PCIBus *bus, int bus_num,
1818                         pci_bus_dev_fn fn, void *opaque)
1819{
1820    bus = pci_find_bus_nr(bus, bus_num);
1821
1822    if (bus) {
1823        pci_for_each_device_under_bus(bus, fn, opaque);
1824    }
1825}
1826
1827const pci_class_desc *get_class_desc(int class)
1828{
1829    const pci_class_desc *desc;
1830
1831    desc = pci_class_descriptions;
1832    while (desc->desc && class != desc->class) {
1833        desc++;
1834    }
1835
1836    return desc;
1837}
1838
1839/* Initialize a PCI NIC.  */
1840PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1841                               const char *default_model,
1842                               const char *default_devaddr)
1843{
1844    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1845    GPtrArray *pci_nic_models;
1846    PCIBus *bus;
1847    PCIDevice *pci_dev;
1848    DeviceState *dev;
1849    int devfn;
1850    int i;
1851    int dom, busnr;
1852    unsigned slot;
1853
1854    if (nd->model && !strcmp(nd->model, "virtio")) {
1855        g_free(nd->model);
1856        nd->model = g_strdup("virtio-net-pci");
1857    }
1858
1859    pci_nic_models = qemu_get_nic_models(TYPE_PCI_DEVICE);
1860
1861    if (qemu_show_nic_models(nd->model, (const char **)pci_nic_models->pdata)) {
1862        exit(0);
1863    }
1864
1865    i = qemu_find_nic_model(nd, (const char **)pci_nic_models->pdata,
1866                            default_model);
1867    if (i < 0) {
1868        exit(1);
1869    }
1870
1871    if (!rootbus) {
1872        error_report("No primary PCI bus");
1873        exit(1);
1874    }
1875
1876    assert(!rootbus->parent_dev);
1877
1878    if (!devaddr) {
1879        devfn = -1;
1880        busnr = 0;
1881    } else {
1882        if (pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
1883            error_report("Invalid PCI device address %s for device %s",
1884                         devaddr, nd->model);
1885            exit(1);
1886        }
1887
1888        if (dom != 0) {
1889            error_report("No support for non-zero PCI domains");
1890            exit(1);
1891        }
1892
1893        devfn = PCI_DEVFN(slot, 0);
1894    }
1895
1896    bus = pci_find_bus_nr(rootbus, busnr);
1897    if (!bus) {
1898        error_report("Invalid PCI device address %s for device %s",
1899                     devaddr, nd->model);
1900        exit(1);
1901    }
1902
1903    pci_dev = pci_new(devfn, nd->model);
1904    dev = &pci_dev->qdev;
1905    qdev_set_nic_properties(dev, nd);
1906    pci_realize_and_unref(pci_dev, bus, &error_fatal);
1907    g_ptr_array_free(pci_nic_models, true);
1908    return pci_dev;
1909}
1910
1911PCIDevice *pci_vga_init(PCIBus *bus)
1912{
1913    vga_interface_created = true;
1914    switch (vga_interface_type) {
1915    case VGA_CIRRUS:
1916        return pci_create_simple(bus, -1, "cirrus-vga");
1917    case VGA_QXL:
1918        return pci_create_simple(bus, -1, "qxl-vga");
1919    case VGA_STD:
1920        return pci_create_simple(bus, -1, "VGA");
1921    case VGA_VMWARE:
1922        return pci_create_simple(bus, -1, "vmware-svga");
1923    case VGA_VIRTIO:
1924        return pci_create_simple(bus, -1, "virtio-vga");
1925    case VGA_NONE:
1926    default: /* Other non-PCI types. Checking for unsupported types is already
1927                done in vl.c. */
1928        return NULL;
1929    }
1930}
1931
1932/* Whether a given bus number is in range of the secondary
1933 * bus of the given bridge device. */
1934static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1935{
1936    return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1937             PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1938        dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1939        bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1940}
1941
1942/* Whether a given bus number is in a range of a root bus */
1943static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1944{
1945    int i;
1946
1947    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1948        PCIDevice *dev = bus->devices[i];
1949
1950        if (dev && IS_PCI_BRIDGE(dev)) {
1951            if (pci_secondary_bus_in_range(dev, bus_num)) {
1952                return true;
1953            }
1954        }
1955    }
1956
1957    return false;
1958}
1959
1960PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1961{
1962    PCIBus *sec;
1963
1964    if (!bus) {
1965        return NULL;
1966    }
1967
1968    if (pci_bus_num(bus) == bus_num) {
1969        return bus;
1970    }
1971
1972    /* Consider all bus numbers in range for the host pci bridge. */
1973    if (!pci_bus_is_root(bus) &&
1974        !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1975        return NULL;
1976    }
1977
1978    /* try child bus */
1979    for (; bus; bus = sec) {
1980        QLIST_FOREACH(sec, &bus->child, sibling) {
1981            if (pci_bus_num(sec) == bus_num) {
1982                return sec;
1983            }
1984            /* PXB buses assumed to be children of bus 0 */
1985            if (pci_bus_is_root(sec)) {
1986                if (pci_root_bus_in_range(sec, bus_num)) {
1987                    break;
1988                }
1989            } else {
1990                if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1991                    break;
1992                }
1993            }
1994        }
1995    }
1996
1997    return NULL;
1998}
1999
2000void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
2001                                  pci_bus_fn end, void *parent_state)
2002{
2003    PCIBus *sec;
2004    void *state;
2005
2006    if (!bus) {
2007        return;
2008    }
2009
2010    if (begin) {
2011        state = begin(bus, parent_state);
2012    } else {
2013        state = parent_state;
2014    }
2015
2016    QLIST_FOREACH(sec, &bus->child, sibling) {
2017        pci_for_each_bus_depth_first(sec, begin, end, state);
2018    }
2019
2020    if (end) {
2021        end(bus, state);
2022    }
2023}
2024
2025
2026PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2027{
2028    bus = pci_find_bus_nr(bus, bus_num);
2029
2030    if (!bus)
2031        return NULL;
2032
2033    return bus->devices[devfn];
2034}
2035
2036#define ONBOARD_INDEX_MAX (16 * 1024 - 1)
2037
2038static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2039{
2040    PCIDevice *pci_dev = (PCIDevice *)qdev;
2041    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2042    ObjectClass *klass = OBJECT_CLASS(pc);
2043    Error *local_err = NULL;
2044    bool is_default_rom;
2045    uint16_t class_id;
2046
2047    /*
2048     * capped by systemd (see: udev-builtin-net_id.c)
2049     * as it's the only known user honor it to avoid users
2050     * misconfigure QEMU and then wonder why acpi-index doesn't work
2051     */
2052    if (pci_dev->acpi_index > ONBOARD_INDEX_MAX) {
2053        error_setg(errp, "acpi-index should be less or equal to %u",
2054                   ONBOARD_INDEX_MAX);
2055        return;
2056    }
2057
2058    /*
2059     * make sure that acpi-index is unique across all present PCI devices
2060     */
2061    if (pci_dev->acpi_index) {
2062        GSequence *used_indexes = pci_acpi_index_list();
2063
2064        if (g_sequence_lookup(used_indexes,
2065                              GINT_TO_POINTER(pci_dev->acpi_index),
2066                              g_cmp_uint32, NULL)) {
2067            error_setg(errp, "a PCI device with acpi-index = %" PRIu32
2068                       " already exist", pci_dev->acpi_index);
2069            return;
2070        }
2071        g_sequence_insert_sorted(used_indexes,
2072                                 GINT_TO_POINTER(pci_dev->acpi_index),
2073                                 g_cmp_uint32, NULL);
2074    }
2075
2076    if (pci_dev->romsize != -1 && !is_power_of_2(pci_dev->romsize)) {
2077        error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
2078        return;
2079    }
2080
2081    /* initialize cap_present for pci_is_express() and pci_config_size(),
2082     * Note that hybrid PCIs are not set automatically and need to manage
2083     * QEMU_PCI_CAP_EXPRESS manually */
2084    if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2085       !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2086        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2087    }
2088
2089    if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2090        pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2091    }
2092
2093    pci_dev = do_pci_register_device(pci_dev,
2094                                     object_get_typename(OBJECT(qdev)),
2095                                     pci_dev->devfn, errp);
2096    if (pci_dev == NULL)
2097        return;
2098
2099    if (pc->realize) {
2100        pc->realize(pci_dev, &local_err);
2101        if (local_err) {
2102            error_propagate(errp, local_err);
2103            do_pci_unregister_device(pci_dev);
2104            return;
2105        }
2106    }
2107
2108    if (pci_dev->failover_pair_id) {
2109        if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
2110            error_setg(errp, "failover primary device must be on "
2111                             "PCIExpress bus");
2112            pci_qdev_unrealize(DEVICE(pci_dev));
2113            return;
2114        }
2115        class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
2116        if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
2117            error_setg(errp, "failover primary device is not an "
2118                             "Ethernet device");
2119            pci_qdev_unrealize(DEVICE(pci_dev));
2120            return;
2121        }
2122        if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2123            || (PCI_FUNC(pci_dev->devfn) != 0)) {
2124            error_setg(errp, "failover: primary device must be in its own "
2125                              "PCI slot");
2126            pci_qdev_unrealize(DEVICE(pci_dev));
2127            return;
2128        }
2129        qdev->allow_unplug_during_migration = true;
2130    }
2131
2132    /* rom loading */
2133    is_default_rom = false;
2134    if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2135        pci_dev->romfile = g_strdup(pc->romfile);
2136        is_default_rom = true;
2137    }
2138
2139    pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2140    if (local_err) {
2141        error_propagate(errp, local_err);
2142        pci_qdev_unrealize(DEVICE(pci_dev));
2143        return;
2144    }
2145
2146    pci_set_power(pci_dev, true);
2147
2148    pci_dev->msi_trigger = pci_msi_trigger;
2149}
2150
2151PCIDevice *pci_new_multifunction(int devfn, bool multifunction,
2152                                 const char *name)
2153{
2154    DeviceState *dev;
2155
2156    dev = qdev_new(name);
2157    qdev_prop_set_int32(dev, "addr", devfn);
2158    qdev_prop_set_bit(dev, "multifunction", multifunction);
2159    return PCI_DEVICE(dev);
2160}
2161
2162PCIDevice *pci_new(int devfn, const char *name)
2163{
2164    return pci_new_multifunction(devfn, false, name);
2165}
2166
2167bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
2168{
2169    return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
2170}
2171
2172PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2173                                           bool multifunction,
2174                                           const char *name)
2175{
2176    PCIDevice *dev = pci_new_multifunction(devfn, multifunction, name);
2177    pci_realize_and_unref(dev, bus, &error_fatal);
2178    return dev;
2179}
2180
2181PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2182{
2183    return pci_create_simple_multifunction(bus, devfn, false, name);
2184}
2185
2186static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2187{
2188    int offset = PCI_CONFIG_HEADER_SIZE;
2189    int i;
2190    for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2191        if (pdev->used[i])
2192            offset = i + 1;
2193        else if (i - offset + 1 == size)
2194            return offset;
2195    }
2196    return 0;
2197}
2198
2199static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2200                                        uint8_t *prev_p)
2201{
2202    uint8_t next, prev;
2203
2204    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2205        return 0;
2206
2207    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2208         prev = next + PCI_CAP_LIST_NEXT)
2209        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2210            break;
2211
2212    if (prev_p)
2213        *prev_p = prev;
2214    return next;
2215}
2216
2217static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2218{
2219    uint8_t next, prev, found = 0;
2220
2221    if (!(pdev->used[offset])) {
2222        return 0;
2223    }
2224
2225    assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2226
2227    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2228         prev = next + PCI_CAP_LIST_NEXT) {
2229        if (next <= offset && next > found) {
2230            found = next;
2231        }
2232    }
2233    return found;
2234}
2235
2236/* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2237   This is needed for an option rom which is used for more than one device. */
2238static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2239{
2240    uint16_t vendor_id;
2241    uint16_t device_id;
2242    uint16_t rom_vendor_id;
2243    uint16_t rom_device_id;
2244    uint16_t rom_magic;
2245    uint16_t pcir_offset;
2246    uint8_t checksum;
2247
2248    /* Words in rom data are little endian (like in PCI configuration),
2249       so they can be read / written with pci_get_word / pci_set_word. */
2250
2251    /* Only a valid rom will be patched. */
2252    rom_magic = pci_get_word(ptr);
2253    if (rom_magic != 0xaa55) {
2254        PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2255        return;
2256    }
2257    pcir_offset = pci_get_word(ptr + 0x18);
2258    if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2259        PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2260        return;
2261    }
2262
2263    vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2264    device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2265    rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2266    rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2267
2268    PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2269                vendor_id, device_id, rom_vendor_id, rom_device_id);
2270
2271    checksum = ptr[6];
2272
2273    if (vendor_id != rom_vendor_id) {
2274        /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2275        checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2276        checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2277        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2278        ptr[6] = checksum;
2279        pci_set_word(ptr + pcir_offset + 4, vendor_id);
2280    }
2281
2282    if (device_id != rom_device_id) {
2283        /* Patch device id and checksum (at offset 6 for etherboot roms). */
2284        checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2285        checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2286        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2287        ptr[6] = checksum;
2288        pci_set_word(ptr + pcir_offset + 6, device_id);
2289    }
2290}
2291
2292/* Add an option rom for the device */
2293static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2294                               Error **errp)
2295{
2296    int64_t size;
2297    char *path;
2298    void *ptr;
2299    char name[32];
2300    const VMStateDescription *vmsd;
2301
2302    if (!pdev->romfile)
2303        return;
2304    if (strlen(pdev->romfile) == 0)
2305        return;
2306
2307    if (!pdev->rom_bar) {
2308        /*
2309         * Load rom via fw_cfg instead of creating a rom bar,
2310         * for 0.11 compatibility.
2311         */
2312        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2313
2314        /*
2315         * Hot-plugged devices can't use the option ROM
2316         * if the rom bar is disabled.
2317         */
2318        if (DEVICE(pdev)->hotplugged) {
2319            error_setg(errp, "Hot-plugged device without ROM bar"
2320                       " can't have an option ROM");
2321            return;
2322        }
2323
2324        if (class == 0x0300) {
2325            rom_add_vga(pdev->romfile);
2326        } else {
2327            rom_add_option(pdev->romfile, -1);
2328        }
2329        return;
2330    }
2331
2332    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2333    if (path == NULL) {
2334        path = g_strdup(pdev->romfile);
2335    }
2336
2337    size = get_image_size(path);
2338    if (size < 0) {
2339        error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2340        g_free(path);
2341        return;
2342    } else if (size == 0) {
2343        error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2344        g_free(path);
2345        return;
2346    } else if (size > 2 * GiB) {
2347        error_setg(errp, "romfile \"%s\" too large (size cannot exceed 2 GiB)",
2348                   pdev->romfile);
2349        g_free(path);
2350        return;
2351    }
2352    if (pdev->romsize != -1) {
2353        if (size > pdev->romsize) {
2354            error_setg(errp, "romfile \"%s\" (%u bytes) is too large for ROM size %u",
2355                       pdev->romfile, (uint32_t)size, pdev->romsize);
2356            g_free(path);
2357            return;
2358        }
2359    } else {
2360        pdev->romsize = pow2ceil(size);
2361    }
2362
2363    vmsd = qdev_get_vmsd(DEVICE(pdev));
2364
2365    if (vmsd) {
2366        snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2367    } else {
2368        snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2369    }
2370    pdev->has_rom = true;
2371    memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize, &error_fatal);
2372    ptr = memory_region_get_ram_ptr(&pdev->rom);
2373    if (load_image_size(path, ptr, size) < 0) {
2374        error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
2375        g_free(path);
2376        return;
2377    }
2378    g_free(path);
2379
2380    if (is_default_rom) {
2381        /* Only the default rom images will be patched (if needed). */
2382        pci_patch_ids(pdev, ptr, size);
2383    }
2384
2385    pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2386}
2387
2388static void pci_del_option_rom(PCIDevice *pdev)
2389{
2390    if (!pdev->has_rom)
2391        return;
2392
2393    vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2394    pdev->has_rom = false;
2395}
2396
2397/*
2398 * On success, pci_add_capability() returns a positive value
2399 * that the offset of the pci capability.
2400 * On failure, it sets an error and returns a negative error
2401 * code.
2402 */
2403int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2404                       uint8_t offset, uint8_t size,
2405                       Error **errp)
2406{
2407    uint8_t *config;
2408    int i, overlapping_cap;
2409
2410    if (!offset) {
2411        offset = pci_find_space(pdev, size);
2412        /* out of PCI config space is programming error */
2413        assert(offset);
2414    } else {
2415        /* Verify that capabilities don't overlap.  Note: device assignment
2416         * depends on this check to verify that the device is not broken.
2417         * Should never trigger for emulated devices, but it's helpful
2418         * for debugging these. */
2419        for (i = offset; i < offset + size; i++) {
2420            overlapping_cap = pci_find_capability_at_offset(pdev, i);
2421            if (overlapping_cap) {
2422                error_setg(errp, "%s:%02x:%02x.%x "
2423                           "Attempt to add PCI capability %x at offset "
2424                           "%x overlaps existing capability %x at offset %x",
2425                           pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2426                           PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2427                           cap_id, offset, overlapping_cap, i);
2428                return -EINVAL;
2429            }
2430        }
2431    }
2432
2433    config = pdev->config + offset;
2434    config[PCI_CAP_LIST_ID] = cap_id;
2435    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2436    pdev->config[PCI_CAPABILITY_LIST] = offset;
2437    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2438    memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2439    /* Make capability read-only by default */
2440    memset(pdev->wmask + offset, 0, size);
2441    /* Check capability by default */
2442    memset(pdev->cmask + offset, 0xFF, size);
2443    return offset;
2444}
2445
2446/* Unlink capability from the pci config space. */
2447void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2448{
2449    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2450    if (!offset)
2451        return;
2452    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2453    /* Make capability writable again */
2454    memset(pdev->wmask + offset, 0xff, size);
2455    memset(pdev->w1cmask + offset, 0, size);
2456    /* Clear cmask as device-specific registers can't be checked */
2457    memset(pdev->cmask + offset, 0, size);
2458    memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2459
2460    if (!pdev->config[PCI_CAPABILITY_LIST])
2461        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2462}
2463
2464uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2465{
2466    return pci_find_capability_list(pdev, cap_id, NULL);
2467}
2468
2469static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2470{
2471    PCIDevice *d = (PCIDevice *)dev;
2472    const char *name = NULL;
2473    const pci_class_desc *desc =  pci_class_descriptions;
2474    int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2475
2476    while (desc->desc &&
2477          (class & ~desc->fw_ign_bits) !=
2478          (desc->class & ~desc->fw_ign_bits)) {
2479        desc++;
2480    }
2481
2482    if (desc->desc) {
2483        name = desc->fw_name;
2484    }
2485
2486    if (name) {
2487        pstrcpy(buf, len, name);
2488    } else {
2489        snprintf(buf, len, "pci%04x,%04x",
2490                 pci_get_word(d->config + PCI_VENDOR_ID),
2491                 pci_get_word(d->config + PCI_DEVICE_ID));
2492    }
2493
2494    return buf;
2495}
2496
2497static char *pcibus_get_fw_dev_path(DeviceState *dev)
2498{
2499    PCIDevice *d = (PCIDevice *)dev;
2500    char name[33];
2501    int has_func = !!PCI_FUNC(d->devfn);
2502
2503    return g_strdup_printf("%s@%x%s%.*x",
2504                           pci_dev_fw_name(dev, name, sizeof(name)),
2505                           PCI_SLOT(d->devfn),
2506                           has_func ? "," : "",
2507                           has_func,
2508                           PCI_FUNC(d->devfn));
2509}
2510
2511static char *pcibus_get_dev_path(DeviceState *dev)
2512{
2513    PCIDevice *d = container_of(dev, PCIDevice, qdev);
2514    PCIDevice *t;
2515    int slot_depth;
2516    /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2517     * 00 is added here to make this format compatible with
2518     * domain:Bus:Slot.Func for systems without nested PCI bridges.
2519     * Slot.Function list specifies the slot and function numbers for all
2520     * devices on the path from root to the specific device. */
2521    const char *root_bus_path;
2522    int root_bus_len;
2523    char slot[] = ":SS.F";
2524    int slot_len = sizeof slot - 1 /* For '\0' */;
2525    int path_len;
2526    char *path, *p;
2527    int s;
2528
2529    root_bus_path = pci_root_bus_path(d);
2530    root_bus_len = strlen(root_bus_path);
2531
2532    /* Calculate # of slots on path between device and root. */;
2533    slot_depth = 0;
2534    for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2535        ++slot_depth;
2536    }
2537
2538    path_len = root_bus_len + slot_len * slot_depth;
2539
2540    /* Allocate memory, fill in the terminating null byte. */
2541    path = g_malloc(path_len + 1 /* For '\0' */);
2542    path[path_len] = '\0';
2543
2544    memcpy(path, root_bus_path, root_bus_len);
2545
2546    /* Fill in slot numbers. We walk up from device to root, so need to print
2547     * them in the reverse order, last to first. */
2548    p = path + path_len;
2549    for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2550        p -= slot_len;
2551        s = snprintf(slot, sizeof slot, ":%02x.%x",
2552                     PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2553        assert(s == slot_len);
2554        memcpy(p, slot, slot_len);
2555    }
2556
2557    return path;
2558}
2559
2560static int pci_qdev_find_recursive(PCIBus *bus,
2561                                   const char *id, PCIDevice **pdev)
2562{
2563    DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2564    if (!qdev) {
2565        return -ENODEV;
2566    }
2567
2568    /* roughly check if given qdev is pci device */
2569    if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2570        *pdev = PCI_DEVICE(qdev);
2571        return 0;
2572    }
2573    return -EINVAL;
2574}
2575
2576int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2577{
2578    PCIHostState *host_bridge;
2579    int rc = -ENODEV;
2580
2581    QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2582        int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2583        if (!tmp) {
2584            rc = 0;
2585            break;
2586        }
2587        if (tmp != -ENODEV) {
2588            rc = tmp;
2589        }
2590    }
2591
2592    return rc;
2593}
2594
2595MemoryRegion *pci_address_space(PCIDevice *dev)
2596{
2597    return pci_get_bus(dev)->address_space_mem;
2598}
2599
2600MemoryRegion *pci_address_space_io(PCIDevice *dev)
2601{
2602    return pci_get_bus(dev)->address_space_io;
2603}
2604
2605static void pci_device_class_init(ObjectClass *klass, void *data)
2606{
2607    DeviceClass *k = DEVICE_CLASS(klass);
2608
2609    k->realize = pci_qdev_realize;
2610    k->unrealize = pci_qdev_unrealize;
2611    k->bus_type = TYPE_PCI_BUS;
2612    device_class_set_props(k, pci_props);
2613}
2614
2615static void pci_device_class_base_init(ObjectClass *klass, void *data)
2616{
2617    if (!object_class_is_abstract(klass)) {
2618        ObjectClass *conventional =
2619            object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
2620        ObjectClass *pcie =
2621            object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2622        ObjectClass *cxl =
2623            object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2624        assert(conventional || pcie || cxl);
2625    }
2626}
2627
2628AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2629{
2630    PCIBus *bus = pci_get_bus(dev);
2631    PCIBus *iommu_bus = bus;
2632    uint8_t devfn = dev->devfn;
2633
2634    while (iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2635        PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
2636
2637        /*
2638         * The requester ID of the provided device may be aliased, as seen from
2639         * the IOMMU, due to topology limitations.  The IOMMU relies on a
2640         * requester ID to provide a unique AddressSpace for devices, but
2641         * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
2642         * to-PCI bridge creates and accepts transactions on behalf of down-
2643         * stream devices.  When doing so, all downstream devices are masked
2644         * (aliased) behind a single requester ID.  The requester ID used
2645         * depends on the format of the bridge devices.  Proper PCIe-to-PCI
2646         * bridges, with a PCIe capability indicating such, follow the
2647         * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
2648         * where the bridge uses the seconary bus as the bridge portion of the
2649         * requester ID and devfn of 00.0.  For other bridges, typically those
2650         * found on the root complex such as the dmi-to-pci-bridge, we follow
2651         * the convention of typical bare-metal hardware, which uses the
2652         * requester ID of the bridge itself.  There are device specific
2653         * exceptions to these rules, but these are the defaults that the
2654         * Linux kernel uses when determining DMA aliases itself and believed
2655         * to be true for the bare metal equivalents of the devices emulated
2656         * in QEMU.
2657         */
2658        if (!pci_bus_is_express(iommu_bus)) {
2659            PCIDevice *parent = iommu_bus->parent_dev;
2660
2661            if (pci_is_express(parent) &&
2662                pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
2663                devfn = PCI_DEVFN(0, 0);
2664                bus = iommu_bus;
2665            } else {
2666                devfn = parent->devfn;
2667                bus = parent_bus;
2668            }
2669        }
2670
2671        iommu_bus = parent_bus;
2672    }
2673    if (!pci_bus_bypass_iommu(bus) && iommu_bus && iommu_bus->iommu_fn) {
2674        return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, devfn);
2675    }
2676    return &address_space_memory;
2677}
2678
2679void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2680{
2681    bus->iommu_fn = fn;
2682    bus->iommu_opaque = opaque;
2683}
2684
2685static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2686{
2687    Range *range = opaque;
2688    uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2689    int i;
2690
2691    if (!(cmd & PCI_COMMAND_MEMORY)) {
2692        return;
2693    }
2694
2695    if (IS_PCI_BRIDGE(dev)) {
2696        pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2697        pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2698
2699        base = MAX(base, 0x1ULL << 32);
2700
2701        if (limit >= base) {
2702            Range pref_range;
2703            range_set_bounds(&pref_range, base, limit);
2704            range_extend(range, &pref_range);
2705        }
2706    }
2707    for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2708        PCIIORegion *r = &dev->io_regions[i];
2709        pcibus_t lob, upb;
2710        Range region_range;
2711
2712        if (!r->size ||
2713            (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2714            !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2715            continue;
2716        }
2717
2718        lob = pci_bar_address(dev, i, r->type, r->size);
2719        upb = lob + r->size - 1;
2720        if (lob == PCI_BAR_UNMAPPED) {
2721            continue;
2722        }
2723
2724        lob = MAX(lob, 0x1ULL << 32);
2725
2726        if (upb >= lob) {
2727            range_set_bounds(&region_range, lob, upb);
2728            range_extend(range, &region_range);
2729        }
2730    }
2731}
2732
2733void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2734{
2735    range_make_empty(range);
2736    pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2737}
2738
2739static bool pcie_has_upstream_port(PCIDevice *dev)
2740{
2741    PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
2742
2743    /* Device associated with an upstream port.
2744     * As there are several types of these, it's easier to check the
2745     * parent device: upstream ports are always connected to
2746     * root or downstream ports.
2747     */
2748    return parent_dev &&
2749        pci_is_express(parent_dev) &&
2750        parent_dev->exp.exp_cap &&
2751        (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2752         pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2753}
2754
2755PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2756{
2757    PCIBus *bus = pci_get_bus(pci_dev);
2758
2759    if(pcie_has_upstream_port(pci_dev)) {
2760        /* With an upstream PCIe port, we only support 1 device at slot 0 */
2761        return bus->devices[0];
2762    } else {
2763        /* Other bus types might support multiple devices at slots 0-31 */
2764        return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2765    }
2766}
2767
2768MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2769{
2770    MSIMessage msg;
2771    if (msix_enabled(dev)) {
2772        msg = msix_get_message(dev, vector);
2773    } else if (msi_enabled(dev)) {
2774        msg = msi_get_message(dev, vector);
2775    } else {
2776        /* Should never happen */
2777        error_report("%s: unknown interrupt type", __func__);
2778        abort();
2779    }
2780    return msg;
2781}
2782
2783void pci_set_power(PCIDevice *d, bool state)
2784{
2785    if (d->has_power == state) {
2786        return;
2787    }
2788
2789    d->has_power = state;
2790    pci_update_mappings(d);
2791    memory_region_set_enabled(&d->bus_master_enable_region,
2792                              (pci_get_word(d->config + PCI_COMMAND)
2793                               & PCI_COMMAND_MASTER) && d->has_power);
2794    if (!d->has_power) {
2795        pci_device_reset(d);
2796    }
2797}
2798
2799static const TypeInfo pci_device_type_info = {
2800    .name = TYPE_PCI_DEVICE,
2801    .parent = TYPE_DEVICE,
2802    .instance_size = sizeof(PCIDevice),
2803    .abstract = true,
2804    .class_size = sizeof(PCIDeviceClass),
2805    .class_init = pci_device_class_init,
2806    .class_base_init = pci_device_class_base_init,
2807};
2808
2809static void pci_register_types(void)
2810{
2811    type_register_static(&pci_bus_info);
2812    type_register_static(&pcie_bus_info);
2813    type_register_static(&cxl_bus_info);
2814    type_register_static(&conventional_pci_interface_info);
2815    type_register_static(&cxl_interface_info);
2816    type_register_static(&pcie_interface_info);
2817    type_register_static(&pci_device_type_info);
2818}
2819
2820type_init(pci_register_types)
2821