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