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