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